Menu

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

AppleScriptの穴

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

タグ: 10.13savvy

AppleScriptでキースキャン

Posted on 2月 26, 2020 by Takaaki Naganoya

Xcode上で作成するAppleScript Cocoa Applicationで、キースキャンを試してみました。

ふだん作っているものだと、各種パラメータをGUI上で設定する程度のもので、キースキャンを行う必要などこれっぽっちもないのですが、いま作っているアプリケーションでキースキャンが必要になってしまったので、昔作ったものを引っ張り出してきました。

AppleScriptのプログラムでキースキャンを行うといえば、AppleScript Appletの起動時に何らかのModifier Keys(ShiftとかOptionとかCommandとかControlとか)が押されていることを検出して動作を変更するといった処理が一般的です。ループ処理中でも、これらのキー入力を定期的に監視することはよく行なっています(処理中に停止したいという要求はあるので)。

–> Watch Demo Movie

–> Download Xcode Project Archive

本プログラムでは、Modifier Keysにかぎらずキーボード入力全般を受け付けています。ただし、キースキャン可能なのは本プログラムが最前面にある場合のみです。

掲載しているコードからではわかりませんが、キー入力の受け付けをNSWindowで行なっています。FirstResponderまわりを一切いじくらずにほぼプログラミングなしでキー受け付けを行おうとした結果NSWindowで行うことになったというわけで、これがベストとも思いません。

とりあえず「こうすればできた」というレベルをおさえておいて、そこから自分の好きな方向に機能を変更していけばよいと思います。

AppleScript名:AppDelegate.applescript
—
— 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

★Click Here to Open This Script 

AppleScript名:keyEventWin.applescript
script keyEvWin
  
  
property parent : class "NSWindow"
  
  
property aButton : missing value
  
  
  
on canBecomeKeyWindow:sender
    return true
  end canBecomeKeyWindow:
  
  
on canBecomeMainWindow:sender
    return true
  end canBecomeMainWindow:
  
  
  
on keyDown:theEvent
    set aCode to (theEvent’s keyCode) as integer
    
    
if aCode = 123 then
      –左
      
current application’s NSApp’s delegate()’s performSelector:"buttonMove:" withObject:(aCode)
      
    else if aCode = 124 then
      –右
      
current application’s NSApp’s delegate()’s performSelector:"buttonMove:" withObject:(aCode)
      
    else if aCode = 126 then
      –上
      
current application’s NSApp’s delegate()’s performSelector:"buttonMove:" withObject:(aCode)
      
    else if aCode = 125 then
      –下
      
current application’s NSApp’s delegate()’s performSelector:"buttonMove:" withObject:(aCode)
      
    end if
    
    
  end keyDown:
  
end script

★Click Here to Open This Script 

Posted in AppleScript Application on Xcode GUI | Tagged 10.13savvy 10.14savvy 10.15savvy NSButton NSEvent NSWindow | Leave a comment

指定のNSImageにNSBezierPathでclearColor塗りつぶし

Posted on 2月 14, 2020 by Takaaki Naganoya

指定色で塗りつぶしたNSImageを用意し、そこにNSBezierPathでclearColorで塗りつぶし(=切り抜き)を行うAppleScriptです。

2005/8/18にCocoa-dev mailing list に対してStefan Schüßler氏が投稿した内容をもとにしています。いろいろ探して回りましたが、ヒットしたのはこの情報だけでした。彼に感謝を。

Re: [NSColor clearColor] and NSBezierPath: not compatible?

NSBezierPath uses the NSCompositeSourceOver operation, therefore clearColor does not do anything. You could change the graphics state in order to clear the path:

  NSGraphicsContext *context;
  context = [NSGraphicsContext currentContext];
  [context saveGraphicsState];
  [context setCompositingOperation:NSCompositeClear];
  [yourBezierPath fill];
  [context restoreGraphicsState];

Hope this helps.

Stefan
AppleScript名:指定のNSImageにNSBezierPathでclearColor塗りつぶし.scptd
— Created 2020-02-14 by Takaaki Naganoya
— 2020 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"
use framework "CoreImage"

property NSColor : a reference to current application’s NSColor
property NSImage : a reference to current application’s NSImage
property NSZeroRect : a reference to current application’s NSZeroRect
property NSBezierPath : a reference to current application’s NSBezierPath
property NSCompositeCopy : a reference to current application’s NSCompositeCopy
property NSGraphicsContext : a reference to current application’s NSGraphicsContext
property NSBitmapImageRep : a reference to current application’s NSBitmapImageRep
property NSCalibratedRGBColorSpace : a reference to current application’s NSCalibratedRGBColorSpace

set {rCol, gCol, bCol} to choose color

set aNSImage to makeColoredNSImage({rCol, gCol, bCol}, 400, 400) of me
set aPath to generateCircle(200, 100, 100) of me

set bImage to my fillImage:aNSImage withTransparentPathFilling:aPath

set aFile to POSIX path of (choose file name)
set sRes to my saveNSImageAtPathAsPNG(bImage, aFile)

on fillImage:aSourceImg withTransparentPathFilling:aPath
  set aSize to aSourceImg’s |size|()
  
set aWidth to (aSize’s width)
  
set aHeight to (aSize’s height)
  
  
set aRep to NSBitmapImageRep’s alloc()’s initWithBitmapDataPlanes:(missing value) pixelsWide:aWidth pixelsHigh:aHeight bitsPerSample:8 samplesPerPixel:4 hasAlpha:true isPlanar:false colorSpaceName:(NSCalibratedRGBColorSpace) bytesPerRow:0 bitsPerPixel:0
  
  
NSGraphicsContext’s saveGraphicsState()
  
  
NSGraphicsContext’s setCurrentContext:(NSGraphicsContext’s graphicsContextWithBitmapImageRep:aRep)
  
  
aSourceImg’s drawInRect:(current application’s NSMakeRect(0, 0, aWidth, aHeight)) fromRect:(NSZeroRect) operation:(NSCompositeCopy) fraction:(1.0)
  
  
NSGraphicsContext’s currentContext()’s setCompositingOperation:(current application’s NSCompositeClear)
  
aPath’s fill()
  
  
NSGraphicsContext’s restoreGraphicsState()
  
  
set newImg to NSImage’s alloc()’s initWithSize:(aSize)
  
newImg’s addRepresentation:aRep
  
  
return newImg
end fillImage:withTransparentPathFilling:

on generateCircle(theRadius, x, y)
  set aRect to current application’s NSMakeRect(x, y, theRadius, theRadius)
  
set aCirCle to NSBezierPath’s bezierPath()
  
aCirCle’s appendBezierPathWithOvalInRect:aRect
  
return aCirCle
end generateCircle

on makeColoredNSImage(colList, aWidth, aHeight)
  copy colList to {rCol, gCol, bCol}
  
set aColor to makeNSColorFromRGBA65535val(rCol, gCol, bCol, 1.0) of me
  
set aColoredImage to fillColorWithImage(aColor, aWidth, aHeight) of me
  
return aColoredImage
end makeColoredNSImage

on fillColorWithImage(aColor, aWidth, aHeight)
  set colordImage to makeNSImageWithFilledWithColor(aWidth, aHeight, aColor, aWidth, aHeight) of me
  
colordImage’s lockFocus()
  
colordImage’s drawAtPoint:{0, 0} fromRect:(current application’s NSZeroRect) operation:(current application’s NSCompositeDestinationIn) fraction:1.0
  
colordImage’s unlockFocus()
  
return colordImage
end fillColorWithImage

on makeNSImageWithFilledWithColor(aWidth, aHeight, fillColor)
  set anImage to NSImage’s alloc()’s initWithSize:(current application’s NSMakeSize(aWidth, aHeight))
  
anImage’s lockFocus()
  
—
  
set theRect to {{x:0, y:0}, {height:aHeight, width:aWidth}}
  
set theNSBezierPath to NSBezierPath’s bezierPath
  
theNSBezierPath’s appendBezierPathWithRect:theRect
  
—
  
fillColor’s |set|()
  
theNSBezierPath’s fill()
  
—
  
anImage’s unlockFocus()
  
—
  
return anImage
end makeNSImageWithFilledWithColor

on makeNSColorFromRGBA65535val(redValue as integer, greenValue as integer, blueValue as integer, alphaValue as integer)
  set aRedCocoa to (redValue / 65535) as real
  
set aGreenCocoa to (greenValue / 65535) as real
  
set aBlueCocoa to (blueValue / 65535) as real
  
set aAlphaCocoa to 1.0 as real
  
set aColor to NSColor’s colorWithCalibratedRed:aRedCocoa green:aGreenCocoa blue:aBlueCocoa alpha:aAlphaCocoa
  
return aColor
end makeNSColorFromRGBA65535val

on saveNSImageAtPathAsPNG(anImage, outPath)
  set imageRep to anImage’s TIFFRepresentation()
  
set aRawimg to current application’s NSBitmapImageRep’s imageRepWithData:imageRep
  
set pathString to current application’s NSString’s stringWithString:outPath
  
set newPath to pathString’s stringByExpandingTildeInPath()
  
set myNewImageData to (aRawimg’s representationUsingType:(current application’s NSPNGFileType) |properties|:(missing value))
  
set aRes to (myNewImageData’s writeToFile:newPath atomically:true) as boolean
  
return aRes
end saveNSImageAtPathAsPNG

★Click Here to Open This Script 

Posted in Image | Tagged 10.13savvy 10.14savvy 10.15savvy NSBezierPath NSBitmapImageRep NSCalibratedRGBColorSpace NSColor NSCompositeCopy NSGraphicsContext NSImage NSZeroRect | 1 Comment

AppleScriptでCoreAnimationを利用

Posted on 2月 13, 2020 by Takaaki Naganoya

Xcode上で作成するCocoa AppleScript Applicationにおいて、CoreAnimationを利用するサンプルProjectです。

–> Download Xcode Project Test with Xcode 11.3.1 + macOS 10.14.6

ひととおり(このぐらい)CoreAnimationでGUI部品をアニメーションするテストを行なっていました。あまり使いすぎるのは下品に見えるとの判断から、実際のアプリケーションでは最低限の地味な利用にとどめていました。

–> Watch Demo (1) Double PDF

–> Watch Demo (2) This Project

