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

月: 2019年9月

Google Chromeで最前面のWindowで表示中のページのHTMLソースを取得する

Posted on 9月 30, 2019 by Takaaki Naganoya

Google Chromeの最前面のウィンドウで表示中のページのHTMLソースを取得するAppleScriptです。

ChromeをMacの自動処理の部品として使おうとはまったく考えませんが、命令が存在しないぐらいで「できない」というのも何なので、JavaScript経由でソースを取得できないか調べてみたら、できました。

あらかじめ、Google Chromeの「表示」>「開発/管理」>「Apple EventsからのJavaScriptを許可」を実行しておく必要があります。

AppleScript名:最前面のウィンドウのHTMLソースを取得する
tell application "Google Chrome"
  tell window 1
    tell active tab
      set htmlRes to (execute javascript "document.getElementsByTagName(’html’)[0].innerHTML")
    end tell
  end tell
end tell

★Click Here to Open This Script 

com.google.Chrome

Posted in Internet JavaScript | Tagged 10.12savvy 10.13savvy 10.14savvy Google Chrome | Leave a comment

PDFのサイズをpointで取得 v2

Posted on 9月 28, 2019 by Takaaki Naganoya

指定PDFのサイズ(幅、高さ)をPointで取得するAppleScriptです。

以前に掲載したバージョンでは、macOS 10.13以降でboundsの値の返り方が変わったことに対応できていないので(それ以前に作ったので無理もないというか、勝手にAppleが仕様を変えたのが悪い)、対処してみました。

AppleScript名:PDFのサイズをpointで取得 v2.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/09/28
—
–  Copyright © 2019 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "Quartz"
use framework "AppKit"

property |NSURL| : a reference to current application’s |NSURL|
property PDFDocument : a reference to current application’s PDFDocument

set aHFSPath to (choose file of type {"com.adobe.pdf"} with prompt "Select PDF")
set sizeRes to retPDFSizeInfo(aHFSPath) of me
–>  {​​​​​width:595.28, ​​​​​height:841.89​​​}

–PDFのサイズを取得する(単位:Point)
on retPDFSizeInfo(aHFSPath)
  set aPOSIX to POSIX path of aHFSPath
  
set aURL to (|NSURL|’s fileURLWithPath:aPOSIX)
  
  
set aPDFdoc to PDFDocument’s alloc()’s initWithURL:aURL
  
set pCount to aPDFdoc’s pageCount()
  
set aPage to aPDFdoc’s pageAtIndex:0
  
  
set aBounds to aPage’s boundsForBox:(current application’s kPDFDisplayBoxMediaBox)
  
  
set aClass to class of aBounds
  
if aClass = record then
    set aSize to |size| of aBounds
  else if aClass = list then
    set aWidth to item 1 of item 2 of aBounds
    
set aHeight to item 2 of item 2 of aBounds
    
set aSize to {width:aWidth, height:aHeight}
  else
    error "Wrong PDF….Can not get bounds from PDF"
  end if
  
  
return aSize
end retPDFSizeInfo

★Click Here to Open This Script 

Posted in list PDF Record | Tagged 10.12savvy 10.13savvy 10.14savvy NSURL PDFDocument | Leave a comment

mapboxSpeech Sample

Posted on 9月 27, 2019 by Takaaki Naganoya

mapboxが提供しているMapBoxSpeechフレームワークを呼び出すAppleScriptです。

mapboxは地図系の各種機能をWeb APIで提供しています。その一環としてGithub上でNatural-sounding text-to-speech Frameworkを提供しており、これをAppleScriptから呼び出してみました。

Github上のサンプルコードでは、AppleScript(Xcode上のプロジェクト)から呼び出すサンプルも掲載されているのですが、通常のScript EditorやScript Debugger上から呼び出す方法は掲載されていませんでした(しかも、サンプルそのままだと動く気配がないんですが、、、)。

# Xcode上で作成したアプリケーションだと、MapboxSpeech.Frameworkが、組み込んだアプリケーション側のInfo.plist内の指定のエントリに書かれているAccess tokenを読み込んでREST APIにアクセスできるとか。単体でAppleScriptからFrameworkを呼び出すような使い方は想定していなかったようです>サンプル

そこで、実際にmapboxにサインアップして、API Key(というか、プロジェクト単位でのToken)を取得、実際にGithub上で公開されているフレームワークをmacOS用にビルドし、通常のAppleScriptから呼び出してみました。

以下のアプレットは実行すると実際に日本語サンプル(たぶん)の文章を読み上げてくれます。実際に本Script(アプレットではなく)をAppleScriptとしてご自分の環境で動かすためには、Frameworkをインストールし、Script Debugger上で動かす(macOS 10.14以降)か、SIPを解除した環境(macOS 10.14以降)でスクリプトエディタ上で実行することになります。その際には、mapboxのWebサイト上でサインアップしてご自分のAccess tokenを取得してください。サインアップすると公開Access tokenを取得できますが、そちらではなく個別のプロジェクトをWebサイト上で作成して(Test AppleScriptとか)、そちらのAccess tokenを利用してください。

–> Download MapboxSpeech.framework(To ~/Library/Frameworks/)

–> mapboxSpeech Sample Run-Only(Code-Signed Executable Applet with Framework)

……で、実際にサンプル文章を読み上げてみたところ、英文なのに英文っぽくない日本語みたいな発音で、ちょっと「ナニコレ?」と思ってしまいましたが、冗談半分で日本語テキストをパラメータに指定してみたら、ちゃんと日本語を読み上げるのでビビりました。

この手のWebサービスで日本語対応はしておらず、英語+ヨーロッパの数カ国語のみサポートというのが普通です。

OS標準のsayコマンドよりも形態素解析が弱いようなので、文節ごとに読点(、)を入れてあげる必要はありますが、それでも日本語のテキストを読み上げてしまうのにはちょっと驚かされました。

AppleScript名:mapboxSpeech Sample.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/09/27
—
–  Copyright © 2019 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use framework "MapboxSpeech" –https://github.com/mapbox/mapbox-speech-swift
use framework "AVFoundation"
use scripting additions

on run
  set theOptions to current application’s MBSpeechOptions’s alloc()
  
theOptions’s initWithText:"こんにちは、私の名前は、「ながのや」 です。"
  
  
set speechSynthesizer to current application’s MBSpeechSynthesizer’s alloc()’s initWithAccessToken:"xx.xxX.X_XXxxxxxXXXXXxXxXXxxX"
  
set theURL to speechSynthesizer’s URLForSynthesizingSpeechWithOptions:theOptions
  
set theData to the current application’s NSData’s dataWithContentsOfURL:theURL
  
  
set aAudioPlayer to current application’s AVAudioPlayer’s alloc()’s initWithData:theData |error|:(missing value)
  
aAudioPlayer’s prepareToPlay()
  
aAudioPlayer’s setNumberOfLoops:0
  
aAudioPlayer’s setDelegate:me
  
aAudioPlayer’s play()
end run

–音楽再生の終了のDelegate Methodを取得
on audioPlayerDidFinishPlaying:anAudioplayer successfully:aFlag
  tell current application to quit
end audioPlayerDidFinishPlaying:successfully:

★Click Here to Open This Script 

Posted in REST API Sound Text to Speech | Tagged 10.12savvy 10.13savvy 10.14savvy | Leave a comment

TTSで日本語数値読み上げ

Posted on 9月 26, 2019 by Takaaki Naganoya

桁数の大きな数値のText To Speech(TTS)読み上げのAppleScriptです。

# 日本語環境における枝葉的な(マニアックな)数値表現の仕様に関する話であり、他の言語では関係ない話です。漢字文化圏で使われる数値表現のようですが、たとえば中国や韓国で使われている数値桁表現との間で厳密な互換性があるかといった確認は行なっておりません

実行前に日本語TTS読み上げ音声の「Otoya」あるいは「Kyoko」をインストールしておいてください。

まず、AppleScriptが指数表示なしに表現できる数値は10^9程度で、それを超えると指数表示になります。

ただし、指数表示になった数値を数値文字列に変換するノウハウは全世界的に共有されており、そのためのサブルーチン(Stringify)を呼び出すだけで済みます。

AppleScriptのsayコマンドでは「100兆」までの読み上げはそれっぽく実行してくれますが、「1000兆」になると読み上げ内容が数字の羅列になってしまいます。

これについても、大きな数値を日本語数値エンコーディング文字列に変換するサブルーチンを昔から公開しており(本Blog開設当初の11年前に掲載)、それを呼び出すだけで日本語数値表現文字列に変換できるため、読み上げられることでしょう。

Number Japanese English
1 一(いち) one
10 十(じゅう) ten
100 百(ひゃく) hundred
1000 千(せん) thousand
10000 万(まん) 10 thousand
100000 十万(じゅうまん) 100 thousand
1000000 百万(ひゃくまん) million
10000000 千万(せんまん) 10 million
100000000 億(おく) 100million
1000000000000 兆(ちょう) villion
1000000000000000 京(けい) thousand villion
100000000000000000 100京(ひゃっけい) trillion
10^24 丈(じょ)
10^28 穣(じょう)
10^52 恒河沙(ごうがしゃ)
10^56 阿僧祇(あそうぎ)
10^60 那由他(なゆた)
10^64 不可思議(ふかしぎ)
10^68 無量大数(むりょうたいすう)

とはいえ、「阿僧祇(あそうぎ、10^56)「那由多(なゆた、10^60)」といった数値桁を読み上げさせるとTTSが正しく読み上げてくれません。さすがにこんなにマニアックな数値表現はカバーしなくてよいでしょう。「丈(じょ)」「穣(じょう)」など似た音の桁が存在するあたり、これらは口に出して読み上げるものではなく、文字で読むためだけのものだと強く感じるものです。

AppleScript名:TTSで日本語数値読み上げ
repeat with i from 0 to 15
  set aNum to (10 ^ i)
  
say Stringify(aNum) of me using "Kyoko" –or "Otoya"
end repeat

on Stringify(x) — for E+ numbers
  set x to x as string
  
set {tids, AppleScript’s text item delimiters} to {AppleScript’s text item delimiters, {"E+"}}
  
if (count (text items of x)) = 1 then
    set AppleScript’s text item delimiters to {tids}
    
return x
  else
    set {n, z} to {text item 1 of x, (text item 2 of x) as integer}
    
set AppleScript’s text item delimiters to {tids}
    
set i to character 1 of n
    
set decSepChar to character 2 of n — "." or ","
    
set d to text 3 thru -1 of n
    
set l to count d
    
if l > z then
      return (i & (text 1 thru z of d) & decSepChar & (text (z + 1) thru -1 of d))
    else
      repeat (z – l) times
        set d to d & "0"
      end repeat
      
return (i & d)
    end if
  end if
end Stringify

★Click Here to Open This Script 

AppleScript名:TTSで日本語数値読み上げ v2
repeat with i from 15 to 70
  set aNum to (10 ^ i)
  
set jRes to encodeJapaneseNumText(aNum) of japaneseNumberEncodingKit
  
say jRes using "Kyoko" –or "Otoya"
end repeat

–課題:オーバーフローチェックを行っていない
set a to "102320120000108220010"
set jRes to encodeJapaneseNumText(a) of japaneseNumberEncodingKit
–> "1垓232京120兆1億822万10"

script japaneseNumberEncodingKit
  –数字文字列を日本語数値表現文字列に変換
  
on encodeJapaneseNumText(aNum)
    
    
set aText to Stringify(aNum) of me
    
set aText to aText as Unicode text
    
set dotText to "." as Unicode text
    
set upperDigit to ""
    
set lowerDigit to ""
    
    
–小数点の処理
    
if dotText is in aText then
      set b to offset of dotText in aText
      
set upperDigit to characters 1 thru (b – 1) of aText
      
set upperDigit to upperDigit as Unicode text
      
set lowerDigit to characters b thru -1 of aText
      
set lowerDigit to lowerDigit as Unicode text
    else
      set upperDigit to aText
    end if
    
    
    
set scaleList3 to {"", "万", "億", "兆", "京", "垓", "丈", "壌", "溝", "砂", "正", "載", "極", "恒河沙", "阿僧梢", "那由他", "不可思議", "無量大数"}
    
set splitDigit to 4
    
set nList to splitByDigit(upperDigit, splitDigit) of me
    
set nList to reverse of nList
    
    
set resText to ""
    
set digCount to 1
    
repeat with i in nList
      set b to (contents of i) as number
      
if b is not equal to 0 then
        set resText to (b as text) & item digCount of scaleList3 & resText
      end if
      
set digCount to digCount + 1
    end repeat
    
    
    
    
return resText & lowerDigit
    
  end encodeJapaneseNumText
  
  
–指定桁数で区切る
  
on splitByDigit(a, splitDigit)
    set aList to characters of a
    
set aList to reverse of aList
    
log aList
    
set resList to {}
    
set tempT to ""
    
set tempC to 1
    
repeat with i in aList
      set tempT to contents of i & tempT
      
if tempC mod splitDigit = 0 then
        set resList to {tempT} & resList
        
