use dropLib : script "display drop dialog" version "1.5"
set aMainMes to "Drop AppleScript" set aSubMes to "Drag and Drop AppleScript files to Table (.scpt & .scptd)" set aUTI to {"com.apple.applescript.script-bundle", "com.apple.applescript.script"} set execButtonTitle to "Execute"
set aRes to (display drop dialog aUTI main message aMainMes sub message aSubMes with initial folder "" OK button title execButtonTitle)
use AppleScript use scripting additions use framework "Foundation" use framework "AppKit"
property NSApp : a reference to current application’s NSApp property NSColor : a reference to current application’s NSColor property NSImage : a reference to current application’s NSImage property NSGradient : a reference to current application’s NSGradient property NSZeroPoint : a reference to current application’s NSZeroPoint property NSBezierPath : a reference to current application’s NSBezierPath
on run set aASCol to choose color set aCocoaList to retCocoaColorList(aASCol, 65535) of me set aCol to makeNSColorFromRGBAList(aCocoaList)
set max to 100 repeat with num from 1 to max my progDockTile(max, num, aCol) delay 0.05 end repeat
#アイコンを元に戻す NSApp’s setApplicationIconImage:(NSImage’s imageNamed:"NSApplicationIcon") end run
#Dockアイコンにプログレスバーを追加 on progDockTile(max, current, strartColor) set appIcon to NSImage’s imageNamed:"NSApplicationIcon" set iconSize to appIcon’s |size|()
tell (NSImage’s alloc()’s initWithSize:iconSize)
lockFocus()
appIcon’s dissolveToPoint:(NSZeroPoint) fraction:1.0 set n to (iconSize’s width) / 16
#プログレスバーの長方形 set myRect to current application’s NSMakeRect(n / 2, n, n * 15, n * 1.6) –>{origin:{x:4.0, y:8.0}, |size|:{width:120.0, height:12.800000190735}}
NSColor’s whiteColor()’s |set|() –>枠色 stroke() end tell
if current is greater than 0 then if current is greater than max then set current to max set myRect’s item 2’s item 1 to (myRect’s item 2’s item 1) / max * current
–set strartColor to NSColor’s colorWithRed:0.15 green:0.55 blue:1 alpha:0.8 set endColor to strartColor’s shadowWithLevel:0.7 set grad to NSGradient’s alloc()’s initWithStartingColor:strartColor endingColor:endColor grad’s drawInBezierPath:it angle:270.0 end tell end if
unlockFocus()
NSApp’s setApplicationIconImage:it end tell
return (current + 1) end progDockTile
–Convert "choose color" RGB list (0-65535) to Cocoa color RGBA Array (0.0-1.0) on retCocoaColorList(aColorList, aMax) set cocoaColorList to {} repeat with i in aColorList set the end of cocoaColorList to i / aMax end repeat set the end of cocoaColorList to 1.0 return cocoaColorList end retCocoaColorList
on makeNSColorFromRGBAList(colList) copy colList to {redValue, greenValue, blueValue, alphaValue} set aColor to NSColor’s colorWithCalibratedRed:redValue green:greenValue blue:blueValue alpha:alphaValue return aColor end makeNSColorFromRGBAList
— Created 2017-03-03 by Takaaki Naganoya — Modified 2018-02-15 by Shane Stanley–Thanks!! — Modified 2018-02-15 by Takaaki Naganoya — Modified 2020-11-04 by Takaaki Naganoya use AppleScript version "2.5" use scripting additions use framework "Foundation" use framework "AppKit"
property aStatusItem : missing value
on run my performSelectorOnMainThread:"init:" withObject:(missing value) waitUntilDone:true end run
on init:aSender set aList to {"Piyomaru", "Software", "", "Takaaki", {"Yes", "No"}, "", "Machine", {"MacBook Pro", "MacBook Air", "Mac mini"}, "", "Quit"}
set aStatusItem to current application’s NSStatusBar’s systemStatusBar()’s statusItemWithLength:(current application’s NSVariableStatusItemLength)
aStatusItem’s setTitle:"🍎" aStatusItem’s setHighlightMode:true aStatusItem’s setMenu:(createMenu(aList) of me)
–Blink Status Bar Item set aButton to aStatusItem’s button() aButton’s setWantsLayer:true my blinkObject:aButton withRepeat:10 withDuration:1.0 –OK –my scaleObject:aButton withRepeat:10 withDuration:0.5 –OK –my rotateObject:aButton forAxis:90 withRepeat:10 withDuration:0.5 –NG –my moveObject:aButton withRepeat:10 withDuration:0.5–NG end init:
on createMenu(aList) set aMenu to current application’s NSMenu’s alloc()’s init() set aCount to 10
set prevMenuItem to ""
repeat with i in aList set j to contents of i set aClass to (class of j) as string
if j is equal to "" then set aMenuItem to (current application’s NSMenuItem’s separatorItem()) (aMenu’s addItem:aMenuItem) else if (aClass = "text") or (aClass = "string") then
if j = "Quit" then set aMenuItem to (current application’s NSMenuItem’s alloc()’s initWithTitle:j action:"actionHandler:" keyEquivalent:"") else set aMenuItem to (current application’s NSMenuItem’s alloc()’s initWithTitle:j action:"actionHandler:" keyEquivalent:"") end if
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE dictionary SYSTEM "file://localhost/System/Library/DTDs/sdef.dtd">
<dictionary xmlns:xi="http://www.w3.org/2003/XInclude">
<!-- We override some standard commands to add several optional properties. -->
<suite name="Standard Suite" code="????" description="Common classes and commands for all applications.">
<xi:include href="file://localhost/System/Library/ScriptingDefinitions/CocoaStandard.sdef" xpointer="xpointer(/dictionary/suite/node()[not((self::command and (@name = 'open')) or (self::class and (@name = 'window')))])"/>
— Created 2017-03-24 by Takaaki Naganoya — 2017 Piyomaru Software use AppleScript version "2.4" use scripting additions use webLib : script "WebKit Utilities"
set targetURL to "http://www.piyocast.com/" display URL targetURL window size {1024, 1024}
— An example AppleScript/Objective-C library that uses the WebKit framework.
use AppleScript use framework "AppKit" use framework "WebKit"
property NSURL : a reference to current application’s NSURL property WebView : a reference to current application’s WebView property NSScreen : a reference to current application’s NSScreen property NSThread : a reference to current application’s NSThread property NSWindow : a reference to current application’s NSWindow property NSURLRequest : a reference to current application’s NSURLRequest property NSMutableDictionary : a reference to current application’s NSMutableDictionary
on _DisplayWebWindowWithURL:theURLString windowSize:theWindowSize — Create and display a horizontally centered window with a WebView
set {thisWindowWidth, thisWindowHeight} to theWindowSize set screenBounds to the NSScreen’s mainScreen’s visibleFrame as any
if class of screenBounds = record then set screenWidth to screenBounds’s |size|’s width set screenHeight to screenBounds’s |size|’s height set windowLeft to ((screenWidth – thisWindowWidth) / 2) + (screenBounds’s origin’s x) set windowBottom to screenHeight – thisWindowHeight + (screenBounds’s origin’s y) – 40 else copy screenBounds to {{originX, originY}, {screenWidth, screenHeight}} set windowLeft to ((screenWidth – thisWindowWidth) / 2) + originX set windowBottom to screenHeight – thisWindowHeight + originY – 40 end if
set theStyleMask to (get current application’s NSTitledWindowMask) + (get current application’s NSClosableWindowMask) + (get current application’s NSMiniaturizableWindowMask) + (get current application’s NSResizableWindowMask) set webWindow to NSWindow’s alloc()’s initWithContentRect:(current application’s NSMakeRect(windowLeft, windowBottom, thisWindowWidth, thisWindowHeight)) ¬ styleMask:theStyleMask backing:(current application’s NSBackingStoreBuffered) defer:false — set webWindow’s title to "WebView Created with AppleScript – " & theURLString
set theWebView to WebView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, thisWindowWidth, thisWindowHeight)) ¬ frameName:"WebKit Frame" groupName:"WebKit Group" set webWindow’s contentView to theWebView
tell webWindow to makeKeyAndOrderFront:(missing value)
— Start loading the URL
set theURL to NSURL’s URLWithString:theURLString set theURLRequest to NSURLRequest’s requestWithURL:theURL tell theWebView’s mainFrame to loadRequest:theURLRequest
webWindow end _DisplayWebWindowWithURL:windowSize:
— The following two handlers exist to deal with running on a background thread. — If we’re on a background thread, we have to run the UI code on the main thread.
on _DisplayWebWindowMainThread:parameterDictionary try set theURLString to parameterDictionary’s objectForKey:"url string" set theWindowSize to parameterDictionary’s objectForKey:"window size"
set webWindow to my _DisplayWebWindowWithURL:theURLString windowSize:theWindowSize
tell parameterDictionary to setObject:webWindow forKey:"result" on error errMsg number errNum using terms from scripting additions display alert "Error!" message errMsg & " (" & errNum & ")" end using terms from tell parameterDictionary to setObject:{errMsg, errNum} forKey:"error" end try end _DisplayWebWindowMainThread:
on display URL theURLString window size theWindowSize — All UI methods must be invoked on the main thread. if (NSThread’s isMainThread) then my _DisplayWebWindowWithURL:theURLString windowSize:theWindowSize else — Parameters, results and error information are communicated between threads via a dictionary. set parameterDictionary to NSMutableDictionary’s dictionary() tell parameterDictionary to setObject:theURLString forKey:"url string" tell parameterDictionary to setObject:theWindowSize forKey:"window size"
its performSelectorOnMainThread:"_DisplayWebWindowMainThread:" withObject:parameterDictionary waitUntilDone:true
— Propagate errors from the other thread
set errInfo to parameterDictionary’s objectForKey:"error" if errInfo is not missing value then error errInfo’s first item number errInfo’s second item
parameterDictionary’s objectForKey:"result" end if end display URL
— — AppDelegate.applescript — keyEvents — — Created by Takaaki Naganoya on 2014/05/09. — Copyright (c) 2014年 Takaaki Naganoya. All rights reserved. —
script AppDelegate property parent : class "NSObject"
— IBOutlets property theWindow : missing value property aButton : missing value
property xMax : 500 property yMax : 500
property aStep : 50
on applicationWillFinishLaunching:aNotification — end applicationWillFinishLaunching:
on applicationShouldTerminate:sender return current application’s NSTerminateNow end applicationShouldTerminate:
on buttonMove:(aCode as integer) set curFrame to aButton’s frame() copy curFrame to {{x, y}, {xWidth, yHeight}}
if aCode = 123 then –Left if x > 0 then set x to x – aStep end if else if aCode = 124 then –Right if x < xMax then set x to x + aStep end if
else if aCode = 126 then –Up if y < yMax then set y to y + aStep end if
else if aCode = 125 then –Down if y > 10 then set y to y – aStep end if else if aCode = 125 then
end if
set newRect to {{x, y}, {xWidth, yHeight}} aButton’s setFrame:newRect aButton’s setNeedsDisplay() end buttonMove: end script
— set up alert set theAlert to NSAlert’s alloc()’s init() tell theAlert its setMessageText:aMainMes
repeat with i in bList (its addButtonWithTitle:i) end repeat end tell
— show alert in modal loop NSRunningApplication’s currentApplication()’s activateWithOptions:0 my performSelectorOnMainThread:"doModal:" withObject:(theAlert) waitUntilDone:true
set aBID to bLen – ((my returnCode) – 1000 + 1) + 1 set my theResult to aBID end dispAlert:
on doModal:aParam set (my returnCode) to aParam’s runModal() end doModal:
— — AppDelegate.applescript — GUI Animation — — Created by Takaaki Naganoya on 2017/02/13. — Copyright 2017 Takaaki Naganoya. All rights reserved. — — http://liu044100.blogspot.jp/2013/07/cabasicanimation.html script AppDelegate property parent : class "NSObject"
— IBOutlets property theWindow : missing value property aPopup : missing value
property gui1 : missing value property gui2 : missing value property gui3 : missing value property gui4 : missing value property gui5 : missing value property gui6 : missing value property gui7 : missing value property gui8 : missing value property gui9 : missing value property guiA : missing value property guiB : missing value property guiC : missing value
on applicationWillFinishLaunching:aNotification — Insert code here to initialize your application before any files are opened end applicationWillFinishLaunching:
on applicationShouldTerminate:sender return current application’s NSTerminateNow end applicationShouldTerminate:
on clicked:sender set aInd to aPopup’s indexOfSelectedItem() set guiList to {gui1, gui2, gui3, gui4, gui5, gui6, gui7, gui8, gui9, guiA, guiB, guiC} repeat with i in guiList if aInd = 0 then (my blinkObject:i) else if aInd = 1 then (my scaleObject:i) else if aInd = 2 then (my rotateObject:i forAxis:"x") else if aInd = 3 then (my rotateObject:i forAxis:"y") else if aInd = 4 then (my rotateObject:i forAxis:"z") else if aInd = 5 then (my moveObject:i) else if aInd = 6 then –my mixtureAnimeObject:i end if delay 0.1 end repeat end clicked:
on blinkObject:aObject set animation to current application’s CABasicAnimation’s animationWithKeyPath:"opacity" animation’s setDuration:0.1 animation’s setAutoreverses:true animation’s setRepeatCount:4 animation’s setFromValue:(current application’s NSNumber’s numberWithFloat:1.0) animation’s setToValue:(current application’s NSNumber’s numberWithFloat:0.0) aObject’s layer()’s addAnimation:animation forKey:"blink" end blinkObject:
on scaleObject:aObject set animation to current application’s CABasicAnimation’s animationWithKeyPath:"transform.scale" animation’s setDuration:0.1 animation’s setAutoreverses:true animation’s setRepeatCount:2 animation’s setFromValue:(current application’s NSNumber’s numberWithFloat:1.0) animation’s setToValue:(current application’s NSNumber’s numberWithFloat:2.0) aObject’s layer()’s addAnimation:animation forKey:"scale-layer" end scaleObject:
on rotateObject:aObject forAxis:anAxis set animation to current application’s CABasicAnimation’s animationWithKeyPath:("transform.rotation." & anAxis) animation’s setDuration:2.0 –animation’s setAutoreverses:false animation’s setRepeatCount:1 animation’s setFromValue:(current application’s NSNumber’s numberWithFloat:0.0) animation’s setToValue:(current application’s NSNumber’s numberWithFloat:4.0 * 3.1415926) aObject’s layer()’s addAnimation:animation forKey:"rotate-layer" end rotateObject:forAxis:
on moveObject:aObject set aFrame to aObject’s frame() copy aFrame to {{fx1, fy1}, {fx2, fy2}} set animation to current application’s CABasicAnimation’s animationWithKeyPath:"position" animation’s setDuration:0.4 animation’s setAutoreverses:false animation’s setRepeatCount:1 animation’s setFromValue:(current application’s NSValue’s valueWithCGRect:(aObject’s frame())) animation’s setToValue:(current application’s NSValue’s valueWithCGRect:(current application’s CGRectMake(100, 100, fx2, fy2))) aObject’s layer()’s addAnimation:animation forKey:"move-layer" end moveObject:
–Not Work Yet….. (* on mixtureAnimeObject:aObject set animation1 to current application’s CABasicAnimation’s animationWithKeyPath:"transform.translation.x" animation1’s setToValue:(current application’s NSNumber’s numberWithFloat:80.0) animation1’s setDuration:3.0
set animation2 to current application’s CABasicAnimation’s animationWithKeyPath:"transform.rotation.z" animation2’s setFromValue:(current application’s NSNumber’s numberWithFloat:0.0) animation2’s setToValue:(current application’s NSNumber’s numberWithFloat:4.0 * 3.1415926) animation2’s setDuration:3.0
set aGroup to current application’s CAAnimationGroup’s animation() aGroup’s setDuration:3.0 aGroup’s setRepeatCount:1.0 aGroup’s setAnimations:(current application’s NSArray’s arrayWithObjects:{animation1, animation2, missing value}) aObject’s layer()’s addAnimation:aGroup forKey:"move-rotate-layer" end mixtureAnimeObject: *) end script
tell application "Numbers" tell document docName tell active sheet tell table 1 repeat with i from 1 to aLen tell row (i + 1) set aRowList to contents of item i of aList repeat with ii from 1 to aWidth tell cell ii set aTmpData to contents of item ii of aRowList ignoring application responses set value to aTmpData end ignoring end tell end repeat end tell end repeat end tell end tell end tell end tell end fillCurrentTable
–Numbersでオープン中の書類の名称一覧からデータ取得元とデータ集約先の書類名をダイアログで選択 on getTargetDocNames() tell application "Numbers" set nList to name of every document end tell
set selList to {nList, nList} set tList to {"データ取得元", "データ集約先"}
set {aRes, bRes} to choose multiple list selList main message "各Numbers書類の役割を選択してください" sub message "「データ取得元」のデータを順次、「データ集約先」の表1に連結します" with title lists tList height 140 width 400 return type item contents without allow same items return {aRes, bRes} end getTargetDocNames
–Numbersでオープン中の書類の選択中のシートの表1からデータを取得して2D Listに on getDataFromNumbersDoc(aDocName, sheetName)
load framework
tell application "Numbers" if (count (every document)) = 0 then return false
tell document aDocName if (count (every sheet)) = 0 then return false
tell sheet sheetName tell table 1 set colCount to column count set rowCount to row count set headerCount to header row count set footerCount to footer row count
set dList to value of every cell of cell range end tell end tell
end tell end tell
–Convert 1D List to 2D List set bList to (current application’s SMSForder’s subarraysFrom:dList groupedBy:colCount |error|:(missing value)) as list set sItem to 1 + headerCount set eItem to rowCount – footerCount set cList to items sItem thru eItem of bList
use dropLib : script "display drop dialog"
set aMainMes to "Drop AppleScript" set aSubMes to "Drag and Drop AppleScript files here" set aUTI to "com.apple.applescript.script" set execButtonTitle to "Execute" set aRes to (display drop dialog aUTI main message aMainMes sub message aSubMes with initial folder "" OK button title execButtonTitle) –> {alias "Machintosh HD:Users:me:Documents:display drop dialog:accept PNG images.scpt", alias "Machintosh HD:Users: me:Documentsaccept Markdown documents.scpt"}
use dropLib : script "display drop dialog"
set aMainMes to "Drop Markdown Documents" set aSubMes to "Drag and Drop Markdown documents here" set aUTI to "net.daringfireball.markdown" set execButtonTitle to "Execute" set aRes to (display drop dialog aUTI main message aMainMes sub message aSubMes with initial folder "" OK button title execButtonTitle) –> {alias "Machintosh HD:Users:me:Documents::–Book 11 「Blog Archives vol5 2013-2014」:2013:01:201301013.md", alias "Machintosh HD:Users:me:Documents::–Book 11 「Blog Archives vol5 2013-2014」:2013:01:201301012.md"}
AppleScript名:accept PNG images with initial folder contents
use scripting additions use dropLib : script "display drop dialog"
set aMainMes to "Drop PNG" set aSubMes to "Drag and Drop png images here" set aUTI to "public.png" set execButtonTitle to "Execute" set iFolder to path to pictures folder –At first, PNG files in this folder is displayed set aRes to (display drop dialog aUTI main message aMainMes sub message aSubMes with initial folder iFolder OK button title execButtonTitle) –> {alias "Machintosh HD:Users:me:Pictures:1015sedhelp2.png", alias "Machintosh HD:Users:me:Pictures:574G01.png", alias "Machintosh HD:Users:me:Pictures:macDown1.png", alias "Machintosh HD:Users:me:Pictures: 2017-09-27 19.33.53.png", alias "Machintosh HD:Users:me:Pictures:2018-11-01 10.54.06.png"
use AppleScript version "2.4" — Yosemite (10.10) or later use framework "Foundation" use framework "AppleScriptObjC" use scripting additions
on run my main() end run on main() # Script Bundle内のResourcesフォルダを求める set resourcePath to POSIX path of (path to me) & "Contents/Resources/" set theBundle to current application’s NSBundle’s bundleWithPath:resourcePath theBundle’s loadAppleScriptObjectiveCScripts()
# set aFolder to path to applications folder set aPath to aFolder’s POSIX path set aURL to current application’s NSURL’s fileURLWithPath:aPath
# 指定フォルダの直下のファイルを取得 set filePaths to current application’s NSFileManager’s defaultManager’s ¬ contentsOfDirectoryAtURL:aURL ¬ includingPropertiesForKeys:{current application’s NSURLNameKey} ¬ options:(current application’s NSDirectoryEnumerationSkipsHiddenFiles) ¬ |error|:(missing value)
set filePaths to filePaths as list set thisFileType to "com.apple.application-bundle"
set fileURLs to {} repeat with anItem in filePaths
set aPath to anItem’s contents’s POSIX path set aURL to (current application’s NSURL’s fileURLWithPath:aPath)
set {aResult, aUTI, aError} to (aURL’s getResourceValue:(reference) ¬ forKey:(current application’s NSURLTypeIdentifierKey) ¬ |error|:(reference))
if (aUTI as text) is thisFileType then set fileURLs’s end to aURL end if end repeat
set optionRec to {fileURLs:fileURLs, fileType:thisFileType}
set aMainMes to "アプリケーションの選択" set aSubMes to "適切なものを以下からえらんでください" set dateObj to my chooseItemByTableView(aMainMes, aSubMes, optionRec) end main
# アラートダイアログでtableviewを表示 on chooseItemByTableView(aMainMes, aSubMes, optionRec) ### set up view set {theView, makeObj} to my makeContentView(optionRec)
set paramObj to {myMessage:aMainMes, mySubMessage:aSubMes, setView:theView, myOption:makeObj} my performSelectorOnMainThread:"raizeAlert:" withObject:paramObj waitUntilDone:true
if (my _retrieve_data) is missing value then error number -128 return (my _retrieve_data) end chooseItemByTableView
## retrieve date on raizeAlert:paramObj set mesText to paramObj’s myMessage set infoText to paramObj’s mySubMessage set theView to paramObj’s setView set aTableObj to paramObj’s myOption
global _retrieve_data set _retrieve_data to missing value
### 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 set aIndexSet to aTableObj’s selectedRowIndexes()
set chooseItems to ((aTableObj’s dataSource())’s arrangedObjects()’s objectsAtIndexes:aIndexSet) as list set _retrieve_data to {} repeat with anItem in chooseItems set _retrieve_data’s end to anItem’s fileURL end repeat end raizeAlert:
## ContentView を作成 on makeContentView(paramObj) ## 準備 set fileURLs to (paramObj’s fileURLs) as list set thisFileType to (paramObj’s fileType) as text
set keyrec to {column1:"Name"} set keyDict to (current application’s NSDictionary’s dictionaryWithDictionary:keyrec)
set theDataSource to current application’s YKZArrayController’s new()
set thisRowHeight to rowHeight() as integer set theDataSource’s _table_view to it end tell end tell
# data sourceに追加 tell (theDataSource) awakeFromNib() set its _file_type to thisFileType
repeat with aURL in fileURLs addObject_({fileURL:aURL}) end repeat
setSelectionIndex_(0) end tell
## NSTableColumn ### Columnの並び順を指定する set viewWidth to 320 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
### Columnの横幅を指定 setWidth_(viewWidth)
### バインディングのオプション — ソートを無効にする set anObj to (current application’s NSNumber’s numberWithBool:false) set aKey to current application’s NSCreatesSortDescriptorBindingOption set bOptions to (current application’s NSDictionary’s dictionaryWithObject:anObj forKey:aKey)
(theDataSource’s _table_view’s addTableColumn:it) end tell
end repeat
## NSScrollView ### Viewの高さを計算 set rowCount to 12 –> 行数を固定 set viewHeight to (thisRowHeight + 2) * rowCount + thisHeaderHeight –> 2を足さないと高さが合わない set vSize to current application’s NSMakeRect(0, 0, viewWidth, viewHeight)
### Viewを作成 tell current application’s NSScrollView’s alloc() tell initWithFrame_(vSize) setBorderType_(current application’s NSBezelBorder) setDocumentView_(theDataSource’s _table_view) –setHasHorizontalScroller_(true) setHasVerticalScroller_(true) set aScroll to it end tell end tell
return {aScroll, theDataSource’s _table_view} end makeContentView
#MARK: – NSValueTransformer script YKZURLToIcon property parent : class "NSValueTransformer" property allowsReverseTransformation : false –>逆変換 property transformedValueClass : a reference to current application’s NSImage –>クラス
#変換処理 on transformedValue:fileURL if fileURL is missing value then return
set appPath to fileURL’s |path|() set iconImage to current application’s NSWorkspace’s sharedWorkspace’s iconForFile:appPath return iconImage end transformedValue: end script
script YKZURLToDisplayedName property parent : class "NSValueTransformer" property allowsReverseTransformation : false –>逆変換 property transformedValueClass : a reference to current application’s NSString –>クラス
#変換処理 on transformedValue:fileURL if fileURL is missing value then return
set appPath to fileURL’s |path|() set displayedName to current application’s NSFileManager’s defaultManager’s displayNameAtPath:appPath return displayedName end transformedValue: end script
#MARK: – Array Controller script YKZArrayController property parent : class "NSArrayController"
#MARK: IBOutlets property _table_view : missing value #MARK: property _data_type : do shell script "uuidgen" property _file_type : ""
on awakeFromNib() –log "YKZArrayController – awakeFromNib" tell _table_view registerForDraggedTypes_({current application’s NSFilenamesPboardType, _data_type}) setDraggingSourceOperationMask_forLocal_(current application’s NSDragOperationCopy, false) end tell
#Transformerの登録 set tNames to {} set tNames’s end to "YKZURLToIcon" set tNames’s end to "YKZURLToDisplayedName" repeat with aTransformer in tNames set theTransformer to current application’s class aTransformer’s new() (current application’s NSValueTransformer’s setValueTransformer:theTransformer forName:aTransformer) end repeat end awakeFromNib
#MARK: Data Source Overrides on numberOfRowsInTableView:aTableView return my content()’s |count|() end numberOfRowsInTableView:
on tableView:aTableView viewForTableColumn:aColumn row:aRow –log "viewForTableColumn"
set aCellView to aTableView’s makeViewWithIdentifier:"YKZTableCellView" owner:me –set isNull to aCellView’s isEqual:(current application’s NSNull’s |null|()) –log isNull as text
if aCellView is missing value then
set frameRect to current application’s NSMakeRect(0, 0, aColumn’s width, aTableView’s rowHeight()) set aCellView to current application’s YKZTableCellView’s alloc’s initWithFrame:frameRect
set anObj to "YKZURLToIcon" set aKey to current application’s NSValueTransformerNameBindingOption set bOptions to (current application’s NSDictionary’s dictionaryWithObject:anObj forKey:aKey) (aCellView’s imageView())’s bind:(current application’s NSValueBinding) toObject:aCellView withKeyPath:"objectValue.fileURL" options:bOptions
set anObj to "YKZURLToDisplayedName" set aKey to current application’s NSValueTransformerNameBindingOption set bOptions to (current application’s NSDictionary’s dictionaryWithObject:anObj forKey:aKey) (aCellView’s textField())’s bind:(current application’s NSValueBinding) toObject:aCellView withKeyPath:"objectValue.fileURL" options:bOptions
end if
return aCellView end tableView:viewForTableColumn:row:
# テーブル内のセルが編集できるか on tableView:aTableView shouldEditTableColumn:aColumn row:aRow return false end tableView:shouldEditTableColumn:row:
# テーブル内をダブルクリックしたらOKボタンを押す on doubleAction:sender log "doubleAction" ## ヘッダをクリックした時は何もしない if (sender’s clickedRow()) is -1 then return
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:
#MARK: Drag Operation Method #ドラッグを開始(ペーストボードに書き込む) on tableView:aTableView writeRowsWithIndexes:rowIndexes toPasteboard:pboard –log "writeRowsWithIndexes" set aData to current application’s NSKeyedArchiver’s archivedDataWithRootObject:rowIndexes pboard’s declareTypes:{_data_type} owner:(missing value) pboard’s setData:aData forType:_data_type return true end tableView:writeRowsWithIndexes:toPasteboard: #ドラッグ途中 on tableView:aTableView validateDrop:info proposedRow:row proposedDropOperation:operation –log "validateDrop" #列の間にドラッグ if (operation is current application’s NSTableViewDropAbove) then return current application’s NSDragOperationMove end if #項目の上にドラッグ set aTypes to info’s draggingPasteboard’s types() if (aTypes’s containsObject:_data_type) as boolean then return current application’s NSDragOperationNone end if return current application’s NSDragOperationNone end tableView:validateDrop:proposedRow:proposedDropOperation: #ドラッグ終了 on tableView:aTableView acceptDrop:info row:row dropOperation:operation –log "acceptDrop" # set pboard to info’s draggingPasteboard() set aTypes to pboard’s types()
if (aTypes’s containsObject:_data_type) as boolean then
set rowData to pboard’s dataForType:_data_type set rowIndexes to current application’s NSKeyedUnarchiver’s unarchiveObjectWithData:rowData
if (rowIndexes’s firstIndex()) < row then set row to row – (rowIndexes’s |count|()) end if
set aRange to current application’s NSMakeRange(row, rowIndexes’s |count|()) set aIndexSet to current application’s NSIndexSet’s indexSetWithIndexesInRange:aRange
set anObj to ((my content())’s objectsAtIndexes:rowIndexes) my removeObjects:anObj my insertObjects:anObj atArrangedObjectIndexes:aIndexSet my rearrangeObjects()
else set pathList to pboard’s propertyListForType:(current application’s NSFilenamesPboardType) –log result as list repeat with aPath in pathList set isAdd to addItem_({filePath:aPath, atIndex:row}) if isAdd then beep end repeat
end if return true end tableView:acceptDrop:row:dropOperation:
#追加する on addItem:sender –> {filePath:aPath, atIndex:aIndex} –log "addItem:" set isAdd to false
#missing valueの時は最後に追加 set {filePath:aPath, atIndex:aIndex} to sender if aIndex is missing value then set aIndex to my content()’s |count|() as number end if
#URLに変換 set appURL to (current application’s NSURL’s fileURLWithPath:aPath) #アプリケーション以外は追加しない set {aResult, aUTI, aError} to (appURL’s getResourceValue:(reference) ¬ forKey:(current application’s NSURLTypeIdentifierKey) ¬ |error|:(reference)) log aUTI if (aUTI as text) is not (my _file_type as text) then return isAdd
#すでにあるか確認 set bList to my content() as list repeat with aRecord in bList if ((appURL’s isEqual:(aRecord’s fileURL)) as boolean) then set isAdd to true exit repeat end if end repeat
#なければ追加 if not isAdd then set anObj to {fileURL:appURL} (my insertObject:anObj atArrangedObjectIndex:aIndex) end if return isAdd end addItem: end script
#MARK: – NSTableCellView script YKZTableCellView property parent : class "NSTableCellView"
on initWithFrame:rect –log "initWithFrame" continue initWithFrame:rect
— – Created by: Edama2 2020/01/10 – Adviced by: Shane Stanley 2020/01/11 – Modified by: Takaaki Naganoya 2020/01/12 — use AppleScript version "2.4" — Yosemite (10.10) or later use framework "Foundation" use framework "AppleScriptObjC" use scripting additions
property _clock_text_view : missing value –> 時計用の文字列 property _clock_timer : missing value –> 時計用のNSTimer
–Script Bundle内のResourcesフォルダを求める set resourcePath to POSIX path of (path to me) & "Contents/Resources/" set theBundle to current application’s NSBundle’s bundleWithPath:resourcePath theBundle’s loadAppleScriptObjectiveCScripts()
my performSelectorOnMainThread:"raizeWindow:" withObject:(missing value) waitUntilDone:true
# ウィンドウを作成 on raizeWindow:aParam
# 時計を更新するNSTimerを作成 set my _clock_timer to current application’s NSTimer’s scheduledTimerWithTimeInterval:1 target:me selector:"idleHandler:" userInfo:(missing value) repeats:true
# 丸いViewを作成 set aFrame to current application’s NSMakeRect(0, 0, 300, 300) tell current application’s RoundView’s alloc() tell initWithFrame_(aFrame) setNeedsDisplay_(true) setSubviews_({my _clock_text_view}) set customView to it end tell end tell
#スクリーンのサイズを調べる set aScreen to current application’s NSScreen’s mainScreen()
# Window set aBacking to current application’s NSWindowStyleMaskBorderless –set aBacking to current application’s NSBorderlessWindowMask set aDefer to current application’s NSBackingStoreBuffered
# |center|() makeKeyAndOrderFront_(me) –>キーウインドウにして前面に持ってくる –setFrame_display_(aFrame, true) –>表示 end tell end tell end raizeWindow:
#タイマー割り込み on idleHandler:aSender set mesStr to time string of (current date) (my _clock_text_view)’s setString:mesStr end idleHandler:
script CocoaAppletAppDelegate property parent : class "NSObject"
on applicationWillFinishLaunching:aNotification — end applicationWillFinishLaunching:
on applicationShouldTerminate:sender return current application’s NSTerminateNow end applicationShouldTerminate:
end script
script CustomWindow property parent : class "NSWindow" property canBecomeKeyWindow : true
property _initial_location : missing value
on mouseDown:theEvent set my _initial_location to theEvent’s locationInWindow() end mouseDown:
on mouseDragged:theEvent –set res to display dialog "mouseDragged" buttons {"OK"} default button "OK" try set screenVisibleFrame to current application’s NSScreen’s mainScreen()’s visibleFrame() set screenVisibleFrame to my myHandler(screenVisibleFrame) set windowFrame to my frame() set windowFrame to my myHandler(windowFrame) set newOrigin to windowFrame’s origin
set currentLocation to theEvent’s locationInWindow() set newOrigin’s x to (newOrigin’s x) + ((currentLocation’s x) – (_initial_location’s x)) set newOrigin’s y to (newOrigin’s y) + ((currentLocation’s y) – (_initial_location’s y))
set tmpY to ((newOrigin’s y) + (windowFrame’s |size|’s height)) set screenY to (screenVisibleFrame’s origin’s y) + (screenVisibleFrame’s |size|’s height) if tmpY > screenY then set newOrigin’s y to (screenVisibleFrame’s origin’s y) + ((screenVisibleFrame’s |size|’s height) – (windowFrame’s |size|’s height)) end if
my setFrameOrigin:newOrigin on error error_message number error_number set error_text to "Error: " & error_number & ". " & error_message display dialog error_text buttons {"OK"} default button 1 return error_text end try
end mouseDragged:
on myHandler(aFrame) if class of aFrame is list then set {{theX, theY}, {theWidth, theHeight}} to aFrame set aFrame to {origin:{x:theX, y:theY}, |size|:{width:theWidth, height:theHeight}} –set aFrame to current application’s NSMakeRect(theX, theY, theWidth, theHeight) end if return aFrame end myHandler end script
script RoundView property parent : class "NSView"
on drawRect:rect set aFrame to my frame() set myColor to current application’s NSColor’s redColor()
tell current application’s NSBezierPath tell bezierPathWithOvalInRect_(aFrame) myColor’s |set|() fill() end tell end tell end drawRect: end script
# 時計を更新するNSTimerを作成 set my _clock_timer to current application’s NSTimer’s scheduledTimerWithTimeInterval:1 target:me selector:"idleHandler:" userInfo:(missing value) repeats:true
# 丸いViewを作成 set aFrame to current application’s NSMakeRect(0, 0, 300, 300) tell current application’s RoundView’s alloc() tell initWithFrame_(aFrame) setNeedsDisplay_(true) setSubviews_({my _clock_text_view}) set customView to it end tell end tell
#スクリーンのサイズを調べる set aScreen to current application’s NSScreen’s mainScreen()
# Window set aBacking to current application’s NSWindowStyleMaskBorderless –set aBacking to current application’s NSBorderlessWindowMask set aDefer to current application’s NSBackingStoreBuffered tell current application’s CustomWindow’s alloc() tell initWithContentRect_styleMask_backing_defer_screen_(aFrame, aBacking, aDefer, false, aScreen) –setTitle_(uniqueName) –>タイトル setBackgroundColor_(current application’s NSColor’s clearColor()) –>背景色 setContentView_(customView) –>内容ビューのセット setDelegate_(me) –>デリゲート setDisplaysWhenScreenProfileChanges_(true) –>スクリーンプロファイルが変更されたときウインドウの内容をアップデートするか setHasShadow_(true) –>ウインドウに影があるか setIgnoresMouseEvents_(false) –>マウスイベントを無視するか –setLevel_((current application’s NSScreenSaverWindowLevel) + 1) –>ウインドウの前後関係の位置 setOpaque_(false) –>ウインドウを不透明にするか setReleasedWhenClosed_(true) –>閉じたときにメモリを解放するか
# |center|() makeKeyAndOrderFront_(me) –>キーウインドウにして前面に持ってくる –setFrame_display_(aFrame, true) –>表示 end tell end tell end raizeWindow
#タイマー割り込み on idleHandler:aSender set mesStr to time string of (current date) (my _clock_text_view)’s setString:mesStr end idleHandler: end script
script CustomWindow property parent : class "NSWindow" property canBecomeKeyWindow : true
property _initial_location : missing value
on mouseDown:theEvent set my _initial_location to theEvent’s locationInWindow() end mouseDown:
on mouseDragged:theEvent –set res to display dialog "mouseDragged" buttons {"OK"} default button "OK" try set screenVisibleFrame to current application’s NSScreen’s mainScreen()’s visibleFrame() set screenVisibleFrame to my myHandler(screenVisibleFrame) set windowFrame to my frame() set windowFrame to my myHandler(windowFrame) set newOrigin to windowFrame’s origin
set currentLocation to theEvent’s locationInWindow() set newOrigin’s x to (newOrigin’s x) + ((currentLocation’s x) – (_initial_location’s x)) set newOrigin’s y to (newOrigin’s y) + ((currentLocation’s y) – (_initial_location’s y))
set tmpY to ((newOrigin’s y) + (windowFrame’s |size|’s height)) set screenY to (screenVisibleFrame’s origin’s y) + (screenVisibleFrame’s |size|’s height) if tmpY > screenY then set newOrigin’s y to (screenVisibleFrame’s origin’s y) + ((screenVisibleFrame’s |size|’s height) – (windowFrame’s |size|’s height)) end if
my setFrameOrigin:newOrigin on error error_message number error_number set error_text to "Error: " & error_number & ". " & error_message display dialog error_text buttons {"OK"} default button 1 return error_text end try
end mouseDragged:
on myHandler(aFrame) if class of aFrame is list then set {{theX, theY}, {theWidth, theHeight}} to aFrame set aFrame to {origin:{x:theX, y:theY}, |size|:{width:theWidth, height:theHeight}} –set aFrame to current application’s NSMakeRect(theX, theY, theWidth, theHeight) end if return aFrame end myHandler end script
script RoundView property parent : class "NSView"
on drawRect:rect set aFrame to my frame() set myColor to current application’s NSColor’s redColor()
tell current application’s NSBezierPath tell bezierPathWithOvalInRect_(aFrame) myColor’s |set|() fill() end tell end tell end drawRect: end script
— Created 2016-01-08 by Takaaki Naganoya — 2016 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" use framework "OSAKit" use framework "AppKit" use tfLib : script "display text fields"
property OSAScript : a reference to current application’s OSAScript property NSTextView : a reference to current application’s NSTextView property OSAScriptView : a reference to current application’s OSAScriptView property OSAScriptController : a reference to current application’s OSAScriptController
property myRes : ""
–OSのメジャーバージョンを数値で取得 set osVer to system attribute "sys2"
if osVer ≥ 15 then set srcStr to "tell application \"Music\" set aSel to first item of selection set aRes to (properties of aSel) end tell" else set srcStr to "tell application \"iTunes\" set aSel to first item of selection set aRes to (properties of aSel) end tell" end if
my performSelectorOnMainThread:"getResultStringFromScript:" withObject:(srcStr) waitUntilDone:true
set aRes to getListFromText(myRes) of me
set aList to {} set bList to {} set aLen to length of aRes
repeat with i from 1 to aLen set {aCon, bCon} to contents of item i of aRes set the end of aList to aCon set the end of bList to bCon end repeat
confirm text fields main message "Track Info" sub message "Properties about selected track" key list aList value list bList
–Get AppleScript’s Result as string on getResultStringFromScript:paramObj set srcStr to paramObj as string set myRes to ""
set targX to 500 –View Width set targY to 200 –View Height
set osaCon to OSAScriptController’s alloc()’s init() set osaView to OSAScriptView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, targX, targY))
set resView to NSTextView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, targX, targY)) resView’s setRichText:true resView’s useAllLigatures:true
set (gList of getListFromTextO) to {} set (outList of getListFromTextO) to {} set (aG of getListFromTextO) to "" set (valList of getListFromTextO) to {}
if (aaText of getListFromTextO) does not start with "{" and (aaText of getListFromTextO) does not end with "}" then return {} end if
set aLen to length of (aaText of getListFromTextO) set (aG of getListFromTextO) to text 2 thru -2 of (aaText of getListFromTextO) set (gList of getListFromTextO) to characters of (aG of getListFromTextO)
set sPos to 2 –1文字目は\"{\"なので2文字目からスキャンを開始する set ePos to 2
set imdF to false –Immediate Data Flag(文字列中を示すダブルクォート内の場合にはtrueになる) set listF to 0 –stacking段数が入る
set attrF to true –属性ラベルスキャン時にtrue、データ末尾スキャン時にfalse
repeat with i in (gList of getListFromTextO)
set j to contents of i
if attrF = true and imdF = false and listF = 0 then
–属性値部分の末尾検出 if j = ":" then if text sPos thru sPos of (aaText of getListFromTextO) = " " then set sPos to sPos + 1 end if set anOut to text sPos thru ePos of (aaText of getListFromTextO) set sPos to ePos + 1 set the end of (valList of getListFromTextO) to anOut set attrF to false –データのスキャンを開始する set imdF to false set listF to 0 end if
else if imdF = false and listF = 0 and j = "," then
–データ部分の末尾検出 set anOut to text sPos thru (ePos – 1) of (aaText of getListFromTextO) set sPos to ePos + 1 set the end of (valList of getListFromTextO) to anOut set the end of (outList of getListFromTextO) to (valList of getListFromTextO) set (valList of getListFromTextO) to {}
set attrF to true –次が属性値ラベルであることを宣言 set imdF to false set listF to 0
else if j = "{" then if imdF = false then set listF to listF + 1 –1段スタックにpush end if else if j = "}" then if imdF = false then set listF to listF – 1 –1段スタックからpop end if else if j = "\"" then if imdF = true then set imdF to false else set imdF to true end if end if
set ePos to ePos + 1
end repeat
–ラストのデータ部分を出力 try set the end of (valList of getListFromTextO) to text sPos thru (ePos – 1) of (aaText of getListFromTextO) set the end of (outList of getListFromTextO) to (valList of getListFromTextO) on error false end try
display dialogは手軽であるもののモーダルなダイアログなので、その後のMac OS Xへの移行時にはいまひとつ合わない感じがしていました。完全にMac OS Xの流儀で書き直されたのが、「display alert」ダイアログです。こちらもモーダル表示ですが、見た目は少しMac OS Xらしく変更されました。
非モーダル表示なUIについては、display notificationで通知表示が使えるようになり、これで一応の解決を見たというところでしょうか。こういう動作をする通知ダイアログは、Newt On Projectの中で「どうしても欲しい」という要望が出て、2000年代初頭にすでに仲間内で作ってもらったものがあり、AppleScriptから半透明のダイアログ(画面右側からスライドアニメーション表示)を表示させていました。
— Created 2019-12-26 by Takaaki Naganoya — 2019 Piyomaru Software use AppleScript version "2.5" use scripting additions use framework "Foundation" use framework "AppKit"
property NSAlert : a reference to current application’s NSAlert property NSRunningApplication : a reference to current application’s NSRunningApplication
property returnCode : 0
set paramObj to {myMessage:"アラート表示", mySubMessage:"アラートダイアログを表示します", myTitle:"たいとる?"} set dRes to displayAlert(paramObj) of me
on displayAlert(paramObj) my performSelectorOnMainThread:"displayAlertDialog:" withObject:(paramObj) waitUntilDone:true if (my returnCode as number) = 1001 then error number -128 return true end displayAlert
on displayAlertDialog:paramObj set aMainMes to myMessage of paramObj set aSubMes to mySubMessage of paramObj set aTitle to myTitle of paramObj
— 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" set myWin to its |window| end tell
myWin’s setTitle:aTitle
— show alert in modal loop NSRunningApplication’s currentApplication()’s activateWithOptions:0 my performSelectorOnMainThread:"doModal:" withObject:(theAlert) waitUntilDone:true
return (aScrollWithTable’s documentView’s selectedRow()) + 1 end displayAlertDialog:
on doModal:aParam set (my returnCode) to aParam’s runModal() end doModal:
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 property _data_type : (current date) as text –do shell script "uuidgen" –>ユニークな文字列ならなんでもいい? 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 (my _data_source)’s setSelectionIndex:0
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 sortDescriptor to (current application’s NSSortDescriptor’s sortDescriptorWithKey:aTitle ascending:true selector:"compare:") setSortDescriptorPrototype_(sortDescriptor)
### 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 date on retrieveData(aTableObj) set aIndexSet to aTableObj’s selectedRowIndexes() set my _retrieve_data to ((my _data_source)’s arrangedObjects()’s objectsAtIndexes:aIndexSet) as list –setSelectionIndexes:aIndexSet log result 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 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 ## ヘッダをクリックした時は何もしない if (sender’s clickedRow()) is -1 then return
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:
# Drag Operation Method ## ドラッグを開始(ペーストボードに書き込む) on tableView:aTableView writeRowsWithIndexes:rowIndexes toPasteboard:pboard –log "writeRowsWithIndexes" set aData to current application’s NSKeyedArchiver’s archivedDataWithRootObject:rowIndexes pboard’s declareTypes:{my _data_type} owner:(missing value) pboard’s setData:aData forType:(my _data_type) return true end tableView:writeRowsWithIndexes:toPasteboard: ## ドラッグ途中 on tableView:aTableView validateDrop:info proposedRow:row proposedDropOperation:operation –log "validateDrop" ### 列の間にドラッグ if (operation is current application’s NSTableViewDropAbove) then return current application’s NSDragOperationMove end if ### 項目の上にドラッグ set aTypes to info’s draggingPasteboard’s types() if (aTypes’s containsObject:(my _data_type)) as boolean then return current application’s NSDragOperationNone end if return current application’s NSDragOperationNone end tableView:validateDrop:proposedRow:proposedDropOperation: ## ドラッグ終了 on tableView:aTableView acceptDrop:info row:row dropOperation:operation –log "acceptDrop" set pboard to info’s draggingPasteboard()
set rowData to pboard’s dataForType:(my _data_type) set rowIndexes to current application’s NSKeyedUnarchiver’s unarchiveObjectWithData:rowData
if (rowIndexes’s firstIndex()) < row then set row to row – (rowIndexes’s |count|()) end if
set aRange to current application’s NSMakeRange(row, rowIndexes’s |count|()) set aIndexSet to current application’s NSIndexSet’s indexSetWithIndexesInRange:aRange
tell my _data_source set anObj to content()’s objectsAtIndexes:rowIndexes removeObjects_(anObj) insertObjects_atArrangedObjectIndexes_(anObj, aIndexSet) rearrangeObjects() end tell return true end tableView:acceptDrop:row:dropOperation: end script
## tell (make MyDialog) return call(aMainMes, aSubMes, optionRec) end tell end chooseData
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
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
— 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
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
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
— 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
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"))
–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
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
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 & " &"