Mac App Storeで販売している100% AppleScriptで記述したアプリケーション「Double PDF 2.0」においても、コマンド実行後にメニューを更新する際、更新したメニューを点滅表示するぐらいの「節度あるお付き合い」にとどめていました。

それが、ここ最近組んでいるアプリケーションではド派手に利用する必要があるようで、再度こうした試作品を引っ張り出してテストしだしています。

AppleScript名:AppDelegate.applescript
—
— 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

★Click Here to Open This Script 

Posted in Animation AppleScript Application on Xcode GUI | Tagged 10.13savvy 10.14savvy 10.15savvy CABasicAnimation NSNumber | Leave a comment

eppcで他のMac上のアプリケーション操作

Posted on 1月 26, 2020 by Takaaki Naganoya

MacScripterのフォーラムでeppcについての質問があったので回答していました。eppcを用いて、ネットワーク上の他のMacを操作する件についての話でした。

eppcは、Remote AppleEventのプロトコル表記であり、自分のマシン上のアプリケーションだと、

application "Finder"

と表記しますが、他のMac上のアプリケーションだと、

application "Finder" of machine "eppc://user:password@machineName.local"

という表記になります。パスワードを書いておかないとダイアログで問い合わせが行われるので、書かなくてもいいです(パスワードが丸裸で書いてあるのは不用心なので、テスト時以外はおすすめしません)。

自分の認識では、ネットワーク上の他のマシンの操作については、

のような認識でした。この認識は間違っているわけではなく、リモートのアプリケーション操作はリモート側のアプレットに行わせるようにして、自分からはリモート側のアプレットのハンドラを呼び出すのがリモートアプリケーション操作の基本的な「作法」です。

GUIアプリケーションを直接操作するのは無理だけど、AppleScriptアプレットを常駐させておいて、アプレットのハンドラを呼び出すことで、各リモートマシン上のアプリケーションを操作できる、と。

で、これが他のメンバーのコメントで(リモートアプリケーションのダイレクト呼び出しは)「macOS 10.15でもできるぞ」という話が出てきて、腰を抜かしました。現状の自分のマシン環境(古いのばっかりですが)で検証してみたところ、たしかに(若干の癖はありますが)、GUIアプリケーションを直接操作できて驚きました(セキュリティ上の制約がいろいろあるので、ローカルでできることすべてがリモートアプリケーションに直接司令できるわけではありません)。


▲テストに用いたMac OS X 10.6.8環境


▲テストに用いたMac OS X 10.7.5環境


▲テストに用いたMac OS X 10.13.6環境

Mac OS X 10.6からmacOS 10.12あたり(厳密には確認できていない)の環境では、明確にリモートAppleEventに制約が加わっていました。

ところが、macOS 10.13あたり(10.12かも。このあたり未確認)から、eppcでGUIアプリケーションの操作ができることが確認できました。

macOS Version Direct eppc to GUI Apps
10.0 (No AppleScript Env)
10.1 Works????
10.2 Works
10.3 Works
10.4 Works
10.5 (???)
10.6 Not Work
10.7 Not Work
10.8 Not Work
10.9 Not Work
10.1 Not Work
10.11 Not Work
10.12 (??? Maybe not work)
10.13 Works
10.14 Works
10.15 Works

eppcのポート

eppcがTCP/IPのどこのポート番号を用いているかは、/etc/servicesを見ると書いてあります。

eppc            3031/udp    # Remote AppleEvents/PPC Toolbox
eppc            3031/tcp    # Remote AppleEvents/PPC Toolbox

なので、VPN接続時にこれらのポートが開いていれば、相手側のマシンをAppleScriptで遠隔操作できることになります(実際には、ファイル共有とかいろいろその他の付随するポートを開けておく必要があるわけですが)。

リモート操作の傾向

ただし、ローカルマシン上のアプリケーションを操作するのと比較して、いくつかの挙動の違いも見られます。

(1)アプリケーションの直接的な起動が効かない

各GUIアプリケーションに「activate」とか「launch」コマンドを送っても無視されます。リモートマシン上でいったんアプリケーションが起動した後に「activate」で最前面に持ってくることは可能ですが、起動していない状態でactivateを実行しても、起動は行われません。

AppleScript名:他のマシン上でSafariを起動
set RemoteMachine to "eppc://me@MacMini2014.local"

using terms from application "Finder"
  tell application "Finder" of machine RemoteMachine
    open application file id "com.apple.Safari"
  end tell
end using terms from

★Click Here to Open This Script 

Finder経由でBundle IDを指定して「application fileをオープンする」という指定であれば、たしかにアプリケーションが起動します。

(2)System Eventsの操作に難あり

面白くなっていろいろリモートアプリケーションを操作していてわかってきたのですが、初期状態だとSystem Eventsが起動していない状態です。いえ、ローカルでもSystem Eventsは常時起動してはいないんでしょうけれど、命令を発行すると自動で起動されます。

この自動起動とか明示的に指定して起動といった操作が受け付けられないので、Finder経由で間接的にapplication fileのオープンというかたちでSystem Eventsの起動を行い、処理を依頼します。

このリモートマシン上のSystem Eventsはしばらく処理が行われないと自動で終了するようなので、何かまとまった処理をSystem Eventsに行わせる前には明示的に起動を司令しておくべきなんでしょう。

AppleScript名:他のマシン上のSystem Eventsを起動する
set RemoteMachine to "eppc://me@MacMini2014.local"

using terms from application "Finder"
  tell application "Finder" of machine RemoteMachine
    open application file id "com.apple.SystemEvents"
  end tell
end using terms from

★Click Here to Open This Script 

(3)けっこう動く

GUIアプリケーションの代表としてSafariを実際に操作してみたところ、

Safariのバージョン名の取得、できました。

AppleScript名:他のマシン上で起動しているアプリケーションのバージョンを取得
set RemoteMachine to "eppc://me@MacMini2014.local"

using terms from application "Safari"
  tell application "Safari" of machine RemoteMachine
    version
  end tell
end using terms from

★Click Here to Open This Script 

Safariの新規ウィンドウの作成、できました。

AppleScript名:他のマシン上で起動しているSafariで新規ウィンドウ作成
set RemoteMachine to "eppc://me@MacMini2014.local"

using terms from application "Safari"
  tell application "Safari" of machine RemoteMachine
    make new document
  end tell
end using terms from

★Click Here to Open This Script 

SafariのウィンドウのURLの取得、できました。

AppleScript名:他のマシン上で起動しているSafariの最前面のウィンドウのURLを取得
set RemoteMachine to "eppc://me@MacMini2014.local"

using terms from application "Safari"
  tell application "Safari" of machine RemoteMachine
    set aURL to URL of front document
  end tell
end using terms from

★Click Here to Open This Script 

SafariのウィンドウのURLの書き換え、できました。

AppleScript名:他のマシン上で起動しているSafariのウィンドウのURLを書き換える
set RemoteMachine to "eppc://me@MacMini2014.local"

using terms from application "Safari"
  tell application "Safari" of machine RemoteMachine
    set URL of document 1 to "http://piyocast.com/as/"
  end tell
end using terms from

★Click Here to Open This Script 

Safariの最前面のウィンドウの内容をメールに転送、できました。

AppleScript名:他のマシン上で起動しているSafariの最前面の内容をメール
set RemoteMachine to "eppc://me@MacMini2014.local"

using terms from application "Safari"
  tell application "Safari" of machine RemoteMachine
    make new document
    
set URL of front document to "http://www.apple.com"
    
delay 3 –wait for page loading
    
email contents of front document
  end tell
end using terms from

★Click Here to Open This Script 

Safariのページローディング検出はいろいろ蓄積されているノウハウもありますが、do javascriptコマンドが問題なく動くレベルまで信用できるのかわからなかったので、delayで単純に時間待ちしています。

実際に動かしてみて、自分がビビるぐらいeppcでリモートアプリケーションの操作ができてしまいました。SIPだとかアプリケーション権限だとかでセキュリティ機能でがんじがらめにされている今日このごろですが、eppc経由でリモートマシン上のアプリケーション操作が緩和されている事実にビビりました。

これはおそらくですが、Xcode上のリモートデバッグとか、そういうあたりの機能の実装時に機能がeppcまわりの機能が再実装されたかコメントアウトしていた箇所が復活したかという話に見えます。

Posted in Remote Control | Tagged 10.13savvy 10.14savvy 10.15savvy Safari | Leave a comment

元号変換v42

Posted on 1月 23, 2020 by Takaaki Naganoya

西暦→和暦の元号を求めるAppleScriptの改修版です。

前バージョンでは、1868年から1887年までの計算が1日ズレるとか(dateオブジェクトの仕様)、明治の計算が合っていなかったので、その点を修正しました。

前バージョンまでは文字列で与えられた日付をいったんdateオブジェクトに変換していました。これは、”2020/11/31″といった正しくない日付が与えられた場合に、”2020/12/1″と妥当な解釈をし直すための処理でした。つまり、エラー対策のためだけにいったんdateオブジェクトに変換していたわけです。

これさえ行わなければ、とくにdateオブジェクトまわりの問題(before1887)は発生しません。dateオブジェクトとして解釈を行わず、単なる文字列を年、月、日に分解して、大小判定するだけの処理に置き換えました(11/31といったカレンダー的におかしな記述は無視)。

明治の計算についてもごにょごにょして修正してみました。

dateとしての年、月、日の妥当性チェックを行いたい場合には、月が1〜12、日が1〜31といった値の範囲チェックを追加で行うぐらいでしょうか。

AppleScript名:元号変換v42
—
–  Created by: Takaaki Naganoya
–  Created on: 2020/01/23
—
–  Copyright © 2020 Piyomaru Software, All Rights Reserved
—

set outList to {}
repeat with i from 1867 to 2021
  set aStr to (i as string) & "/1/25"
  
set {aGengoStr, aGengoNum} to retJapaneseGengo(aStr) of JGengoKit
  
set the end of outList to {i, aGengoStr, aGengoNum}
end repeat

