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

月: 2022年1月

Numbersの表でセル連結箇所が存在していたらすべて連結解除

Posted on 1月 31, 2022 by Takaaki Naganoya

指定のNumbers書類中の指定の表で、セルの連結が行われた箇所が存在していたらすべて連結解除するAppleScriptです。

Numbersの表でセルの連結が存在していると、フィルタ処理などが行えないために、セル連結箇所がないかを調べる手段がないと困ります。でも、そういう便利なコマンドがNumbersのAppleScript用語辞書には存在していないので作りました。

連結箇所が分かれば、個別に連結解除するだけです。ループですべてunmergeします。

動作確認は、M1 Mac mini+macOS 12.3beta+Numbersバージョン11.2で行なっています。


▲処理前 セルが連結されている箇所が複数存在している


▲処理後 すべてのセル結合されている箇所が連結解除された

AppleScript名:指定の表で連結セルがあればすべて分離.scpt
—
–  Created by: Takaaki Naganoya
–  Created on: 2022/01/31
—
–  Copyright © 2022 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

property NSCountedSet : a reference to current application’s NSCountedSet

tell application "Numbers"
  tell front document
    tell active sheet
      tell table 1
        set nList to name of every cell
        
set aRes1 to returnDuplicatesOnly(nList) of me –重複するセルの名称のみピックアップ
        
        
–重複セルを個別に分離
        
repeat with i in aRes1
          set j to contents of i
          
unmerge cell j
        end repeat
      end tell
    end tell
  end tell
end tell

on returnDuplicatesOnly(aList as list)
  set aSet to NSCountedSet’s alloc()’s initWithArray:aList
  
set bList to (aSet’s allObjects()) as list
  
  
set dupList to {}
  
repeat with i in bList
    set aRes to (aSet’s countForObject:i)
    
if aRes > 1 then
      set the end of dupList to (contents of i)
    end if
  end repeat
  
  
return dupList
end returnDuplicatesOnly

★Click Here to Open This Script 

Posted in list Object control | Tagged 10.15savvy 11.0savvy 12.0savvy NSCountedSet Numbers | Leave a comment

Numbersの表でセル連結箇所が存在しているかどうかチェック

Posted on 1月 31, 2022 by Takaaki Naganoya

指定のNumbers書類中の指定の表で、セルの連結が行われた箇所が存在しているかどうかチェックするAppleScriptです。

Numbersの表でセルの連結が存在していると、フィルタ処理などが行えないために、セル連結箇所がないかを調べる手段がないと困ります。でも、そういう便利なコマンドはNumbersのAppleScript用語辞書には存在していません。

動作確認は、M1 Mac mini+macOS 12.3beta+Numbersバージョン11.2で行なっています。

セルが連結されている箇所は、セルのnameが重複していることが判明。すべてのセルの「name」を取得して、重複しているものをチェックするとセル連結の有無がわかります。

B3セルのproperties

{vertical alignment:top, row:row “row2” of table 1 of sheet 1 of document id “6ED4F3E1-57BD-4A1E-8E0E-9C781DE3840E” of application “Numbers”, class:cell, font name:”HiraKakuProN-W3″, formatted value:”2 21″, background color:missing value, formula:missing value, name:”B3″, text wrap:true, text color:{0, 0, 0}, alignment:auto align, column:column “field1” of table 1 of sheet 1 of document id “6ED4F3E1-57BD-4A1E-8E0E-9C781DE3840E” of application “Numbers”, format:automatic, font size:10.0, value:”2 21″}

C3セルのproperties

{vertical alignment:top, row:row “row2” of table 1 of sheet 1 of document id “6ED4F3E1-57BD-4A1E-8E0E-9C781DE3840E” of application “Numbers”, class:cell, font name:”HiraKakuProN-W3″, formatted value:”2 21″, background color:missing value, formula:missing value, name:”B3″, text wrap:true, text color:{0, 0, 0}, alignment:auto align, column:column “field2” of table 1 of sheet 1 of document id “6ED4F3E1-57BD-4A1E-8E0E-9C781DE3840E” of application “Numbers”, format:automatic, font size:10.0, value:”2 21″}

AppleScript名:指定の表でセル連結がないかチェック.scpt
—
–  Created by: Takaaki Naganoya
–  Created on: 2022/01/31
—
–  Copyright © 2022 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

property NSCountedSet : a reference to current application’s NSCountedSet

tell application "Numbers"
  tell front document
    tell active sheet
      tell table 1
        set nList to name of every cell
        
set aRes1 to returnDuplicatesOnly(nList) of me
        
return aRes1
        
–> {"B3"}
      end tell
    end tell
  end tell
end tell

on returnDuplicatesOnly(aList as list)
  set aSet to NSCountedSet’s alloc()’s initWithArray:aList
  
set bList to (aSet’s allObjects()) as list
  
  
set dupList to {}
  
repeat with i in bList
    set aRes to (aSet’s countForObject:i)
    
if aRes > 1 then
      set the end of dupList to (contents of i)
    end if
  end repeat
  
  
return dupList
end returnDuplicatesOnly

★Click Here to Open This Script 

Posted in list Object control | Tagged 10.15savvy 11.0savvy 12.0savvy NSCountedSet Numbers | 1 Comment

macOS 12.3 Beta(21E5196i)、電話番号ピックアップできないバグが直る?

Posted on 1月 28, 2022 by Takaaki Naganoya

macOS 12.3 Beta(21E5196i)が配信され、M1 Mac mini上で実験してみたところ、macOS 12でバグが出ていた「自然言語テキストからNSDataDetectorで電話番号を抽出しようとすると何も出てこない」件(日本語環境限定)が修正されているように見えます。

Thanks Shane!

AppleScript名:与えられたテキストから電話番号を抽出 v2
— Created 2015-08-21 by Shane Stanley
— Modified 2015-08-21 by Takaaki Naganoya
— Modified 2015-08-22 by Shane Stanley
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set theString to "長野谷隆昌
(Takaaki Naganoya)
maro@piyocast.com
http://piyocast.com/as
2015年8月21日〜23日
080-1111-2222
030-1234-5678
東京都練馬区中村橋1-2-3
"

set theDates to (extractPhoneNumberFromNaturalText(theString))
–>  {​​​​​"080-1111-2222"​​​}–macOS 10.12 or other version
–> {"080-1111-2222", "030-1234-5678"}–macOS 13.6 with Intel MacBook Air
–> {"080-1111-2222", "030-1234-5678"}–macOS 14.6 with Intel MacBook Pro
–> {"080-1111-2222", "030-1234-5678"}–macOS 15.7 with Intel MacBook Pro
–> {} –macOS 12 beta 6 with M1 Mac mini
–> {"080-1111-2222", "030-1234-5678"}–macOS 12.3beta1 with M1 Mac mini

on extractPhoneNumberFromNaturalText(aString)
  set anNSString to current application’s NSString’s stringWithString:aString
  
  
