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

アラートダイアログ上にTable Viewを表示 v7_サイズ調整あり

Posted on 12月 24, 2019 by Takaaki Naganoya

先日「macOS Native」のイベント後に秋葉原で顔見知りのScripter3人でカレー食べて帰ってきました。その際に、アラートダイアログ上に作成した箱庭User Interface類の話で盛り上がっていました。「意外と使える」「自分でもいろいろ作ってる」「公開してよ」といったような。

本Scriptはその際の話を受けてEdama2さんが作っている試作品の、さらに試作品になるわけですが、プログラム内容が自分とは別の価値体系で清書し直されており、あいかわらずロジックとコードの美しさにうならされます。また、「本来倒すべき敵」に向けての実装が行われているので、単にテーブルビューを表示するだけには少々機能過剰になっています。

以下、Edama2さんによる投稿内容です。

タイトルは「アラートダイアログ上にTable Viewを表示 v7_サイズ調整あり」

主な変更点は
表示する内容に合わせてviewのサイズを調整
レコードのラベルをヘッダのタイトルにする
Table ViewをダブルクリックするとOKボタンを押す
setAllowsEmptySelection: をfalseにして1行目を選択するようにした

データ作成部分が詰め込み効率優先ではなく可読性を高めた作りになっているのが、Edama2さんらしいところです。また、tellブロックをCocoa Scriptingにも多用しているのも特徴です。

ロジックが読みやすい一方で、Cocoa Framework相手にここまで見やすく書くのは、相当の努力が必要なはずで、Cocoa Scripting時に省いてしまいがちな「清書」という1手間が入っていることを感じさせます。

本Scriptはハンドラ(サブルーチン)が前の方に配置される記法です。AppleScriptはもともとハンドラ宣言部を前に書く言語なので、世界的に見るとこちらが主流です(Shane Stanleyですらハンドラ宣言部は前に書きます)。逆に、自分が他の言語に合わせてハンドラ宣言部を後ろに配置するのは、全体から見ると異端といえます(他の言語と書き方が違いすぎるのはどうかと思って、ハンドラ宣言部を後ろに書いています)。

たしかに、自分の箱庭テーブルビューダイアログではカラム幅とテーブルの縦サイズは一切手をつけていなかったので、縦横幅高さの自動調整が入ると、格段に見やすくなります。

Cocoaの機能を呼び出すAppleScriptにおいても、書きこなれてきたことによりハンドラ内にScript文を書いてさらに内部にハンドラを記述するといったような、論理分割やら階層構造化が本Scriptにおいて多用されています。そのあたり、applescript-stdlib(2015)で見かけましたが、本Scriptのように控えめな利用だと安心できます。

本Script内には継続記号(「¬」)が多用されていますが、macOS日本語ユーザー環境上でScript Debuggerを使っていると、構文確認時にこれがひっかかってエラーになることがあります(というか、実際にウチでこれを編集してなっています)。継続記号がひっかかって構文確認(コンパイル)できないようであれば、いっそ継続記号をすべて削除すべきでしょう。継続記号に「可読性を上げる」以外の機能はないため、削除しても無害です。

AppleScript名:アラートダイアログ上にTable Viewを表示 v7_サイズ調整あり.scpt
on run
  
  
set aTableList to {}
  
set aTableList’s end to {|Name|:"MacBook Air", Price:"119,800円", Specs:"1.6GHzデュアルコアIntel Core i5(Turbo Boost使用時最大3.6GHz)、4MB L3キャッシュ"}
  
set aTableList’s end to {|Name|:"MacBook Pro 13", Price:"139,800円", Specs:"1.4GHzクアッドコアIntel Core i5(Turbo Boost使用時最大3.9GHz)、128MB eDRAM"}
  
set aTableList’s end to {|Name|:"MacBook Pro 15", Price:"258,800円", Specs:"2.6GHz 6コアIntel Core i7(Turbo Boost使用時最大4.5GHz)、12MB共有L3キャッシュ"}
  
set aTableList’s end to {|Name|:"Mac mini", Price:"122,800円", Specs:"3.0GHz 6コアIntel Core i5 Turbo Boost使用時最大4.1GHz 9MB共有L3キャッシュ"}
  
set aTableList’s end to {|Name|:"iMac 21.5", Price:"120,800円", Specs:"2.3GHzデュアルコアIntel Core i5(Turbo Boost使用時最大3.6GHz)"}
  
set aTableList’s end to {|Name|:"iMac 4K 21.5", Price:"142,800円", Specs:"3.6GHzクアッドコアIntel Core i3"}
  
set aTableList’s end to {|Name|:"iMac 5K 27", Price:"198,800円", Specs:"3.0GHz 6コア Intel Core i5(Turbo Boost使用時最大4.1GHz)"}
  
set optionRec to {aTableList:aTableList}
  
set optionRec to optionRec & {aSortOrder:{column1:"Name", column2:"Price", column3:"Specs"}}
  
  
set aMainMes to "項目の選択"
  
set aSubMes to "適切なものを以下からえらんでください"
  
set dateObj to my chooseData(aMainMes, aSubMes, optionRec)
end run

# アラートダイアログでtableviewを表示
on chooseData(aMainMes, aSubMes, optionRec)
  script MyDialog
    property parent : AppleScript
    
use AppleScript
    
use scripting additions
    
use framework "Foundation"
    
property _retrieve_data : missing value
    
on make
      set aClass to me
      
script
        property parent : aClass
      end script
    end make
    
## ダイアログの呼び出し
    
on call(aMainMes, aSubMes, optionRec)
      set paramObj to {myMessage:aMainMes, mySubMessage:aSubMes, myOption:optionRec}
      
parent’s performSelectorOnMainThread:"raize:" withObject:paramObj waitUntilDone:true
      
if (my _retrieve_data) is missing value then error number -128
      
return (my _retrieve_data)
    end call
    
## ダイアログの生成
    
on raize:paramObj
      ###
      
set mesText to paramObj’s myMessage
      
set infoText to paramObj’s mySubMessage
      
set paramObj to paramObj’s myOption
      
### set up view
      
set {theView, makeObj} to my makeContentView(paramObj)
      
### set up alert
      
tell current application’s NSAlert’s new()
        setMessageText_(mesText)
        
setInformativeText_(infoText)
        
addButtonWithTitle_("OK")
        
addButtonWithTitle_("Cancel")
        
setAccessoryView_(theView)
        
tell |window|()
          setInitialFirstResponder_(theView)
        end tell
        
#### show alert in modal loop
        
if runModal() is (current application’s NSAlertSecondButtonReturn) then return
      end tell
      
### retrieve date
      
my retrieveData(makeObj)
    end raize:
    
    
## ContentView を作成
    
property _data_source : missing value
    
on makeContentView(paramObj)
      ## 準備
      
set aList to (paramObj’s aTableList) as list
      
set keyRec to (paramObj’s aSortOrder) as record
      
set keyDict to (current application’s NSDictionary’s dictionaryWithDictionary:keyRec)
      
      
set my _data_source to current application’s NSArrayController’s new()
      
repeat with anItem in aList
        set aDict to (current application’s NSDictionary’s dictionaryWithDictionary:anItem)
        ((
my _data_source)’s addObject:aDict)
      end repeat
      
      
## NSTableView
      
tell current application’s NSTableView’s alloc()
        tell initWithFrame_(current application’s CGRectZero)
          setAllowsEmptySelection_(false)
          
setDataSource_(me)
          
setDelegate_(me)
          
setDoubleAction_("doubleAction:")
          
setGridStyleMask_(current application’s NSTableViewSolidVerticalGridLineMask)
          
setSelectionHighlightStyle_(current application’s NSTableViewSelectionHighlightStyleRegular)
          
setTarget_(me)
          
setUsesAlternatingRowBackgroundColors_(true)
          
          
set thisRowHeight to rowHeight() as integer
          
set aTableObj to it
        end tell
      end tell
      
      
## NSTableColumn
      
### Columnの並び順を指定する
      
set viewWidth to 0
      
set columnsCount to keyDict’s |count|()
      
repeat with colNum from 1 to columnsCount
        
        
set keyName to "column" & colNum as text
        
set aTitle to (keyDict’s objectForKey:keyName)
        
        
tell (current application’s NSTableColumn’s alloc()’s initWithIdentifier:(colNum as text))
          tell headerCell()
            setStringValue_(aTitle)
            
set thisHeaderHeight to cellSize()’s height
          end tell
          
          
set aTableColumn to it
        end tell
        
        
### Columnの横幅を調整
        
tell aTableObj
          addTableColumn_(aTableColumn)
          
–reloadData()
          
set colWidthMax to 0
          
set rowCount to numberOfRows()
          
          
repeat with rowNum from 1 to rowCount
            tell preparedCellAtColumn_row_(colNum – 1, rowNum – 1)
              set thisWidthSize to cellSize()’s width
              
–log result
              
if thisWidthSize is greater than or equal to colWidthMax then set colWidthMax to thisWidthSize
            end tell
          end repeat
        end tell
        
–log colWidthMax
        
        
set colWidthMax to colWidthMax + 5 –> 5は余白
        
tell aTableColumn
          setWidth_(colWidthMax)
        end tell
        
        
set viewWidth to viewWidth + colWidthMax
      end repeat
      
      
## NSScrollView
      
### Viewの高さを計算
      
set viewHeight to (thisRowHeight + 2) * rowCount + thisHeaderHeight –> 2を足さないと高さが合わない
      
set vSize to current application’s NSMakeRect(0, 0, viewWidth + 10, viewHeight) –> 10を足すといい感じの横幅になる
      
      
### Viewを作成
      
tell current application’s NSScrollView’s alloc()
        tell initWithFrame_(vSize)
          setBorderType_(current application’s NSBezelBorder)
          
setDocumentView_(aTableObj)
          
–setHasHorizontalScroller_(true)
          
–setHasVerticalScroller_(true)
          
set aScroll to it
        end tell
      end tell
      
      
return {aScroll, aTableObj}
    end makeContentView
    
    
## retrieve data
    
on retrieveData(aTableObj)
      set aRow to aTableObj’s selectedRow()
      
log result
      
if aRow is -1 then
        set my _retrieve_data to {}
      else
        set my _retrieve_data to ((my _data_source)’s arrangedObjects()’s objectAtIndex:aRow) as record
      end if
    end retrieveData
    
    
    
# NSTableViewDatasource
    
on numberOfRowsInTableView:aTableView
      –log "numberOfRowsInTableView:"
      
return (my _data_source)’s content()’s |count|()
    end numberOfRowsInTableView:
    
# NSTableViewDelegate
    
on tableView:aTableView objectValueForTableColumn:aColumn row:aRow
      –log "objectValueForTableColumn"
      
set keyName to aColumn’s headerCell()’s title()
      
set aDict to (my _data_source)’s arrangedObjects()’s objectAtIndex:aRow
      
set aStr to aDict’s objectForKey:keyName
      
–log result as text
      
return aStr
    end tableView:objectValueForTableColumn:row:
    
# テーブル内のセルが編集できるか
    
on tableView:aTableView shouldEditTableColumn:aColumn row:aRow
      return false
    end tableView:shouldEditTableColumn:row:
    
# テーブル内をダブルクリックしたらOKボタンを押す
    
on doubleAction:sender
      –log "doubleAction"
      
–log sender’s |className|() as text
      
set theEvent to current application’s NSEvent’s ¬
        keyEventWithType:(current application’s NSEventTypeKeyDown) ¬
          location:(current application’s NSZeroPoint) ¬
          
modifierFlags:0 ¬
          
timestamp:0.0 ¬
          
windowNumber:(sender’s |window|()’s windowNumber()) ¬
          
context:(current application’s NSGraphicsContext’s currentContext()) ¬
          
|characters|:return ¬
          
charactersIgnoringModifiers:(missing value) ¬
          
isARepeat:false ¬
          
keyCode:0
      current application’s NSApp’s postEvent:theEvent atStart:(not false)
    end doubleAction:
  end script
  
  
##
  
tell (make MyDialog)
    return call(aMainMes, aSubMes, optionRec)
  end tell
end chooseData

★Click Here to Open This Script 

Posted in dialog GUI | Tagged 10.13savvy 10.14savvy 10.15savvy | 1 Comment

アラートダイアログ上にTable Viewを表示 v6_サーチフィールドつき

Posted on 12月 24, 2019 by Takaaki Naganoya

検索フィールドつきのTable View表示ダイアログを表示するAppleScriptです。項目選択を行う簡易ユーザーインタフェース(ダイアログ)で、選択肢の数が多い場合に備えて項目のキーワード抽出機能を付加したものです。

サーチフィールドの実装は無理かと思っていたのですが、単体でアラートダイアログ上に表示してみたら、予想外にキーボード入力イベントと検索語のクリアのイベントを簡単に拾えたので、Table Viewと組み合わせて試してみました。

AppleScript名:アラートダイアログ上にTable Viewを表示 v6_サーチフィールドつき
— Created 2019-12-23 by Takaaki Naganoya
— 2019 Piyomaru Software
set aRes to displayCondTable() of filterTableDialogView
–> {field3:"3.0GHz 6コア Intel Core i5(Turbo Boost使用時最大4.1GHz)", field2:198800, field1:"iMac 5K 27"}

script filterTableDialogView
  use scripting additions
  
use framework "Foundation"
  
use framework "AppKit"
  
property parent : AppleScript
  
  
property NSView : a reference to current application’s NSView
  
property NSAlert : a reference to current application’s NSAlert
  
property NSIndexSet : a reference to current application’s NSIndexSet
  
property NSPredicate : a reference to current application’s NSPredicate
  
property NSScrollView : a reference to current application’s NSScrollView
  
property NSTableView : a reference to current application’s NSTableView
  
property NSSearchField : a reference to current application’s NSSearchField
  
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 theResult : 0
  
property returnCode : 0
  
property theDataSource : {}
  
property tView : missing value
  
property aDataList : {}
  
  
  