return outList
–> {{1867, "(改暦前)", false}, {1868, "明治", 1}, {1869, "明治", 2}, {1870, "明治", 3}, {1871, "明治", 4}, {1872, "明治", 5}, {1873, "明治", 6}, {1874, "明治", 7}, {1875, "明治", 8}, {1876, "明治", 9}, {1877, "明治", 10}, {1878, "明治", 11}, {1879, "明治", 12}, {1880, "明治", 13}, {1881, "明治", 14}, {1882, "明治", 15}, {1883, "明治", 16}, {1884, "明治", 17}, {1885, "明治", 18}, {1886, "明治", 19}, {1887, "明治", 20}, {1888, "明治", 21}, {1889, "明治", 22}, {1890, "明治", 23}, {1891, "明治", 24}, {1892, "明治", 25}, {1893, "明治", 26}, {1894, "明治", 27}, {1895, "明治", 28}, {1896, "明治", 29}, {1897, "明治", 30}, {1898, "明治", 31}, {1899, "明治", 32}, {1900, "明治", 33}, {1901, "明治", 34}, {1902, "明治", 35}, {1903, "明治", 36}, {1904, "明治", 37}, {1905, "明治", 38}, {1906, "明治", 39}, {1907, "明治", 40}, {1908, "明治", 41}, {1909, "明治", 42}, {1910, "明治", 43}, {1911, "明治", 44}, {1912, "明治", 45}, {1913, "大正", 2}, {1914, "大正", 3}, {1915, "大正", 4}, {1916, "大正", 5}, {1917, "大正", 6}, {1918, "大正", 7}, {1919, "大正", 8}, {1920, "大正", 9}, {1921, "大正", 10}, {1922, "大正", 11}, {1923, "大正", 12}, {1924, "大正", 13}, {1925, "大正", 14}, {1926, "大正", 15}, {1927, "昭和", 2}, {1928, "昭和", 3}, {1929, "昭和", 4}, {1930, "昭和", 5}, {1931, "昭和", 6}, {1932, "昭和", 7}, {1933, "昭和", 8}, {1934, "昭和", 9}, {1935, "昭和", 10}, {1936, "昭和", 11}, {1937, "昭和", 12}, {1938, "昭和", 13}, {1939, "昭和", 14}, {1940, "昭和", 15}, {1941, "昭和", 16}, {1942, "昭和", 17}, {1943, "昭和", 18}, {1944, "昭和", 19}, {1945, "昭和", 20}, {1946, "昭和", 21}, {1947, "昭和", 22}, {1948, "昭和", 23}, {1949, "昭和", 24}, {1950, "昭和", 25}, {1951, "昭和", 26}, {1952, "昭和", 27}, {1953, "昭和", 28}, {1954, "昭和", 29}, {1955, "昭和", 30}, {1956, "昭和", 31}, {1957, "昭和", 32}, {1958, "昭和", 33}, {1959, "昭和", 34}, {1960, "昭和", 35}, {1961, "昭和", 36}, {1962, "昭和", 37}, {1963, "昭和", 38}, {1964, "昭和", 39}, {1965, "昭和", 40}, {1966, "昭和", 41}, {1967, "昭和", 42}, {1968, "昭和", 43}, {1969, "昭和", 44}, {1970, "昭和", 45}, {1971, "昭和", 46}, {1972, "昭和", 47}, {1973, "昭和", 48}, {1974, "昭和", 49}, {1975, "昭和", 50}, {1976, "昭和", 51}, {1977, "昭和", 52}, {1978, "昭和", 53}, {1979, "昭和", 54}, {1980, "昭和", 55}, {1981, "昭和", 56}, {1982, "昭和", 57}, {1983, "昭和", 58}, {1984, "昭和", 59}, {1985, "昭和", 60}, {1986, "昭和", 61}, {1987, "昭和", 62}, {1988, "昭和", 63}, {1989, "平成", 1}, {1990, "平成", 2}, {1991, "平成", 3}, {1992, "平成", 4}, {1993, "平成", 5}, {1994, "平成", 6}, {1995, "平成", 7}, {1996, "平成", 8}, {1997, "平成", 9}, {1998, "平成", 10}, {1999, "平成", 11}, {2000, "平成", 12}, {2001, "平成", 13}, {2002, "平成", 14}, {2003, "平成", 15}, {2004, "平成", 16}, {2005, "平成", 17}, {2006, "平成", 18}, {2007, "平成", 19}, {2008, "平成", 20}, {2009, "平成", 21}, {2010, "平成", 22}, {2011, "平成", 23}, {2012, "平成", 24}, {2013, "平成", 25}, {2014, "平成", 26}, {2015, "平成", 27}, {2016, "平成", 28}, {2017, "平成", 29}, {2018, "平成", 30}, {2019, "平成", 31}, {2020, "令和", 2}, {2021, "令和", 3}}

script JGengoKit
  on retJapaneseGengo(aDate as string)
    set dList to parseByDelim(aDate, "/") of me
    
if length of dList is not equal to 3 then error "Date Format Error"
    
    
copy dList to {aYear, aMonth, aDay}
    
    
tell current application
      
      
set aStr to retZeroPaddingText(aYear, 4) of me & retZeroPaddingText(aMonth, 2) of me & retZeroPaddingText(aDay, 2) of me
      
      
set aGengo to ""
      
if aStr ≥ "20190501" then
        set aGengo to "令和"
        
set aGengoNum to aYear – 2019 + 1
      else if aStr ≥ "19890108" then
        set aGengo to "平成"
        
set aGengoNum to aYear – 1989 + 1
      else if aStr ≥ "19261225" then
        set aGengo to "昭和"
        
set aGengoNum to aYear – 1926 + 1
      else if aStr ≥ "19120730" then
        set aGengo to "大正"
        
set aGengoNum to aYear – 1912 + 1
      else if aStr ≥ "18680125" then
        set aGengo to "明治"
        
if aYear = 1868 then
          set aGengoNum to 1
        else if (aYear ≥ 1869) or (aYear ≤ 1912) then
          set aGengoNum to aYear – 1867
        end if
      else
        –日本では明治以降に太陽暦を導入したのでそれ以前は意味がない?
        
set aGengo to "(改暦前)"
        
set aGengoNum to false
      end if
      
      
return {aGengo, aGengoNum}
    end tell
  end retJapaneseGengo
  
  
–数値にゼロパディングしたテキストを返す
  
on retZeroPaddingText(aNum, aLen)
    set tText to ("0000000000" & aNum as text)
    
set tCount to length of tText
    
set resText to text (tCount – aLen + 1) thru tCount of tText
    
return resText
  end retZeroPaddingText
  
  
on parseByDelim(aData, aDelim)
    set curDelim to AppleScript’s text item delimiters
    
set AppleScript’s text item delimiters to aDelim
    
set dList to text items of aData
    
set AppleScript’s text item delimiters to curDelim
    
return dList
  end parseByDelim
end script

★Click Here to Open This Script 

Posted in Calendar | Tagged 10.13savvy 10.14savvy 10.15savvy | Leave a comment

1867/1/1〜1887/12/31までの範囲のdateオブジェクトからyear, month, dayを取り出すと-1日される?

Posted on 1月 22, 2020 by Takaaki Naganoya

過去のdateオブジェクトを検証する機会があり(明治の元号計算が合っていない件)、いろいろ検証していたところ、1867/1/1から1887/12/1までのdateオブジェクトからyear,month,dayを個別に取り出すと、dayが-1されるという現象が観測されました。

→ 本現象の発生メカニズムはこちら

西暦から和暦に変換する処理で、明治の年が合わないという(自分のプログラム由来の)問題を検討していました。この問題の洗い出しのため、「日」単位で順次和暦変換していたら、そのちょうど(明治→大正など)改元の境目の日付で(原因不明の)計算ミスが起こっていました。

1868/1/25からは明治時代、という判定は行えても、その1868/1/25というdateオブジェクトからYear, Month, Dayの各要素を取り出すと1868, 1, 24という結果に。

以前から「大昔の日付を扱うと問題がありそう」だとは思っていましたが、このように具体的な現象として観測したのは(個人的には)初めてでした(単に覚えていないだけかも)。

確認したのはmacOS 10.14.6とmacOS 10.15.3beta、macOS 10.13.6上ですが、どれも同じ結果になるようです。

# 追試で、OS X 10.7.5でも試してみたところ、同じ結果になりました
# OS X 10.6.8では確認されませんでした

未来のdateオブジェクトは2050年ぐらいまでチェックしてみたものの、問題はありませんでした。

過去に遡ってうるう日が設定されたとかいう話なんでしょうか? そういう話は聞いたことがないのですが、、、

日本においては太陽暦(グレゴリオ暦)を導入したのが明治元年(1868/1/25〜)なので、それ以前の日付をグレゴリオ歴で求めてもいまひとつ実用性がない(?) ともいえますが、少なくとも1868年から1887年までの間のdateオブジェクトから各種の値の取り出しが期待どおりに行われないのは問題といえるでしょう。

多分、もっと昔の日付も同様にdateオブジェクトからの値取り出しを行うと問題が出ると思われますが、前述のような理由からそこまでの日付を計算させることもないだろうかと。

# ふだん使っているgetMLenInternationalに問題があるのかと考えて、昔使っていたgetMLenを引っ張り出してきましたが、こちらはずいぶんと記法がお可愛らしい感じで、、、、

ただ、この件は気がつかなかっただけで、ずいぶん昔から存在している話なのかも????


▲Classic Mac OS 8.6では確認できませんでした(SheepShaver上で動作)この時代にはmonthをas numberで数値にcastできませんでした

AppleScript名:dateTest.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2020/01/22
—
–  Copyright © 2020 Piyomaru Software, All Rights Reserved
—

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

script spd
  property mList : {}
end script

set (mList of spd) to {}
repeat with y from 1867 to 1888
  repeat with m from 1 to 12
    set aLen to getMlen(y, m) of me
    
repeat with d from 1 to aLen
      set aTmpStr to (y as string) & "/" & (m as string) & "/" & (d as string)
      
set aTmpD to date aTmpStr
      
      
set tmpY to year of aTmpD
      
set tmpM to month of aTmpD as number
      
set tmpD to day of aTmpD
      
      
if (tmpY is not equal to y) or (tmpM is not equal to m) or (tmpD is not equal to d) then
        set the end of (mList of spd) to {aTmpD, tmpY, tmpM, tmpD}
      end if
    end repeat
  end repeat
end repeat

return (mList of spd)
–> {{date "1867年1月1日 火曜日 0:00:00", 1866, 12, 31}, …… {date "1887年12月31日 土曜日 0:00:00", 1887, 12, 30}}