set tempT to ""
      end if
      
set tempC to tempC + 1
    end repeat
    
    
if tempT is not equal to "" then
      set resList to {tempT} & resList
    end if
    
    
resList
    
  end splitByDigit
  
  
  
  
on Stringify(x) — for E+ numbers
    set x to x as string
    
set {tids, AppleScript’s text item delimiters} to {AppleScript’s text item delimiters, {"E+"}}
    
if (count (text items of x)) = 1 then
      set AppleScript’s text item delimiters to tids
      
return x
    else
      set {n, z} to {text item 1 of x, (text item 2 of x) as integer}
      
set AppleScript’s text item delimiters to tids
      
set i to character 1 of n
      
set decSepChar to character 2 of n — "." or ","
      
set d to text 3 thru -1 of n
      
set l to count d
      
if l > z then
        return (i & (text 1 thru z of d) & decSepChar & (text (z + 1) thru -1 of d))
      else
        repeat (z – l) times
          set d to d & "0"
        end repeat
        
return (i & d)
      end if
    end if
  end Stringify
end script

★Click Here to Open This Script 

Posted in Number System Text Text to Speech | Tagged 10.12savvy 10.13savvy 10.14savvy | Leave a comment

Safariで現在見えている表を抽出してCSV書き出し

Posted on 9月 24, 2019 by Takaaki Naganoya

Safariの最前面のウィンドウで表示中のページのうち、現在ウィンドウ内に表示中の表要素をCSV書き出ししてNumbersでオープンするAppleScriptです。

このところ下調べを行なっていた「Webブラウザで表示中の要素を処理する」「表示中ではない要素は処理をしない」というScriptです。

これで、「表の一部を選択しておく」とかいった操作は不要になりました。ウィンドウ内に表示されている表をWebコンテンツ内部の表示座標をもとに自動抽出します。表示エリア外に位置しているものは書き出し処理しません。

各DOM ElementsのWebコンテンツ中の表示座標を取得して、絞り込みを行なっています。ただし、各DOM座標はWebブラウザのスクロールにしたがって数値が変わる(相対座標)ため、少々手こずりました。また、本Scriptでは上下スクロールのみ考慮してDOM要素の抽出を行なっており、横に長いページの横方向スクロールは考慮しておりません。

本Scriptは大量一括処理を志向するプログラムではなく、「見えているもの」をそのまま処理してほしいという考えで作ったものでもあり、Webブラウザ(Safari)で表示中のページのソースを取得してそのまま処理しています。つまり、ユーザーが閲覧中のページのデータそのものを処理しています。

これは、ページのソースを取得するコマンドを持っていないGoogle Chromeにはできない処理です(同じURLの内容を別途curlコマンドなどで取得すればOK。Cookie値などの再現が大変でしょうけれども)。

その他、実際に作って使ってみた感想は、装飾用に使われている表データまで取り込んでしまう点に不満があるぐらいでしょうか。これら「ゴミデータ」(再利用する価値のない装飾用の表データ)を区別するために、行数が足りない場合には書き出さないといった「足切り」を行う必要性を感じます。

–> Download VisibleTableExporter(Code-signed executable applet with Framework in its bundle)

AppleScript名:Safariで現在見えている表を抽出してCSV書き出し.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/09/22
—
–  Copyright © 2019 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "HTMLReader" –https://github.com/nolanw/HTMLReader

property NSUUID : a reference to current application’s NSUUID
property NSString : a reference to current application’s NSString
property HTMLDocument : a reference to current application’s HTMLDocument
property NSMutableArray : a reference to current application’s NSMutableArray
property NSJSONSerialization : a reference to current application’s NSJSONSerialization

set aTag to "table"

set indRes to getVisibleElementIndexList(aTag) of me
if indRes = false or indRes = {} then
  display notification "No Visible Table in Web browser"
  
return
end if

tell application "Safari"
  tell front document
    set aSource to source
  end tell
end tell

repeat with i in indRes
  set inList to filterATableAndPaseCells(aSource, i, aTag) of me
  
if inList = false or inList = {} then return
  
set aUUID to current application’s NSUUID’s UUID()’s UUIDString() as text
  
set aNewFile to ((path to desktop) as string) & aUUID & ".csv"
  
saveAsCSV(inList, aNewFile) of me
  
  
tell application "Numbers"
    open (aNewFile as alias)
  end tell
end repeat

tell application "Numbers" to activate

on filterATableAndPaseCells(aSource as string, targInd as integer, aTag as string)
  set aHTML to current application’s HTMLDocument’s documentWithString:(aSource as string)
  
  
–Table要素をリストアップ
  
set eList to (aHTML’s nodesMatchingSelector:aTag) as list
  
set aObj to contents of item (targInd + 1) of eList
  
  
  
–Count columns of Table Header
  
set aTableHeader to (aObj’s nodesMatchingSelector:"tr")’s firstObject()
  
set hList to aTableHeader’s nodesMatchingSelector:"th"
  
set hStrList to {}
  
repeat with i1 in hList
    set the end of hStrList to i1’s textContent() as string
  end repeat
  
set hLen to length of hStrList –count columns
  
  
–Acquire whole table body contents
  
set aTableBody to (aObj’s nodesMatchingSelector:"tbody")’s firstObject()
  
set bList to aTableBody’s nodesMatchingSelector:"td"
  
set bbList to {}
  
repeat with i2 in bList
    set the end of bbList to i2’s textContent() as string
  end repeat
  
  
set tbList to makeList1DTo2D(bbList, hLen) of me
  
  
return {hStrList} & tbList
end filterATableAndPaseCells

–1D Listを2D化
on makeList1DTo2D(orig1DList as list, aMax)
  set tbList to {}
  
set tmpList to {}
  
set aCount to 1
  
  
repeat with i3 in orig1DList
    set j to contents of i3
    
set the end of tmpList to j
    
    
if aCount ≥ aMax then
      set aCount to 1
      
set the end of tbList to tmpList
      
set tmpList to {}
    else
      set aCount to aCount + 1
    end if
  end repeat
  
  
return tbList
end makeList1DTo2D

–Safariのウィンドウ上で表示中のDOM Elementsを座標計算して返す
on getVisibleElementIndexList(aTag as string)
  tell application "Safari"
    set dCount to count every document
    
if dCount = 0 then return false
    
    
set jRes to do JavaScript "var winWidth = window.innerWidth,
winHeight = window.innerHeight,
winLeft = window.scrollX
winTop = window.scrollY,
winBottom = winTop + winHeight,
winRight = winLeft + winWidth,
    elementsArray = document.body.getElementsByTagName(’" & aTag & "’),
    elemLen = elementsArray.length,
inView = [];
      
    var step;
    for (step = 0 ; step < elemLen ; step++) {
      var tmpElem = document.body.getElementsByTagName(’" & aTag & "’)[step];
      var bVar = tmpElem.getBoundingClientRect();
      if (bVar.top > 0 && bVar.top < winHeight) {
        inView.push(step);
      }
    }
    JSON.stringify(inView);"
in front document
    
    
set jList to parseJSONAsList(jRes) of me
    
return jList
    
  end tell
end getVisibleElementIndexList

on parseJSONAsList(jsRes as string)
  set jsonString to NSString’s stringWithString:jsRes
  
set jsonData to jsonString’s dataUsingEncoding:(current application’s NSUTF8StringEncoding)
  
set aJsonDict to NSJSONSerialization’s JSONObjectWithData:jsonData options:0 |error|:(missing value)
  
return aJsonDict as list
end parseJSONAsList

–Save 2D List to CSV file
on saveAsCSV(aList as list, aPath)
  set crlfChar to (string id 13) & (string id 10)
  
set LF to (string id 10)
  
set wholeText to ""
  
  
repeat with i in aList
    set newLine to {}
    
    
–Sanitize (Double Quote)
    
repeat with ii in i
      set jj to ii as text
      
set kk to repChar(jj, string id 34, (string id 34) & (string id 34)) of me –Escape Double Quote
      
set the end of newLine to kk
    end repeat
    
    
–Change Delimiter
    
set aLineText to ""
    
set curDelim to AppleScript’s text item delimiters
    
set AppleScript’s text item delimiters to "\",\""
    
set aLineList to newLine as text
    
set AppleScript’s text item delimiters to curDelim
    
    
set aLineText to repChar(aLineList, return, "") of me –delete return
    
set aLineText to repChar(aLineText, LF, "") of me –delete lf
    
    
set wholeText to wholeText & "\"" & aLineText & "\"" & crlfChar –line terminator: CR+LF
  end repeat
  
  
if (aPath as string) does not end with ".csv" then
    set bPath to aPath & ".csv" as Unicode text
  else
    set bPath to aPath as Unicode text
  end if
  
  
writeToFileAsUTF8(wholeText, bPath, false) of me
  
end saveAsCSV

on writeToFileAsUTF8(this_data, target_file, append_data)
  tell current application
    try
      set the target_file to the target_file as text
      
set the open_target_file to open for access file target_file with write permission
      
if append_data is false then set eof of the open_target_file to 0
      
write this_data as «class utf8» to the open_target_file starting at eof
      
close access the open_target_file
      
return true
    on error error_message
      try
        close access file target_file
      end try
      
return error_message
    end try
  end tell
end writeToFileAsUTF8

on repChar(origText as text, targChar as text, repChar as text)
  set curDelim to AppleScript’s text item delimiters
  
set AppleScript’s text item delimiters to targChar
  
set tmpList to text items of origText
  
set AppleScript’s text item delimiters to repChar
  
set retText to tmpList as string
  
set AppleScript’s text item delimiters to curDelim
  
return retText
end repChar

★Click Here to Open This Script 

Posted in file JavaScript JSON list Text | Tagged 10.12savvy 10.13savvy 10.14savvy HTMLDocument NSJSONSerialization NSMutableArray NSString NSUUID Numbers Safari | 1 Comment

Safariで指定のDOM Elementの情報を取得する

Posted on 9月 22, 2019 by Takaaki Naganoya

Safariで表示中の最前面のDocument内の指定Tag、指定Index(出現順、0はじまり)のDOM Elementの詳細なプロパティ値を取得するAppleScriptです。

複数のTableが存在しているページのそれぞれのプロパティ値を取得してdiffを取るための調査用Scriptです。

AppleScript名:Safariで指定のDOM Elementの情報を取得する
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

tell application "Safari"
  set jsStr to "var elementsArray = document.body.getElementsByTagName(’table’);
    aVar = window.getComputedStyle(elementsArray[1]);
  JSON.stringify(aVar);"
  
  
set aHeight to do JavaScript jsStr in front document
  
set cRes to parseJSONAsRecord(aHeight) of me
end tell