on displayCondTable()
    set (my theResult) to 0 –initialize
    
    
set aDataList to {{field1:"MacBook Air", field2:119800, field3:"1.6GHzデュアルコアIntel Core i5(Turbo Boost使用時最大3.6GHz)、4MB L3キャッシュ"}, {field1:"MacBook Pro 13", field2:139800, field3:"1.4GHzクアッドコアIntel Core i5(Turbo Boost使用時最大3.9GHz)、128MB eDRAM"}, {field1:"MacBook Pro 15", field2:258800, field3:"2.6GHz 6コアIntel Core i7(Turbo Boost使用時最大4.5GHz)、12MB共有L3キャッシュ"}, {field1:"Mac mini", field2:122800, field3:"3.0GHz 6コアIntel Core i5 Turbo Boost使用時最大4.1GHz 9MB共有L3キャッシュ"}, {field1:"iMac 21.5", field2:120800, field3:"2.3GHzデュアルコアIntel Core i5(Turbo Boost使用時最大3.6GHz)"}, {field1:"iMac 4K 21.5", field2:142800, field3:"3.6GHzクアッドコアIntel Core i3"}, {field1:"iMac 5K 27", field2:198800, field3:"3.0GHz 6コア Intel Core i5(Turbo Boost使用時最大4.1GHz)"}, {field1:"iMac Pro", field2:558800, field3:"3.2GHz Intel Xeon W Turbo Boost使用時最大4.2GHz 19MBキャッシュ"}, {field1:"Mac Pro 2019", field2:599800, field3:"3.5GHz 8コアIntel Xeon Wプロセッサ(Turbo Boost使用時最大4.0GHz)"}}
    
    
set paramObj to {myMessage:"項目の選択", mySubMessage:"適切なものを以下からえらんでください", aTableList:aDataList, aSortOrder:{"field1", "field2", "field3"}}
    
    
–my chooseItemByTableView:paramObj –for debug
    
my performSelectorOnMainThread:"chooseItemByTableView:" withObject:paramObj waitUntilDone:true
    
    
return (my theResult)
  end displayCondTable
  
  
  
  
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 800
    
set aHeight to 300
    
    
–Viewをつくる
    
set parentView to NSView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aWidth, aHeight))
    
set aTextInput to makeNSSearchField(0, aHeight – 20, 300, 20) of me
    
    
    
set aScroll to makeTableView(aTList, aWidth, aHeight – 80, labelSortList) of me
    
    
parentView’s setSubviews:{aTextInput, aScroll}
    
    
— 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:(parentView)
      
      
set myWindow to its |window|
    end tell
    
    
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 tmpResult to (aScroll’s documentView’s selectedRow()) + 1
    
set (my theResult) to contents of item tmpResult of ((my theDataSource) as list)
  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 NSMutableArray’s alloc()’s init()
    
theDataSource’s addObjectsFromArray:aDicList
    
    
–TextField
    
set aTextInput to makeNSSearchField(0, 0, 300, 20) of me
    
    
set aScroll to NSScrollView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, aOffset, aWidth, aHeight))
    
set tView to 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 (NSTableColumn’s alloc()’s initWithIdentifier:j)
      (
aColumn’s setWidth:(aWidth div aLen))
      (
aColumn’s headerCell()’s setStringValue:j)
      (
tView’s addTableColumn:aColumn)
    end repeat
    
    
tView’s setDelegate:me
    
tView’s setDataSource:me
    
tView’s reloadData()
    
    
aScroll’s setDocumentView:tView
    
tView’s enclosingScrollView()’s setHasVerticalScroller:true
    
aScroll’s setVerticalLineScroll:(30.0 as real)
    
    
–1行目を選択
    
set aIndexSet to NSIndexSet’s indexSetWithIndex:0
    
tView’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:
  
  
  
on makeNSSearchField(xPos as integer, yPos as integer, myWidth as integer, myHeight as integer)
    set aSearchF to NSSearchField’s alloc()’s initWithFrame:(current application’s NSMakeRect(xPos, yPos, myWidth, myHeight))
    
aSearchF’s setDelegate:(me)
    
return aSearchF
  end makeNSSearchField
  
  
  
–検索クエリ入力時
  
on searchFieldDidStartSearching:(aField)
    set aStr to (aField’s stringValue()) as string
    
set predicStr to "field1 contains[cd] ’" & aStr & "’ OR field3 contains[cd] ’" & aStr & "’"
    
set filteredArray to filterRecListByLabel1((my aDataList), predicStr) of me
    
set (my theDataSource) to filteredArray
    
tView’s reloadData()
  end searchFieldDidStartSearching:
  
  
  
–Search Fieldの「x」ボタンを押したイベント
  
on searchFieldDidEndSearching:(aField)
    set (my theDataSource) to NSMutableArray’s arrayWithArray:(my aDataList)
    
tView’s reloadData()
  end searchFieldDidEndSearching:
  
  
  
–リストに入れたレコードを、指定の属性ラベルの値で抽出
  
on filterRecListByLabel1(aRecList as list, aPredicate as string)
    set aArray to NSMutableArray’s arrayWithArray:aRecList
    
set aPredicate to NSPredicate’s predicateWithFormat:aPredicate
    
set filteredArray to aArray’s filteredArrayUsingPredicate:aPredicate
    
return filteredArray
  end filterRecListByLabel1
  
end script

★Click Here to Open This Script 

Posted in dialog GUI | Tagged 10.13savvy 10.14savvy 10.15savvy NSAlert NSIndexSet NSModalPanelWindowLevel NSMutableArray NSPredicate NSRunningApplication NSScrollView NSSearchField NSTableColumn NSTableView NSView | 8 Comments

アラートダイアログ上にTable Viewを表示 v5_複数キー抽出つき

Posted on 12月 23, 2019 by Takaaki Naganoya

アラートダイアログ上にTableViewを表示し、複数キーの組み合わせによって項目抽出。選択項目のデータを返すAppleScriptです。

あくまで試作品なので、あちらこちらに「お可愛らしい」実装が転がっています。NSBoxがまだまともに使いこなせていないあたりとか(Xcode上で部品として配置するのは楽勝ですが、プログラムから動的に生成して使用するのは別なので)。

抽出キー数は可変で外部から指定できるとよいのですが、本Scriptでは固定です。また、各抽出条件も外部から供給するのが本来あるべき姿ですが、ハードコーディングしています。

あと、TableViewの下側に謎の余白があるのは、めんどくさくなってそのまま放置しています。これで外部から各種パラメータを指定できるようにして、sdefつけて1命令で呼び出せるようにしておけば、レコード数の多い選択項目から条件抽出しつつ項目選択できてよいでしょう。

プログラム内容自体は、高度でもなければ高尚でもありません。実にダラダラとGUI部品のパラメータを設定しているだけです。

AppleScript名:アラートダイアログ上にTable Viewを表示 v5_複数キー抽出つき
— Created 2019-12-22 by Takaaki Naganoya
— 2019 Piyomaru Software
set aRes to displayCondTable() of filterTableDialogView
–> {field3:"3.0GHz 6コア Intel Core i5(Turbo Boost使用時最大4.1GHz)", field2:198800, field1:"iMac 5K 27"}

script filterTableDialogView
  use scripting additions
  
use framework "Foundation"
  
use framework "AppKit"
  
property parent : AppleScript
  
  
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 NSColor : a reference to current application’s NSColor
  
property NSIndexSet : a reference to current application’s NSIndexSet
  
property NSPredicate : a reference to current application’s NSPredicate
  
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 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 NSCompoundPredicate : a reference to current application’s NSCompoundPredicate
  
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 : {}
  
property tView : missing value
  
property aDataList : {}
  
property aSel : 0
  
property bSel : 0
  
property cSel : 0
  
property predList : {}
  
property a1Button : missing value
  
property a2Button : missing value
  
property a3Button : missing value
  
  
on displayCondTable()
    set (my theResult) to 0 –initialize
    
    
set aDataList to {{field1:"MacBook Air", field2:119800, field3:"1.6GHzデュアルコアIntel Core i5(Turbo Boost使用時最大3.6GHz)、4MB L3キャッシュ"}, {field1:"MacBook Pro 13", field2:139800, field3:"1.4GHzクアッドコアIntel Core i5(Turbo Boost使用時最大3.9GHz)、128MB eDRAM"}, {field1:"MacBook Pro 15", field2:258800, field3:"2.6GHz 6コアIntel Core i7(Turbo Boost使用時最大4.5GHz)、12MB共有L3キャッシュ"}, {field1:"Mac mini", field2:122800, field3:"3.0GHz 6コアIntel Core i5 Turbo Boost使用時最大4.1GHz 9MB共有L3キャッシュ"}, {field1:"iMac 21.5", field2:120800, field3:"2.3GHzデュアルコアIntel Core i5(Turbo Boost使用時最大3.6GHz)"}, {field1:"iMac 4K 21.5", field2:142800, field3:"3.6GHzクアッドコアIntel Core i3"}, {field1:"iMac 5K 27", field2:198800, field3:"3.0GHz 6コア Intel Core i5(Turbo Boost使用時最大4.1GHz)"}, {field1:"iMac Pro", field2:558800, field3:"3.2GHz Intel Xeon W Turbo Boost使用時最大4.2GHz 19MBキャッシュ"}, {field1:"Mac Pro 2019", field2:599800, field3:"3.5GHz 8コアIntel Xeon Wプロセッサ(Turbo Boost使用時最大4.0GHz)"}}
    
    
set paramObj to {myMessage:"項目の選択", mySubMessage:"適切なものを以下からえらんでください", aTableList:aDataList, aSortOrder:{"field1", "field2", "field3"}}
    
    
–my chooseItemByTableView:paramObj –for debug
    
my performSelectorOnMainThread:"chooseItemByTableView:" withObject:paramObj waitUntilDone:true
    
    
return (my theResult)
  end displayCondTable
  
  
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 800
    
set aHeight to 400
    
set my aSel to 0
    
set my bSel to 0
    
    
–Viewをつくる
    
set parentView to NSView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aWidth, aHeight))
    
    
    
–BOX Aをつくる
    
set aBox to (NSBox’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, aHeight – 60, aWidth, 60)))
    (
aBox’s setTitle:("Filter Condition"))
    
    
–このあたり、項目数に合わせてUIを可変で生成するように(本Scriptは試作品なので、決め打ちでUI生成)
    
set a1Button to (NSPopUpButton’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, 200, 30)) pullsDown:false)
    
a1Button’s removeAllItems()
    (
a1Button’s addItemsWithTitles:{"▼Select Item", "MacBook", "iMac", "mini", "Air", "Pro"})
    
a1Button’s setTarget:(me)
    
a1Button’s setAction:("mySelector:")
    
a1Button’s setEnabled:(true)
    
    
set a2Button to (NSPopUpButton’s alloc()’s initWithFrame:(current application’s NSMakeRect(220, 0, 200, 30)) pullsDown:false)
    
a2Button’s removeAllItems()
    (
a2Button’s addItemsWithTitles:{"▼Select Item", "150000", "200000", "300000", "400000", "600000"})
    
a2Button’s setTarget:(me)
    
a2Button’s setAction:("mySelector:")
    
a2Button’s setEnabled:(true)
    
    
set a3Button to (NSPopUpButton’s alloc()’s initWithFrame:(current application’s NSMakeRect(440, 0, 200, 30)) pullsDown:false)
    
a3Button’s removeAllItems()
    (
a3Button’s addItemsWithTitles:{"▼Select Item", "デュアルコア", "クアッドコア", "6コア", "8コア"})
    
a3Button’s setTarget:(me)
    
a3Button’s setAction:("mySelector:")
    
a3Button’s setEnabled:(true)
    
    
    (
aBox’s addSubview:a1Button)
    (
aBox’s addSubview:a2Button)
    (
aBox’s addSubview:a3Button)
    
    
    
–BOX Bをつくる
    
set bBox to (NSBox’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aWidth, aHeight – 80)))
    (
bBox’s setTitle:("Data"))
    
    
set aScroll to makeTableView(aTList, aWidth, aHeight – 150, labelSortList) of me
    
    (
bBox’s addSubview:aScroll)
    
    
parentView’s setSubviews:{aBox, bBox}
    
    
— 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:(parentView)
      
      
set myWindow to its |window|
    end tell
    
    
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 tmpResult to (aScroll’s documentView’s selectedRow()) + 1
    
set (my theResult) to contents of item tmpResult of ((my theDataSource) as list)
  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 NSMutableArray’s alloc()’s init()
    
theDataSource’s addObjectsFromArray:aDicList
    
    
set aScroll to NSScrollView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, aOffset, aWidth, aHeight))
    
set tView to 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 (NSTableColumn’s alloc()’s initWithIdentifier:j)
      (
aColumn’s setWidth:(aWidth div aLen))
      (
aColumn’s headerCell()’s setStringValue:j)
      (
tView’s addTableColumn:aColumn)
    end repeat
    
    
tView’s setDelegate:me
    
tView’s setDataSource:me
    
tView’s reloadData()
    
    
aScroll’s setDocumentView:tView
    
tView’s enclosingScrollView()’s setHasVerticalScroller:true
    
aScroll’s setVerticalLineScroll:(30.0 as real)
    
    
–1行目を選択
    
set aIndexSet to NSIndexSet’s indexSetWithIndex:0
    
tView’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:
  
  
  
on mySelector:aObject
    set aIndex to (aObject’s indexOfSelectedItem()) as number
    
filterByMultipleCondition() of me
  end mySelector:
  
  
  
  
on filterByMultipleCondition()
    set prediCatesArray to {}
    
    
set aInd to (my a1Button’s indexOfSelectedItem()) as number
    
set bInd to (my a2Button’s indexOfSelectedItem()) as number
    
set cInd to (my a3Button’s indexOfSelectedItem()) as number
    
    
if {aInd, bInd, cInd} = {0, 0, 0} then
      set (my theDataSource) to NSMutableArray’s arrayWithArray:(my aDataList)
      