–現在のカレンダーで指定年月の日数を返す
on getMlenInternational(aYear as integer, aMonth as integer)
  set theNSCalendar to current application’s NSCalendar’s currentCalendar() — do *not* use initWithCalendarIdentifier:
  
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 getMlenInternational

–指定年の指定月の日数を求める
on getMlen(aYear, aMonth)
  set aYear to aYear as number
  
set aMonth to aMonth as number
  
  
set aDat to (aYear as text) & "/" & (aMonth as text) & "/1"
  
if aMonth is 12 then
    set eDat to ((aYear + 1) as text) & "/" & (1 as text) & "/1"
  else
    set eDat to ((aYear as text) & "/" & (aMonth + 1) as text) & "/1"
  end if
  
  
set eDat to date eDat
  
set eDat to eDat – 1
  
  
set mLen to day of eDat
  
return mLen
end getMlen

★Click Here to Open This Script 

Posted in Calendar History | Tagged 10.13savvy 10.14savvy 10.15savvy | 1 Comment

自然言語テキストから複数の日付情報を抽出

Posted on 1月 21, 2020 by Takaaki Naganoya

自然言語テキストから日付の情報(複数可)を抽出するAppleScriptです。

URLやメールアドレスの抽出では、複数のデータをNSDataDetectorで抽出するAppleScriptは書いてありましたが、日付情報の抽出を行うものはなかったので、書いておきました。

AppleScript名:自然言語テキストから複数の日付情報(複数)を抽出して日付のリストを返す.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2020/01/21
—
–  Copyright © 2020 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use scripting additions

set theDate to getDatesIn("本テキストには次の火曜日という日付情報を含んでいる。明日かもしれない。次の木曜日もそうだ。") of me
–> {date "2020年1月28日 火曜日 12:00:00", date "2020年1月22日 水曜日 12:00:00", date "2020年1月23日 木曜日 12:00:00"}

set theDate to getDatesIn("This text contains next Tuesday. The date may be tomorrow. Next Wednesday happen.") of me
–> {date "2020年1月28日 火曜日 12:00:00", date "2020年1月22日 水曜日 12:00:00", date "2020年1月29日 水曜日 12:00:00"}

on getDatesIn(aString)
  set anNSString to current application’s NSString’s stringWithString:aString
  
set theDetector to current application’s NSDataDetector’s dataDetectorWithTypes:(current application’s NSTextCheckingTypeDate) |error|:(missing value)
  
set theMatchs to theDetector’s matchesInString:anNSString options:0 range:{0, anNSString’s |length|()}
  
if theMatchs = missing value then error "No date found with String:" & aString
  
set dRes to theMatchs’s valueForKeyPath:"date"
  
return dRes as list
end getDatesIn

★Click Here to Open This Script 

AppleScript名:自然言語テキストから複数の日付情報(複数)を抽出して日付と当該箇所のリストを返す v2.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2020/01/21
—
–  Copyright © 2020 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use scripting additions

set theDate to getDatesAndOrigStringsIn("本テキストには次の火曜日という日付情報を含んでいる。明日かもしれない。次の木曜日もそうだ。") of me
–> {{originalStr:"次の火曜日", detectDate:date "2020年1月28日 火曜日 12:00:00"}, {originalStr:"明日", detectDate:date "2020年1月22日 水曜日 12:00:00"}, {originalStr:"次の木曜日", detectDate:date "2020年1月23日 木曜日 12:00:00"}}

set theDate to getDatesAndOrigStringsIn("This text contains next Tuesday. The date may be tomorrow. Next Wednesday happen.") of me
–> {{originalStr:"next Tuesday", detectDate:date "2020年1月28日 火曜日 12:00:00"}, {originalStr:"tomorrow", detectDate:date "2020年1月22日 水曜日 12:00:00"}, {originalStr:"Next Wednesday", detectDate:date "2020年1月29日 水曜日 12:00:00"}}

on getDatesAndOrigStringsIn(aString)
  set anNSString to current application’s NSString’s stringWithString:aString
  
set theDetector to current application’s NSDataDetector’s dataDetectorWithTypes:(current application’s NSTextCheckingTypeDate) |error|:(missing value)
  
set theMatchs to theDetector’s matchesInString:anNSString options:0 range:{0, anNSString’s |length|()}
  
if theMatchs = missing value then error "No date found with String:" & aString
  
set dRes to (theMatchs’s valueForKeyPath:"date") as list
  
set rRes to (theMatchs’s valueForKeyPath:"range") as list
  
  
set allRes to {}
  
set aLen to length of dRes
  
repeat with i from 1 to aLen
    set aSubStr to (anNSString’s substringWithRange:(item i of rRes))
    
set dDate to contents of item i of dRes
    
set the end of allRes to {originalStr:aSubStr as string, detectDate:dDate}
  end repeat
  
  
return allRes
end getDatesAndOrigStringsIn

★Click Here to Open This Script 

Posted in Calendar Natural Language Processing | Tagged 10.12savvy 10.13savvy 10.14savvy 10.15savvy NSDataDetector NSString | Leave a comment

Numbersで書類Aのすべてのシートの表1を、書類Bの現在のシートの表1にまとめる

Posted on 1月 21, 2020 by Takaaki Naganoya

Numbersでオープン中の複数の書類があったときに、書類Aのすべてのシートの表1を、書類Bの現在のシートの表1にまとめるAppleScriptです。

さすがに、機械的な作業すぎて手で行う気にはなれなかったので、ありもののScriptを利用して作ってみました。

こういう用途のために作っておいたライブラリ「choose multiple list」を利用しています。


▲データ取得元


▲データ集約先


▲ダイアログで「データ取得元」と「データ集約先」を選択

BridgePlus内蔵のFrameworkがmacOS 10.14/10.15に邪魔されて認識されない環境では動かせないかもしれません。このあたり、SIP解除するしかないと思わせるものがあります。

ライブラリで複雑な選択を行えるUI部品を作っておいたおかげで、これだけ込み入った動作を行うAppleScriptを書きましたが、Cocoaの機能はほぼ使っていません(getDataFromNumbersDocは作り置きしておいた、頻出ルーチンなので使いまわしています)。choose multiple listライブラリは、こういう用途のために作っておいたものであり、まさにそのぴったりな用途であったといえるでしょう。

AppleScript名:書類Aのすべてのシートの表1を、書類Bの現在のシートの表1にまとめる.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2020/01/20
—
–  Copyright © 2020 Piyomaru Software, All Rights Reserved
—

use AppleScript version "2.7" — High Sierra (10.13) or later
use framework "Foundation"
use scripting additions
use bPlus : script "BridgePlus"
use mulList : script "choose multiple list"

script spd
  property allData : {}
end script

set (allData of spd) to {}

set {aName, bName} to getTargetDocNames() of me

–「データ取得元」のNumbers書類のすべてのシートの表1から2D Listでデータ取得
tell application "Numbers"
  tell document aName
    set sList to name of every sheet
    
repeat with i in sList
      set tmp2DDat to getDataFromNumbersDoc(aName, i) of me
      
set (allData of spd) to (allData of spd) & tmp2DDat
    end repeat
  end tell
end tell

set aHeight to length of (allData of spd)
set aWidth to length of item 1 of (allData of spd)

–「データ集約先」のNumbers書類の現在のシートの表1にまとめた2D Listを展開する(巨大すぎると時間がかかるので、CSV書き出ししてオープンするなどの別の方法を採るべき)
tell application "Numbers"
  tell document bName
    tell active sheet
      set tRes to make new table with properties {row count:aHeight + 1, column count:aWidth}
    end tell
  end tell
end tell

fillCurrentTable(bName, (allData of spd)) of me

–Numbersの書類の現在のシートを、指定の2次元配列でfillする
on fillCurrentTable(docName, aList)
  set aLen to length of aList
  
set aWidth to length of first item of aList
  
  
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
  
  
return cList
  
end getDataFromNumbersDoc

★Click Here to Open This Script 

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

BlogアーカイブのMarkdown書類をリネーム。親、親+1階層フォルダをMM, YYYYとみなして反映

Posted on 1月 19, 2020 by Takaaki Naganoya

Finderで選択中のファイルすべてに対して、親フォルダ名、親+1階層のフォルダ名を反映させたファイル名をつけるAppleScriptです。

Blogアーカイブ本を作るのに、こうした道具を作って使っています。一度書いておけば、2度目からは大幅に時間を短縮できます。最初のファイルから拡張子を取得してそれを後続のファイルすべてに適用するため、同一種類のファイルである必要があります。自分用のツールならではの手抜きといったところでしょうか。

AppleScript名:BlogアーカイブのMarkdown書類をリネーム。親、親+1階層フォルダをMM, YYYYとみなして反映 .scptd
— Created 2020-01-18 by Takaaki Naganoya
— 2020 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

–選択ファイルを取得
tell application "Finder"
  set aSel to selection as alias list –Select documents to Rename
end tell

set aCount to 10 –start
set aStep to 10
set aDigit to 3

–パス情報を取得
set aFirst to first item of aSel
set aPOSIX to POSIX path of aFirst
set aPathStr to (current application’s NSString’s stringWithString:aPOSIX)
set aDateComList to aPathStr’s pathComponents() –ディレクトリごとにパス情報を分割してリスト化
set aExt to aPathStr’s pathExtension() –拡張子

set aYear to (item -3 of aDateComList) as string –親の親フォルダ名
set aMonth to (item -2 of aDateComList) as string –親フォルダ名

–リネーム(数百項目を超える場合にはFinderでは遅すぎるのでNSFileManagerで処理)
tell application "Finder"
  repeat with i in aSel
    set aTEXT to numToZeroPaddingStr(aCount, aDigit, "0") of me –3 digit
    
set aName to aYear & aMonth & aTEXT & "." & aExt
    
set name of i to aName
    
set aCount to aCount + aStep
  end repeat
end tell

–整数の値に指定桁数ゼロパディングして文字列で返す
on numToZeroPaddingStr(aNum as integer, aDigit as integer, paddingChar as text)
  set aNumForm to current application’s NSNumberFormatter’s alloc()’s init()
  
aNumForm’s setPaddingPosition:(current application’s NSNumberFormatterPadBeforePrefix)
  