–> {|95|:"font-style", |50|:"caret-color", |96|:"font-synthesis", |51|:"clear", |97|:"font-variant", webkitMaskPosition:"0% 0%", |52|:"clip", |98|:"font-variant-alternates", webkitHyphens:"manual", |right|:"auto", |53|:"clip-path", |99|:"font-variant-caps", |54|:"clip-rule", backgroundAttachment:"scroll", willChange:"auto", |55|:"color", margin:"0px 0px 20px", marginTop:"0px", |10|:"animation-name", |56|:"color-interpolation", webkitColumnBreakBefore:"auto", baselineShift:"baseline", webkitLineSnap:"none", |11|:"animation-play-state", |57|:"color-interpolation-filters", scrollSnapMargin:"0px", transform:"none", |12|:"animation-timing-function", |58|:"color-rendering", |13|:"background-attachment", |59|:"color-scheme", fontVariantPosition:"normal", gridAutoFlow:"row", |14|:"background-blend-mode", position:"static", |15|:"background-clip", |16|:"background-color", |17|:"background-image", webkitMaskComposite:"source-over", |18|:"background-origin", justifyItems:"normal", |19|:"background-position", colorRendering:"auto", |color|:"rgb(51, 51, 51)", listStyleImage:"none", borderBottom:"0px none rgb(128, 128, 128)", backgroundOrigin:"padding-box", counterIncrement:"none", webkitMaskRepeatY:"", writingMode:"horizontal-tb", borderInlineEndStyle:"none", columnGap:"normal", textDecorationLine:"none", scrollSnapMarginBottom:"0px", strokeColor:"rgba(0, 0, 0, 0)", webkitBoxOrdinalGroup:"1", alignItems:"normal", caretColor:"rgb(51, 51, 51)", webkitMarginBottomCollapse:"collapse", paddingLeft:"0px", fontWeight:"normal", padding:"0px", scrollPaddingTop:"0px", flexGrow:"0", boxSizing:"border-box", webkitBackgroundSize:"auto", marginBottom:"20px", gridTemplateRows:"none", background:"rgba(0, 0, 0, 0) none repeat scroll 0% 0% / auto padding-box border-box", fontDisplay:"", speakAs:"normal", |left|:"auto", webkitBoxDecorationBreak:"slice", scrollSnapAlign:"none none", backgroundPosition:"0% 0%", gridRowStart:"auto", borderBlockStartWidth:"0px", borderTopLeftRadius:"0px", webkitUserDrag:"auto", borderRightColor:"rgb(128, 128, 128)", fontVariantAlternates:"normal", breakInside:"auto", webkitTextZoom:"normal", marker:"", webkitClipPath:"none", strokeLinejoin:"miter", webkitMarquee:"", breakAfter:"auto", webkitMaskPositionX:"0%", whiteSpace:"normal", backgroundColor:"rgba(0, 0, 0, 0)", flexDirection:"row", columns:"auto auto", transformOriginX:"", clip:"auto", emptyCells:"show", transformOrigin:"413.75px 309.4021911621094px", borderLeftColor:"rgb(128, 128, 128)", flex:"0 1 auto", webkitTextStroke:"", clipRule:"nonzero", grid:"none / none / none / row / auto / auto", listStyleType:"disc", maxWidth:"none", borderInlineStartStyle:"none", webkitTextOrientation:"mixed", clipPath:"none", justifySelf:"auto", clear:"none", transformOriginY:"", overflowWrap:"break-word", webkitHyphenateLimitAfter:"auto", tabSize:"8", marginBlockStart:"0px", |120|:"image-rendering", unicodeRange:"", gridColumnEnd:"auto", webkitRubyPosition:"before", |220|:"text-rendering", animationDirection:"normal", webkitMaskOrigin:"border-box", |121|:"isolation", fontStyle:"normal", |320|:"-webkit-text-emphasis-position", |221|:"text-shadow", webkitTextFillColor:"rgb(51, 51, 51)", |122|:"justify-content", borderBottomLeftRadius:"0px", |321|:"-webkit-text-emphasis-style", |80|:"fill-rule", |222|:"text-transform", |123|:"justify-items", |81|:"filter", |322|:"-webkit-text-fill-color", transformOriginZ:"", borderRightWidth:"0px", |82|:"flex-basis", |223|:"text-underline-position", |124|:"justify-self", webkitTextSizeAdjust:"auto", |83|:"flex-direction", |323|:"-webkit-text-orientation", |224|:"top", |84|:"flex-flow", |125|:"kerning", |150|:"opacity", |85|:"flex-grow", |324|:"-webkit-text-security", borderBlockStartStyle:"none", |225|:"touch-action", |40|:"border-top-color", |86|:"flex-shrink", |126|:"left", |250|:"-apple-color-filter", |151|:"order", |41|:"border-top-left-radius", |87|:"flex-wrap", |325|:"-webkit-text-size-adjust", |226|:"transform", border:"0px none rgb(128, 128, 128)", |42|:"border-top-right-radius", |88|:"float", |127|:"letter-spacing", |152|:"orphans", |251|:"-webkit-appearance", |43|:"border-top-style", |89|:"flood-color", |227|:"transform-box", |326|:"-webkit-text-stroke-color", |252|:"-webkit-backdrop-filter", |44|:"border-top-width", |128|:"lighting-color", |153|:"outline-color", |327|:"-webkit-text-stroke-width", borderBlockEndColor:"rgb(128, 128, 128)", |45|:"bottom", |228|:"transform-origin", borderInlineEnd:"0px none rgb(128, 128, 128)", |253|:"-webkit-backface-visibility", |129|:"line-break", |46|:"box-shadow", |154|:"outline-offset", |328|:"-webkit-text-zoom", alignContent:"normal", borderLeftStyle:"none", |47|:"box-sizing", |229|:"transform-style", |254|:"-webkit-background-clip", colorScheme:"auto", shapeOutside:"none", |48|:"buffered-rendering", |155|:"outline-style", |180|:"ry", |329|:"-webkit-transform-style", minBlockSize:"0px", |49|:"caption-side", |255|:"-webkit-background-composite", inlineSize:"827.5px", |280|:"-webkit-font-kerning", |156|:"outline-width", textDecorationColor:"rgb(51, 51, 51)", |181|:"scroll-padding", transitionProperty:"all", webkitBoxDirection:"normal", webkitInitialLetter:"normal", |256|:"-webkit-background-origin", gridColumn:"auto / auto", |281|:"-webkit-font-smoothing", |157|:"overflow-wrap", listStyle:"disc outside none", |182|:"scroll-padding-bottom", webkitMaskBoxImage:"none", floodColor:"rgb(0, 0, 0)", webkitTextEmphasisPosition:"over right", |257|:"-webkit-background-size", scrollSnapMarginRight:"0px", |282|:"-webkit-hyphenate-character", |158|:"overflow-x", webkitTextSecurity:"none", |183|:"scroll-padding-left", columnRule:"0px none rgb(51, 51, 51)", |258|:"-webkit-border-fit", gridColumnStart:"auto", |283|:"-webkit-hyphenate-limit-after", |159|:"overflow-y", touchAction:"auto", |184|:"scroll-padding-right", webkitFontSizeDelta:"", webkitLocale:"ja", |259|:"-webkit-border-horizontal-spacing", |284|:"-webkit-hyphenate-limit-before", colorInterpolation:"sRGB", borderTopColor:"rgb(128, 128, 128)", |185|:"scroll-padding-top", |285|:"-webkit-hyphenate-limit-lines", hangingPunctuation:"none", |186|:"scroll-snap-align", mask:"none", borderRight:"0px none rgb(128, 128, 128)", paddingInlineStart:"0px", webkitBackgroundOrigin:"padding-box", |286|:"-webkit-hyphens", |187|:"scroll-snap-margin", pageBreakAfter:"auto", colorProfile:"", textAnchor:"start", |287|:"-webkit-initial-letter", webkitMaskSize:"auto", |188|:"scroll-snap-margin-bottom", overflowX:"visible", |288|:"-webkit-line-align", strokeLinecap:"butt", |189|:"scroll-snap-margin-left", |289|:"-webkit-line-box-contain", borderBottomColor:"rgb(128, 128, 128)", paddingRight:"0px", fontOpticalSizing:"auto", borderImage:"none", floodOpacity:"1", webkitAspectRatio:"auto", webkitColumnProgression:"normal", alignSelf:"auto", display:"table", borderRadius:"0px", maxInlineSize:"none", minHeight:"0px", strokeMiterlimit:"4", webkitBorderVerticalSpacing:"0px", webkitMaskClip:"border-box", webkitBorderHorizontalSpacing:"0px", objectPosition:"50% 50%", kerning:"0", borderStyle:"none", visibility:"visible", textShadow:"none", borderLeftWidth:"0px", shapeImageThreshold:"0", scrollSnapMarginTop:"0px", markerMid:"none", scrollPadding:"0px", markerEnd:"none", webkitFontKerning:"auto", borderBottomWidth:"0px", float:"none", placeSelf:"auto auto", webkitBackgroundComposite:"source-over", borderTop:"0px none rgb(128, 128, 128)", backgroundRepeat:"repeat", webkitMarqueeDirection:"auto", animationIterationCount:"1", backgroundPositionX:"0%", content:"", transformStyle:"flat", borderInlineEndColor:"rgb(128, 128, 128)", borderBlockStart:"0px none rgb(128, 128, 128)", overflow:"visible", webkitMaskPositionY:"0%", perspective:"none", strokeDashoffset:"0px", outlineColor:"rgb(51, 51, 51)", webkitMarqueeSpeed:"", webkitTextEmphasisStyle:"none", isolation:"auto", borderInlineStartColor:"rgb(128, 128, 128)", textDecorationSkip:"auto", outlineOffset:"0px", objectFit:"fill", textUnderlineOffset:"auto", webkitAppearance:"none", webkitMaskBoxImageWidth:"auto", animationTimingFunction:"ease", borderWidth:"0px", borderSpacing:"0px 0px", captionSide:"top", columnWidth:"auto", rowGap:"normal", webkitMaskBoxImageSource:"none", webkitRtlOrdering:"logical", |70|:"counter-reset", paddingInlineEnd:"0px", |71|:"cursor", |72|:"cx", fontSize:"14.000000953674316px", |73|:"cy", vectorEffect:"none", |74|:"direction", justifyContent:"normal", fillRule:"nonzero", |75|:"display", fontSynthesis:"style weight small-caps", |30|:"border-image-repeat", |76|:"dominant-baseline", |31|:"border-image-slice", |77|:"empty-cells", pageBreakBefore:"auto", |32|:"border-image-source", |78|:"fill", cx:"0px", webkitMaskBoxImageRepeat:"stretch", borderImageSource:"none", |33|:"border-image-width", |79|:"fill-opacity", cy:"0px", outlineStyle:"none", webkitBoxFlex:"0", |34|:"border-left-color", width:"827.5px", webkitMarginBeforeCollapse:"collapse", |35|:"border-left-style", borderRightStyle:"none", |36|:"border-left-width", |0|:"align-content", |37|:"border-right-color", |1|:"align-items", paddingBlockStart:"0px", |size|:"", |2|:"align-self", |38|:"border-right-style", |3|:"alignment-baseline", |4|:"alt", |39|:"border-right-width", webkitFontSmoothing:"auto", |5|:"animation-delay", borderTopWidth:"0px", |6|:"animation-direction", |100|:"font-variant-east-asian", |7|:"animation-duration", |8|:"animation-fill-mode", |200|:"stroke", |9|:"animation-iteration-count", webkitTransformStyle:"flat", |101|:"font-variant-ligatures", counterReset:"none", |300|:"-webkit-mask-box-image", maskType:"luminance", webkitBoxShadow:"none", |201|:"stroke-color", borderBlockEndStyle:"none", |102|:"font-variant-numeric", fontStretch:"normal", textDecorationStyle:"solid", |301|:"-webkit-mask-box-image-outset", cursor:"auto", |202|:"stroke-dasharray", webkitMarqueeStyle:"scroll", |103|:"font-variant-position", animationFillMode:"none", glyphOrientationVertical:"auto", |302|:"-webkit-mask-box-image-repeat", |203|:"stroke-dashoffset", textRendering:"auto", |104|:"font-variation-settings", borderImageRepeat:"stretch", |303|:"-webkit-mask-box-image-slice", |204|:"stroke-linecap", height:"618.8043823242188px", |105|:"font-weight", all:"", |130|:"line-height", |304|:"-webkit-mask-box-image-source", pointerEvents:"auto", textTransform:"none", |205|:"stroke-linejoin", dominantBaseline:"auto", |230|:"transition-delay", |106|:"glyph-orientation-horizontal", filter:"none", |131|:"list-style-image", |305|:"-webkit-mask-box-image-width", |330|:"-webkit-user-drag", |206|:"stroke-miterlimit", paintOrder:"normal", |231|:"transition-duration", |107|:"glyph-orientation-vertical", placeItems:"normal normal", |132|:"list-style-position", |306|:"-webkit-mask-clip", borderInlineStart:"0px none rgb(128, 128, 128)", |331|:"-webkit-user-modify", |207|:"stroke-opacity", textOverflow:"clip", |232|:"transition-property", |108|:"grid-auto-columns", webkitBackdropFilter:"none", |133|:"list-style-type", |307|:"-webkit-mask-composite", webkitMaskRepeat:"repeat", |332|:"-webkit-user-select", |208|:"stroke-width", webkitBoxReflect:"none", |233|:"transition-timing-function", |109|:"grid-auto-flow", |134|:"margin-bottom", |308|:"-webkit-mask-image", |333|:"fullscreen-inset-bottom", |209|:"tab-size", |234|:"unicode-bidi", flexWrap:"nowrap", wordSpacing:"0px", |135|:"margin-left", |309|:"-webkit-mask-origin", |160|:"padding-bottom", |334|:"safe-area-inset-bottom", flexFlow:"row nowrap", |235|:"vector-effect", |260|:"-webkit-border-image", |136|:"margin-right", |161|:"padding-left", |335|:"safe-area-inset-left", transition:"all 0s ease 0s", |236|:"vertical-align", columnFill:"balance", |261|:"-webkit-border-vertical-spacing", |137|:"margin-top", |162|:"padding-right", |336|:"fullscreen-inset-left", maxHeight:"none", |237|:"visibility", alt:"\"\"", |262|:"-webkit-box-align", |138|:"marker-end", marginInlineEnd:"0px", |163|:"padding-top", |337|:"fullscreen-inset-right", webkitMarginTopCollapse:"collapse", |238|:"white-space", gridRowEnd:"auto", |263|:"-webkit-box-decoration-break", |139|:"marker-mid", |164|:"page-break-after", |338|:"fullscreen-auto-hide-duration", fillOpacity:"1", |239|:"widows", |264|:"-webkit-box-direction", overflowY:"visible", |165|:"page-break-before", |339|:"safe-area-inset-right", |190|:"scroll-snap-margin-right", |265|:"-webkit-box-flex", animationDuration:"0s", |290|:"-webkit-line-clamp", |166|:"page-break-inside", marginRight:"0px", |191|:"scroll-snap-margin-top", |266|:"-webkit-box-flex-group", borderInlineStartWidth:"0px", |291|:"-webkit-line-grid", |167|:"paint-order", webkitNbspMode:"normal", |192|:"scroll-snap-type", |267|:"-webkit-box-lines", mixBlendMode:"normal", |292|:"-webkit-line-snap", |168|:"perspective", paddingBlockEnd:"0px", |193|:"shape-image-threshold", src:"", webkitBoxAlign:"stretch", |268|:"-webkit-box-ordinal-group", paddingTop:"0px", |293|:"-webkit-locale", |169|:"perspective-origin", borderBlockEnd:"0px none rgb(128, 128, 128)", |194|:"shape-margin", r:"0px", textAlign:"start", |269|:"-webkit-box-orient", webkitMaskBoxImageOutset:"0px", |294|:"-webkit-margin-after-collapse", webkitTextEmphasis:"", webkitTextStrokeColor:"rgb(51, 51, 51)", |195|:"shape-outside", breakBefore:"auto", wordWrap:"break-word", |295|:"-webkit-margin-before-collapse", minInlineSize:"0px", |196|:"shape-rendering", borderInlineEndWidth:"0px", webkitLineAlign:"none", webkitMaskBoxImageSlice:"0 fill", widows:"auto", perspectiveOrigin:"413.75px 309.4021911621094px", |296|:"-webkit-marquee-direction", x:"0px", y:"0px", |197|:"speak-as", perspectiveOriginX:"", |297|:"-webkit-marquee-increment", |198|:"stop-color", fontFamily:"-apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, Oxygen-Sans, Ubuntu, Cantarell, \"Helvetica Neue\", sans-serif", |298|:"-webkit-marquee-repetition", |199|:"stop-opacity", animationPlayState:"running", webkitHyphenateLimitBefore:"auto", |299|:"-webkit-marquee-style", webkitBoxOrient:"horizontal", order:"0", webkitMaskSourceType:"alpha", fontVariantNumeric:"normal", webkitColumnBreakAfter:"auto", webkitColumnBreakInside:"auto", shapeMargin:"0px", webkitMaskImage:"none", top:"auto", backgroundBlendMode:"normal", listStylePosition:"outside", bottom:"auto", gridTemplateColumns:"none", strokeWidth:"0.8695652484893799px", borderTopRightRadius:"0px", direction:"ltr", webkitBackfaceVisibility:"visible", backgroundPositionY:"0%", rx:"0px", webkitHyphenateLimitLines:"no-limit", ry:"0px", lineBreak:"auto", bufferedRendering:"auto", quotes:"", gridRow:"auto / auto", webkitBorderFit:"border", borderBottomRightRadius:"0px", alignmentBaseline:"auto", textIndent:"0px", paddingBottom:"0px", columnRuleColor:"rgb(51, 51, 51)", fontVariantCaps:"normal", backgroundSize:"auto", |60|:"column-count", columnCount:"auto", |61|:"column-fill", webkitBoxLines:"single", webkitBoxFlexGroup:"1", backgroundRepeatX:"", |62|:"column-gap", glyphOrientationHorizontal:"0deg", lineHeight:"20px", |63|:"column-rule-color", borderBlockEndWidth:"0px", opacity:"1", webkitBackgroundClip:"border-box", webkitBoxPack:"start", |64|:"column-rule-style", |65|:"column-rule-width", borderImageWidth:"1", fontVariantLigatures:"normal", |20|:"background-repeat", |66|:"column-span", |21|:"background-size", |67|:"column-width", gridTemplateAreas:"none", tableLayout:"auto", |22|:"baseline-shift", |68|:"content", webkitBorderImage:"none", |23|:"border-bottom-color", |69|:"counter-increment", animationName:"none", letterSpacing:"normal", |24|:"border-bottom-left-radius", |25|:"border-bottom-right-radius", backgroundClip:"border-box", transitionDelay:"0s", |26|:"border-bottom-style", |27|:"border-bottom-width", webkitCursorVisibility:"auto", |28|:"border-collapse", webkitTextDecorationsInEffect:"none", |29|:"border-image-outset", fill:"rgb(0, 0, 0)", webkitHyphenateCharacter:"auto", animation:"", pageBreakInside:"auto", lightingColor:"rgb(255, 255, 255)", webkitLineClamp:"none", perspectiveOriginY:"", textDecorationThickness:"auto", marginInlineStart:"0px", borderTopStyle:"none", placeContent:"normal normal", backgroundRepeatY:"", textUnderlinePosition:"auto", wordBreak:"normal", columnRuleStyle:"none", webkitUserModify:"read-only", columnSpan:"none", strokeOpacity:"1", webkitMarqueeRepetition:"infinite", webkitMarginCollapse:"", flexBasis:"auto", colorInterpolationFilters:"linearRGB", gap:"normal normal", webkitMask:"", gridArea:"auto / auto / auto / auto", gridTemplate:"none / none / none", resize:"none", borderColor:"rgb(128, 128, 128)", zIndex:"auto", webkitTextCombine:"none", webkitTextStrokeWidth:"0px", borderBottomStyle:"none", fontVariant:"normal", scrollSnapType:"none", textDecoration:"none", webkitTextEmphasisColor:"rgb(51, 51, 51)", orphans:"auto", scrollPaddingRight:"0px", borderImageOutset:"0px", webkitTextDecoration:"none solid rgb(51, 51, 51)", |110|:"grid-auto-rows", marginLeft:"0px", transitionTimingFunction:"ease", |210|:"table-layout", stroke:"none", stopOpacity:"1", |111|:"grid-column-end", |310|:"-webkit-mask-position", stopColor:"rgb(0, 0, 0)", webkitPrintColorAdjust:"economy", |211|:"text-align", unicodeBidi:"normal", |112|:"grid-column-start", |311|:"-webkit-mask-repeat", page:"", |212|:"text-anchor", |113|:"grid-row-end", |312|:"-webkit-mask-size", fontFeatureSettings:"normal", |213|:"text-decoration", |114|:"grid-row-start", webkitMarqueeIncrement:"6px", webkitUserSelect:"text", |313|:"-webkit-mask-source-type", gridAutoRows:"auto", |214|:"text-decoration-color", |115|:"grid-template-areas", |140|:"marker-start", |314|:"-webkit-nbsp-mode", scrollPaddingBottom:"0px", |215|:"text-decoration-line", |240|:"width", |116|:"grid-template-columns", |141|:"mask", |315|:"-webkit-print-color-adjust", borderBlockStartColor:"rgb(128, 128, 128)", |340|:"fullscreen-inset-top", |216|:"text-decoration-skip", fontVariantEastAsian:"normal", |241|:"will-change", |117|:"grid-template-rows", fontVariationSettings:"normal", |142|:"mask-type", |316|:"-webkit-rtl-ordering", marginBlockEnd:"20px", |341|:"safe-area-inset-top", |217|:"text-decoration-style", minWidth:"0px", |242|:"word-break", |118|:"hanging-punctuation", zoom:"1", |143|:"max-height", |317|:"-webkit-text-combine", |218|:"text-indent", gridAutoColumns:"auto", |243|:"word-spacing", |119|:"height", verticalAlign:"baseline", |144|:"max-width", |318|:"-webkit-text-decorations-in-effect", imageRendering:"auto", maxBlockSize:"none", |219|:"text-overflow", outlineWidth:"0px", |244|:"word-wrap", shapeRendering:"auto", webkitLineGrid:"none", |145|:"min-height", |319|:"-webkit-text-emphasis-color", |170|:"place-content", enableBackground:"", |245|:"writing-mode", |270|:"-webkit-box-pack", |146|:"min-width", animationDelay:"0s", |171|:"place-items", boxShadow:"none", scrollSnapMarginLeft:"0px", webkitBorderRadius:"", |246|:"x", |271|:"-webkit-box-reflect", |147|:"mix-blend-mode", |172|:"place-self", |247|:"y", blockSize:"618.8043823242188px", |272|:"-webkit-box-shadow", |148|:"object-fit", columnRuleWidth:"0px", |173|:"pointer-events", backgroundImage:"none", |248|:"z-index", |273|:"-webkit-clip-path", |149|:"object-position", transitionDuration:"0s", |174|:"position", |249|:"zoom", |274|:"-webkit-column-axis", webkitColumnAxis:"auto", |175|:"r", borderImageSlice:"100%", |275|:"-webkit-column-break-after", borderCollapse:"collapse", |176|:"resize", |276|:"-webkit-column-break-before", webkitLineBoxContain:"block inline replaced", |177|:"right", |277|:"-webkit-column-break-inside", |178|:"row-gap", borderLeft:"0px none rgb(128, 128, 128)", |font|:"normal normal normal normal 14.000000953674316px/20px -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, Oxygen-Sans, Ubuntu, Cantarell, \"Helvetica Neue\", sans-serif", webkitMarginAfterCollapse:"collapse", |278|:"-webkit-column-progression", |outline|:"rgb(51, 51, 51) none 0px", scrollPaddingLeft:"0px", |90|:"flood-opacity", |179|:"rx", markerStart:"none", strokeDasharray:"none", |91|:"font-family", |279|:"-webkit-cursor-visibility", flexShrink:"1", webkitMaskRepeatX:"", |92|:"font-optical-sizing", transformBox:"border-box", |93|:"font-size", |94|:"font-stretch"}