tView’s reloadData()
      
return
    end if
    
    
–このあたり、複数条件をハードコーディングしているのは超絶頭悪い。項目数の増減に対応できるべき
    
if aInd > 0 then
      set aTitle to (my a1Button’s title()) as string
      
set the end of prediCatesArray to "field1 contains ’" & aTitle & "’"
    end if
    
    
if bInd > 0 then
      set bTitle to (my a2Button’s title()) as string
      
set the end of prediCatesArray to "field2.integerValue < " & bTitle
    end if
    
    
if cInd > 0 then
      set cTitle to (my a3Button’s title()) as string
      
set the end of prediCatesArray to "field3 contains ’" & cTitle & "’"
    end if
    
    
–データ 抽出
    
set tmpList to filterDictArrayByLabel3((my aDataList), prediCatesArray) of me
    
    
–データ 再表示
    
set (my theDataSource) to NSMutableArray’s arrayWithArray:(tmpList)
    
tView’s reloadData()
  end filterByMultipleCondition
  
  
  
  
–リストに入れたレコードを、指定の属性ラベルの値で抽出(複数PredicatesをANDで合成)
  
on filterDictArrayByLabel3(origArray as list, aPredicateList as list)
    set aArray to NSMutableArray’s arrayWithArray:origArray
    
set predArray to NSMutableArray’s new()
    
    
repeat with i in aPredicateList
      (predArray’s addObject:(NSPredicate’s predicateWithFormat:(contents of i)))
    end repeat
    
    
set pred to current application’s NSCompoundPredicate’s andPredicateWithSubpredicates:predArray
    
set filteredArray to aArray’s filteredArrayUsingPredicate:pred
    
    
return filteredArray
  end filterDictArrayByLabel3
end script

★Click Here to Open This Script 

Posted in dialog GUI list Record search | Tagged 10.13savvy 10.14savvy 10.15savvy NSAlert NSAlertSecondButtonReturn NSBox NSColor NSCompoundPredicate NSIndexSet NSModalPanelWindowLevel NSMutableArray NSPopUpButton NSPredicate NSRunningApplication NSScrollView NSTableColumn NSTableView NSView | 1 Comment

choose multiple list lib

Posted on 12月 10, 2019 by Takaaki Naganoya

choose from listの複数リスト版。複数のポップアップメニューをダイアログ上で選択するUser Interfaceを提供する、「choose multiple list」AppleScriptライブラリです。macOS 10.13以降対応です。


▲選択リスト数は可変

–> Download chooseMultiList(To ~/Library/Script Libraries)

AppleScript name:sample 1.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/12/10
—
–  Copyright © 2019 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.7" — High Sierra (10.13) or later
use framework "Foundation"
use scripting additions
use mulList : script "choose multiple list"

set selList to {{"Red", "Blue", "Yellow", "Brown", "White", "Cyan", "Grey"}, {"Red", "Blue", "Yellow", "Brown", "White", "Cyan", "Grey"}}
set tList to {"1st Segments", "2nd Segments"}

set aRes to choose multiple list selList main message "Select Items Demo" sub message "Select each selection. Same selection items *NOT* allowed" with title lists tList height 140 width 400 return type item contents without allow same items
–> {"Red", "Yellow"}

★Click Here to Open This Script 

AppleScript name:sample 2.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/12/10
—
–  Copyright © 2019 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.7" — High Sierra (10.13) or later
use framework "Foundation"
use scripting additions
use mulList : script "choose multiple list"

set selList to {{"Red", "Blue", "Yellow", "Brown", "White", "Cyan", "Grey"}, {"Red", "Blue", "Yellow", "Brown", "White", "Cyan", "Grey"}}
set tList to {"1st Segments", "2nd Segments"}

set aRes to choose multiple list selList main message "Select Items Demo" sub message "Select each selection. Same selection items allowed" with title lists tList height 140 width 400 return type item numbers with allow same items
–> {1, 1}

★Click Here to Open This Script 

テキストエディタ上でオープン中のテキストのdiff表示を行う場合のファイル選択のために作成したものです。


▲もっと汎用的に差分表示用の部品として活用するために、AppleScript用語辞書の添付が切実に望まれるApple製アプリケーション第1位のFileMerge

AppleScript名:CotEditor –> FileMergeでDiff表示.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/12/10
—
–  Copyright © 2019 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.7" — High Sierra (10.13) or later
use framework "Foundation"
use scripting additions
use mulList : script "choose multiple list"

tell application "CotEditor"
  set dCount to count every document
  
if dCount < 2 then
    display dialog "A few documents…" with title "Error" buttons {"OK"} default button 1
    
return
  else if dCount = 2 then
    –オープン中の書類が2つある場合
    
set aPath to file of document 1
    
set bPath to file of document 2
    
    
set aPOSIX to POSIX path of aPath
    
set bPOSIX to POSIX path of bPath
  else
    –オープン中の書類が2つ以上存在している場合
    
set dList to {}
    
set adList to file of every document
    
    
repeat with i in adList
      set the end of dList to POSIX path of i
    end repeat
    
    
set selList to {dList, dList}
    
set tList to {"Document #1", "Document #2"}
    
    
set aRes to choose multiple list selList main message "Select two files to display diff" sub message "Select each file. Same selection items NOT allowed" with title lists tList height 140 width 700 return type item contents without allow same items
    
    
copy aRes to {aPOSIX, bPOSIX}
    
  end if
end tell

tell application "FileMerge" to activate
do shell script "/usr/bin/opendiff " & quoted form of aPOSIX & " " & quoted form of bPOSIX & " &"

★Click Here to Open This Script 

Posted in dialog GUI list Script Libraries | Tagged 10.13savvy 10.14savvy 10.15savvy CotEditor FileMerge | Leave a comment

choose style lib

Posted on 12月 9, 2019 by Takaaki Naganoya

指定のRTFから書式スタイル名(フォント名、フォントサイズ)を抽出し、そのスタイルをダイアログ上にポップアップメニューで一覧表示し、指定スタイル該当箇所を抽出したプレビュー表示を行いつつ、選択スタイル関連の情報を取得できるAppleScriptライブラリです。動作環境は、macOS 10.13以降です。

–> Download chooseStyleLib(library and sample RTF. Library have to install to ~/Library/Script Libraries)

前バージョンは正常動作するランタイム環境が限定されており、スクリプトエディタ上でCommand-Control-Rで実行する必要がありましたが、このライブラリ版ではScript Debugger上でもScript Menuからでも実行できますし、AppleScript用語辞書(sdef)を書いたので、簡潔かつ手軽に呼び出せるようになりました。

また、AppleScript用語辞書には本Blogと同様の色分け記述で、「★Click Here to Open This Script」をクリックすれば内容がスクリプトエディタに転送されるURLリンク入りのSample Scriptを掲載し、さらに本Blog上の画面キャプチャをリンクしてあるため、実行時の画面イメージも把握できるようになっています。

まんべんなく、すべてのコマンドにSample Scriptを掲載しています。

前バージョンではポップアップメニューにスタイルを適用してWYSIWYGメニューを作成していました。クリックしてメニュー表示を行なっているときにはスタイルが表示されていい感じでしたが、クリックしていない時にはボタンのサイズよりも大きいサイズは欠けて表示されるので、実用性がいまひとつ。そのため、本バージョンではWYSIWYGメニューの機能は省略しました。

ポップアップしていない時にはWYSIWYG表示にならないように機能を両立できるとよかったのですが、、、、

また、前バージョン同様に、「巨大なRTFを指定された場合でも足切りをしない」ようになっているので、あまり巨大なRTFを指定しないようにしてください。

choose style fromコマンド

指定のRTFからスタイル{フォント名,フォントサイズ}を抽出し、ダイアログ上のポップアップメニューで選択したスタイル{フォント名,フォントサイズ}を返します。

AppleScript name:sample1 choose style from.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/12/08
—
–  Copyright © 2019 Piyomaru Software, All Rights Reserved
–  http://piyocast.com/as/
use AppleScript version "2.7" — High Sierra (10.13) or later
use framework "Foundation"
use scripting additions
use chooseStyle : script "chooseStyle"

set aFile to choose file of type {"public.rtf"}

set bRes to choose style from aFile main message "Select Style" sub message "Select style you want to filter" width 400 height 200
–> {"HelveticaNeue-Bold", 16.0}

★Click Here to Open This Script 

choose contens by style fromコマンド

指定のRTFからスタイル{フォント名,フォントサイズ}を抽出し、ダイアログ上のポップアップメニューで選択したスタイルの該当箇所のテキストを返します。

AppleScript name:sample2 choose contens by style from.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/12/08
—
–  Copyright © 2019 Piyomaru Software, All Rights Reserved
–  http://piyocast.com/as/
use AppleScript version "2.7" — High Sierra (10.13) or later
use framework "Foundation"
use scripting additions
use chooseStyle : script "chooseStyle"

set aFile to choose file of type {"public.rtf"}

set fRes to choose contens by style from aFile main message "Select Style" sub message "Select style you want to filter" width 400 height 300
–> "Built-in filters"–text returns

★Click Here to Open This Script 

filter by styleコマンド

指定のRTFファイルから指定のスタイル{フォント名,フォントサイズ}で指定した箇所のテキストを返します。本コマンドはダイアログ表示を行わず、ただRTFからテキスト抽出するだけです。

AppleScript name:sample3 filter by style.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/12/08
—
–  Copyright © 2019 Piyomaru Software, All Rights Reserved
–  http://piyocast.com/as/
use AppleScript version "2.7" — High Sierra (10.13) or later
use framework "Foundation"
use scripting additions
use chooseStyle : script "chooseStyle"

set aFile to choose file of type {"public.rtf"}

set bRes to choose style from aFile main message "Select Style" sub message "Select style you want to filter" width 400 height 200
–> {"HelveticaNeue-Bold", 16.0}

copy bRes to {fName, fSize}

set aRes to filter by style aFile font name fName font size fSize
–>"Built-in filters"

★Click Here to Open This Script 

extract stylesコマンド

指定のRTFファイルからすべてのスタイル{フォント名,フォントサイズ}を抽出します。本コマンドもダイアログ表示は行いません。

AppleScript name:sample4 extract styles.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/12/08
—
–  Copyright © 2019 Piyomaru Software, All Rights Reserved
–  http://piyocast.com/as/
use AppleScript version "2.7" — High Sierra (10.13) or later
use framework "Foundation"
use scripting additions
use chooseStyle : script "chooseStyle"

set aFile to choose file of type {"public.rtf"}
return extract styles aFile
–> {{"HelveticaNeue-Bold", 24.0}, {"HelveticaNeue", 16.0}, {"HelveticaNeue-Bold", 20.0}, {"HelveticaNeue-Bold", 16.0}, {"HelveticaNeue-Italic", 16.0}, {"LucidaGrande", 16.0}, {"Menlo-Regular", 13.6}}

★Click Here to Open This Script 

Posted in dialog GUI RTF Script Libraries | Tagged 10.14savvy 10.15savvy | Leave a comment

指定のフォントとサイズに該当するテキストを抽出する v3

Posted on 12月 1, 2019 by Takaaki Naganoya

指定のRTFファイルから書式情報を取得し、フォント名とフォントサイズのペアをスタイルを反映させたポップアップメニューで選択。RTFの内容を解析したのち、ダイアログが表示されます(ここの所要時間は読ませるRTFのサイズ次第)。ポップアップメニューで書式を選ぶと、すぐさま抽出した箇所をすべてまとめて表示します。

–> Watch Demo Movie

–> Download Script Bundle with Sample data

ダイアログ表示前に書式ごとの抽出を完了し、個別のTabViewに抽出後の文字データを展開しておくので、ポップアップメニューから選択すると、展開ずみのデータを入れてあるTabViewに表示を切り替えるだけ。切り替え時に計算は行わないため、すぐに抽出ずみの文字データが表示されるという寸法です。

今回は短いサンプルデータを処理してみましたが、サンプル抽出時にあらかじめ範囲指定するなどして、データ処理規模を限定することで処理時間を稼ぐこともできることでしょう。

テキストエディットでオープン中のRTF書類のパスを取得して、それを処理対象にしてもいいでしょう。

ただし、やっつけで作ったのでスクリプトエディタ上でCommand-Control-Rで実行しないと動きません(メインスレッド実行をプログラムで強制しても、途中でクラッシュしてしまいます)。それほど時間もかけずに作ったやっつけプログラムなので、あまり原因追求も行えずそのままです。

AppleScript名:アラートダイアログ+Tab View v3.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/09/16
—
–  Copyright © 2019 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"
use rtfLib : script "readStyledTextLib"
use parseLib : script "parseAttrLib"

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 NSMenu : a reference to current application’s NSMenu
property NSArray : a reference to current application’s NSArray
property NSTabView : a reference to current application’s NSTabView
property NSPredicate : a reference to current application’s NSPredicate
property NSTextView : a reference to current application’s NSTextView
property NSMenuItem : a reference to current application’s NSMenuItem
property NSTabViewItem : a reference to current application’s NSTabViewItem
property NSPopUpButton : a reference to current application’s NSPopUpButton
property NSMutableDictionary : a reference to current application’s NSMutableDictionary
property NSRunningApplication : a reference to current application’s NSRunningApplication
property NSFontAttributeName : a reference to current application’s NSFontAttributeName
property NSKernAttributeName : a reference to current application’s NSKernAttributeName
property NSLigatureAttributeName : a reference to current application’s NSLigatureAttributeName
property NSMutableAttributedString : a reference to current application’s NSMutableAttributedString
property NSStrokeWidthAttributeName : a reference to current application’s NSStrokeWidthAttributeName
property NSUnderlineStyleAttributeName : a reference to current application’s NSUnderlineStyleAttributeName
property NSForegroundColorAttributeName : a reference to current application’s NSForegroundColorAttributeName

property TabPosition : 4 —0=Top, 1=Left, 2=Bottom, 3=Right, 4=None