aNumForm’s setPaddingCharacter:paddingChar
  
aNumForm’s setMinimumIntegerDigits:aDigit
  
  
set bNum to current application’s NSNumber’s numberWithInt:aNum
  
set aStr to aNumForm’s stringFromNumber:bNum
  
  
return aStr as text
end numToZeroPaddingStr

★Click Here to Open This Script 

Posted in file File path list Markdown Text | Tagged 10.12savvy 10.13savvy 10.14savvy 10.15savvy Finder NSNumber NSNumberFormatter NSNumberFormatterPadBeforePrefix NSString | Leave a comment

AppleScriptを実行中のランタイムプログラム名を取得する

Posted on 1月 18, 2020 by Takaaki Naganoya

AppleScriptのランタイムプログラム名(ランタイム名)を取得するAppleScriptです。AppleScript自身が「何によって」実行されているか、その実行プログラム名を取得するものです。

AppleScriptには何種類かランタイム環境が存在し、ランタイム環境ごとに若干の動作が変わってくることが知られています。

ランタイム環境ごとにどこが違うといえば、Finderからのselectionを取得できるとかできないとか(AppleScript Studioがこれに該当。もうありませんけれども)、GUI Scriptingの権限の認証を得られるとか得られないとか。ウィンドウを動的に生成して表示したときに最前面に表示できるとかできないとか(Script Menuがこれに該当)。明示的にメインスレッドで実行する機能がないとか(Script Debuggerがこれに該当)。そういうところです(ほかにもあるかもしれない)。

過去に作ったAppleScriptを確認していたところ、プロセス名を取得するだけの使えないプログラムだと思っていたものが、実は「ランタイムプログラムのプログラム名」を取得できるというスゲーものであることを再発見しました。

ながらく、ランタイムプログラム名をAppleScript側から取得する必要性を感じていたため、この機会に調べてみることに。プログラム自体は些細な(↓)ものです。

AppleScript名:ランタイム環境名の表示
— Created 2015-09-08 by Takaaki Naganoya
— 2015 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set procInfo to current application’s NSProcessInfo’s processInfo()
set aName to procInfo’s processName() as string
display dialog aName

★Click Here to Open This Script 

Script Editor上で実行


–> “Script Editor”

Script Debugger上で実行


–> “Script Debugger”

ASObjC Explorer 4上で実行


–> “ASObjC Explorer 4”

Automator上で実行


–> “Automator”
これには驚きました。特別のランタイムプログラムが使われているのか、それとも単に親プロセスとしてのAutomatorが返ってきているのかは不明ですが、識別できるということには意義がありそうです。

Script Menu上で実行


–> “osascript”
これは、よく知られていることなのでとくに驚きはありません。テストを実施したのはmacOS 10.14.6上で、Script Menuは「スクリプトメニュー」という別アプリケーション(/System/Library/CoreServices/ にある)に変更になったOSバージョンですが、ランタイムにosascriptを使い続けていることを確認することになりました(それ以前のOSと挙動が同じなのでそうだと思っていましたけれども)。

Folder Action上で実行




–> “osascript”
Folder Actionは、macOS標準搭載のフォルダ監視機能です。監視対象のフォルダにファイルが追加されたり、移動されたり、フォルダそのものがオープンしたりするとその対象ファイル/フォルダで指定のAppleScriptを実行します。よく、ドラッグ&ドロップで処理を受け付けたり、ネットワーク経由でファイルを受信した場合にAppleScriptを実行するような使われ方をします。
Folder Action Disptcherが実行しているとばかり思っていたのですが、実際に確認したらosascriptでした。ちなみに、Folder ActionはmacOS 10.11でフルに書き換えられてそれ以前とは別物になっています。以前は数秒に一度対象フォルダをチェックする方式でしたが、10.11以降はFSEventsを利用して随時監視対象フォルダへの変更を受け付けます。

Switch Control上で実行



–> “osascript”
障害者向けの機能としてmacOSに標準装備されている、フローティングパレットからAppleScriptを呼び出せる機能である「Switch Control」。手を使わずに操作したり、他のコントローラで操作するような標準的ではない使い方をサポートするための機構ですが、普通に普通の人が使っても役立ちます。 
Switch ControlでAppleScriptを実行する場合のランタイムプログラムはosascriptです。

CotEditor上で実行


–> “osascript”
これは、CotEditorのソースを読んで確認してありました。ここだけ割と手抜き実装ですが、それでも複数のOSA言語に対応できたりと機能的には悪くはありません。むしろ、osascript側のランタイム環境が他の環境よりも一段落ちることに問題が、、、、GUI Scriptingの権限を取得できないこととか、このCotEditorのメニューから実行するとREST APIが呼び出せないとか。同じosascript系でもScript Menuのほうが制約が少ないのは、おそらくアプリケーション自体に許可されている条件の違いによるものでしょう。

FileMaker Pro上でスクリプトステップ「AppleScriptを実行」を実行


–> “FileMaker Pro”
FileMaker Proはランタイムアプリケーションが廃止され、FileMaker Pro AdvancedもFileMaker Proに一本化されたので、v19以降はFileMaker Proは「FileMaker Pro」というランタイムのみでしょう。v19でもFileMaker Pro自体はSandbox化されていないため、微妙にセキュリティ上の制約が少ない=自由度の高いランタイム環境として残っていくことでしょう。

Script EditorからApplet書き出しして実行


–> “applet”
取得できたらいいなぐらいの気持ちで試してみたものの、これが識別できるのはうれしい誤算です。書き出したAppleScript Applet名は「Appletでランタイム名を取得」であったため、この「applet」というものとは異なります(ねんのため)。

AutomatorからApplet書き出しして実行


–> “Application Stub”
見たことのない名前が、、、、やっぱり、これも別ランタイムなんですね、、、、

Script DebuggerからApplet(Enhanced)で書き出しして実行


–> “FancyDroplet”
Appleの標準ランタイムとはあきらかに別物(Enhanced)なので、たぶん別の名前がついているだろうとは思っていましたが、そういう名前でしたか。名前が予想外だったので驚かされましたが、識別できることに意義があります。

Cocoa-AppleScript Appletを実行


–> “CocoaApplet”
Script Editor上で作成できる、通常のAppleScriptとXcode上で作成するCocoa-Applicationの中間的な性格を持つ「Cocoa-AppleScript Applet」でランタイムプログラム名を取得したらこうなりました。

もちろん、実行プログラム名はまったく別の「ランタイム名を表示するだけのCocoa-AppleScript Applet」というものです。

ショートカットで「AppleScriptを実行」アクションを実行


–> “MacHelper”

macOS 12で搭載されたショートカット.app(Shortcuts.app)および不可視プロセスのAppleScriptの補助専用アプリケーション「Shortcuts Events.app」上で、アクション「AppleScriptを実行」でAppleScriptを実行するときのランタイム名は、「MacHelper」です。意外なところで、ユーザーディレクトリ以下にインストールされたAppleScriptライブラリをこのMacHelper環境は認識します。

→ macOS 13上では、ショートカット.app(Shortcuts.app)およびShortcuts Events.app上のランタイム名が「ShortcutsMacHelper」に変更されました。

RedSweater Software「FastScripts」からAppleScriptを実行

red sweater softwareによるメニュー常駐型Script Menuソフトウェア「FastScripts」から実行したときのランタイム名は「FascScripts Script Runner」です。

Knurling Group「Service Station」からAppleScriptを実行

Knurling Groupによるコンテクストメニューのカスタマイズ・ソフトウェア「Service Station」から実行したときのランタイム名は「osascript」です。

ランタイム名が得られることで実現できること

これらのほか、各アプリケーション内でAppleScript呼び出し機能を有するもの(ファイルメーカー、Mail.appなど)でランタイムプログラム名を取得すると有益な情報が得られることでしょう。

これは、地球上にいる人類が観測衛星を打ち上げて「ここは銀河系だ」と観測できるぐらいすごいことなので、割と意義深いものです。実行中のAppleScriptが、「いま、何のプログラムによって自分自身が実行されている」かという情報を取得できます。

ランタイムプログラムの名称取得については、いくつかのAppleScript実行方法を試してみましたが、得られる名前に違いがないことを確認しています。

直接AppleScriptを動かす方法に加え、間接的にAppleScriptを動かす方法も試してみましたが、同じ結果が得られました。

つまり、動的にOSAScriptViewを生成して実行しようが、NSAppleScriptで実行しようが、AppleScriptの「run script」コマンドで実行しようが、取得されるランタイム名には差がありません。

これで、ランタイム環境のプロセスの親プロセスの情報が取得できると、Terminal.app上から起動したosascriptコマンドで呼び出したのか、Script Menu上から呼び出したのかという状況をAppleScript側で認識できることになることでしょう。

ランタイム環境を識別した上で、各環境で実行できない処理を行わないとか、ランタイム環境ごとに処理を分岐できるようになることでしょう。

ちょうど、Edama2さんと「ランタイム環境ごとに若干の挙動の違いが見られるし、利用できるCocoaの機能にも違いがあるから、ランタイム環境ごとに認識コードでも振ってみようか」などと相談していたので、渡りに船でした。

Posted in OSA | Tagged 10.13savvy 10.14savvy 10.15savvy Automator CotEditor Script Debugger Script Editor | Leave a comment

Numbersでオープン中の最前面の書類のすべてのシートの表1の行数合計を計算する

Posted on 1月 15, 2020 by Takaaki Naganoya

Numbersでオープン中の最前面の書類のすべてのシートの表1の行数の合計を計算するAppleScriptです。

Blogアーカイブ本作成のために書いたものです。

この記事数をカウントするために使いました。

AppleScript名:Numbersでオープン中の最前面の書類のすべてのシートの表1の行数合計を計算する
set aCount to 0

tell application "Numbers"
  tell front document
    set sList to every sheet
    
repeat with i in sList
      tell i
        try
          set tmpC to count every row of table 1
          
set aCount to aCount + tmpC
        end try
      end tell
    end repeat
  end tell
end tell

return aCount

★Click Here to Open This Script 

Posted in Number | Tagged 10.13savvy 10.14savvy 10.15savvy Numbers | Leave a comment

アラートダイアログ上にTable Viewを表示 v9_アイコンを表示、Finderからのドラッグ&ドロップ