on parseJSONAsRecord(jsRes)
  set jsonString to current application’s NSString’s stringWithString:jsRes
  
set jsonData to jsonString’s dataUsingEncoding:(current application’s NSUTF8StringEncoding)
  
set aJsonDict to current application’s NSJSONSerialization’s JSONObjectWithData:jsonData options:0 |error|:(missing value)
  
return aJsonDict as record
end parseJSONAsRecord

★Click Here to Open This Script 

Posted in Internet JavaScript JSON | Tagged 10.12savvy 10.13savvy 10.14savvy NSJSONSerialization NSString Safari | 1 Comment

Safariのdo JavaScriptから結果をJSONで返してASの各種オブジェクトに変換

Posted on 9月 22, 2019 by Takaaki Naganoya

Safariのdo JavaScriptコマンドから各種結果を取得してAppleScriptの各種オブジェクトに変換するAppleScriptです。

真剣にSafari上でdo JavaScriptコマンド経由で値の受け渡しをするときに、さまざまな型のデータをJavaScript側からAppleScript側に渡したいことがあります。

ただ、JavaScript側からのデータの受け渡しはそんなにまじめにやっていなかったので、あらためて方法を調べておきました。

AppleScript名:Safariのdo javascriptから結果をJSONで返してASの各種オブジェクトに変換
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/09/22
—
–  Copyright © 2019 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

tell application "Safari"
  if (count every document) = 0 then return
  
  
–String List (1D)
  
set jsRes1 to do JavaScript "var tempVar = [’1’,’2’];
  JSON.stringify(tempVar);"
in front document
  
set aRes to parseJSONAsList(jsRes1) of me
  
–> {"1", "2"}
  
  
–Number List (1D)  
  
set jsRes2 to do JavaScript "var tempVar = [1,2];
  JSON.stringify(tempVar);"
in front document
  
set bRes to parseJSONAsList(jsRes2) of me
  
–> {1, 2}
  
  
–Record  
  
set jsRes3 to do JavaScript "var tempVar2 = { name:’Steve Jobs’, age:32, tel:’080-1234-5678’ };
  JSON.stringify(tempVar2);"
in front document
  
set cRes to parseJSONAsRecord(jsRes3) of me
  
–> {|name|:"Steve Jobs", age:32, tel:"080-1234-5678"}
  
  
–Records in List
  
set jsRes4 to do JavaScript "var tempVar2 = [{ name:’Steve Jobs’, age:32, tel:’080-1234-5678’ },{ name:’Tim Coo’, age:55, tel:’090-1234-5678’ }] ;
  JSON.stringify(tempVar2);"
in front document
  
set dRes to parseJSONAsList(jsRes4) of me
  
–> {{|name|:"Steve Jobs", age:32, tel:"080-1234-5678"}, {|name|:"Tim Coo", age:55, tel:"090-1234-5678"}}
  
  
–Number List (2D)  
  
set jsRes5 to do JavaScript "var tempVar = [[1,2], [3,4], [5,6]];
  JSON.stringify(tempVar);"
in front document
  
set eRes to parseJSONAsList(jsRes5) of me
  
–> {{1, 2}, {3, 4}, {5, 6}}
end tell

on parseJSONAsList(jsRes)
  set jsonString to current application’s NSString’s stringWithString:jsRes
  
set jsonData to jsonString’s dataUsingEncoding:(current application’s NSUTF8StringEncoding)
  
set aJsonDict to current application’s NSJSONSerialization’s JSONObjectWithData:jsonData options:0 |error|:(missing value)
  
return aJsonDict as list
end parseJSONAsList

on parseJSONAsRecord(jsRes)
  set jsonString to current application’s NSString’s stringWithString:jsRes
  
set jsonData to jsonString’s dataUsingEncoding:(current application’s NSUTF8StringEncoding)
  
set aJsonDict to current application’s NSJSONSerialization’s JSONObjectWithData:jsonData options:0 |error|:(missing value)
  
return aJsonDict as record
end parseJSONAsRecord

★Click Here to Open This Script 

AppleScript名:Safariのdo javascriptから結果をJSONで返してASの各種オブジェクトに変換 2
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/09/22
—
–  Copyright © 2019 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