set {theDetector, theError} to current application’s NSDataDetector’s dataDetectorWithTypes:(current application’s NSTextCheckingTypePhoneNumber) |error|:(reference)
  
set theMatches to theDetector’s matchesInString:anNSString options:0 range:{0, anNSString’s |length|()}
  
set theResults to theMatches’s valueForKey:"phoneNumber"
  
  
return theResults as list
end extractPhoneNumberFromNaturalText

★Click Here to Open This Script 

Posted in Bug | Tagged 12.0savvy NSDataDetector NSString | Leave a comment

不可視プロセスで表示したNSAlertを最前面に表示

Posted on 1月 28, 2022 by Takaaki Naganoya

コンテクストメニューからAppleScriptを実行するツール「Service Station」を連日こづき回していろいろ試しています。

その中で、Service StationではScript実行をGUIなしの補助プログラムからosascriptコマンドを経由してAppleScriptを実行しているために、AppleScript中でNSAlertによるダイアログ表示をおこなった際に、ダイアログが最前面に表示されないという問題が生じていました。

これを見たedama2さんから、強制的にNSAlertダイアログを最前面に表示させるコードを提供していただいたので、実際にテストに用いたAppleScriptに入れたものをご紹介します。


▲そのまま普通にNSAlertダイアログを表示させたところ。Service Stationによるコンテクストメニューから実行すると、最前面に表示されないという問題があった


▲edama2さんからもたらされたコードを追加したNSAlertダイアログ。Service Stationから実行しても、問題なく最前面に表示される

コードは2行、効き目はばっちり!

--Move to frontmost (By edama2)
current application's NSApplication's sharedApplication()'s setActivationPolicy:(current application's NSApplicationActivationPolicyRegular)
current application's NSApp's activateIgnoringOtherApps:(true)

副作用として、Dockにターミナルのアイコンが表示され、最前面のアプリケーションが「osascript」になってしまいますが、気にならないところでしょう。

Program Name Name of runtime Support AppleScript document format AS Format NSAlert dialog is displayed in frontmost Can use GUI Scripting functions Can call AppleScript Libraries? Can call AS Library including Frameworks? Can call Generic Cocoa Functions? Can use Cocoa system notification functions?
Service Station osascript Script/Text Script/Applet Script/Text Script No-> Yes Yes Yes No Yes No
Script Menu osascript Script/Scriptd/Applet Script/Scriptd Yes Yes Yes No Yes Yes
Shortcuts Events MacHelper File Embedded Script Text Yes Yes Yes No Yes No
Switch Control Assistive Control File Embedded Script Script (archived) Yes Yes No No Yes No
FastScript 3 FastScripts Script Runner Script/Scriptd/Applet Script/Scriptd Yes Yes Yes No Yes

あれ? edama2さんのおかげで、Service Stationの弱点が1つなくなりましたよ。Service Stationについては、

(1)「Kind–> Script」「AppleScript」でテキストで書いた「.applescript」しかピックアップできないとかいう気の狂ったようなRulesの仕様は要・修正

(2)実行Scriptにフラットな.scptとテキストの.applescriptしか実行できないのはダメ。バンドル形式の.scptdの実行サポートは必須

(3)大量のAppleScriptをコンテクストメニューに入れると使い勝手が落ちるので、Rulesでもう少しこまかく条件付けできるとよさそう。ただし必須ではない

といったところでしょうか。

AppleScript名:Webダイアログ表示(強制最前面).scpt
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

my serviceStationDidSelect("", "", "")

on serviceStationDidSelect(targetedURL, selectedItemURLs, menuKind)
  set aList to {{label:"TEST1", value:403}, {label:"TEST2", value:301}, {label:"TEST3", value:101}, {label:"TEST4", value:65}}
  
set bList to sortRecListByLabel(aList, {"value"}, {false}) of me –降順ソート
  
  
–https://www.amcharts.com/demos/pie-chart/
  
set myStr to retHTML() of me
  
set jsonStr to array2DToJSONArray(bList) of me as string
  
set aString to current application’s NSString’s stringWithFormat_(myStr, jsonStr) as string
  
set paramObj to {myMessage:"Simple Pie Chart", mySubMessage:"This is a AMCharts test", htmlStr:aString, viewSize:{1000, 550}}
  
  
my webD’s displayWebDialog(paramObj)
end serviceStationDidSelect

on array2DToJSONArray(aList)
  set anArray to current application’s NSMutableArray’s arrayWithArray:aList
  
set jsonData to current application’s NSJSONSerialization’s dataWithJSONObject:anArray options:(0 as integer) |error|:(missing value)
  
set resString to current application’s NSString’s alloc()’s initWithData:jsonData encoding:(current application’s NSUTF8StringEncoding)
  
return resString
end array2DToJSONArray

–リストに入れたレコードを、指定の属性ラベルの値でソート
on sortRecListByLabel(aRecList as list, aLabelStr as list, ascendF as list)
  set aArray to current application’s NSArray’s arrayWithArray:aRecList
  
  
set aCount to length of aLabelStr
  
set sortDescArray to current application’s NSMutableArray’s new()
  
repeat with i from 1 to aCount
    set aLabel to (item i of aLabelStr)
    
set aKey to (item i of ascendF)
    
set sortDesc to (current application’s NSSortDescriptor’s alloc()’s initWithKey:aLabel ascending:aKey)
    (
sortDescArray’s addObject:sortDesc)
  end repeat
  
  
return (aArray’s sortedArrayUsingDescriptors:sortDescArray) as list
end sortRecListByLabel

script webD
  —
  
–  Created by: Takaaki Naganoya
  
–  Created on: 2020/06/20
  
—
  
–  Copyright © 2020 Piyomaru Software, All Rights Reserved
  
—
  
use AppleScript
  
use framework "Foundation"
  
use framework "AppKit"
  
use framework "WebKit"
  
use scripting additions
  
property parent : AppleScript
  
  
property |NSURL| : a reference to current application’s |NSURL|
  
property NSAlert : a reference to current application’s NSAlert
  
property NSString : a reference to current application’s NSString
  
property NSButton : a reference to current application’s NSButton
  
property WKWebView : a reference to current application’s WKWebView
  
property WKUserScript : a reference to current application’s WKUserScript
  
property NSURLRequest : a reference to current application’s NSURLRequest
  
property NSRunningApplication : a reference to current application’s NSRunningApplication
  
property NSUTF8StringEncoding : a reference to current application’s NSUTF8StringEncoding
  
property WKUserContentController : a reference to current application’s WKUserContentController
  
property WKWebViewConfiguration : a reference to current application’s WKWebViewConfiguration
  
property WKUserScriptInjectionTimeAtDocumentEnd : a reference to current application’s WKUserScriptInjectionTimeAtDocumentEnd
  
  
property returnCode : 0
  
  
  
on displayWebDialog(paramObj)
    my performSelectorOnMainThread:"browseStrWebContents:" withObject:(paramObj) waitUntilDone:true
  end displayWebDialog
  
  