Posted on 1月 15, 2020 by Takaaki Naganoya

Edama2さんからの投稿Scriptです。アラートダイアログ中に各種GUI部品を詰め込む「箱庭インタフェース」シリーズ。テーブルビューを表示して、Finderからのアプリケーションのドラッグ&ドロップを受け付けるAppleScriptです。

–> Download Editable & Executable Script Bundle Document

カスタムクラスの作り方がわかったので、懲りずにTable Viewネタです。
Thanks  Shane Stanley!

アプリケーションフォルダ直下のアプリを、NSValueTransformerを使ってコラムにローカライズ名とアイコンを表示するのと、finderからのドラッグ&ドロップでアイテムの追加です。
追加時に重複チェックをしているので試す時はユーティリティフォルダか別の場所にあるアプリで試してください。

本Scriptは自分も作りたいと思いつつも調査が進んでいなかったものですが、TableViewでFinderからのドラッグ&ドロップを受け付けます。

これを鍛えて再利用しやすい部品に育てることで、ドロップレットの代替品にできると思っています。macOS 10.12以降、Finder上のファイルをAppleScriptドロップレットにドラッグ&ドロップで処理させても、OS側がダウンロードファイルにつけた拡張属性(Xattr)「com.apple.quarantine」がついているとドロップレット側で処理できなかったりします(回避方法はありますけれども)。

このドロップレットという仕組みを使わずに、同様にドラッグ&ドロップによる処理を手軽にできる代替インタフェースとしてこのようなものを考えていた次第です。自分で作らなくてもEdama2さんが作ってくださったので助かりました、、、、

AppleScript名:アラートダイアログ上にTable Viewを表示 v9_アイコンを表示、Finderからのドラッグ&ドロップ
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()
  
  
## NSTableView
  
tell current application’s NSTableView’s alloc()
    tell initWithFrame_(current application’s CGRectZero)
      setAllowsEmptySelection_(false)
      
setAllowsMultipleSelection_(true)
      
setDataSource_(theDataSource)
      
setDelegate_(theDataSource)
      
setDoubleAction_("doubleAction:")
      
setGridStyleMask_(current application’s NSTableViewSolidVerticalGridLineMask)
      
setSelectionHighlightStyle_(current application’s NSTableViewSelectionHighlightStyleRegular)
      
setTarget_(theDataSource)
      
setUsesAlternatingRowBackgroundColors_(true)
      
      
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)
      
      
### 表示内容をNSArrayControllerにバインディング
      