tell application "Safari"
  if (count every document) = 0 then return
  
  
–String
  
set jsRes1 to do JavaScript "var tempVar = ’1’;
  tempVar;"
in front document
  
–> "1"
  
  
–Number
  
set jsRes2 to do JavaScript "var tempVar = 1;
  tempVar;"
in front document
  
–> 1.0
  
end tell

★Click Here to Open This Script 

Posted in JavaScript JSON Tag | Tagged 10.12savvy 10.13savvy 10.14savvy NSJSONSerialization NSString Safari | 1 Comment

NSApplicationにアクセス

Posted on 9月 21, 2019 by Takaaki Naganoya

NSApplicationにアクセスして実行環境の各種情報を取得するAppleScriptです。

プロセス関連のCocoaオブジェクトは何種類かありますが、

NSApplicationは実行環境そのもの、実行中のアプリケーションの内部情報を取得するオブジェクトのようです。他のアプリケーションをBundle IDで指定してNSApplicationを取得するような処理ができるのかと思って調べていたのですが、どーもできないっぽい。

AppleScriptからSystem Events経由でアクセスするいつものやり方で、取得できない要素はとくにないのですが、一長一短というか得意不得意があるという感じです。

AppleScript名:NSApplicationにアクセス.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/08/04
—
–  Copyright © 2019 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use framework "AppKit"
use scripting additions

set anApp to current application’s NSApplication’s sharedApplication()
–> <ScriptDebuggerApplication: 0x600002562d00>

anApp’s |running| as boolean
–> true

anApp’s enabledRemoteNotificationTypes()
–> 0

anApp’s mainMenu()
–>
(*
<NSMenu: 0x600001878240>
  Title: AMainMenu
  Open bounds: [t=1440, l=0, b=1440, r=0]
  Supermenu: 0x0 (None), autoenable: YES
  Items: (
"<NSMenuItem: 0x6000029294a0 Script Debugger, submenu: 0x6000018780c0 (Script Debugger)>",
"<NSMenuItem: 0x600002929aa0 File, submenu: 0x6000018789c0 (File)>",
"<NSMenuItem: 0x60000292ae20 Edit, submenu: 0x600001878a80 (Edit)>",
"<NSMenuItem: 0x60000291c240 View, submenu: 0x600001878c40 (View)>",
"<NSMenuItem: 0x60000291cfc0 Search, submenu: 0x600001878e80 (Search)>",
"<NSMenuItem: 0x60000291d5c0 Script, submenu: 0x600001878f00 (Script)>",
"<NSMenuItem: 0x60000291e700 Dictionary, submenu: 0x600001879040 (Dictionary)>",
"<NSMenuItem: 0x60000291ef40 Window, submenu: 0x600001879080 (Window)>",
"<NSMenuItem: 0x6000029285a0 Clippings, submenu: 0x600001878840 (Clippings)>",
"<NSMenuItem: 0x60000291f540 Scripts, submenu: 0x6000018791c0 (Scripts)>",
"<NSMenuItem: 0x60000291fc00 Help, submenu: 0x600001879340 (Help)>"
)
*)