property returnCode : 0

property aTabV : missing value
property selectedNum : {}

set aFile to choose file of type {"public.rtf"}

set aStyledStr to readRTFfile(aFile) of rtfLib
set paramObj to {myMessage:"Select Style", mySubMessage:"Select style you want to filter", viewWidth:800, viewHeight:400, myStyledStr:aStyledStr}

my dispTabViewWithAlertdialog:paramObj –for debug
–my performSelectorOnMainThread:"dispTabViewWithAlertdialog:" withObject:paramObj waitUntilDone:true
return selectedNum

on dispTabViewWithAlertdialog:paramObj
  –Receive Parameters
  
set aMainMes to (myMessage of paramObj) as string –Main Message
  
set aSubMes to (mySubMessage of paramObj) as string –Sub Message
  
set aWidth to (viewWidth of paramObj) as integer –TextView width
  
set aHeight to (viewHeight of paramObj) as integer –TextView height
  
set aStyledStr to (myStyledStr of paramObj)
  
  
set attrResTmp to getAttributeRunsFromAttrString(aStyledStr) of parseLib
  
set attrList to attributes of attrResTmp
  
set menuStyle to menuList of attrResTmp
  
  
set selectedNum to {}
  
  
set aView to NSView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aWidth, aHeight))
  
  
–Ppopup Buttonをつくる
  
set a1Button to NSPopUpButton’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, aHeight – 20, 400, 20)) pullsDown:false
  
a1Button’s removeAllItems()
  
  
–WYSIWHG popup menuをつくる
  
set a1Menu to NSMenu’s alloc()’s init()
  
repeat with i from 1 to (length of menuStyle)
    set {tmpFont, tmpSize} to contents of item i of menuStyle
    
set aTitle to (tmpFont & " " & tmpSize as string) & " point"
    
set aMenuItem to (NSMenuItem’s alloc()’s initWithTitle:aTitle action:"actionHandler:" keyEquivalent:"")
    
    
set attributedTitle to makeRTFfromParameters(aTitle, tmpFont, tmpSize, NSColor’s blackColor()) of me
    
    (
aMenuItem’s setEnabled:true)
    (
aMenuItem’s setTarget:me)
    (
aMenuItem’s setTag:(i as string))
    (
aMenuItem’s setAttributedTitle:(attributedTitle))
    (
a1Menu’s addItem:aMenuItem)
  end repeat
  
  
–Ppopup Buttonにmenuをつける
  
a1Button’s setMenu:a1Menu
  
  
–Make Tab View
  
set aTabV to NSTabView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aWidth, aHeight – 30))
  
aTabV’s setTabViewType:(TabPosition)
  
  
  
–TabViewに中身を入れる
  
repeat with i from 1 to (length of menuStyle)
    set {tmpFont, tmpSize} to contents of item i of menuStyle
    
set tmpKey to (tmpFont as string) & "/" & (tmpSize as string)
    
set tmpArry to filterRecListByLabel1(attrList, "styleKey2 == ’" & tmpKey & "’") of me
    
set tmpStr to (tmpArry’s valueForKeyPath:"stringVal") as list
    
    
set aTVItem to (NSTabViewItem’s alloc()’s initWithIdentifier:(i as string))
    (
aTVItem’s setLabel:(i as string))
    
    
    
set aTextView to (NSTextView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aWidth – 10, aHeight – 10)))
    (
aTextView’s setRichText:true)
    
set tmpAttr to makeRTFfromParameters(tmpStr as string, tmpFont, tmpSize, NSColor’s blackColor()) of me
    (
aTextView’s textStorage()’s appendAttributedString:tmpAttr)
    
    (
aTVItem’s setView:aTextView)
    
    (
aTabV’s addTabViewItem:aTVItem)
  end repeat
  
  
  
aView’s setSubviews:{a1Button, aTabV}
  
aView’s setNeedsDisplay: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:(aView)
    
    
–for Help Button
    
its setShowsHelp:(true)
    
its setDelegate:(me)
  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 selectedNum to contents of item ((a1Button’s indexOfSelectedItem()) + 1) of menuStyle
end dispTabViewWithAlertdialog:

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:

–Popup Action Handler
on actionHandler:sender
  set aTag to tag of sender as integer
  
aTabV’s selectTabViewItemAtIndex:(aTag – 1)
end actionHandler:

–書式つきテキストを組み立てる
on makeRTFfromParameters(aStr as string, aFontName as string, aFontSize as real, aColor)
  –フォント
  
set aVal1 to NSFont’s fontWithName:(aFontName) |size|:aFontSize
  
set aKey1 to (NSFontAttributeName)
  
  
–色
  
set aVal2 to aColor
  
set aKey2 to (NSForegroundColorAttributeName)
  
  
–カーニング
  
set aVal3 to 0.0
  
set akey3 to (NSKernAttributeName)
  
  
–アンダーライン
  
set aVal4 to 0
  
set akey4 to (NSUnderlineStyleAttributeName)
  
  
–リガチャ
  
–set aVal5 to 2 –全てのリガチャを有効にする
  
–set akey5 to ( NSLigatureAttributeName)
  
  
–枠線(アウトライン)
  
–set aVal6 to outlineNum
  
–set akey6 to ( NSStrokeWidthAttributeName)
  
  
  
set keyList to {aKey1, aKey2, akey3, akey4}
  
set valList to {aVal1, aVal2, aVal3, aVal4}
  
set attrsDictionary to NSMutableDictionary’s dictionaryWithObjects:valList forKeys:keyList
  
  
set attrStr to NSMutableAttributedString’s alloc()’s initWithString:aStr attributes:attrsDictionary
  
return attrStr
end makeRTFfromParameters

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

★Click Here to Open This Script 

Posted in Color dialog Font GUI Require Control-Command-R to run RTF | Tagged 10.14savvy 10.15savvy NSAlert NSArray NSColor NSFont NSFontAttributeName NSForegroundColorAttributeName NSKernAttributeName NSLigatureAttributeName NSMenu NSMenuItem NSMutableAttributedString NSMutableDictionary NSPopUpButton NSPredicate NSRunningApplication NSStrokeWidthAttributeName NSTabView NSTabViewItem NSTextView NSUnderlineStyleAttributeName NSView | 1 Comment

指定のフォントとサイズに該当するテキストを抽出する v2

Posted on 11月 30, 2019 by Takaaki Naganoya

macOS標準搭載のテキストエディタ「テキストエディット」の最前面のドキュメントから書式情報を取得し、フォント名とフォントサイズのペアをスタイルを反映させたポップアップメニューで選択。選択したスタイルが該当する箇所を抽出したのちにテキスト化してTextViewで結果を表示します。

–> Download Code-signed AppleScript applet executable with libraries


▲Sample RTF(なんでもOK)


▲添付のAppleScriptアプレットは、初回実行時に制御許可のダイアログが表示されます。OKすれば、2回目以降はダイアログ表示されません


▲書式情報をRTF書類から読み込んで、スタイルを反映させたポップアップメニューで表示。サンプル文をRTF書類から取得しているものの、改行部分だけがヒットしたりとなかなかうまくありません


▲一覧から選択


▲RTF書類から指定書式に相当するテキストを抽出して出力

AppleScript名:指定のフォントとサイズに該当するテキストを抽出する v2.scptd
— Created 2019-11-29 by Takaaki Naganoya
— 2019 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use wgMenuLib : script "wysiwygMenuLib" –WYSIWYGポップアップメニューダイアログ ライブラリ
use dtLib : script "dTextView" –TextView表示ライブラリ

script spd
  property fontList : {}
  
property fontSizes : {}
  
property textList : {}
  
property outList : {}
  
property combiList : {}
end script

set (outList of spd) to {}
set (fontList of spd) to {}
set (fontSizes of spd) to {}
set (textList of spd) to {}
set (combiList of spd) to {}

–TextEdit書類から書式情報を根こそぎ取得
tell application "TextEdit"
  tell text of front document
    set (fontList of spd) to font of every attribute run –フォント名
    
set (fontSizes of spd) to size of every attribute run –文字サイズ
    
set (textList of spd) to character of every attribute run –文字
  end tell
end tell

–ポップアップメニュー選択用のデータを作成
set aLen to length of (fontList of spd)
set menuList to {}
set sampleList to {}
repeat with i from 1 to aLen
  set tmpFont to contents of item i of (fontList of spd)
  
set tmpSize to contents of item i of (fontSizes of spd)
  
set tmpSample to (contents of item i of (textList of spd)) as string
  
set tmpList to {tmpFont, tmpSize}
  
if {tmpList} is not in (combiList of spd) then
    set the end of (combiList of spd) to tmpList
    
set the end of menuList to (tmpFont & " — " & tmpSize as string) & " point ex.:" & tmpSample
  end if
end repeat

–WYSIWYGポップアップメニューで項目選択
set paramObj to {myMessage:"Select Attribute", mySubMessage:"Select target attribute", segmentMes:{menuList}, segmentTitles:{"Select combination of font name and size"}, segmentAttributes:(combiList of spd)}
set fRes to makeMenuAndcheck(paramObj) of wgMenuLib
if fRes = 0 then return

copy item (first item of fRes) of (combiList of spd) to {aFont, aSize}

–取得した条件にもとづいて、根こそぎ取得した書式と照合を行いつつループ
repeat with i from 1 to length of (fontList of spd)
  set tmpFont to contents of item i of (fontList of spd)
  
set tmpSize to contents of item i of (fontSizes of spd)
  
  
–文字サイズをざっくり判定することで「大、中、小」といったおおまかな切り分けも可能
  
if {tmpFont, tmpSize} = {aFont, aSize} then
    set tmpCon to (contents of item i of (textList of spd)) as string
    
if tmpCon does not contain "•" then –ごみ取り
      set the end of (outList of spd) to tmpCon
    end if
  end if
end repeat

–結果をTextViewで表示
set aStr to retListedText(outList of spd, return) of me
set eRes to (display text view aStr main message "Result" sub message "" with properties {font name:aFont, size:aSize, width:800, height:400})

on retListedText(aList, aSeparator)
  set aText to ""
  
set curDelim to AppleScript’s text item delimiters
  
set AppleScript’s text item delimiters to aSeparator
  
set aText to aList as text
  
set AppleScript’s text item delimiters to curDelim
  
return aText
end retListedText

★Click Here to Open This Script 

Posted in dialog GUI list RTF | Tagged 10.13savvy 10.14savvy 10.15savvy | Leave a comment

Appleがいまだに直さない致命的なPDFViewのバグに対処v2

Posted on 11月 22, 2019 by Takaaki Naganoya

macOS 10.13のBetaの時にはなかったのに、Release版がバグだらけでリリース。PDFViewについて多大なる被害を受けております。PDFViewをScripting Bridge経由で使うと、macOS 10.14も10.15も状況は同じです。きちんと動かないので、仕様と言い切ることは難しいところでしょう。未修正のバグが放置されているという状況です。

Developper Supportに報告しても返答も何もないので、PDFViewのScripting Bridgeまわりはバグだらけのまま直すつもりもないのでしょう。Xcode上でプログラムを組みだすと、腹の立つことのオンパレードです。

AppleのDevelopperライセンスの延長時期がやってくると、日頃からバグだらけでOSをリリースするわバグは直さないわで、嫌がらせを受け続けているのになんでこれを契約延長しなくてはならないのか理解に苦しみます。

Apple系のMailing Listでは主流ともいえるCocoa-Dev ML上でもAppleのあり方に疑問を呈したり文句を(ていねいなお言葉で)述べる投稿がここ数週間(macOS 10.15のリリース以降)激増している今日このごろです。

いまいちどPDFViewまわりを確認してみると、PDFViewのcurrentPageを取得できない未修正の特大バグに続いて、goToPreviousPage、goToNextPageも効きません。つまり、現在表示中のページの取得も、前後ページへの移動もできないという状況です。


▲まともにオブジェクトを返してこないcurrentPage

とりあえず、Xcode上でヘッダーファイル「PDFView.h」を確認していると、currentPageのかわりになりそうなものを見つけました。それが、visiblePages。PDFView上で表示中のページを(複数)返してくるわけで、単ページ表示時にはなんとかこれが使えるかも? ということで試してみました。

–> Download pdfviewAgainstAppleBug (Xcode Project)


▲currentPageのかわりに使えそうなvisiblePages。こっちは機能している

これが使えたので応用し、かなり遠回りな処理にはなりますが、表示中のページの前後移動もできるようにしてみました。

ただ、PDFViewをもとにしたクリックスルーなPDFViewを使ってみると、いまひとつ想定どおりに動作してくれません。まだいろいろ試してみる必要がありそうです。
→ クリックスルーPDFViewは結局動作するようになり、Double PDF v2に実装できました

これらのほか、PDFViewはページ変更時のイベントやドキュメント変更時のイベントが送信されないなど、苦労させられまくりです。

Posted in Bug GUI PDF | Tagged 10.14savvy 10.15savvy PDFView | Leave a comment

アラートダイアログ上のWebViewに世界地図を表示 v2b

Posted on 11月 20, 2019 by Takaaki Naganoya

世界地図のSVGをHTMLReader.frameworkでparseして、目的のノードに塗り色の指定を行い、WkWebView上で表示するAppleScriptです。

–> Download selectCountry2(Code-signed AppleScript executable applet)

昨日のものがあくまでSVGのParseと表示が目的の試作品であったのに対し、本Scriptは連続してポップアップメニューから対象を選んで表示するというものです。

同様にmacOS 10.15.1上で作成しましたが、このバージョンのOS環境ではAppleScriptアプレットにFrameworkを入れてAppleScript内から呼び出すことが標準のランタイム(Script Editorから書き出した場合)では行えないようになっており、Script Debuggerから「Application(Enhanced)」で書き出さないと呼び出せないようです(これはちょっとひどいかも、、、、)。