bind_toObject_withKeyPath_options_(current application’s NSValueBinding, theDataSource, "arrangedObjects", bOptions)
      
      (
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

★Click Here to Open This Script 

AppleScript名:subClasses
#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
    
    
setAutoresizingMask_(current application’s NSViewWidthSizable)
    
    
tell current application’s NSImageView’s alloc
      tell initWithFrame_(current application’s NSMakeRect(0, 0, 16, 16))
        setImageScaling_(current application’s NSImageScaleProportionallyUpOrDown)
        
setImageAlignment_(current application’s NSImageAlignCenter)
        
        
my setImageView:it
        
my addSubview:it
      end tell
    end tell
    
    
tell current application’s NSTextField’s alloc
      tell initWithFrame_(current application’s NSMakeRect(20, 2, 200, 14))
        setBordered_(false)
        
setDrawsBackground_(false)
        
setEditable_(false)
        
        
my setTextField:it
        
my addSubview:it
      end tell
    end tell
    
    
return me
  end initWithFrame:
end script

★Click Here to Open This Script 

Posted in dialog GUI | Tagged 10.13savvy 10.14savvy 10.15savvy NSAlert NSArrayController NSBundle NSCreatesSortDescriptorBindingOption NSDictionary NSNumber NSScrollView NSTableCellView NSTableView NSURL NSValueBinding NSValueTransformer | Leave a comment

Numbersで各シート名称を置換

Posted on 1月 15, 2020 by Takaaki Naganoya

Numbersでオープン中の最前面の書類中にあるすべてのシートの名前を置換するAppleScriptです。

内容は簡単ですが、Numbersにそうした機能が存在しないので、作っておくと便利です。アーカイブ本を作るのに、こうした(↓)資料を作る必要があるわけですが、そのためにこうしたこまごまとしたScriptをその場で作って作業の効率化を図っています。


▲上の画像あくまでは処理イメージなので、厳密に同一データの処理前・処理後の画面スナップショットではありません。各シートの名称の一部の文字列(YYYY部分)のみ置換されていることをご確認ください

AppleScript名:Numbersで各シート名称を置換
tell application "Numbers"
  tell front document
    set tList to every sheet
    
repeat with i in tList
      tell i
        set aName to name
        
set bName to replaceText(aName, "2011_", "2013_") of me
        
set name to bName
      end tell
    end repeat
  end tell
end tell

–任意のデータから特定の文字列を置換
on replaceText(origData, origText, repText)
  set curDelim to AppleScript’s text item delimiters
  
set AppleScript’s text item delimiters to {origText}
  
set origData to text items of origData
  
set AppleScript’s text item delimiters to {repText}
  
set origData to origData as text
  
set AppleScript’s text item delimiters to curDelim
  
return origData
end replaceText

★Click Here to Open This Script 

Posted in Text | Tagged 10.12savvy 10.13savvy 10.14savvy 10.15savvy Numbers | Leave a comment

AppleScript, my(me), it

Posted on 1月 8, 2020 by Takaaki Naganoya

Script Object関連の調べ物をしていて、AppleのWebサイト掲載のReferenceを見ていたら、サンプルをまじえて説明されていたので、理解が深まりました。

AppleScript:トップレベルObject。不変
my(me):現在のScript Object。可変
it:現在のアプリケーションObject。可変

AppleScript > my(me) ≧ it

というレベルになっていることもよく理解できました。

ただ、サンプルが自分的にいまひとつわかりやすくなかったので、自分用に書き換えてみました。バージョン取得ではなく、「名前を取得」しないといまひとつ分からないんじゃないでしょうか。

AppleScript名:testScript
me
–> «script»–実行中のAppleScript書類(Script Object)

AppleScript
–> «script AppleScript»

it
–> «script»–current target object

tell application "Finder"
  it
  
–> application "Finder"–current target object
  
  
–testMe() –> error "Finderでエラーが起きました: testMeを続けることができません。" number -1708
  
testMe() of me
  
testMe() of aTEST of me
  
testMe() of bTEST of aTEST of me
end tell

on testMe()
  set aName to name of me
  
–> "testScript"
  
display dialog aName –Name of this AppleScript document file
end testMe

script aTEST
  on testMe()
    set aName to name of me
    
–> "aTEST"
    
display dialog aName –Name of this script object (aTEST)
  end testMe
  
  
script bTEST
    on testMe()
      set aName to name of me
      
–> "bTEST"
      
display dialog aName –Name of this script object (bTEST)
    end testMe
  end script
end script

★Click Here to Open This Script 

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

最前面のアプリケーションの用語辞書を表示する v4

Posted on 1月 8, 2020 by Takaaki Naganoya

最前面のアプリケーションのAppleScript用語辞書をオープンするAppleScriptです。

macOS標準装備のScript Menuに入れて呼び出すことを前提に作りました。はるかかなた昔に作って、OSバージョンが上がるごとに細かい改修を行なって使い続けているものです。

この手のScriptは日常的にAppleScriptを書いている人間なら、たいてい書いてみたことがあるはずです。しかし、あまり生真面目なアプローチでアプリケーションバンドル中のsdefのパスを求めてオープンといった処理を行っていると、「例外」にブチ当たって困惑します。

sdefファイルを直接持っていないAdobe Creative Cloud製品です。InDesignあたりがそうなんですが、直接sdefを保持しておらず、どうやら実行時に動的に組み立てるようで、絶体パス(absolute path)で指定してもsdefをオープンできません。

また、Microsoft Office系アプリケーションのsdefも、外部の(OS側のsdef)テンプレートをincludeするようなので、生真面目に対象アプリケーションのInfo.plistの情報をもとにアプリケーションバンドル中のsdefファイルをオープンするように処理すると、sdefの一部のみを表示するようになってしまって、sdef全体を表示することができません。

そうしたもろもろの問題に当たって、結局アプリケーションそのものをScript Editorでオープンするように指定しています。

AppleScript名:–このアプリケーションの用語辞書を表示する v4
— Created 2017-07-23 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

–最前面のプロセスのファイルパスを取得する
set aFile to path to frontmost application
set aRec to (getAppPropertyFromInfoPlist(aFile, "NSAppleScriptEnabled") of me) as boolean

–スクリプト用語辞書をScript Editorでオープンする手順
if aRec = true then
  –OS X 10.10でScript Editor側からアプリケーションをオープンしてもダメだったので、Finder側からScript Editorで指定アプリをオープンすることに
  
try
    tell application "Finder"
      set apFile to (application file id "com.apple.scripteditor2") as alias
      
open aFile using application file apFile
    end tell
  on error
    tell application id "com.apple.scripteditor2"
      open aFile
    end tell
  end try
  
  
tell application id "com.apple.scripteditor2" to activate
  
else
  display dialog "本アプリケーションは、各種OSA言語によるコントロールに対応していません。" buttons {"OK"} default button 1 with icon 2 with title "Scripting非対応"
end if

on getAppPropertyFromInfoPlist(aP, aPropertyLabel)
  set aURL to current application’s |NSURL|’s fileURLWithPath:(POSIX path of aP)
  
set aBundle to current application’s NSBundle’s bundleWithURL:aURL
  
set aDict to aBundle’s infoDictionary()
  
  
set aRes to aDict’s valueForKey:aPropertyLabel
  
if aRes is not equal to missing value then
    set aRes to aRes as anything
  end if
  
  
return aRes
end getAppPropertyFromInfoPlist

★Click Here to Open This Script 

Posted in sdef | Tagged 10.12savvy 10.13savvy 10.14savvy 10.15savvy Script Editor | Leave a comment

path to temporary items

Posted on 1月 6, 2020 by Takaaki Naganoya

AppleScript users ML上で2016/10/16〜18に行われていた議論の内容を自分でも再確認しました(Thanks Yvan!)。一時フォルダの場所を求める「path to temporary items」の値が、macOS 10.12から変更になっています。


▲AppleScript Users ML上の議論のフロー(Mail Flow Visualizerによりバッチ出力。つまり、Mail.app上で出力フローを選択してAppleScriptでフロー図出力しています)

AppleScript標準装備の「path to」コマンドは、Classic MacOS環境からMac OS X環境に移行した後に重要度が上がったコマンドです。OS側が用意している特別な意味を持つフォルダの場所を返してくれます。

とくに、(いまさらですが)Mac OS X環境はマルチユーザー環境なので、とくにPicturesとかDocumentsとかDesktopとかの特別なフォルダのパスを求める機能は基礎的ではあるものの、とても重要です。このあたりをめんどくさがってなんでもかんでも固定パスで書きたがる人を見かけたことがありますが、その人が書いたプログラムは他のユーザー環境で動かなくて苦労していました(本人ではなく周囲の人々が)。

AdobeのCS/CCアプリケーションのサンプルAppleScriptでも固定パスで書かれたものを多数見かけましたが、あれはなんだったんでしょう。

ドメイン

もともと、path toコマンドにより求められる各種パスには、

system domain:/System 
network domain:/Network
user domain:~

などのほか、

local domain:/Library
Classic domain: Classic Mac OSのシステムフォルダ(Classic環境をサポートするOS&ハードウェアの組み合わせ上でのみ有効)

などの「ドメイン」が指定できることになっていました。system domainはOSのSystemが利用、User domainはユーザーのホームフォルダ以下。network domainはmacOSのNetBootが廃止/他の機能への移行対象となっている(すでに、iMac ProではNetBoot非サポート)ほか、そのような環境下にないと有意な結果が得られません。

作業用一時フォルダtemporary items

ドメインの区分けが存在するものの、これらの区分のうちClassic domainははるかかなた昔に消滅、network domainも使ったことのあるユーザーは稀(まれ)でしょう。

そんな中、作業用の一時フォルダの場所を求める「path to temporary items」の仕様がmacOS 10.12で変更になっていました。

テンポラリフォルダの特性ゆえに、細かいディレクトリ名はユーザー環境ごと、実行時ごとに微妙に異なりますが(赤字部分が変化する部分)、上の図では(↑)どのあたりに作られるのかという点に着目して色分けしてみました。

macOS 10.12以降では、user domainでもsystem domainでも同じような場所が指定されることになることがわかります。

ちなみに、Cocoaの機能を用いて求められる一時フォルダはまた別の場所が示されています。

use framework "Foundation"

current application’s NSTemporaryDirectory() as text
–> "/var/folders/h4/jfhlwst88xl9z0001s7k9vk00000gr/T/"

★Click Here to Open This Script 

Posted in File path History | Tagged 10.12savvy 10.13savvy 10.14savvy 10.15savvy | Leave a comment

ディスプレイの輝度変更

Posted on 1月 5, 2020 by Takaaki Naganoya

ディスプレイの輝度変更を行うAppleScriptです。

AppleScriptにディスプレイの輝度変更を行う機能はないので、GUI Scripting経由で(画面上のGUI部品を野蛮に操作して)変更するか、あるいは「他の方法」を採用することになります。

本Scriptは「他の方法」をとってみたものです。画面の輝度変更については、そのようなニーズがあり、割とまともにOSに機能が実装されていることもあり、IOKitを呼び出して変更している例がいろいろ見つかります(Objective-Cとかで)。そういったものをFramework化してAppleScriptから呼び出すか、あるいはコマンドライン上で動作するプログラムをAppleScript内に入れて呼び出すか、といったところになります。

Github上で探し物をしてみたところ、nriley氏の「brightness」というツールがコマンドライン上から呼び出せるようになっており、AppleScriptのバンドル内に突っ込んで呼び出しやすそうでした。

そこで、実際にAppleScriptバンドル書類中に突っ込んで、いい感じに呼び出せるように最低限の機能を実装してみました。ディスプレイの接続数の確認(getDisplayNumber)、指定ディスプレイの現在の輝度確認(getBrightNess)、そして指定ディスプレイの輝度設定(setBrightNess)です。

–> Download displayBrightness.scptd (Script Bundle with brightness binary in its bundle)

ディスプレイ番号は1から始まるものとして扱っています。輝度は0.0〜1.0(1.0が一番明るい)までの値を指定します。

一応、brightnessユーティリティでは複数のディスプレイが接続された状態を前提に処理しているのですが、どうせ輝度変更ができるのはMacBook ProやiMacなどの内蔵ディスプレイだけです。外部接続したディスプレイの輝度は変更できません。

本Scriptのようなお気楽実装だと問題になってくるのが、

(1)デスクトップマシン(MacPro、Mac miniなど)で外部ディスプレイを接続していない(ヘッドレス運用)の場合への対処
(2)ノート機+iMac/iMac Proで、メインディスプレイを本体内蔵ディスプレイ「以外のもの」に指定している場合への対処
(3)ノート機で、Lid Closed Mode運用している(本体を閉じて外部ディスプレイをつないで使っている)状態への対処

などです。本Scriptはそこまで厳密な対応を行っていません。ただ、実用上はこのぐらいで問題はなさそうだ、という「割り切り」を行って手を抜いています。

各条件でテストを行って「使える」という確証が得られたら、sdef(AppleScript用語辞書)をつけたライブラリにでもするとよさそうです。

また、本Script中に同梱しているbrightnessツールの実行ファイルはNotarizationを通していないため、2020年2月3日を過ぎると10.15.2以降のmacOSで何らかのダイアログが出て実行をキャンセルされる可能性がありますが、正直なところmacOS 10.15.xは「バグが多すぎ」「実用性なし」と判断。macOS 10.15.xは自分としては「パス」するつもりなので、現時点において対処する必要性を感じません(仕事で納品するバイナリについては全力で対処しますが)。

AppleScript名:displayBrightness.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2020/01/04
—
–  Copyright © 2020 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use scripting additions

set dRes to getDisplayNumber() of me
–> 1

set bRes to getBrightNess(1) of me
–> 0.763672

set sRes to setBrightNess(1, 0.7) of me

on getDisplayNumber()
  set myPath to POSIX path of (path to me)
  
set cmdPath to myPath & "Contents/Resources/brightness"
  
set aRes to do shell script quoted form of cmdPath & " -l"
  
set pList to paragraphs of aRes
  
return (length of pList) div 2
end getDisplayNumber

on getBrightNess(displayNumber as integer)
  set dRes to getDisplayNumber() of me
  
if dRes < displayNumber then error "Your parameter is too large (" & "there is " & (dRes as string) & " display only)."
  
  
set targDispNumber to displayNumber – 1
  
set targString to "display " & (targDispNumber as string) & ": brightness "
  
  
set myPath to POSIX path of (path to me)
  
set cmdPath to myPath & "Contents/Resources/brightness"
  
set aRes to do shell script quoted form of cmdPath & " -l"
  
  
repeat with i in (paragraphs of aRes)
    set j to contents of i
    
if j begins with targString then
      set aOffset to offset of targString in j
      
set resStr to text (aOffset + (length of targString)) thru -1 of j
      
return resStr
    end if
  end repeat
  
  
error "Display’s brightness information is not present"
end getBrightNess

on setBrightNess(displayNumber as integer, targBrightnewss as real)
  set dRes to getDisplayNumber() of me
  
if dRes < displayNumber then error "Your parameter is too large (" & "there is " & (dRes as string) & " display only)."
  
  
set targDispNumber to displayNumber – 1
  
set targString to "display " & (targDispNumber as string) & ": brightness "
  
  
set myPath to POSIX path of (path to me)
  
set cmdPath to myPath & "Contents/Resources/brightness"
  
set aRes to do shell script quoted form of cmdPath & " -l"
  
  
set hitF to false
  
repeat with i in (paragraphs of aRes)
    set j to contents of i
    
if j begins with targString then
      set hitF to true
      
exit repeat
    end if
  end repeat
  
  
if hitF = false then error "There is no display (" & (displayNumber as string) & ")"
  
  
set bRes to do shell script quoted form of cmdPath & " " & (targBrightnewss as string)
  
  
set curBright to getBrightNess(displayNumber) of me
  
  
–結果を評価する
  
if (targBrightnewss as real) is not equal to (curBright as real) then
    return false
  else
    return true
  end if
end setBrightNess

★Click Here to Open This Script 

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

Double PDF v2 Now On Sale

Posted on 1月 3, 2020 by Takaaki Naganoya

Mac App Storeで、Piyomaru SoftwareによるMac用アプリケーション「Double PDF」の新バージョンv2.0をリリースしました。100% AppleScriptで記述しています。

本バージョンは、macOS 10.13においてScripting Bridge経由でPDFViewを正しくアクセスできないバグが発生している症状を回避したものです。表示中のページ管理などをすべてアプリケーション側で行うことにより、機能の回復を実現しました(書いていて情けない)。

v1ではGPUImage.frameworkを利用して画像処理していましたが、これを取り外してすべてAppleScriptで処理するように変更しました。

■v2.0の追加機能
・ダークモード対応
・画像比較時のカラーモード追加(従来はグレースケールのみ)
・30言語に対応(English, Catalan, Chinese, Croatian, Czech, Danish, Dutch, Finnish, French, German, Greek, Hindi, Hungarian, Indonesian, Italian, Japanese, Korean, Malay, Norwegian Bokmål, Polish, Portuguese, Romanian, Russian, Simplified Chinese, Slovak, Spanish, Swedish, Thai, Traditional Chinese, Turkish, Ukrainian, Vietnamese)
・Unicode文字の「Zero Width Space」削除機能を追加

■v2.0の修正機能
・順次Diffチェック時に、アプリケーションアイコン上に描画するプログレスバーの進捗度が間違っていたのを修正

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

指定文字列のAppleScriptを実行してエラー詳細を取得

Posted on 1月 1, 2020 by Takaaki Naganoya

指定文字列のAppleScriptをコンパイル(構文確認、中間コードへのコンパイル)、実行してエラーの詳細を取得するAppleScriptです。

AppleScript名:指定文字列のAppleScriptを実行してエラー詳細を取得.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2020/01/01
—
–  Copyright © 2020 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use scripting additions

set asSourceString to "set a to 123
beepz"
–This AppleScript text has an error

set asObj to current application’s NSAppleScript’s alloc()’s initWithSource:(asSourceString)

–AppleScriptオブジェクトがコンパイル(構文確認、中間コードへの解釈)ずみかどうかをチェック
set isCompiledF1 to asObj’s isCompiled()
–> false

–コンパイル(構文確認)してエラー確認
set isCompiledF2 to asObj’s compileAndReturnError:(reference)
–> {true, missing value}

set exeRes1 to asObj’s executeAndReturnError:(reference)
–> {<NSAppleEventDescriptor: null()>, missing value}–No error

–> {missing value, (NSDictionary) {NSAppleScriptErrorMessage:"beepz変数は定義されていません。", NSAppleScriptErrorBriefMessage:"beepz変数は定義されていません。", NSAppleScriptErrorNumber:-2753, NSAppleScriptErrorRange:(NSConcreteValue) NSRange: {13, 5}}}

★Click Here to Open This Script 

Posted in OSA | Tagged 10.12savvy 10.13savvy 10.14savvy 10.15savvy NSAppleScript | Leave a comment

display text fields Library v1.3

Posted on 12月 31, 2019 by Takaaki Naganoya

「display text fields」AppleScriptライブラリをv1.3にアップデートしました。

–> Download display text fields_v13 (To ~/Library/Script Libraries/)

v1.3ではテキストフィールドの最大横幅の計算を修正し、フィールド数が増えたときにダイアログ上から項目がはみ出さないようにScroll Viewをつけるようにしました。

本来目的としていた用途に使ってみたらイマイチだった点を修正した格好です。AppleScriptで取得した各種アプリケーションのオブジェクトのプロパティ情報をダイアログ上で一覧表示して確認するというのが、自分がこのライブラリを作った目的です。

以下は、サンプルスクリプト「文字列で指定したAppleScriptの実行結果をテキストで取得する v2」についての説明です。

割とえげつない処理をしていますが、作りためておいたルーチンを引っ張り出してきただけなので、書くのにさほど時間はかけていません。

こうしたAppleScriptのプロパティ値をparseするには、スクリプトエディタの結果欄を文字列として取得するか(GUI Scripting経由でやったことがあります)、こうしてメモリ上にスクリプトエディタ+結果表示用のビューを生成してメモリ上でAppleScriptを実行して結果をテキストで取得するということになると思います。前者だとGUI Scriptingの実行権限が必要になるため、Cocoaの機能を利用したほうが手軽という状況です。

(途中で入れ替えた)v2では、macOS 10.15対応、ランタイム環境によってはうまく動かない「as anything」の使用をやめるなどの変更を加えました。

AppleScript名:文字列で指定したAppleScriptの実行結果をテキストで取得する v2.scpt
— 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
  
  
osaCon’s setScriptView:osaView
  
osaCon’s setResultView:resView
  
  
osaView’s setString:srcStr
  
osaCon’s runScript:(missing value)
  
  
set myRes to resView’s |string|() as string
end getResultStringFromScript:

–スクリプトエディタのresult欄に返ってきたテキストをリストに変える
on getListFromText(aText)
  
  
script getListFromTextO
    property aaText : ""
    
property gList : {}
    
property outList : {}
    
property aG : ""
    
property valList : {}
  end script
  
  
copy aText to (aaText of getListFromTextO)
  
  
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
  
  
return contents of (outList of getListFromTextO)
  
end getListFromText

★Click Here to Open This Script 

Posted in dialog GUI OSA | Tagged 10.13savvy 10.14savvy 10.15savvy iTunes NSTextView OSAScript OSAScriptController OSAScriptView | Leave a comment

Post navigation

  • Older posts
  • Newer posts

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

Google Search

Popular posts

  • 開発機としてM2 Mac miniが来たのでガチレビュー
  • macOS 15, Sequoia
  • Pages本執筆中に、2つの書類モード切り替えに気がついた
  • Numbersで選択範囲のセルの前後の空白を削除
  • メキシカンハットの描画
  • Pixelmator Pro v3.6.4でAppleScriptからの操作時の挙動に違和感が
  • AppleScriptによる並列処理
  • Safariで「プロファイル」機能を使うとAppleScriptの処理に影響
  • macOS 15でも変化したText to Speech環境
  • AppleScript入門③AppleScriptを使った「自動化」とは?
  • デフォルトインストールされたフォント名を取得するAppleScript
  • macOS 15 リモートApple Eventsにバグ?
  • 【続報】macOS 15.5で特定ファイル名パターンのfileをaliasにcastすると100%クラッシュするバグ
  • AppleScript入門① AppleScriptってなんだろう?
  • macOS 14で変更になったOSバージョン取得APIの返り値
  • Script Debuggerの開発と販売が2025年に終了
  • NSObjectのクラス名を取得 v2.1
  • macOS 15:スクリプトエディタのAppleScript用語辞書を確認できない
  • 有害ではなくなっていたSpaces
  • AVSpeechSynthesizerで読み上げテスト

Tags

10.11savvy (1101) 10.12savvy (1242) 10.13savvy (1391) 10.14savvy (587) 10.15savvy (438) 11.0savvy (283) 12.0savvy (212) 13.0savvy (194) 14.0savvy (147) 15.0savvy (135) CotEditor (66) Finder (51) iTunes (19) Keynote (119) NSAlert (61) NSArray (51) NSBitmapImageRep (20) NSBundle (20) NSButton (34) NSColor (53) NSDictionary (28) NSFileManager (23) NSFont (21) NSImage (41) NSJSONSerialization (21) NSMutableArray (63) NSMutableDictionary (22) NSPredicate (36) NSRunningApplication (56) NSScreen (30) NSScrollView (22) NSString (119) NSURL (98) NSURLRequest (23) NSUTF8StringEncoding (30) NSView (33) NSWorkspace (20) Numbers (76) Pages (55) Safari (44) Script Editor (27) WKUserContentController (21) WKUserScript (20) WKWebView (23) WKWebViewConfiguration (22)

カテゴリー

  • 2D Bin Packing
  • 3D
  • AirDrop
  • AirPlay
  • Animation
  • AppleScript Application on Xcode
  • Beginner
  • Benchmark
  • beta
  • Bluetooth
  • Books
  • boolean
  • bounds
  • Bug
  • Calendar
  • call by reference
  • check sum
  • Clipboard
  • Cocoa-AppleScript Applet
  • Code Sign
  • Color
  • Custom Class
  • date
  • dialog
  • diff
  • drive
  • Droplet
  • exif
  • file
  • File path
  • filter
  • folder
  • Font
  • Font
  • GAME
  • geolocation
  • GUI
  • GUI Scripting
  • Hex
  • History
  • How To
  • iCloud
  • Icon
  • Image
  • Input Method
  • Internet
  • iOS App
  • JavaScript
  • JSON
  • JXA
  • Keychain
  • Keychain
  • Language
  • Library
  • list
  • Locale
  • Localize
  • Machine Learning
  • Map
  • Markdown
  • Menu
  • Metadata
  • MIDI
  • MIME
  • Natural Language Processing
  • Network
  • news
  • Noification
  • Notarization
  • Number
  • Object control
  • OCR
  • OSA
  • parallel processing
  • PDF
  • Peripheral
  • process
  • PRODUCTS
  • QR Code
  • Raw AppleEvent Code
  • Record
  • rectangle
  • recursive call
  • regexp
  • Release
  • Remote Control
  • Require Control-Command-R to run
  • REST API
  • Review
  • RTF
  • Sandbox
  • Screen Saver
  • Script Libraries
  • sdef
  • search
  • Security
  • selection
  • shell script
  • Shortcuts Workflow
  • Sort
  • Sound
  • Spellchecker
  • Spotlight
  • SVG
  • System
  • Tag
  • Telephony
  • Text
  • Text to Speech
  • timezone
  • Tools
  • Update
  • URL
  • UTI
  • Web Contents Control
  • WiFi
  • XML
  • XML-RPC
  • イベント(Event)
  • 未分類

アーカイブ

  • 2025年6月
  • 2025年5月
  • 2025年4月
  • 2025年3月
  • 2025年2月
  • 2025年1月
  • 2024年12月
  • 2024年11月
  • 2024年10月
  • 2024年9月
  • 2024年8月
  • 2024年7月
  • 2024年6月
  • 2024年5月
  • 2024年4月
  • 2024年3月
  • 2024年2月
  • 2024年1月
  • 2023年12月
  • 2023年11月
  • 2023年10月
  • 2023年9月
  • 2023年8月
  • 2023年7月
  • 2023年6月
  • 2023年5月
  • 2023年4月
  • 2023年3月
  • 2023年2月
  • 2023年1月
  • 2022年12月
  • 2022年11月
  • 2022年10月
  • 2022年9月
  • 2022年8月
  • 2022年7月
  • 2022年6月
  • 2022年5月
  • 2022年4月
  • 2022年3月
  • 2022年2月
  • 2022年1月
  • 2021年12月
  • 2021年11月
  • 2021年10月
  • 2021年9月
  • 2021年8月
  • 2021年7月
  • 2021年6月
  • 2021年5月
  • 2021年4月
  • 2021年3月
  • 2021年2月
  • 2021年1月
  • 2020年12月
  • 2020年11月
  • 2020年10月
  • 2020年9月
  • 2020年8月
  • 2020年7月
  • 2020年6月
  • 2020年5月
  • 2020年4月
  • 2020年3月
  • 2020年2月
  • 2020年1月
  • 2019年12月
  • 2019年11月
  • 2019年10月
  • 2019年9月
  • 2019年8月
  • 2019年7月
  • 2019年6月
  • 2019年5月
  • 2019年4月
  • 2019年3月
  • 2019年2月
  • 2019年1月
  • 2018年12月
  • 2018年11月
  • 2018年10月
  • 2018年9月
  • 2018年8月
  • 2018年7月
  • 2018年6月
  • 2018年5月
  • 2018年4月
  • 2018年3月
  • 2018年2月

https://piyomarusoft.booth.pm/items/301502

メタ情報

  • ログイン
  • 投稿フィード
  • コメントフィード
  • WordPress.org

Forum Posts

  • 人気のトピック
  • 返信がないトピック

メタ情報

  • ログイン
  • 投稿フィード
  • コメントフィード
  • WordPress.org
Proudly powered by WordPress
Theme: Flint by Star Verte LLC