anApp’s servicesMenu()
(*
<NSMenu: 0x600001878340>
  Title: Services
  Open bounds: [t=nan, l=6.95319e-310, b=nan, r=6.95319e-310]
  Supermenu: 0x6000018780c0 (Script Debugger), autoenable: YES
  Items: (
"<NSMenuItem: 0x60000e924cc0 Add to Wunderlist>",
"<NSMenuItem: 0x60000e927120 ATOK\U30a4\U30df\U30af\U30eb\U3067\U691c\U7d22>",
"<NSMenuItem: 0x60000e926f40 Evernote \U306b\U8ffd\U52a0>",
"<NSMenuItem: 0x60000e926a60 Finder\U3067\U60c5\U5831\U3092\U898b\U308b>",
"<NSMenuItem: 0x60000e927e40 Finder\U306b\U8868\U793a>",
"<NSMenuItem: 0x60000e9275a0 \U958b\U304f>",
"<NSMenuItem: 0x60000e9279c0 man\U30da\U30fc\U30b8\U3092\U30bf\U30fc\U30df\U30ca\U30eb\U3067\U958b\U304f>",
"<NSMenuItem: 0x60000e9246c0 \U30bf\U30fc\U30df\U30ca\U30eb\U306eman\U30da\U30fc\U30b8\U30a4\U30f3\U30c7\U30c3\U30af\U30b9\U3067\U691c\U7d22>",
"<NSMenuItem: 0x60000e924c00 \U30b9\U30c6\U30a3\U30c3\U30ad\U30fc\U30e1\U30e2\U3092\U4f5c\U6210>",
"<NSMenuItem: 0x60000e9249c0 \U30b9\U30dd\U30fc\U30af\U30f3\U30c8\U30e9\U30c3\U30af\U3068\U3057\U3066iTunes\U306b\U8ffd\U52a0>",
"<NSMenuItem: 0x60000e9244e0 \U30c6\U30ad\U30b9\U30c8\U3092\U7c21\U4f53\U5b57\U4e2d\U56fd\U8a9e\U306b\U5909\U63db>",
"<NSMenuItem: 0x60000e927a20 \U30c6\U30ad\U30b9\U30c8\U3092\U5168\U89d2\U306b\U5909\U63db>",
"<NSMenuItem: 0x60000e9276c0 \U30c6\U30ad\U30b9\U30c8\U3092\U534a\U89d2\U306b\U5909\U63db>",
"<NSMenuItem: 0x60000e9247e0 \U30c6\U30ad\U30b9\U30c8\U3092\U7e41\U4f53\U5b57\U4e2d\U56fd\U8a9e\U306b\U5909\U63db>",
"<NSMenuItem: 0x60000e925440 \U30de\U30c3\U30d7\U3092\U8868\U793a>",
"<NSMenuItem: 0x60000e926040 \U30a4\U30e1\U30fc\U30b8\U3092\U8aad\U307f\U8fbc\U3080>",
"<NSMenuItem: 0x60000e925ec0 \U30c7\U30b9\U30af\U30c8\U30c3\U30d7\U30d4\U30af\U30c1\U30e3\U3092\U8a2d\U5b9a>",
"<NSMenuItem: 0x60000e926c40 Skim\U3067URL\U3092\U958b\U304f>",
"<NSMenuItem: 0x60000e9266a0 Skim\U3067\U30d5\U30a1\U30a4\U30eb\U3092\U9<<description truncated at 2000 characters out of 4221>>"
*)

anApp’s mainWindow()
–> <ScriptWindow: 0x7ffd73e344c0>

anApp’s keyWindow()
–> <ScriptWindow: 0x7ffd73e344c0>

anApp’s |windows|()
(*
(NSArray) {
  <NSPanel: 0x600003139500>,
  <NSWindow: 0x60000312e500>,
  <MiniDebuggerWindow: 0x7ffd73e0b870>,
  <LNSFindWrapAroundWindow: 0x60000312b000>,
  <NSToolTipPanel: 0x7ffd73dee5e0>,
  <NSPanel: 0x600003104800>,
  <NSPanel: 0x600003104700>,
  <NSWindow: 0x60000315c800>,
  <NSColorPanel: 0x7ffce4aa99c0>,
  <NSWindow: 0x600003121d00>,
  <ScriptWindow: 0x7ffd73e344c0>,
  <NSComboBoxWindow: 0x7ffce4f27700>
}
*)

anApp’s dockTile()
–> <NSDockTile: 0x60000221db00>

anApp’s dockTile()’s |size|()
–> {width:128.0, height:128.0}

anApp’s dockTile()’s owner()
–> <ScriptDebuggerApplication: 0x600003f38480>

anApp’s dockTile()’s showsApplicationBadge()
–> false

anApp’s dockTile()’s badgeLabel()

anApp’s applicationIconImage()
–> <NSImage 0x60000573be40 Size={128, 128} Reps=( ……

anApp’s acceptsFirstResponder()
–> false

anApp’s becomeFirstResponder()
–> true

★Click Here to Open This Script 

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

指定アプリケーションの指定言語のstringsファイルの内容をすべて取り出す

Posted on 9月 21, 2019 by Takaaki Naganoya

バンドルIDで指定したアプリケーションのResourcesフォルダ中の、指定ロケールのstringsファイルをすべて読み込んでkeyを取り出すAppleScriptです。

アプリケーション内の指定のローカライズしたメッセージ(テキスト)の内容を取り出すことはできますが、そのためにはキーを知っておく必要があります。そのキーを取り出してローカライズされた文字列を取り出すため、キーを調査してみました。

これをそのまま何かのツールなりScriptに使うというものではなく、いわゆる「下調べ」のためのScriptの部品です。

ほぼ、ありもののルーチンを再利用しただけのプログラムでできていますが、ありものはありもので、数千本のAppleScriptのストックからそれを探し出してくるのも一苦労です。

アプリケーションバンドル内のResourcesフォルダ以下の(各lprojフォルダ以下の)stringsファイルの中身はまんま(シリアライズした)NSDictionaryなので、そのままDictionaryに読み込んでallkey()などのメソッドを実行できます。昔のstringsファイルはテキストファイルだったような気がしますが、テキストファイルだとparseしないといけないんで、ビルド時にparseしておいてDictionaryの状態でファイルに書いておくのは正しいと思います。

Xcode 8あたりから、アプリケーションのローカライズのルールが変更になったようで、基本となる言語環境がBase.lprojになり、英語はen.lprojといった1ローカライズ言語という位置付けに変更になりました。

NSLocalizedStringFromTableInBundleを使ってアクセスしようかとも思ったのですが、こちらはまだ目的を達成できていません。


▲Xcode 11上で実験的に作成したAppleScriptアプリケーションのバンドル構造(左)。ローカライズしていない状態だとEnglishではなくBase.lprojが作成される。右はKeynote.app/Contents/Resources/ja.lprojフォルダの内容。stringsファイルが大量に存在している

AppleScript名:指定アプリケーションの指定言語のstringsファイルの内容をすべて取り出す.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/09/21
—
–  Copyright © 2019 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"

property |NSURL| : a reference to current application’s |NSURL|
property NSArray : a reference to current application’s NSArray
property NSBundle : a reference to current application’s NSBundle
property NSPredicate : a reference to current application’s NSPredicate
property NSDictionary : a reference to current application’s NSDictionary
property NSWorkspace : a reference to current application’s NSWorkspace
property NSFileManager : a reference to current application’s NSFileManager
property NSMutableDictionary : a reference to current application’s NSMutableDictionary
property NSURLTypeIdentifierKey : a reference to current application’s NSURLTypeIdentifierKey
property NSDirectoryEnumerationSkipsHiddenFiles : a reference to current application’s NSDirectoryEnumerationSkipsHiddenFiles
property NSDirectoryEnumerationSkipsPackageDescendants : a reference to current application’s NSDirectoryEnumerationSkipsPackageDescendants

set targID to "com.apple.iWork.Keynote"

set bRes to getLocalizationsFromBundleID(targID) of me
–>  {"de", "he", "en_AU", "ar", "el", "ja", "en", "uk", "es_419", "zh_CN", "es", "da", "it", "sk", "pt_PT", "ms", "sv", "cs", "ko", "Base", "no", "hu", "zh_HK", "tr", "pl", "zh_TW", "en_GB", "vi", "ru", "fr_CA", "fr", "fi", "id", "nl", "th", "pt", "ro", "hr", "hi", "ca"}

set curLang to first item of (choose from list bRes)
set aPath to retPathFromBundleID(targID) of me

set aPath to aPath & "/Contents/Resources/" & curLang & ".lproj"
set sList to getFilepathListByUTI(aPath, "com.apple.xcode.strings-text", "POSIX") of me

set aMDict to NSMutableDictionary’s new()

repeat with i in sList
  set j to contents of i
  
set aDict to (NSDictionary’s alloc()’s initWithContentsOfFile:j)
  (
aMDict’s addEntriesFromDictionary:aDict)
end repeat

return aMDict’s allKeys() as list
–> {"Interactive Bubble Chart", "Rehearse Slideshow", "PMT_ARGUMENT_1", "ACCRINTM_ARGUMENT_4_MODE_0", "Truck_378",….}

on getLocalizationsFromBundleID(aBundleID)
  set aRes to retPathFromBundleID(aBundleID) of me
  
if aRes = false then error "Wrong Bundle ID."
  
return getSpecifiedAppFilesLocalizationListWithDuplication(aRes) of me
end getLocalizationsFromBundleID

–指定アプリケーションファイルの、指定Localeにおけるローカライズ言語リストを求める。重複を許容
on getSpecifiedAppFilesLocalizationListWithDuplication(appPOSIXpath)
  set aURL to (|NSURL|’s fileURLWithPath:appPOSIXpath)
  
set aBundle to NSBundle’s bundleWithURL:aURL
  
set locList to aBundle’s localizations()
  
return locList as list
end getSpecifiedAppFilesLocalizationListWithDuplication

on retPathFromBundleID(aBundleID)
  set aURL to NSWorkspace’s sharedWorkspace()’s URLForApplicationWithBundleIdentifier:aBundleID
  
if aURL = missing value then return false –Error
  
return aURL’s |path|() as string
end retPathFromBundleID

on getFilepathListByUTI(aFolPOSIX, aUTI as string, aFileType as string)
  script spdFile
    property urlList : {}
  end script
  
  
if aFileType is not in {"file", "POSIX"} then return {}
  
  
set aFM to NSFileManager’s defaultManager()
  
set aFolExt to (aFM’s fileExistsAtPath:aFolPOSIX isDirectory:true) as boolean
  
if aFolExt = false then return {} –フォルダ自体が存在しなければヌルリストを返す
  
  
set aURL to |NSURL|’s fileURLWithPath:aFolPOSIX
  
set theOptions to ((NSDirectoryEnumerationSkipsPackageDescendants) as integer) + ((NSDirectoryEnumerationSkipsHiddenFiles) as integer)
  
set urlArray to (aFM’s contentsOfDirectoryAtURL:aURL includingPropertiesForKeys:{} options:theOptions |error|:(missing value))
  
if urlArray = missing value then return {}
  
  
set (urlList of spdFile) to urlArray as list
  
set newList to {}
  
  
repeat with i in (urlList of spdFile)
    set j to POSIX path of i
    
set tmpUTI to my retUTIfromPath(j)
    
set utiRes to my filterUTIList({tmpUTI}, aUTI)
    
    
if utiRes is not equal to {} then
      if aFileType = "POSIX" then
        set the end of newList to j
      else if aFileType = "file" then
        set the end of newList to POSIX file j
      end if
    end if
    
  end repeat
  
  
return newList
end getFilepathListByUTI

–指定のPOSIX pathのファイルのUTIを求める
on retUTIfromPath(aPOSIXPath)
  set aURL to |NSURL|’s fileURLWithPath:aPOSIXPath
  
set {theResult, theValue} to aURL’s getResourceValue:(reference) forKey:NSURLTypeIdentifierKey |error|:(missing value)
  
  
if theResult = true then
    return theValue as string
  else
    return theResult
  end if
end retUTIfromPath

–UTIリストが指定UTIに含まれているかどうか演算を行う
on filterUTIList(aUTIList, aUTIstr)
  set anArray to NSArray’s arrayWithArray:aUTIList
  
set aPred to NSPredicate’s predicateWithFormat_("SELF UTI-CONFORMS-TO %@", aUTIstr)
  
set bRes to (anArray’s filteredArrayUsingPredicate:aPred) as list
  
return bRes
end filterUTIList

★Click Here to Open This Script 

Posted in file Record URL UTI | Tagged 10.12savvy 10.13savvy 10.14savvy NSArray NSBundle NSDictionary NSDirectoryEnumerationSkipsHiddenFiles NSDirectoryEnumerationSkipsPackageDescendants NSFileManager NSMutableDictionary NSPredicate NSURL NSURLTypeIdentifierKey NSWorkspace | Leave a comment

コンテンツ中の表示中のエリア座標を取得する

Posted on 9月 18, 2019 by Takaaki Naganoya

Safariで表示中のWebコンテンツの表示範囲の座標を取得するAppleScriptです。

Webブラウザに対するAppleScriptの処理といえば、

 (1)表示中のURLを取得して処理
 (2)表示中のコンテンツにJavaScriptを実行したりGUI Scripting経由で操作(特定要素をカウントしたりFormに値を入れたりボタンを押したり)
 (3)表示中のHTMLソースを取得して処理
 (4)Webブラウザそのものの環境情報(Bookmarkや履歴など)にアクセスして処理
 (5)選択中のテキストを取得して処理
 (6)テキストを選択しておいて、その内容が該当する要素を抽出

といった操作を行ってきました。

(1)は、Webブラウザで表示中のURLを他のプログラムで処理する場合などに便利な、基礎的な処理です。
(2)は、ロボット的なScriptにありがちな、メニューの奥深く(URLで一発オープンが無理なログインを要求される構造のWebサイトとか)にあるデータを定期的に取得するような処理によく使います。
(3)は、(1)の延長線上にあるもので、HTMLReaderなどのHTMLそのものを解釈して処理できる高機能フレームワークと組み合わせてWebスクレイピングを行うものです
(4)は、書いてあるとおりブックマークや履歴などにアクセスして統計処理を行なったりしています。
(5)は、ちょっとした調べ物や翻訳などを行いたい場合に使っています。
(6)は、(3)の処理を行いたいが、処理対象の要素(表など)が複数あるので、どの要素なのか特定するための補助情報としてテキスト選択を要求するものです。

このうち、(6)に該当する処理が現状だといまひとつです。Webブラウザ上でテキストを選択しておく必要があるというのでは使い勝手がよくありません。

Webコンテンツのうち、Webブラウザ上で表示中の要素を取得するようなやり方であれば、その方が使い勝手がよいことでしょう。Wikipedia上の表データを使いまわしたいが、対象ページ上に表が複数あるので、いま現在Webブラウザのウィンドウ上で見えている範囲内に存在する表を取り出すようにすれば、より気の利いた処理になることでしょう。

AppleScript名:コンテンツ中の表示中のエリア座標を取得する
–https://stackoverflow.com/questions/9271747/can-i-detect-the-user-viewable-area-on-the-browser
tell application "Safari"
  set dCount to count every document
  
if dCount = 0 then return
  
  
set aHeight to do JavaScript "window.innerHeight;" in front document
  
set sHeight to do JavaScript "window.scrollY;" in front document
  
  
set aWidth to do JavaScript "window.innerWidth;" in front document
  
set sWidth to do JavaScript "window.scrollX;" in front document
  
  
return {myWidth:aWidth, scrollX:sWidth, myHeight:aHeight, scrollY:sHeight}
end tell

★Click Here to Open This Script 

Posted in JavaScript Web Contents Control | Tagged 10.12savvy 10.13savvy 10.14savvy Safari | Leave a comment

MacDownのopenコマンドで.mdファイルをオープンできない問題

Posted on 9月 18, 2019 by Takaaki Naganoya

メイン環境をmacOS 10.14に移行してみたら、MarkdownエディタのMacDownがopenコマンドでファイルをオープンできなくなっていました。かなり困ります。

ただ、この問題には思い当たる節がありました。MacDownのopenコマンドは仕様がおかしく、「バグっぽい実装でたまたま動いていたものが、OS側の動作が変わって動かなくなった」ものと推測。

MacDownのopenコマンドはfileのlistを要求してくるので、わざわざ、

set aFile to choose file of type {"net.daringfireball.markdown"}

tell application "MacDown"
	open {aFile}
end tell

のような記述が求められました。アプリケーション側の実装に合わせて書くのがScripterなので、仕方なくこういう記述をしてきましたが、納得はしていませんでした。

MacDownのsdefファイルを調べてみたところ、openコマンドのパラメータにlist=”yes”の記述があったので、これを削除。

<command name="open" code="aevtodoc" description="Open a document.">
 <direct-parameter description="The file to be opened.">
  <type type="file"/>
 </direct-parameter>
</command>

のように手元のMacDownのsdefの内容を書き換えてみたら、

set aFile to choose file of type {"net.daringfireball.markdown"}

tell application "MacDown"
	open aFile
end tell

リストで渡さないように書くと、macOS 10.14上でも問題なくAppleScriptから.mdファイルのオープンを実行できるようになりました。

Posted in Bug Markdown | Tagged 10.14savvy MacDown | Leave a comment

メイン環境をmacOS 10.14.6に移行

Posted on 9月 17, 2019 by Takaaki Naganoya

macOS 10.13「macOS Vista」の出来がひどかったので、試験環境にのみ入れただけで、メイン環境には入れていませんでした。macOS 10.14は長らく開発環境にのみ入れて、メインマシンの環境はずっと10.12のまま。

ただ、時間の経過とともにmacOS 10.12はセキュリティー系のサポート(OSに穴があった場合にアップデート)が切れたので、やむなくOSのアップデートを行うことに。

問題はアップデート先のOSバージョン選定です。

 macOS 10.13:史上最悪。天地がひっくり返ってもあり得ません
 macOS 10.14:10.13の印象が悪すぎたおかげで好印象。ただし、10.13のように毎日問題を起こすような問題児ではないというだけで、開発に使わなかった機能は未検証

という評価。macOS 10.15Betaも隔離環境にインストールしてありますが、Beta 6あたりからおかしな挙動が増えてきて、「とても常用できない」という結論に。この期におよんで新機能の追加まで行って、どういうつもりなんだかよくわかりません。

というわけで、10.15も問題児のようなので、消去法で10.14に移行しました。最近のmacOSは一般リリースが公開βみたいな品質なので、最新OSを使うことがリスクになりつつあります。

メイン環境にのみ入れて使っているメールの整理を行うボットScript群は、もともとASObjcExtras.frameworkを呼び出していたのですが(もっと以前に書いたので)、BridgePlusを呼び出すように書き換えてScript DebuggerからExtendedアプレット書き出しして(アプレットに組み込んだFramework呼び出しができるのは、このExtendedアプレットとXcode上で作成したCocoa-AppleScriptアプリケーションのみ)動かしています。

Posted in Release | Leave a comment

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

Posted on 9月 16, 2019 by Takaaki Naganoya

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

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

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

AppleScript名:アラートダイアログ上にTab View+Popup Buttonを表示して切り替え
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/09/16
—
–  Copyright © 2019 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"

property NSView : a reference to current application’s NSView
property NSAlert : a reference to current application’s NSAlert
property NSMenu : a reference to current application’s NSMenu
property NSTabView : a reference to current application’s NSTabView
property NSMenuItem : a reference to current application’s NSMenuItem
property NSTabViewItem : a reference to current application’s NSTabViewItem
property NSPopUpButton : a reference to current application’s NSPopUpButton
property NSRunningApplication : a reference to current application’s NSRunningApplication

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

property returnCode : 0

property aTabV : missing value
property selectedNum : 1

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

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

on dispTabViewWithAlertdialog:paramObj
  –Receive Parameters
  
set aMainMes to (myMessage of paramObj) as string –Main Message
  
set aSubMes to (mySubMessage of paramObj) as string –Sub Message
  
set aWidth to (viewWidth of paramObj) as integer –TextView width
  
set aHeight to (viewHeight of paramObj) as integer –TextView height
  
  
  
set selectedNum to 0
  
  
set aView to NSView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aWidth, aHeight))
  
  
–Ppopup Buttonをつくる
  
set a1Button to NSPopUpButton’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, aHeight – 20, 400, 20)) pullsDown:false
  
a1Button’s removeAllItems()
  
  
set a1Menu to NSMenu’s alloc()’s init()
  
  
repeat with i from 1 to 8
    set aTitle to "Selection #" & (i as string)
    
set aMenuItem to (NSMenuItem’s alloc()’s initWithTitle:aTitle action:"actionHandler:" keyEquivalent:"")
    (
aMenuItem’s setEnabled:true)
    (
aMenuItem’s setTarget:me)
    (
aMenuItem’s setTag:(i as string))
    (
a1Menu’s addItem:aMenuItem)
  end repeat
  
  
a1Button’s setMenu:a1Menu
  
  
–Make Tab View
  
set aTabV to NSTabView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aWidth, aHeight – 30))
  
aTabV’s setTabViewType:(TabPosition)
  
aTabV’s setTabViewType:(TabPosition)
  
  
repeat with i from 1 to 8
    set aTVItem to (NSTabViewItem’s alloc()’s initWithIdentifier:(i as string))
    (
aTVItem’s setLabel:(i as string))
    
    
–make custom view within a tab view item here
    
    (
aTabV’s addTabViewItem:aTVItem)
  end repeat
  
  
  
aView’s setSubviews:{a1Button, aTabV}
  
aView’s setNeedsDisplay:true
  
  
  
— set up alert
  
set theAlert to NSAlert’s alloc()’s init()
  
tell theAlert
    –for Messages
    
its setMessageText:(aMainMes)
    
its setInformativeText:(aSubMes)
    
    
–for Buttons
    
its addButtonWithTitle:"OK"
    
its addButtonWithTitle:"Cancel"
    
    
–Add Accessory View
    
its setAccessoryView:(aView)
    
    
–for Help Button
    
its setShowsHelp:(true)
    
its setDelegate:(me)
  end tell
  
  
  
— show alert in modal loop
  
NSRunningApplication’s currentApplication()’s activateWithOptions:0
  
my performSelectorOnMainThread:"doModal:" withObject:(theAlert) waitUntilDone:true
  
if (my returnCode as number) = 1001 then error number -128
  
  
set selectedNum to (a1Button’s indexOfSelectedItem()) + 1
end dispTabViewWithAlertdialog:

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

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

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

★Click Here to Open This Script 

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

Skimでオープン中のPDFで選択中のテキストを返す

Posted on 9月 16, 2019 by Takaaki Naganoya

フリーでScriptableなmacOS用PDFビューワー「Skim」上でオープン中のPDFで、選択中のテキストの内容を取得するAppleScriptです。