世界地図はWikipediaから拾ってきたもので、ISO国コードではなく名称でIDが振ってあり、日本もJapanではなくHokkaido、Honshu、Shikoku、Kyushuuに分けて登録されています。


▲Script Editor上でサードパーティFramework呼び出しの動作ができているのは、この実行環境でSIPを解除してあるからです

AppleScript名:アラートダイアログ上のWebViewに世界地図を表示 v2b.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/11/18
—
–  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 "HTMLReader" –https://github.com/nolanw/HTMLReader
use framework "WebKit"
use scripting additions

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

property theResult : 0
property returnCode : 0
property aWebView : missing value
property aLog : missing value
property tmpURL : ""

tell current application
  set mePath to ((path to me) as string) & "Contents:Resources:World_map_-_low_resolution.svg"
  
set svgCon to read (mePath as alias)
  
  
set aWidth to 950
  
set aHeight to 650
  
  
  
set paramObj to {myMessage:"Browse World map", mySubMessage:"This is a sample SVG World map", targContents:svgCon, myWidth:(aWidth), myHeight:(aHeight)}
  
–my browseLocalWebContents:paramObj
  
my performSelectorOnMainThread:"browseLocalWebContents:" withObject:(paramObj) waitUntilDone:true
  
return aLog
end tell

on browseLocalWebContents:paramObj
  set aMainMes to (myMessage of paramObj) as string
  
set aSubMes to (mySubMessage of paramObj) as string
  
set tmpURL to (targContents of paramObj) as string –local contents
  
set aWidth to (myWidth of paramObj) as integer
  
set aHeight to (myHeight of paramObj) as integer
  
  
  
set aView to current application’s NSView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aWidth, aHeight))
  
  
–Ppopup Buttonをつくる
  
set a1Button to current application’s NSPopUpButton’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, aHeight – 26, 200, 24)) pullsDown:(false)
  
a1Button’s removeAllItems()
  
  
–Menuの中身を作る  
  
set aHTML to current application’s HTMLDocument’s documentWithString:(tmpURL)
  
set fList to (aHTML’s nodesMatchingSelector:"path")’s valueForKeyPath:"attributes.id"
  
set fList to fList’s sortedArrayUsingSelector:"compare:"
  
  
a1Button’s addItemWithTitle:"▼Select"
  
  
repeat with i in fList
    (a1Button’s addItemWithTitle:(i as string))
  end repeat
  
  
a1Button’s setTarget:(me)
  
a1Button’s setAction:("mySelector:")
  
a1Button’s setEnabled:(true)
  
  
set aWebView to makeWebViewAndLoadContents(tmpURL, aWidth, aHeight – 40) of me
  
  
aView’s addSubview:a1Button
  
aView’s addSubview:aWebView
  
  
— 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
  
  
–Stop Web View Action
  
set bURL to |NSURL|’s URLWithString:"about:blank"
  
set bReq to NSURLRequest’s requestWithURL:bURL
  
aWebView’s loadRequest:bReq
  
  
if (my returnCode as number) = 1001 then error number -128
end browseLocalWebContents:

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

on viewDidLoad:aNotification
  return true
end viewDidLoad:

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

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

on mySelector:aSender
  set targetCountry to (aSender’s title()) as string
  
  
set aHTML to current application’s HTMLDocument’s documentWithString:(tmpURL as string)
  
  
set eList to (aHTML’s nodesMatchingSelector:"path") as list
  
set fList to (aHTML’s nodesMatchingSelector:"path")’s valueForKeyPath:"attributes.id"
  
  
–Search Target Country
  
set aRes to (fList)’s indexOfObject:(targetCountry)
  
if (aRes = current application’s NSNotFound) or (aRes > 9.99999999E+8) then
    error "Target country not found"
  end if
  
  
set aRes to aRes + 1
  
  
–Rewrite target country’s fill color on SVG
  
set tmpNode to contents of item aRes of (eList)
  (
tmpNode’s setObject:"Red" forKeyedSubscript:"fill") –Change Target Country’s fill color
  
  
set svgCon to (tmpNode’s |document|()’s serializedFragment()) as string –HTMLReaderはこういう処理ができるところが好き
  
  
aWebView’s loadHTMLString:svgCon baseURL:(missing value)
end mySelector:

on makeWebViewAndLoadContents(aContents as string, aWidth as integer, aHeight as integer)
  set aConf to WKWebViewConfiguration’s alloc()’s init()
  
  
–指定URLのJavaScriptをFetch
  
set jsSource to my fetchJSSourceString(aContents)
  
set userScript to WKUserScript’s alloc()’s initWithSource:jsSource injectionTime:(WKUserScriptInjectionTimeAtDocumentEnd) forMainFrameOnly:true
  
set userContentController to WKUserContentController’s alloc()’s init()
  
userContentController’s addUserScript:(userScript)
  
aConf’s setUserContentController:userContentController
  
  
set aWebView to WKWebView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aWidth, aHeight)) configuration:aConf
  
aWebView’s setNavigationDelegate:me
  
aWebView’s setUIDelegate:me
  
aWebView’s setTranslatesAutoresizingMaskIntoConstraints:true
  
aWebView’s setOpaque:false
  
aWebView’s setBackgroundColor:(NSColor’s clearColor())
  
–aWebView’s scrollView()’s setBackgroundColor:(NSColor’s clearColor())
  
  
aWebView’s loadHTMLString:aContents baseURL:(missing value)
  
return aWebView
end makeWebViewAndLoadContents

★Click Here to Open This Script 

Posted in dialog geolocation GUI Image SVG | Tagged 10.13savvy 10.14savvy 10.15savvy HTMLDocument NSAlert NSButton NSColor NSImage NSRunningApplication NSScreen NSString NSURL NSURLRequest NSUTF8StringEncoding WKUserContentController WKUserScript WKUserScriptInjectionTimeAtDocumentEnd WKWebView WKWebViewConfiguration | Leave a comment

アラートダイアログ上のWebViewに円グラフを表示

Posted on 11月 18, 2019 by Takaaki Naganoya

アラートダイアログ上のWebViewにSVGで作った円グラフを表示するAppleScriptです。

Objective-Cで作られたチャート表示フレームワークなどを呼び出して試していますが、スクリプトエディタ上で作成したAppleScriptから呼び出すと、アニメーションしなかったり表示が行えなかったりといろいろ環境にフィットしていません。

# 逆をいえば、Xcode上でCocoa AppleScriptアプリケーションを作成した場合には割とチャート表示部品をそのまま使えます

そこで、単純なグラフ表示を行うようにレベルを下げ、SVGをWkWebView上に表示する形式にしてみました。

本Scriptでは最低限のサンプルを表示させていますが、SVGの組み立てをもう少し強化してグラフの背景を透明にできればいい感じになるのではないでしょうか。


▲世界地図あたりだといい感じに見えるかもしれません。当該の国だけ色を変えるような処理を仕込めば何かに使えそうです。

AppleScript名:アラートダイアログ上のWebViewに円グラフを表示.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/11/18
—
–  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 "WebKit"
use scripting additions

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

property theResult : 0
property returnCode : 0

–set svgCon to read (choose file)
set svgCon to retSampleSVG() of me

set paramObj to {myMessage:"Browse Pie Chart", mySubMessage:"This is a sample pie chart made by SVG", targContents:svgCon}
–my browseLocalWebContents:paramObj
my performSelectorOnMainThread:"browseLocalWebContents:" withObject:(paramObj) waitUntilDone:true

on browseLocalWebContents:paramObj
  set aMainMes to (myMessage of paramObj) as string
  
set aSubMes to (mySubMessage of paramObj) as string
  
set tmpURL to (targContents of paramObj) as string –local contents
  
  
set aWidth to 330
  
set aHeight to 430
  
  
–WebViewをつくる
  
set aConf to WKWebViewConfiguration’s alloc()’s init()
  
  
–指定URLのJavaScriptをFetch
  
set jsSource to my fetchJSSourceString(tmpURL)
  
set userScript to WKUserScript’s alloc()’s initWithSource:jsSource injectionTime:(WKUserScriptInjectionTimeAtDocumentEnd) forMainFrameOnly:true
  
set userContentController to WKUserContentController’s alloc()’s init()
  
userContentController’s addUserScript:(userScript)
  
aConf’s setUserContentController:userContentController
  
  
set aWebView to WKWebView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aWidth, aHeight – 100)) configuration:aConf
  
aWebView’s setNavigationDelegate:me
  
aWebView’s setUIDelegate:me
  
aWebView’s setTranslatesAutoresizingMaskIntoConstraints:true
  
aWebView’s setOpaque:false
  
aWebView’s setBackgroundColor:(NSColor’s clearColor())
  
–aWebView’s scrollView()’s setBackgroundColor:(NSColor’s clearColor())
  
  
aWebView’s loadHTMLString:tmpURL baseURL:(missing value)
  
  
  
— set up alert  
  
set theAlert to NSAlert’s alloc()’s init()
  
tell theAlert
    its setMessageText:aMainMes
    
its setInformativeText:aSubMes
    
its addButtonWithTitle:"OK"
    
its addButtonWithTitle:"Cancel"
    
its setAccessoryView:aWebView
  end tell
  
  
— show alert in modal loop
  
NSRunningApplication’s currentApplication()’s activateWithOptions:0
  
my performSelectorOnMainThread:"doModal:" withObject:(theAlert) waitUntilDone:true
  
  
–Stop Web View Action
  
set bURL to |NSURL|’s URLWithString:"about:blank"
  
set bReq to NSURLRequest’s requestWithURL:bURL
  
aWebView’s loadRequest:bReq
  
  
if (my returnCode as number) = 1001 then error number -128
end browseLocalWebContents:

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

on viewDidLoad:aNotification
  return true
end viewDidLoad:

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

on retSampleSVG()
  return "<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" width=\"300\" height=\"300\" fill-opacity=\"0.9\">
<path d=\"M 150,0 A 150,150 0 1,1 141.8986347236027,299.7810664959306 L 150,150 Z\" fill=\"#0153d8\" stroke=\"#fff\"></path>
<text x=\"170\" y=\"150\" fill=\"#fff\" font-size=\"20\">Piyomaru</text>
<text x=\"170\" y=\"190\" fill=\"#fff\" font-size=\"40\">50.86%</text>
</svg>"
end retSampleSVG

★Click Here to Open This Script 

Posted in dialog GUI | Tagged 10.13savvy 10.14savvy 10.15savvy NSAlert NSButton NSColor NSImage NSRunningApplication NSScreen NSString NSURL NSURLRequest NSUTF8StringEncoding WKUserContentController WKUserScript WKUserScriptInjectionTimeAtDocumentEnd WKWebView WKWebViewConfiguration | 1 Comment

checkboxLib v2

Posted on 11月 17, 2019 by Takaaki Naganoya

アラートダイアログで指定の1D List(1次元配列)に入れた項目からのユーザー選択を求めるAppleScript Librariesです。

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

–> Watch Demo Movie

本ライブラリはAppleScript用語辞書に画像とムービーを含んでおり、ジャスト、この記事に掲載のものを参照しています(この記事とかリンク画像やムービーを削除すると、AppleScript用語辞書にも表示されなくなる仕様)。インターネット接続環境下にない場合には、AppleScript用語辞書内の画像やムービーは表示されません。

そのかわりに、辞書サイズが小さくなっているので、良し悪しかと。

前バージョンからの変更点は、アラートダイアログ表示時にあらかじめ項目選択しておく指定(selection items)を追加した点です。


▲サンプルScriptと、実行時の画面キャプチャとひととおおり実行したときのムービーがAppleScript用語辞書に掲載されています


▲サンプルScriptは、本Blogと同様の仕様で、サンプル下部のリンク「★Click Here to Open This Script」をクリックすればスクリプトエディタ/Script Debuggerに内容が転送されます

AppleScript名:sample 1
— Created 2019-08-07 by Takaaki Naganoya
— 2019 Piyomaru Software
use chkLib : script "checkboxLib"

set tList to {"Carrot", "Burdock", "Radish", "Potato", "Cabege", "Lettuce", "Komatsuna", "Garlic", "Tomato", "bok choy", "Shiitake Mushroom", "Onion"}
set cRes to choose checkbox main message "Main Title" with columns 2 with titles tList checkbox type standard return type item number selection items {true, true, true, true, true, true, true, true, false, false, false, false}
–> {1, 2, 3, 4, 5, 6, 7, 8}–Selected Index numbers (starts from 1)

★Click Here to Open This Script 

Posted in dialog GUI Script Libraries sdef | Tagged 10.13savvy 10.14savvy 10.15savvy | Leave a comment

アラートダイアログ上にNSBoxを介してPopup Menuを表示

Posted on 11月 14, 2019 by Takaaki Naganoya

アラートダイアログ上に複数のポップアップメニュー(項目数可変)を表示し、指定リスト(配列)からの選択を行うAppleScriptです。

以前、Segmented Controlで作ったものがありましたが、Segmented Controlだと絶望的に実用性がないので、ポップアップボタンに差し替えてみたものです。

AppleScript名:アラートダイアログ上にNSBoxを介してPopup Menuを表示
— Created 2019-11-14 by Takaaki Naganoya
— 2019 Piyomaru Software
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
use framework "AppKit"

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 NSRunningApplication : a reference to current application’s NSRunningApplication

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
my performSelectorOnMainThread:"chooseMultipleSegments:" withObject:paramObj waitUntilDone:true

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

on chooseMultipleSegments:paramObj
  set aMainMes to (myMessage of paramObj) as string
  
set aSubMes to (mySubMessage of paramObj) as string
  
set segMes2DList to (segmentMes of paramObj) as list
  
set segTitleList to (segmentTitles of paramObj) as list
  
  
set aTmpY to (length of segMes2DList) * 60
  
  
–BoX + Segmented Control をつくる
  
set segsList to {}
  
set boxLIst to {}
  
set segsCount to 0
  
set tmpMaxX to 400
  
  
set aCount to 1
  
  
repeat with i in segMes2DList
    set a1Button to (current application’s NSPopUpButton’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, tmpMaxX – 30, 30)) pullsDown:false)
    