on browseStrWebContents:paramObj
    set aMainMes to myMessage of paramObj as string
    
set aSubMes to mySubMessage of paramObj as string
    
set htmlString to (htmlStr of paramObj) as string
    
–set jsDelimList to (jsDelimiters of paramObj) as list
    
set webSize to (viewSize of paramObj) as list
    
    
copy webSize to {aWidth, aHeight}
    
    
–WebViewをつくる
    
set aConf to WKWebViewConfiguration’s alloc()’s init()
    
    
set aWebView to WKWebView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aWidth, aHeight)) configuration:aConf
    
aWebView’s setNavigationDelegate:me
    
aWebView’s setUIDelegate:me
    
aWebView’s setTranslatesAutoresizingMaskIntoConstraints:true
    
using terms from scripting additions
      set bURL to |NSURL|’s fileURLWithPath:(POSIX path of (path to me))
    end using terms from
    
aWebView’s loadHTMLString:htmlString baseURL:(bURL)
    
    
–Move to frontmost (By edama2)
    
current application’s NSApplication’s sharedApplication()’s setActivationPolicy:(current application’s NSApplicationActivationPolicyRegular)
    
current application’s NSApp’s activateIgnoringOtherApps:(true)
    
    
— set up alert  
    
set theAlert to NSAlert’s alloc()’s init()
    
tell theAlert
      its setMessageText:aMainMes
      
its setInformativeText:aSubMes
      
its addButtonWithTitle:"OK"
      
–its addButtonWithTitle:"Cancel"
      
its setAccessoryView:aWebView
      
      
set myWindow to its |window|
    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
    
    
##後始末
    
aWebView’s stopLoading()
    
set js to "window.open(’about:blank’,’_self’).close();"
    
aWebView’s evaluateJavaScript:js completionHandler:(missing value)
    
set aWebView to missing value
    
  end browseStrWebContents:
  
  
  
on doModal:aParam
    set (my returnCode) to (aParam’s runModal()) as number
  end doModal:
  
  
  
on viewDidLoad:aNotification
    return true
  end viewDidLoad:
  
  
  
on fetchJSSourceString(aURL)
    set jsURL to |NSURL|’s URLWithString:aURL
    
set jsSourceString to NSString’s stringWithContentsOfURL:jsURL encoding:(NSUTF8StringEncoding) |error|:(missing value)
    
return jsSourceString
  end fetchJSSourceString
  
  
  
on pickUpFromToStr(aStr as string, s1Str as string, s2Str as string)
    using terms from scripting additions
      set a1Offset to offset of s1Str in aStr
      
if a1Offset = 0 then return false
      
set bStr to text (a1Offset + (length of s1Str)) thru -1 of aStr
      
set a2Offset to offset of s2Str in bStr
      
if a2Offset = 0 then return false
      
set cStr to text 1 thru (a2Offset – (length of s2Str)) of bStr
      
return cStr as string
    end using terms from
  end pickUpFromToStr
  
  
  
–リストを任意のデリミタ付きでテキストに
  
on retArrowText(aList, aDelim)
    using terms from scripting additions
      set aText to ""
      
set curDelim to AppleScript’s text item delimiters
      
set AppleScript’s text item delimiters to aDelim
      
set aText to aList as text
      
set AppleScript’s text item delimiters to curDelim
      
return aText
    end using terms from
  end retArrowText
  
  
on array2DToJSONArray(aList)
    set anArray to current application’s NSMutableArray’s arrayWithArray:aList
    
set jsonData to current application’s NSJSONSerialization’s dataWithJSONObject:anArray options:(0 as integer) |error|:(missing value) –0 is
    
set resString to current application’s NSString’s alloc()’s initWithData:jsonData encoding:(current application’s NSUTF8StringEncoding)
    
return resString
  end array2DToJSONArray
  
  
  
on parseByDelim(aData, aDelim)
    using terms from scripting additions
      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 using terms from
  end parseByDelim
  
end script

on retHTML()
  return "<!doctype html>
<head>
<meta charset=\"utf-8\">
<!– Styles –>
<style>
body { background-color: #000000; color: #ffffff; }
#chartdiv {
width: 100%;
height: 500px;
}

</style>
</head>
<body>

<!– Resources –>
<script src=\"https://www.amcharts.com/lib/4/core.js\"></script>
<script src=\"https://www.amcharts.com/lib/4/charts.js\"></script>
<script src=\"https://www.amcharts.com/lib/4/themes/dark.js\"></script>
<script src=\"https://www.amcharts.com/lib/4/themes/animated.js\"></script>