フリーかつオープンソースで提供されているアプリケーションのうち、奇跡的に豊富なAppleScript対応機能を備えるPDFビューワー、それがSkimです。Skimに比べればPreview.appなど取るに足らない存在。「PDFビューワー四天王」のうち、その最上位に君臨するアプリケーションこそがSkimです(四天王とかいいつつ、Skim、Preview、Acrobatの3人しかいないのはお約束)。


▲SkimでPDFをオープンし、「AppleScriptってなんだろう?」の文字列を選択

ただ、そんなグレートな存在のSkimでも、「選択中のテキストを取得する」という処理を書いたことはありませんでした。

Skimの「selection」によって取得されるのがテキストではなくRTFなので、AppleScriptの基本的な機能ではこのRTFはひどく扱いが難しいデータ「でした」。

しかし、Cocoaの機能を利用することで、テキストへの変換は可能です。

それでも、Cocoaが期待するRTFのデータとAppleScriptの世界のRTFのデータ同士の変換が難儀でした。食後の腹ごなしに行うには手に余るといったレベル。

そこで、お気軽データ変換の最後の砦であるクリップボードを経由してRTFをAppleScriptの世界からCocoaの世界に受け渡してみたところ、大成功。あとは、PDFから取得したテキストデータによくあることですが、日本語のテキストだとUnicodeのNormalize方法の問題によりひらがな/カタカナと濁点や半濁点が分離した状態で返ってきました。

これについても、Cocoaの機能を利用してNormalizeを行い、常識的なテキストに変換できました。

AppleScript名:Skimでオープン中のPDFの選択中のテキストを返す
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/09/16
—
–  Copyright © 2019 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

tell application "Skim"
  tell front document
    set aSel to selection
    
repeat with i in aSel
      set aCon to contents of i
      
set rList to RTF of aCon
      
      
set sCon to ""
      
repeat with ii in rList
        set the clipboard to ii
        
set aText to getClipboardAsText() of me
        
set aCon to aCon & aText
      end repeat
      
      
set aStr to textfy(aCon) of me
      
return aStr
    end repeat
  end tell
end tell

–Normalize Unicode Text in NFKC
on textfy(aText as string)
  set aStr to current application’s NSString’s stringWithString:aText
  
set aNFKC to aStr’s precomposedStringWithCompatibilityMapping()
  
return aNFKC as string
end textfy

–Clipboard内の情報をテキストとして取得する
on getClipboardAsText()
  — get the pasteboard items
  
set theClip to current application’s NSPasteboard’s generalPasteboard()
  
set pbItems to theClip’s pasteboardItems()
  
  
set theStrings to {}
  
  
repeat with anItem in pbItems
    if (anItem’s types()’s containsObject:(current application’s NSPasteboardTypeString)) then
      set end of theStrings to (anItem’s stringForType:(current application’s NSPasteboardTypeString)) as text
    end if
  end repeat
  
  
return theStrings as text
end getClipboardAsText

★Click Here to Open This Script 

とか言ってたら、夕飯の買い物に出かけようとした頃にShane Stanleyから「もっとシンプルに書けるよー」というサンプルが届いて脱力しました。もっと簡潔に書けたようです(同一サンプルで日本語データに対してチェックずみ)。

ただ、PDFから文字取り出ししたあとは、Unicodeの再Normalizeは割とやらないといけないケースが多いので、選択部分(selection)からRTFじゃなくてcharacterでデータを取り出せばよかったというあたりが反省点でしょうか。

set theText to ""
tell application "Skim"
  tell front document
    set aSel to selection
    
repeat with anItem in aSel
      set theText to theText & (characters of anItem) as text
    end repeat
  end tell
end tell
return theText

★Click Here to Open This Script 

Posted in Clipboard RTF Text | Tagged 10.12savvy 10.13savvy 10.14savvy NSPasteboard NSPasteboardTypeString NSString Skim | Leave a comment

tableExtractor

Posted on 9月 15, 2019 by Takaaki Naganoya

Safariで表示中のページのうち、テキストを選択中のキーワードを含む表をCSVファイルに書き出してNumbersでオープンするAppleScriptです。

–> Download tableExtractor Run-Only (Code-Signed Executable including Framework in its bundle)

–> Watch Demo movie

実行前にSafariの「開発」メニューから、「スマート検索フィールドからのJavaScriptの実行を許可」「AppleEventからのJavaScriptの実行を許可」を実行しておく必要があります(実行済みの場合には必要ありません)。


▲Safariで表示中のページのうち、CSV書き出ししたい表のテキストを選択


▲本Scriptで表をCSVに書き出してNumbersでオープン

以前に作成した「Safariで表示中のPageの選択中の文字を含む表データを取得」Scriptがいい線を行っていた(あらかじめ表中のテキストを選択しておく、という前提条件がかったるいかと思っていたのに、そうでもなかった)ので、ありもののサブルーチンを追加して、表部分のHTMLからのタグ削除やCSV書き出しなどを行えるようにしました。

本Scriptは表データをCSV書き出しする必要はどこにもないのですが、Numbers v6.1に「表を新規作成して表のセル数を指定すると多くの場合にエラーになる」というバグがあるので、Numbersを直接操作してデータ出力させることはやっていません。

処理時間もさほどかからないので、表示中のページのすべての表オブジェクトをCSV化したり、表を選択するUIを実装して、「どの表を出力するか?」という選択処理をしてもいいかもしれません。


▲漫然とMacOS日本語で書き出ししたため文字化けしたもの(左)、UTF8を指定して書き出ししたために文字化けしなくなったもの(右)

途中でCSV書き出しした表データに文字化けが発生していたのですが、これはUTF8でファイル書き出ししていなかったためでした。

本Scriptは前バージョンよりもキーワードの検出処理をていねいに行なっています。各TableのHTMLに対してタグの除去を行なったうえでWebブラウザ上で選択中の文字列を含んでいるかどうかをチェックしています。

AppleScript名:tableExtractor.scptd
— Created 2019-09-15 by Takaaki Naganoya
— 2019 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "HTMLReader" –https://github.com/nolanw/HTMLReader

property NSString : a reference to current application’s NSString
property HTMLDocument : a reference to current application’s HTMLDocument
property NSMutableArray : a reference to current application’s NSMutableArray

tell application "Safari"
  set dList to every document –Sometimes "count every document"causes error
  
if length of dList = 0 then return
  
  
–Get URL
  
tell front document
    set aURL to URL
  end tell
  
  
–Get Selected Text
  
set aRes to do JavaScript "var selObj = window.getSelection();
  var selStr = (selObj).getRangeAt(0);
  unescape(selStr);"
in front document
  
  
if aRes = "" then return
end tell

set aRes to filterATableAndPaseCells(aURL, aRes) of me
if aRes = false then
  display notification "I could not filter table data…"
  
return
end if

–Save 2D List to temp CSV file on desktop folder
set savePath to ((path to desktop) as string) & (do shell script "uuidgen") & ".csv"
saveAsCSV(aRes, savePath) of me

tell application "Numbers"
  activate
  
open file savePath
end tell

on filterATableAndPaseCells(aURL, aKeyword)
  set aData to (do shell script "curl " & aURL)
  
set aHTML to current application’s HTMLDocument’s documentWithString:(aData as string)
  
  
–Table要素をリストアップ
  
set eList to (aHTML’s nodesMatchingSelector:"table")
  
  
–Table要素のうちSafari上で選択中の文字列を含むものをサーチ(指定データを含むものを抽出)
  
set hitF to false
  
repeat with i in eList
    set cellList to i’s children()’s array()
    
set htmlSource to i’s serializedFragment() as string –HTML source
    
set html2 to trimStrFromTo(htmlSource, "<", ">") of me
    
set html3 to repChar(html2, return, "") of me
    
    
if html3 contains aKeyword then
      set hitF to true
      
exit repeat
    end if
  end repeat
  
if hitF = false then return false
  
  
–Count columns of Table Header
  
set aTableHeader to (i’s nodesMatchingSelector:"tr")’s firstObject()
  
set hList to aTableHeader’s nodesMatchingSelector:"th"
  
set hStrList to {}
  
repeat with i1 in hList
    set the end of hStrList to i1’s textContent() as string
  end repeat
  
set hLen to length of hStrList –count columns
  
  
–Acquire whole table body contents
  
set aTableBody to (i’s nodesMatchingSelector:"tbody")’s firstObject()
  
set bList to aTableBody’s nodesMatchingSelector:"td"
  
set bbList to {}
  
repeat with i2 in bList
    set the end of bbList to i2’s textContent() as string
  end repeat
  
  
set tbList to makeList1DTo2D(bbList, hLen) of me
  
  
return {hStrList} & tbList
end filterATableAndPaseCells

–1D Listを2D化
on makeList1DTo2D(orig1DList, aMax)
  set tbList to {}
  
set tmpList to {}
  
set aCount to 1
  
  
repeat with i3 in orig1DList
    set j to contents of i3
    
set the end of tmpList to j
    
    
if aCount ≥ aMax then
      set aCount to 1
      
set the end of tbList to tmpList
      
set tmpList to {}
    else
      set aCount to aCount + 1
    end if
  end repeat
  
  
return tbList
end makeList1DTo2D

on trimStrFromTo(aParamStr, fromStr, toStr)
  set theScanner to current application’s NSScanner’s scannerWithString:aParamStr
  
set anArray to current application’s NSMutableArray’s array()
  
  
repeat until (theScanner’s isAtEnd as boolean)
    set {theResult, theKey} to theScanner’s scanUpToString:fromStr intoString:(reference)
    
    
theScanner’s scanString:fromStr intoString:(missing value)
    
set {theResult, theValue} to theScanner’s scanUpToString:toStr intoString:(reference)
    
if theValue is missing value then set theValue to ""
    
    
theScanner’s scanString:toStr intoString:(missing value)
    
    
anArray’s addObject:theValue
  end repeat
  
  
if anArray’s |count|() = 0 then return aParamStr
  
  
copy aParamStr to curStr
  
repeat with i in (anArray as list)
    set curStr to repChar(curStr, fromStr & i & toStr, "") of me
  end repeat
  
  
return curStr
end trimStrFromTo

on repChar(aStr, targStr, repStr)
  set aString to current application’s NSString’s stringWithString:aStr
  
set bString to aString’s stringByReplacingOccurrencesOfString:targStr withString:repStr
  
set cString to bString as string
  
return cString
end repChar

–2D List to CSV file
on saveAsCSV(aList, aPath)
  –set crlfChar to (ASCII character 13) & (ASCII character 10)
  
set crlfChar to (string id 13) & (string id 10)
  
set LF to (string id 10)
  
set wholeText to ""
  
  
repeat with i in aList
    set newLine to {}
    
    
–Sanitize (Double Quote)
    
repeat with ii in i
      set jj to ii as text
      
set kk to repChar(jj, string id 34, (string id 34) & (string id 34)) of me –Escape Double Quote
      
set the end of newLine to kk
    end repeat
    
    
–Change Delimiter
    
set aLineText to ""
    
set curDelim to AppleScript’s text item delimiters
    
set AppleScript’s text item delimiters to "\",\""
    
set aLineList to newLine as text
    
set AppleScript’s text item delimiters to curDelim
    
    
set aLineText to repChar(aLineList, return, "") of me –delete return
    
set aLineText to repChar(aLineText, LF, "") of me –delete lf
    
    
set wholeText to wholeText & "\"" & aLineText & "\"" & crlfChar –line terminator: CR+LF
  end repeat
  
  
if (aPath as string) does not end with ".csv" then
    set bPath to aPath & ".csv" as Unicode text
  else
    set bPath to aPath as Unicode text
  end if
  
  
writeToFileUTF8(wholeText, bPath, false) of me
  
end saveAsCSV

on writeToFileUTF8(this_data, target_file, append_data)
  tell current application
    try
      set the target_file to the target_file as text
      
set the open_target_file to open for access file target_file with write permission
      
if append_data is false then set eof of the open_target_file to 0
      
write this_data as «class utf8» to the open_target_file starting at eof
      
close access the open_target_file
      
return true
    on error error_message
      try
        close access file target_file
      end try
      
return error_message
    end try
  end tell
end writeToFileUTF8

★Click Here to Open This Script 

Posted in file Internet JavaScript list Text | Tagged 10.12savvy 10.13savvy 10.14savvy HTMLDocument NSMutableArray NSString Numbers Safari | 1 Comment

htmlの並列ダウンロード処理

Posted on 9月 13, 2019 by Takaaki Naganoya

Webコンテンツ(HTML)の並列ダウンロードを行うAppleScriptです。

Webコンテンツからデータを抽出する際に、あらかじめ一括でHTMLを並列ダウンロードしておいて、ダウンロードずみのデータを一括処理すると処理時間を大幅に短縮できます。「戦場の絆」Wikiから機体データの表をすべて取得するのに、順次HTMLを取得して抽出していた場合には3〜4分程度かかっていたものを、並列ダウンロードしたのちにデータ処理するように変更すれば、これが十数秒程度にまで高速化できます。