a1Button’s removeAllItems()
    (
a1Button’s addItemsWithTitles:(i))
    
    
set aDBounds to a1Button’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, tmpMaxX – 10, 60)))
    (
aBox’s setTitle:(item aCount of segTitleList))
    (
aBox’s addSubview:a1Button)
    (
aBox’s setBorderType:0) –NSNoBorder, this method is depreceted in macOS 10.14. Which is alternative?
    
    
if tmpWidth > tmpMaxX then set tmpMaxX to tmpWidth
    
    
set the end of segsList to a1Button –選択検出用
    
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 + 10, aTmpY + 20))
  
theView’s setSubviews:boxLIst
  
  
— create a Scroll View
  
set aScroll to NSScrollView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, tmpMaxX + 10, 300))
  
aScroll’s setDocumentView:theView
  
aScroll’s documentView()’s scrollPoint:(current application’s NSMakePoint(0, aTmpY + 10)) –Force scroll to top
  
  
theView’s enclosingScrollView()’s setHasHorizontalScroller:false
  
theView’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
  
  
set my returnSels to {}
  
repeat with i in segsList
    set tmpSegSel to (i’s indexOfSelectedItem()) 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 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 dialog GUI | Tagged 10.12savvy 10.13savvy 10.14savvy 10.15savvy NSAlert NSBox NSRunningApplication NSScrollView NSView | Leave a comment

アラートダイアログ上にカレンダー1か月分を表示して選択 有効日指定あり v3a

Posted on 11月 13, 2019 by Takaaki Naganoya

アラートダイアログ上に指定月のカレンダー1か月分を表示してユーザーの日付選択(複数可)をもとめるAppleScriptです。

NSDatePickerを用いて日付選択のダイアログを作っていたら、日付がとても小さくて現代のMacの画面解像度にとても合っておらず、もっと大きめのカレンダーで選択したいと考えて作ったものです。

(1)カレンダーの表示サイズを大型化

現代のMacの画面にNSDatePickerをそのまま表示すると、とても小さくて見ていられないので、表示サイズを自由に変えられるカレンダー選択部品を作ってみました。どれか1つの日付を選択するものではなく、複数の日付を選択して、リストで結果を返してきます。

▲画面上で見やすいようにカレンダー部品を大型化

(2)選択無効日指定

あらかじめ、日付選択の対象外とする日付を指定できるようにしました。

(3)過去日付の選択無効

過去の日付を表示・選択できないようにする指定です。

▲過去日付を無効に指定すると、現在日時よりも過去の日付は選択できない

(4)曜日を現在のLocale情報から変更

曜日に用いる文字列を現在のLocale情報から取得するようにしてみました。本来であれば、日曜日はじまり「ではない」カレンダーを用いている場所もあるので(香港とかフランスとか?)、どの曜日から表示開始するかを自由選択にしたいところですが、そこまでは作り込んでいません。

▲Localeに合わせた曜日が表示される(ただし、年/月は固定フォーマット)

実用性を考えれば、Calendar.appのように日付選択とスケジュール確認が行えるものが望ましいのですが、そこまで作り込む手間をかけるほどのものでもないですし、表示対象月の移動を行おうとしてclickイベントを拾いつつカレンダー再描画に失敗した「残骸」です。見た目はいいのに完成度がいまひとつというあたりが残念です。

AppleScript名:アラートダイアログ上にカレンダー1か月分を表示して選択 有効日指定あり v3a
— Created 2019-10-15 by Takaaki Naganoya
— 2019 Piyomaru Software
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
use framework "AppKit"

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 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 NSTextField : a reference to current application’s NSTextField
property NSMutableArray : a reference to current application’s NSMutableArray
property NSButtonTypeOnOff : a reference to current application’s NSButtonTypeOnOff
property NSMutableDictionary : a reference to current application’s NSMutableDictionary
property NSRunningApplication : a reference to current application’s NSRunningApplication
property NSFontAttributeName : a reference to current application’s NSFontAttributeName
property NSKernAttributeName : a reference to current application’s NSKernAttributeName
property NSMutableParagraphStyle : a reference to current application’s NSMutableParagraphStyle
property NSLigatureAttributeName : a reference to current application’s NSLigatureAttributeName
property NSMutableAttributedString : a reference to current application’s NSMutableAttributedString
property NSUnderlineStyleAttributeName : a reference to current application’s NSUnderlineStyleAttributeName
property NSParagraphStyleAttributeName : a reference to current application’s NSParagraphStyleAttributeName
property NSForegroundColorAttributeName : a reference to current application’s NSForegroundColorAttributeName

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

property tYear : 0
property tMonth : 0
property theAlert : missing value
property theView : missing value

on run
  set tYear to 2019
  
set tMonth to 11
  
set ignoreP to true
  
set ndList to {2, 3, 4, 9, 10, 13, 16, 17, 23, 24, 25, 30} –選択表示させない日付
  
set paramObj to {myMessage:"", mySubMessage:"適切な日付を以下からえらんでください", targetYear:tYear, targetMonth:tMonth, nodisp:ndList, ignorePast:ignoreP}
  
  
–Detect Past Date Error
  
set curDate to current date
  
set dLimit to getMlen(tYear, tMonth) of me
  
set tmpDate to getDateInternational(tYear, tMonth, dLimit) of me
  
if (tmpDate < curDate) and (ignoreP = true) then error (("Target month is past (" & tYear as string) & "/" & tMonth as string) & "/1 is past. Today is " & date string of curDate & ")"
  
  
–my chooseItemByCheckBox:paramObj –for Debugging
  
my performSelectorOnMainThread:"chooseItemByCheckBox:" withObject:(paramObj) waitUntilDone:true
  
return my sort1DNumList:(my theResult) ascOrder:true
  
–> {1, 3, 5, 7, 9, 11}
end run

on chooseItemByCheckBox:(paramObj)
  set aMainMes to (myMessage of paramObj) as string
  
set aSubMes to (mySubMessage of paramObj) as string
  
set aMatList to (matrixTitleList of paramObj) as list
  
set tYear to (targetYear of paramObj) as integer
  
set tMonth to (targetMonth of paramObj) as integer
  
set noDispList to (nodisp of paramObj) as list
  
set ignoreP to (ignorePast of paramObj) as boolean
  
  
if aMainMes = "" then
    set aMainMes to "日付を選択してください"
  end if
  
  
set theView to makeCalendarView(tYear, tMonth, noDispList, ignoreP) of me
  
  
–Select the first radio button item
  
set my theResult to {}
  
  
— 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
    
    
–for Help Button
    
–its setShowsHelp:(true)
    
its setDelegate:(me)
    
set aWin to its |window|()
  end tell
  
  
aWin’s setLevel:(current application’s NSFloatingWindowLevel)
  
  
— 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 chooseItemByCheckBox:

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

on clicked:aParam
  set aTag to (tag of aParam) as integer
  
  
–clicked
  