<!– Chart code –>
<script>
am4core.ready(function() {

// Themes begin
am4core.useTheme(am4themes_dark);
am4core.useTheme(am4themes_animated);
// Themes end

// Create chart instance
var chart = am4core.create(\"chartdiv\", am4charts.PieChart);

// Add data
chart.data = %@;

// Add and configure Series
var pieSeries = chart.series.push(new am4charts.PieSeries());
pieSeries.dataFields.value = \"value\";
pieSeries.dataFields.category = \"label\";
pieSeries.slices.template.stroke = am4core.color(\"#fff\");
pieSeries.slices.template.strokeOpacity = 1;

// This creates initial animation
pieSeries.hiddenState.properties.opacity = 1;
pieSeries.hiddenState.properties.endAngle = -90;
pieSeries.hiddenState.properties.startAngle = -90;

chart.hiddenState.properties.radius = am4core.percent(0);

}); // end am4core.ready()
</script>

<!– HTML –>
<div id=\"chartdiv\"></div>
</body>
</html>"

end retHTML

★Click Here to Open This Script 

Posted in JSON Review | Tagged 12.0savvy NSAlert NSButton NSRunningApplication NSString NSURL NSURLRequest Service Station WKUserContentController WKUserScript WKUserScriptInjectionTimeAtDocumentEnd WKWebView WKWebViewConfiguration | Leave a comment

Service Stationと他のメニュー系AppleScript実行環境との比較

Posted on 1月 28, 2022 by Takaaki Naganoya

AppleScriptの実行環境のうち、メニューから実行するタイプのものと「Service Station」の比較を行なってみました。

■Service Station


コンテクストメニューからAppleScriptを実行するツール。Finder上で選択中のファイルに応じてコンテクストメニューに表示する内容を変更できる。

■Script Menu(Apple)


macOS標準装備、メニューバーから呼び出し可能。アプリケーションごとに自動メニュー切り替え。指定フォルダ以下の内容を階層化したメニューとして表示する。

■Shorcuts Events(Apple)


macOS 12より標準装備。ショートカットをメニューバーから実行できる。メニューバーに表示するよう指定したものが表示される。階層化メニューはサポートしていない。単なるメニューのくせに、アホみたいに動作が遅い。壊れているのかと思えるほど。iCloudを経由して第三者にアクションを配布できるようになっている点が他の環境にない特徴。ただし、まだバグの塊。

■Switch Control(Apple)

macOS標準装備。アクセシビリティ系の機能。画面上に自由に配置できるフローティングパレット式AppleScriptランチャー。知る人ぞ知る超便利機能!!!

■FastScript 3(Red Sweater Software)


Script Menuの強化版。よく使うScriptを上に表示するとか、キーボードショートカットを設定して呼び出せる。キーワード検索によりScriptの絞り込みがインクリメンタルに行えるなど、大量のScriptを効率的に呼び出すための機能を備える。

AS実行環境としてはまだこなれていないService Station

Program Name Name of runtime Support AppleScript document format AS Format NSAlert dialog is displayed in frontmost Can use GUI Scripting functions Can call AppleScript Libraries? Can call AS Library including Frameworks? Can call Generic Cocoa Functions? Can use Cocoa system notification functions?
Service Station osascript Script/Text Script/Applet Script/Text Script No Yes Yes No Yes No
Script Menu osascript Script/Scriptd/Applet Script/Scriptd Yes Yes Yes No Yes Yes
Shortcuts Events MacHelper File Embedded Script Text Yes Yes Yes No Yes No
Switch Control Assistive Control File Embedded Script Script (archived) Yes Yes No No Yes No
FastScript 3 FastScripts Script Runner Script/Scriptd/Applet Script/Scriptd Yes Yes Yes No Yes

GUIなしプロセス中でosascript経由でAppleScriptの実行を行なっているので、Service StationだけNSAlertによるダイアログ表示が最前面に出てこないという問題があります。

ホームディレクトリ下のAppleScriptライブラリは呼べるし、Cocoaの機能やGUI Scriptingの機能も呼べる、標準的な環境に近いレベルにはあると思われます。

実行Scriptにバンドル形式のAppleScript(.scptd)を指定できないというのは、激弱としかいいようがありませんが、作者がバンドル形式のAppleScriptのことを知らないことが原因のように見えます。

コンテクストメニューからAppleScriptを呼び出せるようにする、というのは他のツールに見られない特徴といえますが、いまScript Menuに入れている膨大なファイル処理系のScriptを、そのままコンテクストメニューから呼べるようにすると、邪魔すぎます(膨大なScriptが表示されて上下にスクロールしまくり)。

コンテクストメニューへの階層メニュー表示をサポートしないと、自分は他のツールで使っているScriptを移行させられません。ただ、そこまでメニューにAppleScriptをホスティングしているユーザーはそうそういなさそうなので、機能強化してもそれに追いついてこられるユーザーが少なさそう。

作業で使うAppleScriptを、その場でちょっとだけ呼び出すようにして運用しないと、大量のAppleScriptがあふれかえって運用そのものが行えません。使い所が難しいツールといえるのかも? 

自分が「欲しい」と思える機能は、結局自分で作るしかなさそうな気配がしています。


▲Script Menuから呼び出している、Finder上で選択中のファイルに対して実行するScript群。こんなのコンテクストメニューには表示し切れない

Posted in Review | Tagged 12.0savvy Service Station | Leave a comment

マウスの右クリックメニューをカスタマイズするService Station

Posted on 1月 26, 2022 by Takaaki Naganoya

マウスの右クリックで表示されるコンテクストメニューをカスタマイズするツール、「Service Station」(Version 2020.9 (23))を購入して、macOS 12.2+M1 Mac miniの環境で試してみました。

同ツールはMac App Storeで販売されており、フリーでダウンロードしたのち、App内購入(1,840円)で購入できます。

OS標準のScript MenuにFinder上で選択中のファイルを対象としたAppleScriptを大量に仕込んで使っていますが、やはりコンテクストメニューから呼び出せたほうが便利なので、試してみることにしました。

Mac App Storeからダウンロードした状態(フリーで使えるお試し版)ではAppleScriptの起動はできないため、App内購入が必要です。

サポートページ(Github)、Twitterアカウントなどが公開されています。

この手のツールは、AppleScriptに対する知識が少ないデベロッパーが開発したものが多く、実際に使ってみると不満を覚える確率がきわめて高いジャンルです。これまでにも、実際に試すと「使い物にならない」と判断したツールがほとんどであるため、十分な検証が必要でしょう。

# デフォルト状態でAppleScriptの実行を指定できないのは、試用版の制限なのでご注意ください。

Service StationでAppleScript書類をコンテクストメニューから処理してみよう

本ツールのUser Interfaceはきわめてシンプルです。「Rules」でどのようにファイルを特定し、「Menu Items」でオープンするアプリケーションやAppleScriptを指定します。

初期状態では、「Folders」「Images」「Text」の3つのRulesが設定されています。ここに、AppleScript書類を処理するRulesを追加してみましょう。

どのような方法でAppleScript書類を特定できるのか、Rulesのポップアップを調べてみると……

「Kind -> Script」で「AppleScript」を指定するとよさそうです。Rulesを指定したあとで、「Menu Items」にサンプルScriptを指定してみましょう。特定のハンドラ宣言を記述したAppleScriptをここに指定できるようになっています(フラットなScriptだけであってバンドル形式は予想どおり実行できません)。


▲実行Scriptとしてバンドル形式のAppleScript書類(.scptd)を認識しないので、バンドル内に実行バイナリやAppleScriptライブラリを突っ込むのは無理

Service Stationで実行指定するAppleScriptは、~/Library/Application Scripts/com.knurling.ServiceStation.Attendant フォルダに入れる必要があります。

Finder上で試してみると…..AppleScript書類(.scpt、.scptd)を認識しません(ーー;;;


▲この設定にしたくなるが、この指定方法だとAppleScript書類(.scptおよび.scptd)を認識しない。罠なのでこの設定はしてはいけない。作者は.applescriptのテキスト形式のAppleScriptしか試していないもよう

この作者は「AppleScript書類」をテキスト形式(.applescript)でしかチェックしていないようです。なので、さきほどの「Rules」で提示された「Kind -> Script is AppleScript」は罠(Trap)なので選択してはいけません。

拡張子で指定しても応答しません(scpt、scptd)。RulesでUTIを指定できるようなので、

フラットなScript書類「com.apple.applescript.script」、バンドルScript書類「com.apple.applescript.script-bundle」、Script DebuggerのバンドルScript書類「com.latenightsw.osa.bundle」をAny条件で(どれかがヒットしたら該当したものとみなす)登録してみました。

はい。今度は問題なく、Finder上でAppleScript書類を選択した状態で表示させた(マウスの右クリック)コンテクストメニューでサンプルAppleScript(処理用のハンドラを記載しただけ)がメニューに表示され、添付のサンプルScript(「System Setup」タブの「Sample Scripts」ボタンを押すと表示される)を実行できました。

Service Station経由で実行したAppleScript(サンプルScript)は以下のような内容です。

AppleScript名:AppleScript.scpt
on serviceStationDidSelect(targetedURL, selectedItemURLs, menuKind)
  display dialog "targetedURL:
" & targetedURL & "

" & "selectedItemURLs:
"
& selectedItemURLs & "

" & "menuKind:
"
& menuKind
end serviceStationDidSelect

★Click Here to Open This Script 

ランタイム環境はosascript

お約束で、Service StationのAppleScriptランタイム環境名は知っておかなければいけないので、

AppleScript名:Runtime名を表示.scpt
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

on serviceStationDidSelect(targetedURL, selectedItemURLs, menuKind)
  set procInfo to current application’s NSProcessInfo’s processInfo()
  
set aName to procInfo’s processName() as string
  
display dialog aName
end serviceStationDidSelect

★Click Here to Open This Script 

こんなAppleScriptを書いて実験してみると….

のように、「osascript」を呼び出して実装していることがわかりました。

NSAlertダイアログを表示するも、最前面に表示されず

ランタイム環境が「osascript」だと、自前でアラートダイアログを表示させたときに「最前面に表示されない」といった問題が生じる可能性があります(osascriptでお手軽実装するの勘弁してほしい。Script側に苦労を押し付けないでほしい)。あとは、GUIなしプロセスで実行するようなので、GUI Scriptingの認証を通せるか不明です。

また、どこぞのネット上のサーバー上のREST APIにアクセスしようとしてもセキュリティ上の制約で「アクセスできない」可能性もあります(実行プロセス側でネット接続の許可をもらっていないと無理)。今後も検証が必要です。

現時点でみつけた「おや?」という仕様は、Rulesでルールを作った状態で複数のAppleScript書類を選択すると、コンテクストメニューにService Stationの項目が出てこないという点です。画像の複数選択には反応するようですが、自前で設定したRulesだと複数ファイル選択時に応答しません。

# これは、追試によって設定アプリケーションを終了させるまで設定が反映されない部分があることが判明

また、Service StationのRulesから呼び出すAppleScriptのハンドラで、受け渡されるのはHFS path stringであってURLではありませんし(fURLなのか?)、複数のURLを受信できるような表記がありながらも、本バージョンでは1つのURL(正確にはHFS path)しか受け渡されません。

# 追試の結果、複数のパス(fURL)が受け渡されていることが判明

本ツールの開発者はAppleScriptを日常的に書いていない気配が濃厚ですが、それでも修正されれば我慢できないというほどでもないでしょう。


▲予想どおり、NSAlertのダイアログを表示してもランタイムがosascriptなので最前面に表示されなかった(GUIなしの不可視プロセスからosascriptを実行した際の挙動)。CDN上のJavaScriptライブラリの呼び出しは行えた

パラメータの型チェックを試してみました。

AppleScript名:パラメータの型チェック.scpt
on serviceStationDidSelect(targetedURL, selectedItemURLs, menuKind)
  set c1 to (class of targetedURL) as string
  
set c2 to (class of selectedItemURLs) as string
  
set c3 to (class of menuKind) as string
  
  
display dialog "targetedURL:
" & c1 & "

" & "selectedItemURLs:
"
& c2 & "

" & "menuKind:
"
& c3
end serviceStationDidSelect

★Click Here to Open This Script 

サンプルScriptの記述がよくないせいで勘違いしてしまったようです。targetedURLはfURL、selectedItemURLsはList、menuKindはintegerで返ってきていました。

ホームディレクトリ内のAppleScriptライブラリを呼び出す

コンテクストメニューから呼び出すAppleScript内で、ホームディレクトリ以下のAppleScriptライブラリを呼び出すことができるか確認してみました。

結論:呼べる

AppleScript名:AppleScript v2_with_Library.scpt
use AppleScript version "2.4"
use scripting additions
use radioLib : script "displayTextView"

on serviceStationDidSelect(targetedURL as «class furl», selectedItemURLs as list, menuKind as integer)
  set aStr to do shell script "cal 2022"
  
display text view aStr main message "Main Message" sub message "Sub Message" with properties {font name:"Courier", size:13, width:600, height:300}
end serviceStationDidSelect

★Click Here to Open This Script 

Posted in news Review | Tagged 12.0savvy NSProcessInfo Service Station | Leave a comment

16bitカラー値から明度を取得 v1.1

Posted on 1月 20, 2022 by Takaaki Naganoya

choose colorコマンドやiWorkアプリケーションが返してくる16ビットのカラー値({R,G,B})から明度情報を取得するAppleScriptです。0から1までの値を返し、0に近づくほど暗く、1に近づくほど明るい色であることを表現しています。

色情報同士を比較して、明るい箇所に指定している色データと暗い箇所に指定している色データを、RGB値から自動認識するような処理に使っています。

また、ファイル名から「章」(Chapter)の番号を検出して、実際のツメ(Index)の選択部分を暗い色で塗り直す処理も行なっています。

–> Watch Demo Movie

Pages書類の上に作成したツメ(辞書などの端に印刷されているAからZのインデックス)に対して、ツメのオブジェクトを(座標や形状から)自動認識したあとに、色の塗り分け情報を本ルーチンを用いて自動認識。濃い色を現在の選択箇所の色、明るい(淡い)色を通常の箇所の色情報として扱い、あらかじめツメに指定していた色情報を用いて実際の章構成を反映させてツメのオブジェクト(表)を再構成する処理に必須のものです。

明度情報の取得には、グレースケールに変換してグレー度(whiteComponent)を明度とみなして計算しています。直感的にこちらのほうが、まっとうな処理(HSB色空間の色に変換してからBrightnessを取得)よりもしっくり来る計算結果だったので採用しています。

おまけで、2つの色情報のうちどちらが暗いか、結果をインデックス値で返す処理ルーチンをつけています。これも、選択色と非選択色の自動識別のために必要なものです。

AppleScript名:16bitカラー値から明度を取得 v1.1.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2022/01/20
—
–  Copyright © 2022 Piyomaru Software, All Rights Reserved
—

set a1Col to {26148, 65535, 58650}
set a1Col to choose color default color a1Col
set w1Col to calcBrightnessFrom16bitColorList(a1Col) of colorBrightnessKit
–> 0.900838315487

set a2Col to {2966, 23133, 21203}
set a2Col to choose color default color a2Col
set w2Col to calcBrightnessFrom16bitColorList(a2Col) of colorBrightnessKit
–> 0.37399661541–0に近いのでこちらのほうが暗い

set cIndRes to calcColorPairsDarkerCol(a1Col, a2Col) of colorBrightnessKit
–> {2, 1}–暗い順にインデックス値を返す

–色情報から明度を計算するKit。0に近い値が暗い。CMYKやグレースケール値は対象外。RGBのみ
script colorBrightnessKit
  
  
use AppleScript
  
use framework "Foundation"
  
use framework "AppKit"
  
use scripting additions
  
property parent : AppleScript
  
  
property NSColor : a reference to current application’s NSColor
  
property NSString : a reference to current application’s NSString
  
property NSAttributedString : a reference to current application’s NSAttributedString
  
property NSUTF16StringEncoding : a reference to current application’s NSUTF16StringEncoding
  
property NSDeviceWhiteColorSpace : a reference to current application’s NSDeviceWhiteColorSpace
  
  
  
–2つの16ビットカラー値でそれぞれ明度を計算し、暗いものから順にインデックス値を返す
  
on calcColorPairsDarkerCol(aCol as list, bCol as list)
    set b1 to calcBrightnessFrom16bitColorList(aCol) of me
    
set b2 to calcBrightnessFrom16bitColorList(bCol) of me
    
if b1 ≥ b2 then
      return {2, 1} –bColのほうが暗い
    else
      return {1, 2} –aColのほうが暗い
    end if
  end calcColorPairsDarkerCol
  
  
  
–16ビットカラー値から明度を計算
  
on calcBrightnessFrom16bitColorList(colList as list)
    copy colList to {rVal, gVal, bVal}
    
–NSColorを作成
    
set aCol to makeNSColorFromRGBAval(rVal, gVal, bVal, 65535, 65535) of me
    
— グレースケール化
    
set gCol to aCol’s colorUsingColorSpaceName:(NSDeviceWhiteColorSpace)
    
set wComp to gCol’s whiteComponent() –whiteComponentを取得することで擬似的に明度情報を取得  
    
return wComp
  end calcBrightnessFrom16bitColorList
  
  
  
–HTMLカラー値あから明度を計算
  
on calcBrightnessFromHTMLColorCodeStr(aStr as string)
    set {rVal, gVal, bVal} to rgbHex2nunList(aStr) of me
    
–NSColorを作成
    
set aCol to makeNSColorFromRGBAval(rVal, gVal, bVal, 255, 255) of me
    
— グレースケール化
    
set gCol to aCol’s colorUsingColorSpaceName:(NSDeviceWhiteColorSpace)
    
set wComp to gCol’s whiteComponent() –whiteComponentを取得することで擬似的に明度情報を取得  
    
return wComp
  end calcBrightnessFromHTMLColorCodeStr
  
  
  
on makeNSColorFromRGBAval(redValue as integer, greenValue as integer, blueValue as integer, alphaValue as integer, aMaxVal as integer)
    set aRedCocoa to (redValue / aMaxVal) as real
    
set aGreenCocoa to (greenValue / aMaxVal) as real
    
set aBlueCocoa to (blueValue / aMaxVal) as real
    
set aAlphaCocoa to (alphaValue / aMaxVal) as real
    
set aColor to NSColor’s colorWithCalibratedRed:aRedCocoa green:aGreenCocoa blue:aBlueCocoa alpha:aAlphaCocoa
    
return aColor
  end makeNSColorFromRGBAval
  
  
  
  
on decodeCharacterReference(aStr)
    set anNSString to NSString’s stringWithString:aStr
    
set theData to anNSString’s dataUsingEncoding:(NSUTF16StringEncoding)
    
set styledString to NSAttributedString’s alloc()’s initWithHTML:theData documentAttributes:(missing value)
    
set plainText to (styledString’s |string|()) as string
    
return plainText
  end decodeCharacterReference
  
  
  
  
–HTMLコードのRGB 16進数コードを数値リストに変換
  
on rgbHex2nunList(aHexStr)
    –エラーチェック
    
if aHexStr does not start with "#" then return false
    
if length of aHexStr is not equal to 7 then return false
    
set bHex to text 2 thru -1 of aHexStr
    
    
set {rStr, gStr, bStr} to {text 1 thru 2 of bHex, text 3 thru 4 of bHex, text 5 thru 6 of bHex}
    
    
set bList to {}
    
repeat with i in {rStr, gStr, bStr}
      set j to contents of i
      
set the end of bList to aHexStrToNum(j) of me
    end repeat
    
    
return bList
  end rgbHex2nunList
  
  
  
–16進数文字列を10進数数値に変換する
  
on aHexStrToNum(hexStr)
    set hStr to "0123456789ABCDEF"
    
    
set aNum to 0
    
set aLen to length of hexStr
    
    
repeat with i from aLen to 1 by -1
      
      
set aCon to contents of character i of hexStr
      
using terms from scripting additions
        set aVal to (offset of aCon in hStr) – 1
      end using terms from
      
set aNum to aNum + aVal * (16 ^ (aLen – i))
      
    end repeat
    
    
return aNum as integer
  end aHexStrToNum
end script

★Click Here to Open This Script 

Posted in Color list | Tagged 10.15savvy 11.0savvy 12.0savvy NSColor | Leave a comment

Skim v1.6.8でScripting機能のバグを修正

Posted on 1月 18, 2022 by Takaaki Naganoya

フリーのPDFビューワー「Skim」の最新版v1.6.8で、前バージョンで発生していたAppleScriptのサポート機能のバグが修正されました。どちらかといえば、OS側の不具合のような雰囲気も漂っています。

Posted in Bug | Tagged macOS 12 Skim | Leave a comment

SafariでブックマークされたURL一覧を取得

Posted on 1月 7, 2022 by Takaaki Naganoya

Safariのブックマークに登録されたURL一覧を取得するAppleScriptです。

SafariのAppleScript対応機能に、ブックマーク操作系のものは存在していません。そのため、Bookmarks.plistを直接読み込んでデータの絞り込みを行なっています。

Bookmarks.plistを実際に読んでみると、ツリー(フォルダ)とリーフ(個別のブックマーク)があって、本Scriptではリーフ部分しか読んでいないのですが、とりあえず試作レベルということで。

読むのはいいんですが、追加が大変そうなので(BookmarkのIDとか外部で勝手に追加できるものなんだろうか。UUIDっぽいけど)ブックマーク登録は野蛮にGUI Scripting経由でメニューを操作することになるのでしょう。

AppleScript名:SafariのBookmarks.plistから登録URLを取得
—
–  Created by: Takaaki Naganoya
–  Created on: 2022/01/07
—
–  Copyright © 2022 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.7"
use framework "Foundation"
use scripting additions

script spdB
  property urlList : {}
end script

set (urlList of spdB) to getBookmarkedURLs() of me
set (urlList of spdB) to cleanUp1DList((urlList of spdB), missing value) of me –Sweep missing value items

–Read Bookmarked URLs
on getBookmarkedURLs()
  set newPath to "~/Library/Safari/Bookmarks.plist"
  
set aRec to my readPlistAt:newPath
  
return ((aRec’s Children)’s valueForKey:"URLString") as list
end getBookmarkedURLs

–Read Plist
on readPlistAt:thePath
  set thePath to current application’s NSString’s stringWithString:thePath
  
set thePath to thePath’s stringByExpandingTildeInPath()
  
set theDict to current application’s NSDictionary’s dictionaryWithContentsOfFile:thePath
  
return theDict
end readPlistAt:

–1D Listのスイープ
on cleanUp1DList(aList as list, cleanUpItems as list)
  set bList to {}
  
repeat with i in aList
    set j to contents of i
    
if j is not in cleanUpItems then
      set the end of bList to j
    end if
  end repeat
  
return bList
end cleanUp1DList

★Click Here to Open This Script 

Posted in Record | Tagged 10.15savvy 11.0savvy 12.0savvy Safari | Leave a comment

Intel MacとApple Silicon Macの速度差〜画像処理

Posted on 1月 2, 2022 by Takaaki Naganoya

macOS 11から12に移行して、なぜかリリースが近づくにつれて細かいバグや巨大なバグが顕在化し、まだ手放しでおすすめできる状況にないのが心苦しいところですが、AppleScriptからのCocoa呼び出しについてはIntel Mac/Apple Silicon Macでも速度が向上。とくに、Apple Silicon Macでの速度向上が顕著です。

で、特定の処理(巨大なlistやrecord in list同士の検索)でM1 Mac miniがiMac Proの2.5倍ぐらい速いといったベンチマークは出しているわけですが、いかにもApple Silicon Macで処理が速そうな画像処理のベンチマークを実施してみました。

Intel Mac mini 2014が手元からなくなってしまったので、以前のメインマシンであったMacBook Pro Retina 2012(MacBookPro10,1)と比較してみました。

ベンチマーク内容は、指定の画像が空白かどうかをチェックするというものです。フルHD画像でも4K画像でも8K画像でも、1ピクセルでも白くない点があれば検出できるという処理内容。外部のGPUImage FrameworkやPhotoshopのヒストグラム処理を呼び出すよりもAppleScriptだけで処理した方が速いというものです(8K画像だとPhotoshopの方が速いかも)。


▲画像解像度の変化と処理時間の相関。グラフは数値が小さいほど高速。巨大な画像になると処理速度差が大きくなる傾向にある?

だいたい、MacBook Pro Retina 2012と比べて3〜4倍ぐらいM1 Mac miniの方が高速です。MacBook Pro Retina 2012は2017年のMacBook Pro 13インチといい勝負ぐらいの速度が出ており、古い割にはごく最近まで使えていました。

そこから3〜4倍高速ということで、M1 Mac miniはコストの割にはパワフルです。ファンレスのMacBook Air M1でも同程度の速度が出るはずです。

一方で、M1 Pro/M1 Max搭載のMacBook ProでM1機よりも大幅に高速なのかと言われると……このぐらいの静止画の処理程度だとごくわずかな差しかつかないはずです。下手をすると、速度差がないかもしれません。

→ Download blank_image_detection_benchmark.zip (including script libraries)

–> Download test Data


▲バーが短いほど高速。M1がM1 Maxの2倍高速という結果が出てしまった。M1 Max MBPは2014年のIntel Mac miniより少し速いだけのマシンという結果に。2018年のIntel Mac miniとの比較だとM1 Max MBPよりもIntel Mac miniのほうが速そう

M1、M1 Max、M1 Ultra(最上位機種)で処理時間を比較した結果。予想どおりM1がM1 MaxやM1 Ultraよりも2倍以上高速。もはや8K画像ぐらいは、大きなデータにならないというべきなのか。

AppleScript名:画像の空白判定 v4_bench_時間計測.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2022/01/01
—
–  Copyright © 2022 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.7"
use framework "Foundation"
use framework "AppKit"
use scripting additions
use mdLib : script "Metadata Lib" version "2.0.0"
use easyTable : script "display table by list"

set aFol to choose folder

set aResList to perform search in folders {aFol} predicate string "kMDItemContentTypeTree CONTAINS %@" search arguments {"public.image"}

set aList to {}
repeat with i in aResList
  set a1Dat to current application’s NSDate’s timeIntervalSinceReferenceDate()
  
  
set iRes to checkImageIsWhite(i) of blankImageKit of me
  
  
set b1Dat to current application’s NSDate’s timeIntervalSinceReferenceDate()
  
set c1Dat to b1Dat – a1Dat
  
  
set aName to (current application’s NSString’s stringWithString:i)’s lastPathComponent() as string
  
  
if iRes = true then
    set jRes to "White"
  else
    set jRes to "Black"
  end if
  
  
–log {aName, jRes}
  
  
set the end of aList to {aName, jRes, c1Dat}
end repeat

set fLabels to {"File name", "Result", "Estimate(Seconds)"}
set aRes to (display table by list aList main message "Blank Image check" size {800, 600} labels fLabels)
return aList

script blankImageKit
  use AppleScript version "2.7" — High Sierra (10.13) or later
  
use framework "Foundation"
  
use framework "AppKit"
  
use scripting additions
  
property parent : AppleScript
  
  
property NSData : a reference to current application’s NSData
  
property |NSURL| : a reference to current application’s |NSURL|
  
property NSColor : a reference to current application’s NSColor
  
property NSImage : a reference to current application’s NSImage
  
property NSBezierPath : a reference to current application’s NSBezierPath
  
property NSBitmapImageRep : a reference to current application’s NSBitmapImageRep
  
  
  
–Compare Original Data and
  
on checkImageIsWhite(aFile)
    set aPOSIXpath to POSIX path of aFile
    
set aURL to |NSURL|’s fileURLWithPath:(aPOSIXpath)
    
    
set aNSImage to NSImage’s alloc()’s initWithContentsOfURL:(aURL)
    
set bNSImage to NSImage’s alloc()’s initWithContentsOfURL:(aURL)
    
    
set fillColor1 to NSColor’s clearColor()
    
set blankNSImage1 to drawImageWithFilledColor(aNSImage, fillColor1) of me
    
    
set fillColor2 to makeNSColorFromRGBAval(65535, 65535, 65535, 65535, 65535) of me –white
    
set blankNSImage2 to drawImageWithFilledColor(bNSImage, fillColor2) of me
    
    
set aTiff to blankNSImage1’s TIFFRepresentation()
    
set bTiff to blankNSImage2’s TIFFRepresentation()
    
    
set chkWhite to (aTiff’s isEqualToData:bTiff) as boolean
    
    
return chkWhite
  end checkImageIsWhite
  
  
  
on getSizeOfImage(anNSImage)
    set aSize to anNSImage’s |size|()
    
set aClass to class of aSize
    
if aClass = record then
      copy aSize to theSize –To macOS 10.12.x
    else –macOS 10.13 or later
      set sizeX to (item 1 of item 2 of aSize)
      
set sizeY to (item 2 of item 2 of aSize)
      
set theSize to {width:sizeX, height:sizeY}
    end if
    
return theSize
  end getSizeOfImage
  
  
  
–指定サイズの画像を作成し、背景を指定色で塗る
  
on drawImageWithFilledColor(anImage, fillColor)
    set aSize to getSizeOfImage(anImage) of me
    
    
anImage’s lockFocus()
    
    
set theRect to {{x:0, y:0}, {width:(width of aSize), height:(height of aSize)}}
    
set theNSBezierPath to NSBezierPath’s bezierPath
    
theNSBezierPath’s appendBezierPathWithRect:theRect
    
fillColor’s |set|()
    
theNSBezierPath’s fill()
    
    
anImage’s unlockFocus()
    
    
return anImage
  end drawImageWithFilledColor
  
  
  
–aMaxValを最大値とする数値でNSColorを作成して返す
  
on makeNSColorFromRGBAval(redValue as integer, greenValue as integer, blueValue as integer, alphaValue as integer, aMaxVal as integer)
    set aRedCocoa to (redValue / aMaxVal) as real
    
set aGreenCocoa to (greenValue / aMaxVal) as real
    
set aBlueCocoa to (blueValue / aMaxVal) as real
    
set aAlphaCocoa to (alphaValue / aMaxVal) as real
    
set aColor to NSColor’s colorWithCalibratedRed:aRedCocoa green:aGreenCocoa blue:aBlueCocoa alpha:aAlphaCocoa
    
return aColor
  end makeNSColorFromRGBAval
  
end script

★Click Here to Open This Script 

Posted in Image | Tagged 10.14savvy 10.15savvy 11.0savvy 12.0savvy NSBezierPath NSBitmapImageRep NSColor NSData NSDate NSImage NSURL | Leave a comment

CotEditorで選択範囲の行頭にある数字をリナンバーする v1

Posted on 1月 2, 2022 by Takaaki Naganoya

CotEditorでオープン中の最前面の書類の選択範囲のテキストを行ごとにチェックし、行頭に存在する数字を、それらのうちの最小値を検出しつつ、指定のステップ数でリナンバー(番号振り直し)を行うAppleScriptです。

さまざまな項目の整理のために、テキストの先頭に仮想的なノンブル(ページ番号的なもの、ソート順を指定するための番号)を振っています。この番号ではじまるテキストをもとにFinder上でフォルダ整理をしており、項目の前後関係を入れ替えると…前後関係を明示するために、番号を振り直す必要が出てくるわけです。

# Numbers上やExcel上で行うと、余計な書体スタイルなどが入ってきて邪魔なので、テキストエディタ上で行うことが多いです

その番号の振り直しを行うAppleScriptです。macOS 12.2beta+CotEditor v4.0.9で動作確認を行っています。


▲選択範囲内の行頭の番号を振り直す。ちなみに、表示例はボツになった本の企画

本来は「行頭にある数字」を指示する必要があるものの、まだうまく機能していません。桁数でなんとなく判別しているだけです。


▲フォント作者の方々の合意を得られなさそうで流れた企画「同人フォントソムリエ」

AppleScript名:選択範囲の行頭にある数字をリナンバーする v1.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2022/01/02
—
–  Copyright © 2022 Piyomaru Software, All Rights Reserved
—

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

property NSMutableArray : a reference to current application’s NSMutableArray

property myNumStep : 1000

tell application "CotEditor"
  tell front document
    set aSel to contents of selection
    
set aSelList to paragraphs of aSel
  end tell
end tell

–範囲指定がない場合
if length of aSelList = 0 then
  display dialog "Error: No Selection" buttons {"OK"} default button 1 with icon 2
  
return
end if

–過大な範囲指定チェック
if length of aSelList > 1000 then
  set bRes to button returned of (display dialog "選択範囲が1000行を超えています。処理に時間がかかることが予想されますが、実行しますか?")
end if

–行頭の数字部分のみ取得して、数字の最小値を取得する
set topNumList to getNumbersAtLineBegennings(aSelList) of me
set minNum to calcIntMinAsStr(topNumList) of me

–行頭部分の数字部分のみリナンバー
set bRes to renumberNumsAtLineBegennings(aSelList, minNum as integer, myNumStep) of me

–1D Arrayを改行コードをデリミタに指定しつつテキスト化
set outStr to retDelimedText(bRes, return) of me

tell application "CotEditor"
  tell front document
    set contents of selection to outStr
  end tell
end tell

–行頭に入っている数字の文字のみリナンバー
–実際には行頭判定はまだ行えていない。行頭の番号と文の途中に出てくる数字の区別は「桁数」でのみ行っている
on renumberNumsAtLineBegennings(aSelList as list, firstNum as string, stepNum as number)
  set aDigit to length of firstNum –桁数
  
copy firstNum to aCount
  
  
set aRes to {}
  
  
repeat with i in aSelList
    set j to (contents of i) as string
    
set nRes to (getNumberCharsOnlyAtBegening(j) of me) as string
    
    
if nRes is not equal to "" then –InputとOutputが違った
      set n1Res to removeNumCharsOnly(j, aDigit) of me
      
set tmpNumStr to zeroPadding(aCount, aDigit) of me
      
set n1Res to tmpNumStr & n1Res
      
set aCount to aCount + stepNum
      
set the end of aRes to n1Res
    else
      set the end of aRes to j
    end if
  end repeat
  
  
return aRes
end renumberNumsAtLineBegennings

–1D Listの最小値を文字列で返す
on calcIntMinAsStr(aList as list)
  set nArray to (NSMutableArray’s arrayWithArray:aList)
  
set maxRes to (nArray’s valueForKeyPath:"@min.self")’s intValue()
  
return maxRes as string
end calcIntMinAsStr

–行頭に入っている数字の文字のみ抽出
on getNumbersAtLineBegennings(aSelList as list)
  set aRes to {}
  
repeat with i in aSelList
    set j to contents of i
    
set nRes to getNumberCharsOnlyAtBegening(j) of me
    
if nRes is not equal to "" then
      set the end of aRes to nRes
    end if
  end repeat
  
  
return aRes
end getNumbersAtLineBegennings

–数字のみ返す
on getNumberCharsOnlyAtBegening(aStr as string)
  set anNSString to current application’s NSString’s stringWithString:aStr
  
set anNSString to anNSString’s stringByReplacingOccurrencesOfString:"[^0-9]{4,}" withString:"" options:(current application’s NSRegularExpressionSearch) range:{0, anNSString’s |length|()}
  
return anNSString as text
end getNumberCharsOnlyAtBegening

–数字のみ削除して返す
on removeNumCharsOnly(aStr as string, aDigit)
  set anNSString to current application’s NSString’s stringWithString:aStr
  
set anNSString to anNSString’s stringByReplacingOccurrencesOfString:("[0-9]{" & (aDigit as string) & ",}") withString:"" options:(current application’s NSRegularExpressionSearch) range:{0, anNSString’s |length|()}
  
return anNSString as text
end removeNumCharsOnly

–指定桁数で指定の数にゼロパディングして文字列を返す
on zeroPadding(aNum as number, aDigit as number)
  set aText to "00000000000" & (aNum as text)
  
set aLen to length of aText
  
set aRes to text (aLen – aDigit + 1) thru -1 of aText
  
return aRes
end zeroPadding

–1D Listを指定デリミタをはさみつつテキストに
on retDelimedText(aList as list, aDelim as string)
  set aText to ""
  
set curDelim to AppleScript’s text item delimiters
  
set AppleScript’s text item delimiters to aDelim
  
set aText to aList as text
  
set AppleScript’s text item delimiters to curDelim
  
return aText
end retDelimedText

★Click Here to Open This Script 

Posted in regexp Text | Tagged 10.15savvy 11.0savvy 12.0savvy CotEditor | Leave a comment

電子書籍(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