既存のプログラムを修正してHTMLのダウンロード用に仕立ててみました。並列キュー(未処理タスク数)へのアクセスはAppleScriptからはできなかった(実行すると結果が返ってこなかった)のですが、そこに手をつけずに並列処理の完了状態を検出しています。

ダウンロードが完了したデータはlist(配列)に入るので、リクエスト数と完了リクエスト数をループ内でチェックし、完了アイテム数がリクエスト数と同じになれば終了、条件を満たさない場合でも指定のタイムアウト時間を超えたらエラー終了という処理を行なっています。

問題点は、スクリプトエディタ上では実行できるもののScript Debugger上では実行できないことです(結果が返ってきません)。AppleScriptアプレットに書き出して実行してみたところ、結果が返ってきません。ただし、Script Menuからの実行は行えます(macOS 10.12.6、10.13.6、10.14.6で同様)。XcodeのAppleScript Appのプロジェクト内で実行することはできました。

このように、ランタイム環境に実行状況が左右される点にご注意ください。ただし、そうしたマイナス面を補ってあまりあるほどダウンロードは高速です。90ファイル強のダウンロードを数秒で完了(マシン、ネットワーク速度、ダウンロード先サーバーの負荷状況、キャッシュ状態などに左右される、参考値です)するため、ダウンロード後に各HTMLからのデータ抽出も高速に行えます。

AppleScript名:htmlの並列ダウンロード処理
— Created 2019-09-13 by Takaaki Naganoya
— 2019 Piyomaru Software
—
– オリジナル: HTTP からファイルをダウンロードして、ローカルに保存する方法(shintarou_horiのブログ)
— http://shintarou-hori.hatenablog.com/entry/2014/03/15/193604

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

property |NSURL| : a reference to current application’s |NSURL|
property NSData : a reference to current application’s NSData
property NSString : a reference to current application’s NSString
property NSOperationQueue : a reference to current application’s NSOperationQueue
property NSInvocationOperation : a reference to current application’s NSInvocationOperation
property NSUTF8StringEncoding : a reference to current application’s NSUTF8StringEncoding

property aTimer : missing value

script spd
  property mList : {}
  
property resList : {}
end script

set (mList of spd) to {}
set (resList of spd) to {}
set baseURL to "https://w.atwiki.jp/senjounokizuna/pages/"

set numList to {25, 1594, 890, 70, 1669, 82, 1717, 997, 1080, 1614, 1712, 159, 1311, 1694, 1752, 1263}

set urlList to {}
repeat with i in numList
  set the end of urlList to (baseURL & i as string) & ".html"
end repeat

set aLen to length of urlList
set paramObj to {urls:urlList, timeOutSec:60}

–set (resList of spd) to downloadHTMLConcurrently(urlList, 60) of me
my performSelectorOnMainThread:"downloadHTMLConcurrently:" withObject:(paramObj) waitUntilDone:true
return length of (mList of spd)

on downloadHTMLConcurrently:paramObj
  set urlList to (urls of paramObj) as list
  
set timeOutS to (timeOutSec of paramObj) as real
  
set aLen to length of urlList
  
  
repeat with i in urlList
    set j to contents of i
    
set aURL to (|NSURL|’s URLWithString:j)
    
set aQueue to NSOperationQueue’s new()
    
set aOperation to (NSInvocationOperation’s alloc()’s initWithTarget:me selector:"execDL:" object:aURL)
    (
aQueue’s addOperation:aOperation)
  end repeat
  
  
–Check Completion
  
set compF to false
  
set loopTimes to (timeOutS * 10)
  
repeat loopTimes times
    if length of (mList of spd) = aLen then
      set compF to true
      
exit repeat
    end if
    
delay 0.1
  end repeat
  
  
if compF = false then error "Concurrent download timed out"
end downloadHTMLConcurrently:

on execDL:theURL
  set receiveData to NSData’s alloc()’s initWithContentsOfURL:theURL
  
if receiveData = missing value then
    return
  end if
  
  
set aFileName to theURL’s |lastPathComponent|()
  
my performSelectorOnMainThread:"saveData:" withObject:{receiveData, aFileName} waitUntilDone:false
end execDL:

on saveData:theDataArray
  copy theDataArray to {theData, saveFileName}
  
set aCon to NSString’s alloc()’s initWithData:theData encoding:NSUTF8StringEncoding
  
set the end of (mList of spd) to {fileName:saveFileName as string, contentsData:aCon as string}
end saveData:

★Click Here to Open This Script 

Posted in list Network URL | Tagged 10.12savvy 10.13savvy 10.14savvy NSData NSInvocationOperation NSOperationQueue NSString NSURL NSUTF8StringEncoding | Leave a comment

sdefの内容を強引に取得する

Posted on 9月 12, 2019 by Takaaki Naganoya

指定アプリケーションのsdefの内容を強引に取得するAppleScriptです。

スクリプトエディタをAppleScriptからコントロールして、指定アプリケーションのsdef(AppleScript用語辞書)の内容を取得します。もちろん、AppleScript対応のアプリケーションに限ります。対応/非対応の判定はあらかじめ行なっておいてください。

そもそも、なんでこれが必要になったかといえば、各種AppleScript Libraryの整備のための資料として、既存のAppleScript対応アプリケーションの識別コード(4文字コード)を取得して確認しておきたかったためです。

そこで、まっとうな方法だと、

step 1:対象アプリケーションのInfo.plistの内容を確認してsdefの名称を取得

step 2:アプリケーションバンドル内のsdefを取得

という流れになります。これで済めば処理は非常に短時間に完了します。ファイル処理だけなので。

しかし、実際にやってみると…………標準的な方法でsdefを取得できないアプリケーションがいくつか存在することに気づきます。

(1)Adobe Illustratorなど

バンドル内にsdefが存在しない。動的にプログラムでsdefを生成しているのでは?

(2)scriptSuite+scriptTerminologyに分かれている場合

バンドル内にsdefではなく.scriptSuiteファイルと.scriptTerminologyファイルを格納。テキストエディット(TextEdit.app)やスクリプトエディタ(Script Editor.app)などが該当する。

また、一部のアプリケーション(MS-Officeなど)ではsdefファイルのうち一部を外部からincludeしているため、アプリケーションバンドル内のsdefファイルを読んだだけでは完全なsdefが取得できないといった問題もあります。

そこで、この「スクリプトエディタをコントロールしてsdefの内容を取得する」という頭の悪そうな処理が必要になりました。シェルのsdefコマンドを使えばいいんじゃない? という意見も出てきそうですが、現行環境(macOS 10.14.x)でsdefコマンドはうまく動いていないように見えます。

AppleScript名:sdefの内容を強引に取得する.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/09/12
—
–  Copyright © 2019 jp.piyomarusoft, All Rights Reserved
—

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

set aPath to (choose file of type "com.apple.application-bundle" default location (path to applications folder) with prompt "Select an application")
set sdefContents to getForceSdefContentsUsingSE2(aPath) of me

on getForceSdefContentsUsingSE2(anAlias)
  try
    tell application id "com.apple.ScriptEditor2"
      open anAlias
      
tell front document
        set dictPath to path
      end tell
    end tell
  on error erM
    return erM
  end try
  
  
  
tell current application
    set aSdef to read dictPath
  end tell
  
  
tell application id "com.apple.ScriptEditor2"
    tell front document
      close without saving
    end tell
  end tell
  
  
return aSdef
end getForceSdefContentsUsingSE2

★Click Here to Open This Script 

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

指定フォルダ以下のアプリケーションを取得して、Scriptabilityをチェック

Posted on 9月 11, 2019 by Takaaki Naganoya

指定フォルダ以下のアプリケーションをSpotlightで検索して、それらのうちAppleScript対応の(Scriptableな)ものを集計するAppleScriptです。

Shane StanleyのMetadata Libを呼び出してSpotlight検索を行い、アプリケーションファイルの一覧を取得。その後、各アプリケーションのInfo.plistの情報を取得してNSAppleScriptEnabled=trueのアプリケーションのパスをlist(array)に追加します。

ただし、一部のApple製のアプリケーションに見られるように、NSAppleScriptEnabled=trueであるにもかかわらず、実際のAppleScriptサポート機能が実装されていないものもありますので(例:iBooks Author)これだけではScript対応かどうかの完全な判断は行えません。

一方、AppleScriptなどのOSA言語によるコントロールに対応していないアプリケーションはこれで完全にフィルタできます。NSAppleScriptEnabledのエントリがInfo.plistに存在しないものは非対応アプリケーションです。

非対応のアプリケーションに対して、AppleScriptからは起動、終了、ファイルのオープン、印刷などの基礎的な操作やアプリケーションの情報取得(名称やバージョンなど)、Finder経由で指定書類をアプリケーションでオープン、ぐらいの操作。また、GUI Scriptingによるメニューやボタンの強制操作しかできません。

AppleScript名:指定フォルダ以下のアプリケーションを取得して、Scriptabilityをチェック.scptd
— Created 2019-09-11 by Takaaki Naganoya
— 2019 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"
use mdLib : script "Metadata Lib" version "2.0.0" –https://macosxautomation.com/applescript/apps/Script_Libs.html

set origPath to POSIX path of (choose folder default location (path to applications folder))
set aResList to mdLib’s searchFolders:{origPath} searchString:("kMDItemContentType == %@") searchArgs:{"com.apple.application-bundle"}

set allCount to length of aResList
set sList to {}

repeat with i in aResList
  set j to contents of i
  
set sRes to retAppScriptabilityFromBundleIPath(j) of me
  
if sRes = true then
    set the end of sList to j
  end if
end repeat

return (length of sList)
–> 297

–指定パスからアプリケーションのScriptabilityをbooleanで返す
on retAppScriptabilityFromBundleIPath(appPath as string)
  set aDict to (current application’s NSBundle’s bundleWithPath:appPath)’s infoDictionary()
  
set aRes to aDict’s valueForKey:"NSAppleScriptEnabled"
  
if aRes = missing value then return false
  
return aRes as boolean
end retAppScriptabilityFromBundleIPath

★Click Here to Open This Script 

Posted in file list Spotlight | Tagged 10.12savvy 10.13savvy 10.14savvy NSBundle | Leave a comment

choose location script Library

Posted on 9月 8, 2019 by Takaaki Naganoya

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

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

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

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

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

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


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

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

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

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

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

★Click Here to Open This Script 

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

display table Script Library

Posted on 9月 7, 2019 by Takaaki Naganoya

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

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

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

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

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

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

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

...........

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

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

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

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

use easyTable : script "display table by list"

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

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

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

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

★Click Here to Open This Script 

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

Post navigation

  • Older posts

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

Google Search

Popular posts

  • macOS 13, Ventura(継続更新)
  • アラートダイアログ上にWebViewで3Dコンテンツを表示(WebGL+three.js)v3
  • UI Browserがgithub上でソース公開され、オープンソースに
  • macOS 13 TTS Voice環境に変更
  • Xcode 14.2でAppleScript App Templateを復活させる
  • 2022年に書いた価値あるAppleScript
  • ChatGPTで文章のベクトル化(Embedding)
  • 新発売:AppleScriptからSiriを呼び出そう!
  • iWork 12.2がリリースされた
  • 従来と異なるmacOS 13の性格?
  • 新発売:CotEditor Scripting Book with AppleScript
  • macOS 13対応アップデート:AppleScript実践的テクニック集(1)GUI Scripting
  • AS関連データの取り扱いを容易にする(はずの)privateDataTypeLib
  • macOS 13でNSNotFoundバグふたたび
  • macOS 12.5.1、11.6.8でFinderのselectionでスクリーンショット画像をopenできない問題
  • ChatGPTでchatに対する応答文を取得
  • 新発売:iWork Scripting Book with AppleScript
  • Finderの隠し命令openVirtualLocationが発見される
  • macOS 13.1アップデートでスクリプトエディタの挙動がようやくまともに
  • あのコン過去ログビューワー(暫定版)

Tags

10.11savvy (1101) 10.12savvy (1242) 10.13savvy (1390) 10.14savvy (586) 10.15savvy (434) 11.0savvy (277) 12.0savvy (185) 13.0savvy (55) CotEditor (60) Finder (47) iTunes (19) Keynote (98) NSAlert (60) NSArray (51) NSBezierPath (18) NSBitmapImageRep (20) NSBundle (20) NSButton (34) NSColor (51) NSDictionary (27) NSFileManager (23) NSFont (18) NSImage (41) NSJSONSerialization (21) NSMutableArray (62) NSMutableDictionary (21) NSPredicate (36) NSRunningApplication (56) NSScreen (30) NSScrollView (22) NSString (117) NSURL (97) NSURLRequest (23) NSUTF8StringEncoding (30) NSView (33) NSWorkspace (20) Numbers (56) Pages (37) Safari (41) Script Editor (20) WKUserContentController (21) WKUserScript (20) WKUserScriptInjectionTimeAtDocumentEnd (18) WKWebView (23) WKWebViewConfiguration (22)

カテゴリー

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

アーカイブ

  • 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