if aTag is not in (my theResult) then
    set the end of (my 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:

–書式つきテキストを組み立てる
on makeRTFfromParameters(aStr as string, fontName as string, aFontSize as real, aKerning as real, aLineSpacing as real)
  set aVal1 to NSFont’s fontWithName:fontName |size|:aFontSize
  
set aKey1 to (NSFontAttributeName)
  
  
set aVal2 to NSColor’s blackColor()
  
set aKey2 to (NSForegroundColorAttributeName)
  
  
set aVal3 to aKerning
  
set akey3 to (NSKernAttributeName)
  
  
set aVal4 to 0
  
set akey4 to (NSUnderlineStyleAttributeName)
  
  
set aVal5 to 2 –all ligature ON
  
set akey5 to (NSLigatureAttributeName)
  
  
set aParagraphStyle to NSMutableParagraphStyle’s alloc()’s init()
  
aParagraphStyle’s setMinimumLineHeight:(aLineSpacing)
  
aParagraphStyle’s setMaximumLineHeight:(aLineSpacing)
  
set akey7 to (NSParagraphStyleAttributeName)
  
  
set keyList to {aKey1, aKey2, akey3, akey4, akey5, akey7}
  
set valList to {aVal1, aVal2, aVal3, aVal4, aVal5, aParagraphStyle}
  
set attrsDictionary to NSMutableDictionary’s dictionaryWithObjects:valList forKeys:keyList
  
  
set attrStr to NSMutableAttributedString’s alloc()’s initWithString:aStr attributes:attrsDictionary
  
return attrStr
end makeRTFfromParameters

on 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

–指定月のカレンダーを1D List(7 days x 6 weeks) で返す
on retListCalendar(tYear, tMonth)
  set mLen to getMlen(tYear, tMonth) of me
  
set aList to {}
  
  
set fDat to getDateInternational(tYear, tMonth, 1) of me
  
tell current application
    set aOffset to (weekday of fDat) as number
  end tell
  
  
–header gap
  
repeat (aOffset – 1) times
    set the end of aList to ""
  end repeat
  
  
–calendar body
  
repeat with i from 1 to mLen
    set the end of aList to (i as string)
  end repeat
  
  
–footer gap
  
repeat (42 – aOffset – mLen + 1) times
    set the end of aList to ""
  end repeat
  
  
return aList
end retListCalendar

–現在のカレンダーで指定年月の日数を返す(国際化対応版)
on getMlen(aYear as integer, aMonth as integer)
  set theNSCalendar to current application’s NSCalendar’s currentCalendar()
  
set theDate to theNSCalendar’s dateWithEra:1 |year|:aYear |month|:aMonth |day|:1 hour:0 minute:0 |second|:0 nanosecond:0
  
set theResult to theNSCalendar’s rangeOfUnit:(current application’s NSDayCalendarUnit) inUnit:(current application’s NSMonthCalendarUnit) forDate:theDate
  
return |length| of theResult
end getMlen

–現在のカレンダーで指定年月のdate objectを返す
on getDateInternational(aYear, aMonth, aDay)
  set theNSCalendar to current application’s NSCalendar’s currentCalendar()
  
set theDate to theNSCalendar’s dateWithEra:1 |year|:aYear |month|:aMonth |day|:aDay hour:0 minute:0 |second|:0 nanosecond:0
  
return theDate as date
end getDateInternational

–ローカライズされた曜日名称を返す
on getLocalizedDaynames(aLoc)
  set df to current application’s NSDateFormatter’s alloc()’s init()
  
df’s setLocale:(current application’s NSLocale’s localeWithLocaleIdentifier:aLoc)
  
set dayNames to df’s standaloneWeekdaySymbols() as list
  
return dayNames
end getLocalizedDaynames

–ローカライズされた月名称を返す
on getLocalizedMonthnames(aLoc)
  set df to current application’s NSDateFormatter’s alloc()’s init()
  
df’s setLocale:(current application’s NSLocale’s localeWithLocaleIdentifier:aLoc)
  
set monthNames to df’s standaloneMonthSymbols() as list
  
return monthNames
end getLocalizedMonthnames

–ローカライズされた曜日の名称を返す
on getLocalizedWeekdaySymbol(aLoc)
  set df to current application’s NSDateFormatter’s alloc()’s init()
  
df’s setLocale:(current application’s NSLocale’s localeWithLocaleIdentifier:aLoc)
  
set dayNames to df’s weekdaySymbols()
  
return dayNames as list
end getLocalizedWeekdaySymbol

–ローカライズされた曜日の名称(短縮版)を返す
on getLocalizedShortWeekdaySymbol(aLoc)
  set df to current application’s NSDateFormatter’s alloc()’s init()
  
df’s setLocale:(current application’s NSLocale’s localeWithLocaleIdentifier:aLoc)
  
set dayNames to df’s shortWeekdaySymbols()
  
return dayNames as list
end getLocalizedShortWeekdaySymbol

–ローカライズされた曜日の名称(短縮記号)を返す
on getLocalizedVeryShortWeekdaySymbol(aLoc)
  set df to current application’s NSDateFormatter’s alloc()’s init()
  
df’s setLocale:(current application’s NSLocale’s localeWithLocaleIdentifier:aLoc)
  
set dayNames to df’s veryShortWeekdaySymbols()
  
return dayNames as list
end getLocalizedVeryShortWeekdaySymbol

–ローカライズされた曜日の名称を返す
on getLocalizedVeryStandaloneWeekdaySymbols(aLoc)
  set df to current application’s NSDateFormatter’s alloc()’s init()
  
df’s setLocale:(current application’s NSLocale’s localeWithLocaleIdentifier:aLoc)
  
set dayNames to df’s standaloneWeekdaySymbols()
  
return dayNames as list
end getLocalizedVeryStandaloneWeekdaySymbols

–ローカライズされた曜日の名称を返す
on getLocalizedShortStandaloneWeekdaySymbols(aLoc)
  set df to current application’s NSDateFormatter’s alloc()’s init()
  
df’s setLocale:(current application’s NSLocale’s localeWithLocaleIdentifier:aLoc)
  
set dayNames to df’s shortStandaloneWeekdaySymbols()
  
return dayNames as list
end getLocalizedShortStandaloneWeekdaySymbols

–ローカライズされた曜日の名称を返す
on getLocalizedVeryShortStandaloneWeekdaySymbols(aLoc)
  set df to current application’s NSDateFormatter’s alloc()’s init()
  
df’s setLocale:(current application’s NSLocale’s localeWithLocaleIdentifier:aLoc)
  
set dayNames to df’s veryShortStandaloneWeekdaySymbols()
  
return dayNames as list
end getLocalizedVeryShortStandaloneWeekdaySymbols

–カレンダー表示ビューを作成
on makeCalendarView(tYear as integer, tMonth as integer, noDispList as list, ignoreP as boolean)
  set colNum to 7
  
set rowNum to 8
  
set aLen to (colNum * rowNum)
  
  
set aButtonCellWidth to 70 –56
  
set aButtonCellHeight to 40
  
  
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 aFontSize to 30
  
set bArray to current application’s NSMutableArray’s new()
  
  
–Make Header (Month, Year)
  
set x to 1
  
set tmpB to (NSTextField’s alloc()’s initWithFrame:(current application’s NSMakeRect(((x – 1) * aButtonCellWidth), ((aLen – aCount) div colNum) * (aButtonCellHeight), aButtonCellWidth * 4, aButtonCellHeight)))
  (
tmpB’s setEditable:false)
  (
tmpB’s setBordered:false)
  (
tmpB’s setDrawsBackground:false)
  (
tmpB’s setAlignment:(current application’s NSLeftTextAlignment))
  (
tmpB’s setStringValue:((tYear as string) & " / " & tMonth as string))
  (
tmpB’s setFont:(NSFont’s fontWithName:"Times-Roman" |size|:40))
  (
bArray’s addObject:tmpB)
  
  
set aCount to aCount + 1
  
  
  
–Make Header (Weekday)
  
set curLocale to current application’s NSLocale’s currentLocale()
  
set aDS10 to (curLocale’s objectForKey:(current application’s NSLocaleIdentifier)) as string
  
set wdList to getLocalizedShortStandaloneWeekdaySymbols(aDS10) of me
  
set y to 2
  
  
repeat with x from 1 to 7
    set j to contents of item x of wdList
    
set tmpB to (NSTextField’s alloc()’s initWithFrame:(current application’s NSMakeRect(((x – 1) * aButtonCellWidth), ((aLen – aCount) div colNum – 1) * (aButtonCellHeight), aButtonCellWidth, aButtonCellHeight / 2)))
    (
tmpB’s setEditable:false)
    (
tmpB’s setAlignment:(current application’s NSCenterTextAlignment))
    (
tmpB’s setStringValue:(j))
    (
bArray’s addObject:tmpB)
  end repeat
  
  
set aCalList to retListCalendar(tYear, tMonth) of me
  
set aCount to 1
  
  
  
–Make Calendar (Calendar Body)
  
set curDat to current date
  
  
repeat with y from 3 to rowNum
    repeat with x from 1 to colNum
      set j to contents of item aCount of aCalList
      
set tmpB to (NSButton’s alloc()’s initWithFrame:(current application’s NSMakeRect(((x – 1) * aButtonCellWidth), ((aLen – aCount) div colNum – 2) * aButtonCellHeight, aButtonCellWidth, aButtonCellHeight)))
      
      
set tmpDate to getDateInternational(tYear, tMonth, j as integer) of me
      
set tmpF to (tmpDate < curDat) as boolean
      
      
if ignoreP = false then
        set dispF to true
      else if ignoreP = true and tmpF = false then
        set dispF to true
      else
        set dispF to false
      end if
      
      
if (j as integer) is not in noDispList then
        if (dispF = true) then
          (tmpB’s setTitle:(j as string))
          (
tmpB’s setFont:(NSFont’s fontWithName:"ArialMT" |size|:aFontSize))
          
–set attrTitle to makeRTFfromParameters((aCount as string), "ArialMT", aFontSize, 0, (aFontSize * 1.2)) of me
          
–(tmpB’s setAttributedTitle:(attrTitle))
          (
tmpB’s setShowsBorderOnlyWhileMouseInside:true)
          (
tmpB’s setAlignment:(current application’s NSCenterTextAlignment))
          (
tmpB’s setEnabled:(j ≠ ""))
          (
tmpB’s setTarget:me)
          (
tmpB’s setAction:("clicked:"))
          (
tmpB’s setButtonType:(NSButtonTypeOnOff))
          (
tmpB’s setHidden:(j = ""))
          
if j is not equal to "" then
            (tmpB’s setTag:(j))
            (
bArray’s addObject:tmpB)
          end if
        end if
      end if
      
set aCount to aCount + 1
    end repeat
  end repeat
  
  (
aView’s setSubviews:bArray)
  
return aView
end makeCalendarView

★Click Here to Open This Script 

Posted in Calendar dialog GUI | Tagged 10.14savvy 10.15savvy NSAlert NSButton NSButtonTypeOnOff NSColor NSFont NSFontAttributeName NSForegroundColorAttributeName NSKernAttributeName NSLigatureAttributeName NSMutableArray NSMutableAttributedString NSMutableDictionary NSMutableParagraphStyle NSOffState NSOnState NSParagraphStyleAttributeName NSRunningApplication NSTextField NSUnderlineStyleAttributeName NSView | Leave a comment

日付ダイアログで開始時と終了時を選択する

Posted on 10月 23, 2019 by Takaaki Naganoya

edama2さんからの投稿です。いつもながら、(同じAppleScriptを書いているのに)異種格闘技のようなフレーバーの違いを感じるものですが、ソースコードを美しく書くことへのこだわりと、実際に実現されている機能については折り紙つきです。

—- >8 投稿ここから

タイトルは「日付ダイアログで開始時と終了時を選択する」です。
「アラートダイアログ上のDate Pickerで日付選択」をベースに日付をふたつ選択できるようにしました
結果はレコードで帰って返ってきます

--> {|開始日|:date "2019年10月23日 水曜日 21:23:04", |終了日|:date "2019年10月24日 木曜日 21:23:04"}

NSDatePickerのコメントアウトしている部分を変更するとカレンダー以外にもできます

スプリクトオブジェクトの使い方が奇怪(?)だと思うかもしれませんが、
script-factory さんのクラスオブジェクトのやり方を参考に結果のプロパティ値を本体と分離するためにこうしています。

制作環境:macOS10.14.6
—– >8 投稿ここまで

まず「property parent : AppleScript」で腰を抜かしてしまいました。なるほど、こういう逃げ道があったんですか。Script文の中にCocoaの機能を呼び出すAppleScriptObjCを書く方法がなかなか見つからずに、個人的にそういう書き方はしてこなかったところですが、これは実際に試してみないと。

AppleScriptで作った部品を積み上げて新しい概念や機能を実現することには関心がありますが、記法の限界を探るという方向にはほとんど興味がないので、参考になります。

自分も、NSDatePickerにNSBoxをかぶせてアラートダイアログに表示させるところまでは同様に作っていたんですが、サイズの調整に手間取って、思い通りの表示を行えていませんでした。はい、まさにこういう形のものが作りたかった(利用したかった)ので、これを見て勉強させていただきましょう。

AppleScript名:日付ダイアログで開始時と終了時を選択する.scpt
on run
  set dateObj to my chooseDate("期間を選択", "開始日と終了日を選択してください。", "開始日", "終了日")
end run

#カレンダー作成対象の年、月を選択(ただし、日付をクリックして選択しないと値を取得できないので注意)
on chooseDate(aMainMes, aSubMes, aLabel1, aLabel2)
  script MyDialog
    property parent : AppleScript
    
use AppleScript
    
use scripting additions
    
use framework "Foundation"
    
property _the_date : missing value
    
on make
      set aClass to me
      
script
        property parent : aClass
      end script
    end make
    
## ダイアログの呼び出し
    
on chooseDate(aMainMes, aSubMes, aLabel1, aLabel2)
      set paramObj to {myMessage:aMainMes, mySubMessage:aSubMes, myLabel1:aLabel1, myLabel2:aLabel2}
      
parent’s performSelectorOnMainThread:"raize:" withObject:paramObj waitUntilDone:true
      
return (my _the_date)
    end chooseDate
    
## ダイアログの生成
    
on raize:paramObj
      set aMainMes to paramObj’s myMessage
      
set aSubMes to paramObj’s mySubMessage
      
set aLabel1 to paramObj’s myLabel1
      
set aLabel2 to paramObj’s myLabel2
      
set setTime1 to current date
      
set setTime2 to setTime1 + days
      
      
set aList to {}
      
set aList’s end to {boxLabel:aLabel1, aTime:setTime1}
      
set aList’s end to {boxLabel:aLabel2, aTime:setTime2}
      
      
set viewList to {}
      
set datePickerList to {}
      
set parentViewWidth to 0
      
set aMargin to 8
      
      
set countItem to count aList
      
repeat with num from 1 to countItem
        set anItem to (aList)’s item num
        
        
set setLabel to anItem’s boxLabel
        
set setTime to anItem’s aTime
        
        
## create a view
        
set opt to current application’s NSYearMonthDayDatePickerElementFlag
        
–set opt to opt + (current application’s NSHourMinuteSecondDatePickerElementFlag as integer)
        
tell current application’s NSDatePicker’s new()
          –setDatePickerStyle_(current application’s NSClockAndCalendarDatePickerStyle) –> 10.13以下
          
setDatePickerStyle_(current application’s NSDatePickerStyleClockAndCalendar) –> 10.14以上 カレンダー
          
–setDatePickerStyle_(current application’s NSDatePickerStyleTextField) –> 10.14以上 テキスト入力
          
–setDatePickerStyle_(current application’s NSDatePickerStyleTextFieldAndStepper) –> 10.14以上 ステップ入力
          
setDatePickerElements_(opt)
          
setDateValue_(setTime)
          
set thisSize to fittingSize()
          
setFrameSize_(thisSize)
          
          
### 余白の大きさを指定
          
set aWidth to (thisSize’s width) + aMargin * 3.75
          
set aHeight to (thisSize’s height) + aMargin * 5.25
          
set boxFrameSize to current application’s NSMakeSize(aWidth, aHeight)
          
setFrameOrigin_(current application’s NSMakePoint(aMargin, aMargin))
          
log frame()
          
set theDatePicker to it
        end tell
        
        
tell current application’s NSBox’s new()
          setTitle_(setLabel)
          
addSubview_(theDatePicker)
          
setFrameSize_(boxFrameSize)
          
setFrameOrigin_(current application’s NSMakePoint(parentViewWidth, 0))
          
set viewList’s end to it
        end tell
        
        
### 親NSViewの大きさを指定
        
set countItem2 to count viewList
        
repeat with num2 from num to countItem2
          set anItem2 to viewList’s item num2
          
set tmpFrame to anItem2’s frame()
          
set aBoxWidt to current application’s NSWidth(tmpFrame)
          
set parentViewHeight to current application’s NSHeight(tmpFrame)
          
set parentViewWidth to parentViewWidth + aMargin + aBoxWidt
          
log result
        end repeat
        
        
###
        
set datePickerList’s end to {pickerObj:theDatePicker, keyLabel:setLabel}
      end repeat
      
      
tell current application’s NSView’s new()
        –setAutoresizingMask_(0)
        
–setAutoresizesSubviews_(true)
        
setFrameSize_(current application’s NSMakeSize(parentViewWidth, parentViewHeight))
        
setSubviews_(viewList)
        
set theView to it
      end tell
      
      
## set up alert
      
tell current application’s NSAlert’s new()
        setMessageText_(aMainMes)
        
setInformativeText_(aSubMes)
        
addButtonWithTitle_("OK")
        
addButtonWithTitle_("Cancel")
        
setAccessoryView_(theView)
        
set returnCode to runModal() — show alert in modal loop
      end tell
      
      
if returnCode = (current application’s NSAlertSecondButtonReturn) then error number -128
      
      
## retrieve date
      
set keyList to {}
      
set dateList to {}
      
repeat with anItem in datePickerList
        set keyList’s end to anItem’s keyLabel
        
set dateList’s end to (anItem’s pickerObj)’s dateValue() as date
      end repeat
      
set my _the_date to (current application’s NSDictionary’s dictionaryWithObjects:dateList forKeys:keyList) as record
      
log result
    end raize:
  end script
  
  
##
  
tell (make MyDialog)
    return chooseDate(aMainMes, aSubMes, aLabel1, aLabel2)
  end tell
end chooseDate

★Click Here to Open This Script 

Posted in Calendar dialog GUI | Tagged 10.14savvy 10.15savvy | Leave a comment

display text fields script Library v1.1

Posted on 10月 21, 2019 by Takaaki Naganoya

ちょっとしたデータをText Fieldの組み合わせでアラートダイアログ上に表示するUser Interfaceを提供するAppleScriptライブラリです。

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

本ライブラリは、あまり考えずにデータ内容を表示してユーザーへの確認を行うことが目的でした。実際に使ってみると、フィールド内容を微修正するような用途にも使いたいというニーズがPiyomaru Software内で出てきました。

従来の「display text fields」は単なる表示用(フィールド内容編集不可)、新規追加した「confirm text fields」コマンドではダイアログに表示したデータのユーザーによる編集が可能で、編集したデータ内容をリストで返します(キャンセルボタンのクリック時にはfalseが返る)。データの表示と微修正に便利だと思います。

もちろん、Piyomaru Software製のScript Libraryの共通仕様でAppleScript用語辞書そのものにサンプルAppleScriptを収録しているため、すぐに動かせます。

ただ、コマンドの説明文がグダグダで、いまいち英語の内容として意味が取りにくいような、、、、

AppleScript名:sample script2
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/10/05
—
–  Copyright © 2019 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
use tfLib : script "display text fields"

set vRes1 to (confirm text fields main message "Zip archive Result" sub message "Edit this data to proc." key list {"scpt", "scptd", "applescript"} value list {98, 16, 3})
–> {"980", "160", "30"}

★Click Here to Open This Script 

Posted in dialog GUI Script Libraries | Tagged 10.12savvy 10.13savvy 10.14savvy 10.15savvy | Leave a comment

display text fields script Library

Posted on 10月 5, 2019 by Takaaki Naganoya

ちょっとしたデータをText Fieldの組み合わせでアラートダイアログ上に表示するUser Interfaceを提供するAppleScriptライブラリです。

–> displayTextFields (To ~/Library/Script Libraries/)

ラベル部、データ部の文字数から画面上の描画幅を計算して、ダイアログサイズやフィールドのサイズを動的に変更します(まだいまひとつかも)。表示するデータの量が多い場合にエラーを出すべきなのですが、そこはとくにケアしていません。

こういう地味な部品があるとデータ内容確認に便利であるものの、なぜか存在していないのでついでに作ってみました。

AppleScript sample name : sample script_eng
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/10/05
—
–  Copyright © 2019 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
use tfLib : script "display text fields"

display text fields main message "Result" sub message "Files in the Zip Archive" key list {".scpt", ".scptd", ".applescript"} value list {98, 16, 3}

★Click Here to Open This Script 

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

アラートダイアログ上にTab View+Popup Buttonを表示して切り替え

Posted on 9月 16, 2019 by Takaaki Naganoya

アラートダイアログ上にTabViewとPopup Buttonを表示して、Popup Menuの選択状況に合わせてTabViewの表示ビューを切り替え、Popup Menuの選択アイテムを1はじまりの番号で返すAppleScriptです。

最終的には各TabViewItem内にCustomViewを生成して、各種データ(TableとかWebとかImageとか)を一覧から選択するようなUI部品として使い回すつもりです。

このバージョンではTabViewのタブが表示状態になっていますが、最終的にはタブレスのTabViewとして表示することになります。

AppleScript名:アラートダイアログ上にTab View+Popup Buttonを表示して切り替え
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/09/16
—
–  Copyright © 2019 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4"
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 NSMenu : a reference to current application’s NSMenu
property NSTabView : a reference to current application’s NSTabView
property NSMenuItem : a reference to current application’s NSMenuItem
property NSTabViewItem : a reference to current application’s NSTabViewItem
property NSPopUpButton : a reference to current application’s NSPopUpButton
property NSRunningApplication : a reference to current application’s NSRunningApplication

property TabPosition : 0 —0=Top, 1=Left, 2=Bottom, 3=Right, 4=None

property returnCode : 0

property aTabV : missing value
property selectedNum : 1

set paramObj to {myMessage:"Main Message", mySubMessage:"Sub information", viewWidth:500, viewHeight:300}

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

on dispTabViewWithAlertdialog:paramObj
  –Receive Parameters
  
set aMainMes to (myMessage of paramObj) as string –Main Message
  
set aSubMes to (mySubMessage of paramObj) as string –Sub Message
  
set aWidth to (viewWidth of paramObj) as integer –TextView width
  
set aHeight to (viewHeight of paramObj) as integer –TextView height
  
  
  
set selectedNum to 0
  
  
set aView to NSView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aWidth, aHeight))
  
  
–Ppopup Buttonをつくる
  
set a1Button to NSPopUpButton’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, aHeight – 20, 400, 20)) pullsDown:false
  
a1Button’s removeAllItems()
  
  
set a1Menu to NSMenu’s alloc()’s init()
  
  
repeat with i from 1 to 8
    set aTitle to "Selection #" & (i as string)
    
set aMenuItem to (NSMenuItem’s alloc()’s initWithTitle:aTitle action:"actionHandler:" keyEquivalent:"")
    (
aMenuItem’s setEnabled:true)
    (
aMenuItem’s setTarget:me)
    (
aMenuItem’s setTag:(i as string))
    (
a1Menu’s addItem:aMenuItem)
  end repeat
  
  
a1Button’s setMenu:a1Menu
  
  
–Make Tab View
  
set aTabV to NSTabView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aWidth, aHeight – 30))
  
aTabV’s setTabViewType:(TabPosition)
  
aTabV’s setTabViewType:(TabPosition)
  
  
repeat with i from 1 to 8
    set aTVItem to (NSTabViewItem’s alloc()’s initWithIdentifier:(i as string))
    (
aTVItem’s setLabel:(i as string))
    
    
–make custom view within a tab view item here
    
    (
aTabV’s addTabViewItem:aTVItem)
  end repeat
  
  
  
aView’s setSubviews:{a1Button, aTabV}
  
aView’s setNeedsDisplay: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:(aView)
    
    
–for Help Button
    
its setShowsHelp:(true)
    
its setDelegate:(me)
  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 selectedNum to (a1Button’s indexOfSelectedItem()) + 1
end dispTabViewWithAlertdialog:

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:

–Popup Action Handler
on actionHandler:sender
  set aTag to tag of sender as integer
  
aTabV’s selectTabViewItemAtIndex:(aTag – 1)
end actionHandler:

★Click Here to Open This Script 

Posted in dialog GUI Menu | Tagged 10.12savvy 10.13savvy 10.14savvy NSAlert NSMenu NSMenuItem NSPopUpButton NSRunningApplication NSTabView NSTabViewItem NSView | Leave a comment

choose location script Library

Posted on 9月 8, 2019 by Takaaki Naganoya

位置情報リストを与え、リスト+地図表示していずれかを選択するUser Interfaceを提供するAppleScriptライブラリです。

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

リストに入れた所定のラベルを持つレコードを与えると、地図表示して選択できます。

set aPlaceList to {{title:"Ginza", latitude:"35.67229109", longitude:"139.76575278"}....}

のような名称、緯度、経度のセットを与えます。各位置情報については適宜計算してください(自分はYahoo!の住所ジオコーダーサービスを利用しています)。

地図の表示タイプをGUI上から切り替えられますが、AppleScriptのオプション「initial map type」で初期表示地図タイプを指定できます。


▲初期表示タイプ「map」「satellite」「mixture」(左より)

sdefがいまひとつうまく想定どおりに動いていません。位置情報リストのラベルを予約語として動作させたかったのに、そう動いていませんが、とりあえず現状はこんな感じです(^ー^;; あと、Optional=”Yes”を指定しても省略可能表示になっていないのが謎です。いいのか悪いのか、機能自体に影響がないので現状このままですが、、、

AppleScript名:choose loc sample script
— Created 2019-09-08 by Takaaki Naganoya
— 2019 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use cLoc : script "choose location"

set aPlaceList to {{title:"Ginza", latitude:"35.67229109", longitude:"139.76575278"}, {title:"Shinjuku", latitude:"35.69096528", longitude:"139.70403520"}, {title:"Kyoto", latitude:"35.00394764", longitude:"135.76277689"}, {title:"Shibuya", latitude:"35.66621547", longitude:"139.71090224"}, {title:"Marunouchi", latitude:"35.67982632", longitude:"139.76364660"}, {title:"Omote-sando", latitude:"35.66621547", longitude:"139.71090224"}, {title:"Nagoya-Sakae", latitude:"35.16556738", longitude:"136.90693150"}, {title:"Fukuoka-Tenjin", latitude:"33.58682428", longitude:"130.39764326"}, {title:"Shinsai-bashi", latitude:"34.67225640", longitude:"135.49985757"}}

set cRes to (choose location from aPlaceList main message "Select Apple Retail Store in Japan" sub message "These stores are almost same. All products are same. The most of visitors are waiting people to repair their broken products." with size {900, 500} initial map type map)

★Click Here to Open This Script 

Posted in dialog geolocation GUI Script Libraries sdef | Tagged 10.12savvy 10.13savvy 10.14savvy | 1 Comment

display table Script Library

Posted on 9月 7, 2019 by Takaaki Naganoya

2D List(二次元配列)データを気軽に表UIでプレビューするUser Interfaceを提供するdisplay table Script Library+サンプルコードです。

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

表UIを提供する部品としては、Shane StanleyのMyriad Tables Libが存在しており、ひじょうに充実した機能を備えているため、同様でかつ機能が低いものを提供する必要はないはずです。

ですが、同ライブラリはバンドル内にFrameworkを含んでおり、SIPによる機能制限でそのままではmacOS 10.14以降の環境ではこのライブラリを(スクリプトエディタでは)呼べないなどの問題があります。ホームディレクトリ以下のFrameworkのバイナリを呼べないわけです。Script Debuggerを使ったり、アプレットとして書き出せばクリアできるものの、利用シーンが限定されるきらいがありました(このあたり、GUIなしのsdefつきアプリケーションとして仕立ててライブラリのバンドル内に入れれば回避できるのではないかと思っていますが、どうなりますやら)。

そこで、2D List(二次元配列)データのプレビューなど、最低限の機能をそなえたライブラリを(主に自分用に)作ってみたものです。もともと、NSTableViewで表示するためには2D List(2次元配列)ではなくRecord in List(行ごとに各フィールドが属性ラベルの付いたRecord)になっている必要があります。この、2D List → Record in Listの変換処理が面倒なので、その部分を中心に、汎用部品として使えるように機能をまとめてみました。

NSTableViewの各セルのタイトルをRecord in Listの各ラベル値に設定しており、上記のデータは、

(NSArray) {
	{
		ダッシュ時間:"2.2cnt",
		ダッシュ距離:"?m",
		タックルダメージ:"20",
		ダッシュ速度:"208km/h",
		ジャンプ速度:"167km/h",
		硬直時間:"38f",
		セッティング名:"旋(旋回)    ",
		アーマー値:"284",
		歩行速度:"100km/h",
		旋回速度:"10.9rpm",
		備考:""
	},

...........

	{
		ダッシュ時間:"2.1cnt",
		ダッシュ距離:"?m",
		タックルダメージ:"20",
		ダッシュ速度:"180km/h",
		ジャンプ速度:"144km/h",
		硬直時間:"38f",
		セッティング名:"装(装甲)    ",
		アーマー値:"343",
		歩行速度:"100km/h",
		旋回速度:" 9.7rpm",
		備考:""
	}
}

という、日本語の属性ラベルのついたRecord(Dictionary)に変換・表示しています。

dialog上のアイコン表示部品を画像のプレビュー用に使ってみたりと、例によって好き放題やっていますが、アイコン関連のファイルパス/URLを指定しなければ通常の動作を行います。

AppleScript名:display table by list sample
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/08/25
—
–  Copyright © 2019 jp.piyomarusoft, All Rights Reserved
—
use AppleScript version "2.5" — El Capitan (10.11) or later
use framework "Foundation"
use scripting additions

use easyTable : script "display table by list"

set msURL to "http://web.gundam-kizuna.jp/sp/image/index/img/p/QBP89Z-T_2o62sJWBQC7BSsw08wZuZ28keecHZs9Io4"

set aList to {{"旋(旋回) ", "284", "208km/h", "2.2cnt", "?m", "167km/h", "10.9rpm", "38f", "20", "100km/h", ""}, {"硬(硬直減) ", "286", "206km/h", "2.1cnt", "?m", "165km/h", "10.3rpm", "34f", "20", "100km/h", ""}, {"歩(歩行) ", "293", "206km/h", "2.2cnt", "?m", "165km/h", "10.3rpm", "38f", "20", "111km/h", ""}, {"跳(ジャンプ)", "263", "202km/h", "2.1cnt", "?m", "183km/h", "10.3rpm", "39f", "20", "100km/h", ""}, {"走(ダッシュ)", "248", "224km/h", "2.3cnt", "?m", "161km/h", "10.3rpm", "40f", "20", "100km/h", ""}, {"機(機動) ", "243", "216km/h", "2.2cnt", "?m", "177km/h", "10.6rpm", "39f", "20", "100km/h", ""}, {"推(ブースト)", "296", "196km/h", "2.4cnt", "?m", "157km/h", "10.0rpm", "38f", "20", "100km/h", ""}, {"突(タックル)", "298", "190km/h", "2.1cnt", "?m", "152km/h", " 9.7rpm", "38f", "30", "100km/h", ""}, {"装(装甲) ", "343", "180km/h", "2.1cnt", "?m", "144km/h", " 9.7rpm", "38f", "20", "100km/h", ""}}

set fLabels to {"セッティング名", "アーマー値", "ダッシュ速度", "ダッシュ時間", "ダッシュ距離", "ジャンプ速度", "旋回速度", "硬直時間", "タックルダメージ", "歩行速度", "備考"}

set aRes to (display table by list aList main message "項目の選択" sub message "適切なものを以下からえらんでください" size {1200, 400} labels fLabels icon msURL timed out 5)

★Click Here to Open This Script 

Posted in GUI Script Libraries sdef URL | Tagged 10.12savvy 10.13savvy 10.14savvy | Leave a comment

pickup color Script Library

Posted on 8月 31, 2019 by Takaaki Naganoya

指定した複数の色からどれかを選ぶコマンドを提供するAppleScriptライブラリ+呼び出しサンプルScriptです。

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

使い道があるんだかないんだか微妙ですが、本来であれば何らかの画像を入力して、画像内の色をポスタライズして色数を減らし、その上で本ライブラリのようなインタフェースを用いて色選択。元画像のうち選択色の占めるエリアをダイアログ上で点滅表示……という処理が行いたいところです。

アラートダイアログのアイコン表示部分は、本来なら実行をリクエストしたアプリケーションのアイコンが表示されますが、選択色のプレビュー領域に使ってみました。このアイコン表示は最前面のアプリケーションのアイコンが入るべきという「ルール」があるわけですが、最前面のアプリケーションが何であるかは分かりきっています。

別の運用方法でもっと便利になるのであれば、そういうことを試してみてもいいでしょう。


▲本来は、指定画像中の色を検出して、選択した色が表示されているエリアのみ点滅表示させたい。Xcode上で作ればできそう、、、、

また、Frameworkを呼び出してNSImageから色名をダイナミックに生成するという処理も、ライブラリとして運用するために取り外していますが、これも取り外したくはない部品です。

本来やりたい処理のすべてができているわけではないので、本ライブラリはまだまだ試作品レベルです。

色データを8ビットの整数値で与えるか、16ビットの整数値で与えるかをEnum「max255」「max65535」で表現していますが、もう少しスマートに表現したいところです。

AppleScript名:pickup color sample
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/08/31
—
–  Copyright © 2019 jp.piyomarusoft, All Rights Reserved
—
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use colPic : script "pickup color"

set ap1List to {{65535, 0, 65535}, {0, 32896, 16448}, {65535, 65531, 2689}, {0, 32896, 65535}, {8608, 65514, 1548}, {46003, 46003, 46003}, {19702, 31223, 40505}}

set cRes to pickup color ap1List main message "Color Dialog" sub message "Choose a color from popup button" color max max65535

★Click Here to Open This Script 

Posted in Color GUI OSA Script Libraries sdef | Tagged 10.12savvy 10.13savvy 10.14savvy | 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