Menu

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

AppleScriptの穴

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

タグ: 10.14savvy

SVGの要素を走査するじっけん v2

Posted on 11月 19, 2019 by Takaaki Naganoya

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

–> Download countrySel(Code-Signed AppleScript applet executable. Its icon is customized version by Script Debbuger)


▲いかにもなメルカトル図法の世界地図。極地に行くほど巨大に表現される。国によっては国土が小さいために色を変えてもこの縮尺だとわからないことも

SVGをparseするのにXML Parser系のFrameworkを軒並み試してみたのですが、所定の要素を掘り進んでいくまでは楽にできるものの、検索先のnodeまで行って属性値を書き換えたあとでrootまで戻り、属性値を書き換えたXML全体を文字列化するような機能を備えたものは見つかりませんでした。

この手の処理で圧倒的に便利なのがHTMLReader.framework。書き換え要素を検索して、書き換えたあとにrootまで戻り、Document全体を文字列化して返すような処理が楽勝です。この手の処理が楽にできるプログラムは、自分が知っているかぎりではこれだけです。

本ScriptはmacOS 10.15.1上で作って試してみましたが、驚いたことに、アプリケーション書き出ししたときに、Apple純正のランタイムだとAppleScriptアプレット内にバンドルしたフレームワークにアクセスできなくなっていました。

セキュリティを強化したいのは理解できますが、いささかやりすぎではないでしょうか。この先、Script Debuggerを用いて書き出したランタイムまで実行できなくなったとしたらXcode上で作らないと実行できなくなってしまうことでしょう。いささかやりすぎのようにも思えます。

Script Debuggerから「Application(Apple)」で書き出すと、Frameworkにアクセスできないんだか、WkWebViewにアクセスできないんだか不明ですが、macOS 10.15上では地図が表示できません。


▲Script Debugger上でアプレット書き出しするさいに、Applicaion(Enhanced)で書き出さないとバンドル内のフレームワーク呼び出しができなかった。Script Debuggerがないと手も足も出ない


▲ISO国コードから選択。「JP」を選ぶと日本が、「AU」を選ぶとオーストラリアが赤く表示される


▲SVGの世界地図をテキストエディタでオープンしたところ

AppleScript名:SVGの要素を走査するじっけん v2.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/11/19
—
–  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
use webDialog : script "webViewLib"

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

property textArray : missing value
property anError : missing value

–Choose Target Country
set isoCountry to (current application’s NSLocale’s ISOCountryCodes()) as list
set cRes to choose from list isoCountry with prompt "Select Target Country"

set targetCountry to contents of first item of cRes

–Load SVG World map in this bundle
set mePath to ((path to me) as string) & "Contents:Resources:world-2.svg"
set aData to read (mePath as alias)
set aHTML to current application’s HTMLDocument’s documentWithString:(aData as string)

set eList to (aHTML’s nodesMatchingSelector:"path") as list
set fList to (aHTML’s nodesMatchingSelector:"path")’s valueForKeyPath:"attributes.id"

–Search Target Country
set aRes to (fList)’s indexOfObject:(targetCountry)
if (aRes = current application’s NSNotFound) or (aRes > 9.99999999E+8) then
  error "Target country not found"
end if
set aRes to aRes + 1 — (Cocoa array index begins from 0, AppleScript is 1)

–Rewrite target country’s fill color on SVG
set tmpNode to contents of item aRes of (eList)
(
tmpNode’s setObject:"Red" forKeyedSubscript:"fill") –Change Target Country’s fill color

set svgCon to (tmpNode’s |document|()’s serializedFragment()) as string –HTMLReaderはこういう処理ができるところが好き

–Alert Dialog上でSVGを表示
dispWebViewByString(svgCon, "This is " & targetCountry, "This is your indicated country by 2 character country code") of webDialog

★Click Here to Open This Script 

Posted in dialog Image SVG Text XML | Tagged 10.13savvy 10.14savvy 10.15savvy HTMLDocument NSString | 1 Comment

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

Posted on 11月 18, 2019 by Takaaki Naganoya

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

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

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

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

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


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

AppleScript名:アラートダイアログ上のWebViewに円グラフを表示.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/11/18
—
–  Copyright © 2019 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use framework "AppKit"
use framework "WebKit"
use scripting additions

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

property theResult : 0
property returnCode : 0

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

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

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

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

on viewDidLoad:aNotification
  return true
end viewDidLoad:

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

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

★Click Here to Open This Script 

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

checkboxLib v2

Posted on 11月 17, 2019 by Takaaki Naganoya

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

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

–> Watch Demo Movie

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

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

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


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


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

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

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

★Click Here to Open This Script 

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

指定アプリケーション内の現在のLocaleの指定stringsファイル内の指定キーの値を取得する

Posted on 11月 16, 2019 by Takaaki Naganoya

Bundle IDで指定したアプリケーションのバンドル中(/Contents/Resources/)の現在のLocalizationに存在する指定のstringsファイル内で、指定キーの値を取得するAppleScriptです。

アプリケーションバンドル内の各ローカライズフォルダの名称は一意に決定されているものでもなく、ある程度の「ゆらぎ」が生じています。

/Contents/Resources/Japanese.lproj/
/Contents/Resources/ja.lproj/

NSLocaleからcurrentLocale()を取得すると、「ja-JP」のような識別子が得られます。これと上記のパターンのフォルダとの付け合わせのためのメソッドがどこかに存在しているはずなのですが、現状では見つけられていません(ないと各アプリケーションが正しくメニュー表示できていないので)。

まだいまひとつ、しっくりきていません。

AppleScript名:指定アプリケーション内の現在のLocaleの指定stringsファイル内の指定キーの値を取得する.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/11/15
—
–  Copyright © 2019 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
use framework "AppKit"

property |NSURL| : a reference to current application’s |NSURL|
property NSBundle : a reference to current application’s NSBundle
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 NSLocaleCountryCode : a reference to current application’s NSLocaleCountryCode
property NSLocaleLanguageCode : a reference to current application’s NSLocaleLanguageCode
property NSLocaleCollatorIdentifier : a reference to current application’s NSLocaleCollatorIdentifier

set targID to "com.apple.iWork.Keynote"
set targFile to "Keynote" –"Keynote.strings" file
set targKey to "Arrange"
set vStr to getAValInASpecifiedStringFileOfAllLocaleInABundle(targID, targFile, targKey) of me
–> "配置"

on getAValInASpecifiedStringFileOfAllLocaleInABundle(targID, targFile, targKey)
  set aPath to retPathFromBundleID(targID) of me
  
  
set aURL to (|NSURL|’s fileURLWithPath:aPath)
  
set aBundle to NSBundle’s bundleWithURL:aURL
  
  
set aLocale to (current application’s NSLocale’s preferredLanguages()’s firstObject()) as string
  
  
set curLocale to current application’s NSLocale’s currentLocale()
  
set aDS11 to (curLocale’s objectForKey:(NSLocaleLanguageCode)) as string
  
set aDS12 to (curLocale’s objectForKey:(NSLocaleCountryCode)) as string
  
set aDS5 to (curLocale’s objectForKey:(NSLocaleCollatorIdentifier)) as string
  
–set bID to (current application’s NSBundle’s mainBundle()’s preferredLocalizations()’s firstObject()) as string
  
  
set langIDList to {aDS11, aLocale, aDS12, aDS5} –> {"ja", "ja-JP", "JP", "ja-JP"}
  
  
repeat with i in langIDList
    set j to contents of i
    
set aRes to (aBundle’s pathForResource:targFile ofType:"strings" inDirectory:"" forLocalization:(j))
    
set aDict to (NSDictionary’s alloc()’s initWithContentsOfFile:aRes)
    
if aDict is not equal to missing value then
      set aVal to (aDict’s valueForKeyPath:(targKey))
      
if aVal is not equal to missing value then
        return aVal as string
      end if
    end if
  end repeat
  
  
return false
end getAValInASpecifiedStringFileOfAllLocaleInABundle

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

★Click Here to Open This Script 

Posted in list System Text URL | Tagged 10.12savvy 10.13savvy 10.14savvy 10.15savvy NSBundle NSDictionary NSFileManager NSLocaleCollatorIdentifier NSLocaleCountryCode NSLocaleLanguageCode NSURL NSWorkspace | 2 Comments

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

Posted on 11月 14, 2019 by Takaaki Naganoya

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

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

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

property NSBox : a reference to current application’s NSBox
property NSView : a reference to current application’s NSView
property NSAlert : a reference to current application’s NSAlert
property NSScrollView : a reference to current application’s NSScrollView
property NSRunningApplication : a reference to current application’s NSRunningApplication

property returnCode : 0
property returnSels : {}

set paramObj to {myMessage:"項目選択", mySubMessage:"以下の各項目を選択してください。", segmentMes:{{"Red1", "Blue1", "Yellow1", "Brown1", "White1", "Cyan1", "Grey1"}, {"Red2", "Blue2", "Yellow2", "Brown2", "White2", "Cyan2", "Grey2"}, {"Red3", "Blue3", "Yellow3", "Brown3", "White3", "Cyan3", "Grey3"}, {"Red4", "Blue4", "Yellow4", "Brown4", "White4", "Cyan4", "Grey4"}, {"Red5", "Blue5", "Yellow5", "Brown5", "White5", "Cyan5", "Grey5"}}, segmentTitles:{"1st Segments", "2nd Segments", "3rd Segments", "4th Segments", "5th Segments"}}

–my chooseMultipleSegments:paramObj
my performSelectorOnMainThread:"chooseMultipleSegments:" withObject:paramObj waitUntilDone:true

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

on chooseMultipleSegments:paramObj
  set aMainMes to (myMessage of paramObj) as string
  
set aSubMes to (mySubMessage of paramObj) as string
  
set segMes2DList to (segmentMes of paramObj) as list
  
set segTitleList to (segmentTitles of paramObj) as list
  
  
set aTmpY to (length of segMes2DList) * 60
  
  
–BoX + Segmented Control をつくる
  
set segsList to {}
  
set boxLIst to {}
  
set segsCount to 0
  
set tmpMaxX to 400
  
  
set aCount to 1
  
  
repeat with i in segMes2DList
    set a1Button to (current application’s NSPopUpButton’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, tmpMaxX – 30, 30)) pullsDown:false)
    
a1Button’s removeAllItems()
    (
a1Button’s addItemsWithTitles:(i))
    
    
set aDBounds to a1Button’s |bounds|()
    
set tmpWidth to getWidth(aDBounds) of me
    
    
set aBox to (NSBox’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, aTmpY – segsCount – 60, tmpMaxX – 10, 60)))
    (
aBox’s setTitle:(item aCount of segTitleList))
    (
aBox’s addSubview:a1Button)
    (
aBox’s setBorderType:0) –NSNoBorder, this method is depreceted in macOS 10.14. Which is alternative?
    
    
if tmpWidth > tmpMaxX then set tmpMaxX to tmpWidth
    
    
set the end of segsList to a1Button –選択検出用
    
set the end of boxLIst to aBox –表示用
    
    
set segsCount to segsCount + 60
    
set aCount to aCount + 1
  end repeat
  
  
— create a view
  
set theView to NSView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, tmpMaxX + 10, aTmpY + 20))
  
theView’s setSubviews:boxLIst
  
  
— create a Scroll View
  
set aScroll to NSScrollView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, tmpMaxX + 10, 300))
  
aScroll’s setDocumentView:theView
  
aScroll’s documentView()’s scrollPoint:(current application’s NSMakePoint(0, aTmpY + 10)) –Force scroll to top
  
  
theView’s enclosingScrollView()’s setHasHorizontalScroller:false
  
theView’s enclosingScrollView()’s setHasVerticalScroller:true
  
  
  
— set up alert
  
set theAlert to NSAlert’s alloc()’s init()
  
tell theAlert
    its setMessageText:aMainMes
    
its setInformativeText:aSubMes
    
its addButtonWithTitle:"OK"
    
its addButtonWithTitle:"Cancel"
    
its setAccessoryView:aScroll
  end tell
  
  
— show alert in modal loop
  
NSRunningApplication’s currentApplication()’s activateWithOptions:0
  
my performSelectorOnMainThread:"doModal:" withObject:(theAlert) waitUntilDone:true
  
if (my returnCode as number) = 1001 then error number -128
  
  
set my returnSels to {}
  
repeat with i in segsList
    set tmpSegSel to (i’s indexOfSelectedItem()) as number
    
set the end of (my returnSels) to tmpSegSel + 1
  end repeat
end chooseMultipleSegments:

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

on clickedSeg:aSender
  set aSel to aSender’s selectedSegment()
end clickedSeg:

on getWidth(aDBounds)
  if class of aDBounds = list then
    –macOS 10.13 or later
    
return item 1 of item 1 of aDBounds
  else
    –macOS 10.10….10.12
    
return width of |size| of aDBounds
  end if
end getWidth

★Click Here to Open This Script 

Posted in dialog GUI | Tagged 10.12savvy 10.13savvy 10.14savvy 10.15savvy NSAlert NSBox NSRunningApplication NSScrollView NSView | Leave a comment

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

Posted on 11月 13, 2019 by Takaaki Naganoya

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

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

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

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

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

(2)選択無効日指定

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

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

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

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

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

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

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

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

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

property NSFont : a reference to current application’s NSFont
property NSView : a reference to current application’s NSView
property NSAlert : a reference to current application’s NSAlert
property NSColor : a reference to current application’s NSColor
property NSButton : a reference to current application’s NSButton
property NSOnState : a reference to current application’s NSOnState
property NSOffState : a reference to current application’s NSOffState
property NSTextField : a reference to current application’s NSTextField
property NSMutableArray : a reference to current application’s NSMutableArray
property NSButtonTypeOnOff : a reference to current application’s NSButtonTypeOnOff
property NSMutableDictionary : a reference to current application’s NSMutableDictionary
property NSRunningApplication : a reference to current application’s NSRunningApplication
property NSFontAttributeName : a reference to current application’s NSFontAttributeName
property NSKernAttributeName : a reference to current application’s NSKernAttributeName
property NSMutableParagraphStyle : a reference to current application’s NSMutableParagraphStyle
property NSLigatureAttributeName : a reference to current application’s NSLigatureAttributeName
property NSMutableAttributedString : a reference to current application’s NSMutableAttributedString
property NSUnderlineStyleAttributeName : a reference to current application’s NSUnderlineStyleAttributeName
property NSParagraphStyleAttributeName : a reference to current application’s NSParagraphStyleAttributeName
property NSForegroundColorAttributeName : a reference to current application’s NSForegroundColorAttributeName

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

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

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

on chooseItemByCheckBox:(paramObj)
  set aMainMes to (myMessage of paramObj) as string
  
set aSubMes to (mySubMessage of paramObj) as string
  
set aMatList to (matrixTitleList of paramObj) as list
  
set tYear to (targetYear of paramObj) as integer
  
set tMonth to (targetMonth of paramObj) as integer
  
set noDispList to (nodisp of paramObj) as list
  
set ignoreP to (ignorePast of paramObj) as boolean
  
  
if aMainMes = "" then
    set aMainMes to "日付を選択してください"
  end if
  
  
set theView to makeCalendarView(tYear, tMonth, noDispList, ignoreP) of me
  
  
–Select the first radio button item
  
set my theResult to {}
  
  
— set up alert  
  
set theAlert to NSAlert’s alloc()’s init()
  
tell theAlert
    its setMessageText:aMainMes
    
its setInformativeText:aSubMes
    
its addButtonWithTitle:"OK"
    
its addButtonWithTitle:"Cancel"
    
its setAccessoryView:theView
    
    
–for Help Button
    
–its setShowsHelp:(true)
    
its setDelegate:(me)
    
set aWin to its |window|()
  end tell
  
  
aWin’s setLevel:(current application’s NSFloatingWindowLevel)
  
  
— show alert in modal loop
  
NSRunningApplication’s currentApplication()’s activateWithOptions:0
  
my performSelectorOnMainThread:"doModal:" withObject:(theAlert) waitUntilDone:true
  
if (my returnCode as number) = 1001 then error number -128
  
end chooseItemByCheckBox:

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

on clicked:aParam
  set aTag to (tag of aParam) as integer
  
  
–clicked
  
if aTag is not in (my theResult) then
    set the end of (my theResult) to aTag
  else
    set theResult to my deleteItem:aTag fromList:theResult
  end if
end clicked:

on deleteItem:anItem fromList:theList
  set theArray to NSMutableArray’s arrayWithArray:theList
  
theArray’s removeObject:anItem
  
return theArray as list
end deleteItem:fromList:

–1D List(数値)をsort / ascOrderがtrueだと昇順ソート、falseだと降順ソート
on sort1DNumList:theList ascOrder:aBool
  tell current application’s NSSet to set theSet to setWithArray_(theList)
  
tell current application’s NSSortDescriptor to set theDescriptor to sortDescriptorWithKey_ascending_(missing value, true)
  
set sortedList to theSet’s sortedArrayUsingDescriptors:{theDescriptor}
  
return (sortedList) as list
end sort1DNumList:ascOrder:

–Help Button Clicked Event Handler
on alertShowHelp:aNotification
  set aRes to display dialog "Do you change all checkbox state?" buttons {"All Off", "All On", "Cancel"} default button 3 with icon 1
  
set bRes to (button returned of aRes) as string
  
  
if bRes = "All Off" then
    set bLen to bArray’s |count|()
    
set theResult to {}
    
repeat with i from 0 to bLen
      ((bArray’s objectAtIndex:i)’s setState:(current application’s NSOffState))
    end repeat
    
  else if bRes = "All On" then
    set bLen to bArray’s |count|()
    
set theResult to {}
    
repeat with i from 0 to bLen
      ((bArray’s objectAtIndex:i)’s setState:(current application’s NSOnState))
      
set the end of theResult to i + 1
    end repeat
  end if
  
  
return false –trueを返すと親ウィンドウ(アラートダイアログ)がクローズする
end alertShowHelp:

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

on makeNSTextField(xPos as integer, yPos as integer, myWidth as integer, myHeight as integer, editableF as boolean, setVal as string, backgroundF as boolean, borderedF as boolean)
  set aNSString to NSTextField’s alloc()’s initWithFrame:(current application’s NSMakeRect(xPos, yPos, myWidth, myHeight))
  
aNSString’s setEditable:(editableF)
  
aNSString’s setStringValue:(setVal)
  
aNSString’s setDrawsBackground:(backgroundF)
  
aNSString’s setBordered:(borderedF)
  
return aNSString
end makeNSTextField

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

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

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

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

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

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

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

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

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

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

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

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

★Click Here to Open This Script 

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

指定アプリケーションの指定ロケールのフォルダ内の該当キーワードを含むstringsファイル情報を抽出する

Posted on 11月 13, 2019 by Takaaki Naganoya

Bundle IDで指定したアプリケーションからすべてのLocaleを取得し、ダイアログ選択したLocale内のすべてのstringsファイルを読み込んでNSDictionary化して指定のキーワードを含むものを抽出するAppleScriptです。

指定キーワードが含まれていた場合には、

キー, 値, stringsファイルのパス

をリストで返します。調査のための下調べを行うものです。

AppleScript名:指定アプリケーションの指定ロケールのフォルダ内の該当キーワードを含むstringsファイル情報を抽出する
—
–  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.Finder"
set targWords to "のコピー"

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"}

–Select Localization
set curLang to first item of (choose from list bRes)

–Get All strings file path within a bundle
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

–Get Every Key & Value pair then filter target keyword
set aMDict to NSMutableDictionary’s new()
set hitList to {}
repeat with ii in sList
  set jj to contents of ii
  
set aDict to (NSDictionary’s alloc()’s initWithContentsOfFile:jj)
  (
aMDict’s addEntriesFromDictionary:aDict)
  
  
set kList to aMDict’s allKeys() as list
  
set vList to aMDict’s allValues() as list
  
  
set kCount to 1
  
repeat with i in vList
    set j to contents of i
    
if j contains targWords then
      set the end of hitList to {contents of item kCount of kList, j, jj}
    end if
    
set kCount to kCount + 1
  end repeat
  
end repeat

return hitList
–> {{"PW5_V2", "^0項目のコピーの準備中", "/System/Library/CoreServices/Finder.app/Contents/Resources/Japanese.lproj/Localizable.strings"}, …}

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 File path UTI | Tagged 10.12savvy 10.13savvy 10.14savvy 10.15savvy Finder NSArray NSBundle NSDictionary NSDirectoryEnumerationSkipsHiddenFiles NSDirectoryEnumerationSkipsPackageDescendants NSFileManager NSMutableDictionary NSPredicate NSURL NSURLTypeIdentifierKey NSWorkspace | Leave a comment

指定アプリケーション内の全Localeの指定stringsファイル内の指定キーの値を取得する

Posted on 11月 13, 2019 by Takaaki Naganoya

Bundle IDで指定したアプリケーションのバンドル中(/Contents/Resources/)のすべてのLocalizationに存在する指定のstringsファイル内で、指定キーの値を取得するAppleScriptです。

macOSの日本語環境では、Finder上でコピーしたファイルのファイル名の後方に「のコピー」といった文字列が追記されますが、他のLocaleでどのような文字列が使用されているか調査するために作成したものです。

AppleScript名:指定アプリケーション内の全Localeの指定stringsファイル内の指定キーの値を取得する.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/11/12
—
–  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

set targID to "com.apple.Finder"
set targFile to "Localizable.strings"
set targKey to "N4_V2"
set vList to getAValInASpecifiedStringFileOfAllLocaleInABundle(targID, targFile, targKey) of me
–> {{"he", "עותק של ^=1 ^=0"}, {"en_AU", "^=1 copy ^=0"}, {"ar", "نسخة ^=0 من ^=1"}, {"el", "^=1 αντίγραφο ^=0"}, {"uk", "^=1 копія ^=0"}, {"English", "^=1 copy ^=0"}, {"es_419", "Copia de ^=1 ^=0"}, {"zh_CN", "^=1的副本 ^=0"}, {"Dutch", "^=1 kopie ^=0"}, {"da", "^=1-kopi ^=0"}, {"sk", "^=1 – kópia ^=0"}, {"pt_PT", "^=1 – cópia ^=0"}, {"German", "^=1 Kopie ^=0"}, {"ms", "salinan ^=0 ^=1"}, {"sv", "^=1 (kopia ^=0)"}, {"cs", "^=1 (kopie ^=0)"}, {"ko", "^=1 복사본 ^=0"}, {"no", "^=1-kopi ^=0"}, {"hu", "^=1 másolat ^=0"}, {"zh_HK", "^=1 副本 ^=0"}, {"Spanish", "^=1 copia ^=0"}, {"tr", "^=1 kopyası ^=0"}, {"pl", "^=1-kopia ^=0"}, {"zh_TW", "^=1 拷貝 ^=0"}, {"en_GB", "^=1 copy ^=0"}, {"French", "^=1 copie ^=0"}, {"vi", "Bản sao ^=1 ^=0"}, {"ru", "^=1 — копия ^=0"}, {"fr_CA", "^=1 copie ^=0"}, {"fi", "^=1 kopio ^=0"}, {"id", "Salinan ^=1 ^=0"}, {"th", "^=1 สำเนา ^=0"}, {"pt", "^=1 – cópia ^=0"}, {"ro", "^=1 – copie ^=0"}, {"Japanese", "^=1のコピー^=0"}, {"hr", "^=1 kopija ^=0"}, {"hi", "^=1 कॉपी ^=0"}, {"Italian", "^=1 copia ^=0"}, {"ca", "^=1 còpia ^=0"}}

on getAValInASpecifiedStringFileOfAllLocaleInABundle(targID, targFile, targKey)
  –Get App Path
  
set aPath to retPathFromBundleID(targID) of me
  
  
–Get all Localizations
  
set bRes to getLocalizationsFromBundleID(targID) of me
  
  
set hitList to {}
  
  
–Loop with Localizations in an application bundle
  
repeat with iii in bRes
    set jjj to contents of iii
    
set allPath to aPath & "/Contents/Resources/" & jjj & ".lproj/" & targFile
    
set aDict to (NSDictionary’s alloc()’s initWithContentsOfFile:allPath)
    
if aDict is not equal to missing value then
      set aVal to (aDict’s valueForKeyPath:(targKey))
      
if aVal is not equal to missing value then
        set the end of hitList to {jjj, aVal as string}
      end if
    end if
  end repeat
  
  
return hitList
end getAValInASpecifiedStringFileOfAllLocaleInABundle

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

★Click Here to Open This Script 

Posted in System Text | Tagged 10.12savvy 10.13savvy 10.14savvy 10.15savvy Finder NSArray NSBundle NSDictionary NSFileManager NSMutableDictionary NSPredicate NSURL NSURLTypeIdentifierKey NSWorkspace | Leave a comment

数値に3桁セパレータを付加、外して数値に戻す v2

Posted on 11月 12, 2019 by Takaaki Naganoya

10進数の数字文字列に3桁セパレータを付加、外して数字文字列に戻すAppleScriptです。

めんどくさい上にCocoaに機能があり、かつそれほど大量のデータ処理を行うわけでもない(スピードを要求されない)処理のはずなので、手抜きでCocoaの機能を呼び出しています。

AppleScript名:数値に3桁セパレータを付加、外して数値に戻す v2
— Created 2016-10-12 by Takaaki Naganoya
— 2016 Piyomaru Software
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
–3桁セパレータ文字「,」をNSLocaleのcurrentLocaleから取得するように変更

property NSString : a reference to current application’s NSString
property NSLocale : a reference to current application’s NSLocale
property NSCharacterSet : a reference to current application’s NSCharacterSet
property NSNumberFormatter : a reference to current application’s NSNumberFormatter
property NSLocaleGroupingSeparator : a reference to current application’s NSLocaleGroupingSeparator
property NSNumberFormatterDecimalStyle : a reference to current application’s NSNumberFormatterDecimalStyle

set aNum to 100000000
set aStr to formatNum(aNum) of me
–> "100,000,000"

set bNum to deFromatNumStr(aStr) of me
–>  "100000000"

on formatNum(theNumber as number)
  set theResult to NSNumberFormatter’s localizedStringFromNumber:theNumber numberStyle:(NSNumberFormatterDecimalStyle)
  
return theResult as text
end formatNum

on deFromatNumStrAndRetNumber(theNumericString as string)
  set aThousandSep to NSLocale’s currentLocale()’s objectForKey:(NSLocaleGroupingSeparator)
  
set notWantChars to NSCharacterSet’s characterSetWithCharactersInString:aThousandSep
  
set targStr to NSString’s stringWithString:theNumericString
  
set newStr to (targStr’s componentsSeparatedByCharactersInSet:notWantChars)’s componentsJoinedByString:""
  
return ((newStr as string) as number) –Danger in OS X 10.10 (floating point casting bug)
end deFromatNumStrAndRetNumber

on deFromatNumStr(theNumericString as string)
  set aThousandSep to NSLocale’s currentLocale()’s objectForKey:(NSLocaleGroupingSeparator)
  
set notWantChars to NSCharacterSet’s characterSetWithCharactersInString:aThousandSep
  
set targStr to NSString’s stringWithString:theNumericString
  
set newStr to (targStr’s componentsSeparatedByCharactersInSet:notWantChars)’s componentsJoinedByString:""
  
return (newStr as string)
end deFromatNumStr

★Click Here to Open This Script 

Posted in Number Text | Tagged 10.12savvy 10.13savvy 10.14savvy 10.15savvy NSCharacterSet NSLocale NSLocaleGroupingSeparator NSNumberFormatter NSNumberFormatterDecimalStyle NSString | Leave a comment

10進数とn進数文字列の相互変換

Posted on 11月 12, 2019 by Takaaki Naganoya

10進数の数値とn進数の文字列を相互変換するAppleScriptです。

もともと、AppleScriptの言語仕様上、10進数とn進数文字列との相互変換機能は存在しないのですが、サードパーティから機能拡張書類(OSAX)でそのような機能が提供され、さらにClassic MacOSからMac OS Xへの移行時にそれらの機能拡張書類が使えなくなって(一部は移行)、個別にそれらの機能をスクリプター側で実装してMailing ListやBBS上、Blogなどで共有してきたという経緯があります。

AppleScript Users MLに流れていたもののような気がしますが、自分で作ったものかもしれません。出どころ不明です。

ただ、2進数変換や16進数変換などの各種変換ルーチンが乱立していたところに、「これ、全部1つで済むんじゃね?」と思ってまとめたような気がしないでもありません。自分で作っても簡単なので。

Cocoaの機能を一切使っていません。たしかにCocoaの機能を用いての変換も行えるのですが、データのサイズがとても小さい(桁数が少ない)ので、Cocoaの機能を呼び出さないほうが高速です。

もしも、AppleScriptの予約語のようにこれらの機能を呼び出したい場合には、これらのScriptをAppleScript Librariesにして、AppleScript用語辞書をつけて書き出せば(辞書はなくても大丈夫ですが)、

use nthLib: script "nThConvLib"

のように呼び出すことができるようになっています(macOS 10.9以降)。

AppleScript名:10進数をn進数文字列に変換する
set a to 100

–10進→16進数変換
set b to aNumToNthDecimal(a, 16, 4, {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"}, true) of me
–> "64"

–10進→8進数変換
set c to aNumToNthDecimal(a, 8, 4, {"0", "1", "2", "3", "4", "5", "6", "7"}, true) of me
–> "144"

–10進→2進数変換
set d to aNumToNthDecimal(a, 2, 8, {"0", "1"}, false) of me
–> "01100100"

–10進数をn進数文字列に変換する

–origNum:変換対象の数字
–nTh: n進数のn
–stringLength: 出力指定桁(上位桁のアキはゼロパディングされる)
–zeroSuppress: 上位桁がゼロになった場合に評価を打ち切るかのフラグ、ゼロパディングを行わない(ゼロサプレスする)場合に指定
on aNumToNthDecimal(origNum, nTh, stringLength, stringSetList, zeroSuppress)
  set resString to {}
  
repeat with i from stringLength to 1 by -1
    if {origNum, zeroSuppress} = {0, true} then exit repeat
    
set resNum to (origNum mod nTh)
    
set resText to contents of item (resNum + 1) of stringSetList
    
set resString to resText & resString
    
set origNum to origNum div nTh
  end repeat
  
return (resString as string)
end aNumToNthDecimal

★Click Here to Open This Script 

AppleScript名:n進数文字列を10進数に変換する v2a
–2進数文字列→10進数数値変換
set a to "11"
set b to aNthToDecimal(a, {"0", "1"}) of me
–> 3

–8進数文字列→10進数数値変換
set a to "144"
set c to aNthToDecimal(a, {"0", "1", "2", "3", "4", "5", "6", "7"}) of me
–> 100

–16進数文字列→10進数数値変換
set a to "64"
set b to aNthToDecimal(a, {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"}) of me
–> 100

–n進数文字列を10進数に変換する
on aNthToDecimal(origStr as string, nTh as list)
  set resNumber to 0
  
set sList to reverse of (characters of origStr)
  
set aLen to length of nTh
  
set digitCount to 0
  
  
repeat with i in sList
    set j to contents of i
    
set aRes to (offsetInList(j, nTh) of me)
    
    
set resNumber to resNumber + (aLen ^ digitCount) * (aRes – 1)
    
set digitCount to digitCount + 1
  end repeat
  
  
return resNumber as integer
end aNthToDecimal

–元はCocoaの機能を利用していたが、処理対象のデータが小さいのでOld Style AppleScriptで書き直した
on offsetInList(aChar as string, aList as list)
  set aCount to 1
  
repeat with i in aList
    set j to contents of i
    
if aChar is equal to j then
      return aCount
    end if
    
set aCount to aCount + 1
  end repeat
  
return 0
end offsetInList

★Click Here to Open This Script 

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

Tanzakuの実証実験用バージョン「Tanshio」の配布を開始

Posted on 11月 6, 2019 by Takaaki Naganoya

Tanzakuの実証試験用バージョン「Tanshio」の配布を開始しました。Tanzakuは、Piyomaru Softwareが開発中の自然言語インタフェース系自動処理プログラムの最新シリーズです。

# Tanzakuの派生シリーズや実験プログラムは「Tan-XXX」と命名します。

TanshioはTanzakuで予定している各種機能の縮小版をひととおり実装して、使い勝手を調べたりユーザー環境でうまく動作するかといったことを検証するためのものです。本バージョンには2020/1/31までの動作期限を設けています。

–> Download Tanshio(70KB)

Tanzakuの動作原理は、「ファイル名にユーザーが行いたい内容を記述することで、Tanzakuプログラムがそれを解釈して実行する」というものです(Talking Droplet)。

Tanshioでは、指定アプリケーションのメニュー項目をファイル名に記述することで、その項目をクリックします。

アプリケーション名>メニュー名>メニュー項目名1>メニュー項目名2

のように、階層メニュー名称をファイル名に記述することで、一切のプログラミングなしにメニュー項目の自動クリックを実現するものです。プログラミングを一切行わず、ファイル名を付け替えるだけでメニューのクリックを行い、ファイル名の指定が正しくない場合にはアプリケーション名、メニュー名などをユーザーに問い合わせることで、正しいファイル名を自動フィードバックします。

コマンドをファイル名から取得し、ファイル名のつけかえにより動作を変更し(可塑性のあるプログラム)、いったんコマンドを受理したあとはツールのように振る舞うといったTanzakuの主な特徴を備えています。さらに、入力コマンド(ファイル名)を誤った場合にはユーザーに対して選択肢を提示して正しいコマンドへと誘導する仕様もこのTanshioに実装。実際に使ってみてウザくないかといった確認を行うためのテストベッドです。

動作OSバージョンはmacOS 10.14.6および10.15.xですが、10.14を推奨します。また、システム環境設定の「セキュリティとプライバシー」で、「アクセシビリティ」「オートメーション」などの項目にTanshioを登録する必要があるため、実行・運用にあたってはシステム管理者権限が必要になります。


▲初期状態のTanshio


▲初期状態だとファイル名にアプリケーション名やメニュー項目名が書かれていないため、エラーになる


▲操作アプリケーション選択


▲操作メニュー選択


▲操作メニュー項目選択(コマンドにたどり着くまで繰り返し)


▲Tanshioが自分自身のファイル名を書き換え、正しく、アプリケーション名やメニュー名、メニュー項目名などが記入される。

この状態でTanshioを実行すると、目的のアプリケーションのメニューを操作します。


▲別のアプリケーションや別のメニュー項目をクリックするように変更したい場合にはファイル名を「Tanshio」のような短い名前に付け替えると起動時にアプリケーション選択/メニュー選択を行う

実際に使ってみて

同じメニュー項目をトグルで差し替えるような処理を行っているアプリケーションだと(例:CotEditorの「表示」>「行番号を表示」/「行番号を非表示」)、メニュー項目名をそのまま指定しても、実行2回目になるとメニュー項目が存在していないので、エラーになってアプリケーション選択とメニュー選択のやり直しになるようです。

なーるーほーどー(汗)

Posted in GUI Scripting | Tagged 10.14savvy 10.15savvy | 2 Comments

指定フォルダ以下のすべてのファイルとフォルダ名から絵文字を除去する v2

Posted on 11月 5, 2019 by Takaaki Naganoya

指定フォルダ以下のすべてのファイル名とフォルダ名から絵文字を除去するAppleScriptです。Shane StanleyのremoveEmojiルーチンを使っています。

macOS 10.14.1で絵文字が大幅に追加されたため、これらの絵文字をファイル名に用いていた場合には10.14.1以下のバージョンのOS環境にそのままファイルを持っていくことができません。

 Zipアーカイブ → 展開時にエラー
 DiskImageにコピーするファイルを格納し、古いOSに持って行ってドライブとしてマウントしてファイルコピー → コピーできない(エラー)

という状態になります。絵文字自体に害はないのですが、規格がコロコロ変わる(追加される)ことで、ファイル名に用いるのには問題があるということでしょう。


▲もともとのファイル名、フォルダ名。絵文字を大量に使用している(普段はファイル名に絵文字は使っていません)


▲本Scriptで一括で処理したファイル名、フォルダ名。害のない1️⃣2️⃣3️⃣などの文字だけは残る

実際に作ってみたら、aliasに対するリネームはしょっちゅう行ってきたものの、POSIX pathを用いて指定フォルダ以下すべてをリネームするようなScriptは組んでいなかったので、ちょっと考えさせられました。


▲本Scriptでリネームして、CotEditorのScript PackをmacOS 10.13.6の環境に持っていけました。ただ、絵文字がないと寂しい感じがします

指定フォルダ以下のファイル/フォルダを一括取得するのに、今回はあえてSpotlightを使っていません。ファイルサーバー上のファイル/フォルダを処理する可能性がありそうなのと、外部ライブラリを使わないほうがよいと考え、このような構成になっています。

AppleScript名:指定フォルダ以下のすべてのファイルとフォルダ名から絵文字を除去する v2.scptd
—
—  Created by: Takaaki Naganoya
—  Created on: 2019/11/04
—
—  Copyright © 2019 Piyomaru Software, All Rights Reserved
—

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

property |NSURL| : a reference to current application’s |NSURL|
property NSString : a reference to current application’s NSString
property NSPredicate : a reference to current application’s NSPredicate
property NSFileManager : a reference to current application’s NSFileManager
property NSMutableArray : a reference to current application’s NSMutableArray
property NSRegularExpressionSearch : a reference to current application’s NSRegularExpressionSearch
property NSURLBookmarkResolutionWithoutUI : a reference to current application’s NSURLBookmarkResolutionWithoutUI

set aFol to POSIX path of (choose folder)

set anArray to NSMutableArray’s array()
set erArray to NSMutableArray’s array()
set aPath to NSString’s stringWithString:aFol
set dirEnum to NSFileManager’s defaultManager()’s enumeratorAtPath:aPath

repeat
  set aName to (dirEnum’s nextObject())
  
if aName = missing value then exit repeat
  
set aFullPath to aPath’s stringByAppendingPathComponent:aName
  
  
anArray’s addObject:aFullPath
end repeat

—逆順に(フォルダの深い場所&ファイル名から先に処理)
set revArray to (anArray’s reverseObjectEnumerator()’s allObjects()) as list

—リネーム
repeat with i in revArray
  set j to (NSString’s stringWithString:(contents of i))
  
set curName to j’s lastPathComponent() as string
  
set newName to removeEmoji(curName) of me
  
  
if curName is not equal to newName then
    set fRes to renameFileItem(j as string, newName) of me
    
if fRes = false then
      (erArray’s addObject:{j, newName})
    end if
  end if
end repeat

return erArray as list —リネームできなかったパス(フルパス、リネームするはずだった名称)

—絵文字除去
on removeEmoji(aStr)
  set aNSString to NSString’s stringWithString:aStr
  
return (aNSString’s stringByReplacingOccurrencesOfString:"[\\U0001F600-\\U0001F64F\\U0001F300-\\U0001F5FF\\U0001F680-\\U0001F6FF\\U00002600-\\U000026FF\\U00002700-\\U000027BF\\U0000FE00-\\U0000fE0F\\U0001F900-\\U0001F9FF\\U0001F1E6-\\U0001F1FF\\U00002B50-\\U00002B50\\U0000231A-\\U0000231B\\U00002328-\\U000023FA\\U000024C2-\\U000024C2\\U0001F194-\\U0001F194\\U0001F170-\\U0001F251\\U000025AB-\\U000025FE\\U00003297-\\U00003299\\U00002B55-\\U00002B55\\U00002139-\\U00002139\\U00002B1B-\\U00002B1C\\U000025AA-\\U000025AA\\U0001F004-\\U0001F004\\U0001F0CF-\\U0001F0CF]" withString:"" options:(NSRegularExpressionSearch) range:{0, aNSString’s |length|()}) as text
end removeEmoji

—ファイル/フォルダのリネーム
on renameFileItem(aPOSIXPath, newName)
  set theNSFileManager to NSFileManager’s defaultManager()
  
set POSIXPathNSString to NSString’s stringWithString:(aPOSIXPath)
  
  
–Make New File Path
  
set anExtension to POSIXPathNSString’s pathExtension()
  
set newPath to (POSIXPathNSString’s stringByDeletingLastPathComponent()’s stringByAppendingPathComponent:newName) –’s stringByAppendingPathExtension:anExtension
  
  
–Rename
  
if theNSFileManager’s fileExistsAtPath:newPath then
    return true
  else
    set theResult to theNSFileManager’s moveItemAtPath:POSIXPathNSString toPath:newPath |error|:(missing value)
    
if (theResult as integer = 1) then
      return (newPath as string)
    else
      return false
    end if
  end if
end renameFileItem

★Click Here to Open This Script 

Posted in file File path regexp Text | Tagged 10.14savvy 10.15savvy NSFileManager NSMutableArray NSPredicate NSRegularExpressionSearch NSString NSURL | Leave a comment

文字列から絵文字を削除

Posted on 11月 4, 2019 by Takaaki Naganoya

Shane Stanleyから投稿してもらった(いただいた)実用レベルの絵文字削除ルーチンです。

いろんな方面からツッコミが入って、徐々に実用レベルに到達するのではないかと予想していた絵文字削除ルーチン、いきなり最終兵器的なルーチンの登場により、「これでいいでしょ?」と思えるレベルに到達しました。

AppleScript名:remove emoji v0
—
—  Created by: Shane Stanley
—  Created on: 2019/11/04
—
use AppleScript version "2.7" — High Sierra (10.13) or later
use framework "Foundation"
use scripting additions

removeEmoji("2203)🔄❎⚙️🇯🇵簡易日本語形態素解析📚してそれっぽく❌伏せ字に(□に置き換え).scptd") of me
–> "2203)簡易日本語形態素解析してそれっぽく伏せ字に(□に置き換え).scptd"

on removeEmoji(aStr)
  set aNSString to current application’s NSString’s stringWithString:aStr
  
— Emoticons, Misc Symbols and Pictographs, Transport and Map, Misc symbols, Dingbats, Variation Selectors, Supplemental Symbols and Pictographs, Flags
  
return (aNSString’s stringByReplacingOccurrencesOfString:"[\\U0001F600-\\U0001F64F\\U0001F300-\\U0001F5FF\\U0001F680-\\U0001F6FF\\U00002600-\\U000026FF\\U00002700-\\U000027BF\\U0000FE00-\\U0000fE0F\\U0001F900-\\U0001F9FF\\U0001F1E6-\\U0001F1FF]" withString:"" options:(current application’s NSRegularExpressionSearch) range:{0, aNSString’s |length|()}) as text
end removeEmoji

★Click Here to Open This Script 

ただ、そこは一応「すべての絵文字」を入力して試しておく必要を感じるところ。手作業でぽちぽちキーボードから(絵文字バレットから)絵文字を入力しまくって本ルーチンで処理してみたところ、どうも文字コード上の「飛び地」にあるとおぼしき絵文字が消えません。

なので、削除テーブル部分に「消えなかった絵文字のコード」をこれでもかと追加しまくり、削除対象文字テーブルを強化してみました。一部、対象文字よりもひろめに削除範囲が指定されている箇所もありますが、本ルーチンは主にファイル名に対して使用された絵文字を除去してファイルの後方互換性を確保すること(最新のOSよりも古いバージョンのOSとファイルを安全に交換すること)が目的なので、そんなマイナー記号類が削除されても気にしないことにします。

すべての絵文字が削除されたわけではないといいますか、絵文字っぽい文字でなくなっただけで残っていたりもするのですが、今度はこれらの文字を消すと実害もありそうなので、現状ではこのぐらいでよいかと思われます。

もちろん、すぐにCotEditorのメニューに突っ込んで、選択範囲の絵文字を削除できるようにしておきました。

AppleScript名:remove emoji.scptd
—
—  Created by: Shane Stanley
—  Created on: 2019/11/04
—  Modified by: Takaaki Naganoya (Emoji Table Data)

use AppleScript version "2.7" — High Sierra (10.13) or later
use framework "Foundation"
use scripting additions

set allEmoji to "☺️☹️☠️✌️☝️🖐✍️1️⃣2️⃣3️⃣⚙️😀😃😄😁😆😅😂🤣☺️😊😇🙂🙃😉😌😍🥰😘😗😙😚😋😛😝😜🤪🤨🧐🤓😎🤩🥳😏😒😞😔😟😕🙁☹️😣😖😫😩🥺😢😭😤😡🤬🤯😳🥵🥶😱😨😨😰😥😓🤗🤔🤭🤫🤥😶😐😑😬🙄😯😦😧😮😲😴🤤😪😵🤐🥴🤢🤮🤧😷🤒🤕🤑🤠😈👿👹👺🤡💩👻💀☠️👽👾🤖🎃😺😸😹😻😼😽🙀😿😾🤲👐🙌👏🤝👍👎👊✊🤛🤜🤞✌️🤟🤘👌👈👉👆👇☝️✋🤚🖐🖖👋🤙💪🖕✍️🙏🦶🦵🐶🐱🐭🐰🦊🐻🐼🐨🐯🦁🐮🐷🐽🐸🐵🙈🙉🙊🐒🐔🐧🐦🐤🐣🐥🦆🦅🦉🦇🐗🐴🦄🐝🐛🦋🐌🐞🐜🦟🦗🕷🕸🦂🐍🦎🦖🐙🦑🦐🦞🦀🐡🐟🐬🐳🦈🐊🐅🐆🦓🦍🐘🦛🦏🐪🐫🦘🐃🐂🐄🐎🐏🐑🦙🐐🦌🐕🐩🐈🐓🦃🦚🦜🦢🕊🐇🦝🦡🐁🐀🐿🐲🌵🎄🌲🌳🌴🌱🌿🍀🍃🍂🍁🍄🌾🌹🥀🌺🌼🌻🌚🌕🌖🌗🌘🌒🌎💫⭐️🌟⚡️☄️💥🔥🌪🌈🌤⛅️🌥☁️🌦🌧⛈🌩❄️☃️🌬💨💧💦☔️🌫🍏🍎🍐🍊🍋🍌🍇🍓🍈🍒🍑🍍🥥🥝🍅🍆🥑🌶🌽🥕🥔🍠🥐🥯🍞🥖🥨🧀🥚🍳🥞🥓🥩🍗🍖🦴🦴🌭🍕🥪🥙🌮🌯🥗🥘🥫🍝🍜🍛🍣🍱🍤🍙🍚🍘🍥🥠🥮🍢🍦🍰🎂🍭🍬🍫🍿🍩🍪🌰🥜🍯🥛🍼☕️🍵🥤🍶🍺🍻🥂🍷🥃🍸🍹🍾🥄🍴🍽🥣🥡🥢🧂🏀⚾️🥎🎾🏐🏉🥏🎱🏓🏸🏒🏏⛳️🏹🎣🥊🥋🎽🛹🛷⛸🥌🎿⛷🏂🏋️‍♂️🤼‍♀️🤼‍♂️🤺🤾‍♀️🤾‍♂️🏌️‍♀️🏌️‍♂️🏇🧘‍♀️🧘‍♂️🏄‍♀️🏄‍♂️🏊‍♀️🏊‍♂️🤽‍♀️🤽‍♂️🚣‍♀️🚣‍♂️🧗‍♀️🧗‍♂️🚵‍♀️🚵‍♂️🚴‍♀️🚴‍♂️🏆🥇🥈🥉🏅🎖🏵🎗🎫🎟🎪🤹‍♀️🤹‍♂️🎭🎨🎬🎤🎧🎼🎹🥁🎷🎺🎸🎻🎲♟🎯🎳🎮🎰🧩🚗🚙🚌🚎🏎🚓🚑🚒🚐🚛🚜🛴🚲🏍🚨🚔🚍🚘🚖🚡🚠🚟🚃🚋🚞🚝🚄🚅🚈🚂🚆🚇🚊✈️🛫🛬🛩💺🛰🚀🛸🚁🛶⛵️🚤🛳⛴🚢⚓️⛽️🚧🚦🚥🚏🗺🗿🗽🗼🏰🏯🏟🎡🎢🎠⛲️⛱🏖🏝🏜🌋⛰🏔🗻🏕🏠🏡🏘🏚🏗🏭🏢🏬🏣🏤🏥🏦🏨🏪🏫🏩💒🏛⛪️🕌🕍🕋⛩🛤🗾🎑🏞🌅🌄🌠🎇🎆🌇🌆🏙🌃🌌🌉🌁⌚️📱📲💻⌨️🖥🖨🖱🖲🕹🗜💽💾💿📀📼📷📸📹🎥📽🎞📞☎️📟📠📺📻🎙🎚🎛🧭⏱⏲⏰🕰⌛️⏳📡🔋🔌💡🔦🕯🧯🛢💸💵💴💰💳💎⚖️🧰🔧🔨⚒🛠⛏🔩🧱⛓🧲💣🧨🔪🗡⚔️🛡🚬⚰️⚱️🏺🔮📿🧿💈🔭🔬🕳💊💉🧬🦠🧫🧪🌡🧹🧺🧻🚽🚰🚿🛁🛀🧼🧽🧴🛎🔑🗝🚪🛋🛌🧸🖼🛒🎁🎈🎏🎀🎊🎉🎎🏮🎐✉️📩📨📧💌📥📤📦🏷📪📫📬📭📮📯📜📃📄📑🧾📊📈📉🗒🗓📆📅🗑📇🗳🗄📋📁📂🗂🗞📰📓📔📒📕📗📘📙📚📖🔖🧷🔗📎🖇📐📏🧮📌📍✂️🖊🖋✒️🖌🖍📝✏️🔍🔎🔏🔐🔒🔓🔓❤️🧡💛💚💙💜🖤💔❣️💕💞💗💖💘💝💟☮️✝️☪️🕉☸️✡️🔯🕎☯️☦️🛐⛎♈️♉️♊️♋️♌️♍️♎️♏️♐️♑️♒️♓️🆔⚛️🉑☣️📴📳🈶🈚️🈸🈺🈷️✴️🆚💮🉐㊙️㊗️🈴🈵🈲🅰️🅱️🆎🆑🅾️🆘❌⭕️🛑⛔️📛🚫💯💢♨️🚷🚯🚱🔞📵🚭❗️❕❓❓❔‼️⁉️🔅🔆〽️⚠️🚸🔱⚜️🔰✅🈯️💹❇️✳️❎🌐💠Ⓜ️🌀💤🏧♿️🅿️🈳🈂️🛂🛃🛄🛅🚹🚺🚼🚻🚮🎦📶🈁🔣ℹ️🔤🔡🔠🆖🆗🆙🆙🆒🆕🆓0️⃣1️⃣2️⃣3️⃣4️⃣5️⃣6️⃣7️⃣8️⃣9️⃣🔟🔢#️⃣*️⃣▶️⏸⏯⏹⏺⏭⏮⏩⏪⏫⏬🔼🔽⬅️⬇️↘️↖️↕️↙️↗️⬆️➡️◀️⏏️↪️↩️↔️⤵️🔀🔁🔄🔃⤵️⤴️🎵🎶➕➖➗♾💲💱©️👁‍🗨🔚🔙🔛🔝🔜➰➿➿☑️🔘🔴🔵🔺🔻🔸🔹🔶🔷🔳🔲▫️◽️◻️⬜️🔈🔇🔉🔊🔔🔔🔔🔕📣📢💬💭🗯♣️♦️🃏🎴🕐🕑🕒🕓🕔🕕🕖🕗🕘🕙🕚🕛🕜🕝🕞🕟🕠🕡🕢🕣🕤🕥🕥🕦🕧🀄️♥️♠️⬛️◼️◾️▪️⚪️✔️〰️®️™️✖️⭐️🏴🏁🏴‍☠️🏳️🚩🏳️‍🌈🇺🇳🇮🇸🇮🇪🇦🇿🇦🇫🇺🇸🇦🇪🇩🇿🇦🇷🇦🇼🇦🇱🇦🇲🇦🇮🇦🇴🇦🇬🇦🇩🇾🇪🇬🇧🏴󠁧󠁢󠁳󠁣󠁴󠁿🏴󠁧󠁢󠁷󠁬󠁳󠁿🇮🇱🇮🇹🇮🇶🇮🇷🇮🇳🇮🇩🇼🇫🇺🇬🇺🇦🇺🇿🇺🇾🇪🇨🇪🇬🇪🇪🇪🇹🇪🇷🇸🇻🇦🇺🇦🇹🇦🇽🇴🇲🇳🇱🇧🇶🇬🇭🇨🇻🇬🇬🇬🇾🇰🇿🇶🇦🇨🇦🇮🇨🇬🇦🇨🇲🇬🇲🇰🇭🇬🇳🇬🇼🇨🇾🇨🇺🇨🇺🇨🇼🇬🇷🇰🇮🇰🇬🇬🇹🇬🇵🇬🇺🇰🇼🇨🇰🇬🇱🇨🇽🇬🇩🇭🇷🇰🇾🇰🇪🇨🇮🇨🇨🇨🇨🇨🇷🇽🇰🇰🇲🇨🇴🇨🇬🇨🇩🇸🇦🇬🇸🇼🇸🇧🇱🇸🇹🇿🇲🇵🇲🇸🇲🇸🇱🇩🇯🇬🇮🇯🇪🇯🇲🇬🇪🇸🇾🇸🇬🇸🇽🇿🇼🇨🇭🇸🇪🇸🇩🇪🇸🇸🇷🇱🇰🇸🇰🇸🇮🇸🇿🇸🇨🇸🇳🇷🇸🇰🇳🇻🇨🇸🇭🇸🇴🇸🇧🇹🇨🇹🇭🇹🇯🇹🇿🇨🇿🇹🇩🇹🇳🇨🇱🇹🇻🇩🇰🇩🇪🇹🇬🇹🇰🇩🇴🇩🇲🇹🇹🇹🇲🇹🇷🇹🇴🇳🇬🇳🇷🇳🇦🇳🇺🇳🇮🇳🇮🇳🇪🇳🇨🇳🇿🇳🇵🇳🇫🇳🇫🇳🇴🇧🇭🇭🇹🇵🇰🇻🇦🇵🇦🇻🇺🇧🇸🇵🇬🇧🇲🇵🇼🇵🇾🇧🇧🇭🇺🇧🇩🇵🇳🇫🇯🇵🇭🇫🇮🇧🇹🇵🇷🇫🇴🇫🇰🇧🇷🇫🇷🇧🇬🇧🇫🇧🇳🇧🇮🇻🇳🇧🇯🇻🇪🇧🇾🇧🇿🇵🇪🇧🇪🇵🇱🇧🇦🇧🇼🇧🇴🇵🇹🇭🇳🇲🇭🇲🇴🇲🇰🇲🇬🇾🇹🇲🇼🇲🇱🇲🇹🇲🇶🇲🇾🇮🇲🇫🇲🇲🇲🇲🇽🇲🇺🇲🇷🇲🇿🇲🇨🇲🇻🇲🇩🇲🇦🇲🇳🇲🇪🇲🇸🇯🇴🇱🇦🇱🇻🇱🇹🇱🇾🇱🇮🇱🇷🇷🇴🇱🇺🇷🇼🇱🇸🇱🇧🇷🇪🇷🇺🇮🇴🇻🇬🇰🇷🇪🇺🇰🇷🇭🇰🇪🇭🇬🇶🇨🇫🇨🇳🇹🇱🇿🇦🇸🇸🇦🇶🇯🇵🎌🇬🇫🇵🇫🇹🇫🇻🇮🇦🇸🇲🇵🇰🇵"
removeEmoji(allEmoji) of me
–> "1⃣2⃣3⃣‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‼⁉〽0⃣1⃣2⃣3⃣4⃣5⃣6⃣7⃣8⃣9⃣#⃣*⃣⬅⬇↘↖↕↙↗⬆↪↩↔⤵⤵⤴©‍〰®™‍‍󠁧󠁢󠁳󠁣󠁴󠁿󠁧󠁢󠁷󠁬󠁳󠁿"

on removeEmoji(aStr)
  set aNSString to current application’s NSString’s stringWithString:aStr
  
  
— Emoticons, Misc Symbols and Pictographs, Transport and Map, Misc symbols, Dingbats, Variation Selectors, Supplemental Symbols and Pictographs, Flags
  
return (aNSString’s stringByReplacingOccurrencesOfString:"[\\U0001F600-\\U0001F64F\\U0001F300-\\U0001F5FF\\U0001F680-\\U0001F6FF\\U00002600-\\U000026FF\\U00002700-\\U000027BF\\U0000FE00-\\U0000fE0F\\U0001F900-\\U0001F9FF\\U0001F1E6-\\U0001F1FF\\U00002B50-\\U00002B50\\U0000231A-\\U0000231B\\U00002328-\\U000023FA\\U000024C2-\\U000024C2\\U0001F194-\\U0001F194\\U0001F170-\\U0001F251\\U000025AB-\\U000025FE\\U00003297-\\U00003299\\U00002B55-\\U00002B55\\U00002139-\\U00002139\\U00002B1B-\\U00002B1C\\U000025AA-\\U000025AA\\U0001F004-\\U0001F004\\U0001F0CF-\\U0001F0CF]" withString:"" options:(current application’s NSRegularExpressionSearch) range:{0, aNSString’s |length|()}) as text
end removeEmoji

★Click Here to Open This Script 

Posted in regexp Text | Tagged 10.14savvy 10.15savvy NSRegularExpressionSearch NSString | 2 Comments

文字列から絵文字のみ削除するじっけん

Posted on 11月 3, 2019 by Takaaki Naganoya

文字列から絵文字だけを削除する実験です(まだ、完全にはうまく削除しきれていないので)。

→ きちんと動くバージョン 文字列から絵文字を削除

CotEditorのScript PackをmacOS 10.13環境にインストールしようとして、Zipアーカイブが展開できないとか、ファイル名に絵文字が入っているためにファイルコピー自体が行えないという現象に直面しました。

macOS 10.14.1で絵文字が70個ほど追加になったという記録があるので、

macOS Mojave 10.14.1
アップデートこのアップデートの内容は以下の通りです。グループ FaceTime のビデオ通話とオーディオ通話に対応しました。最大 32 人の参加者が同時に通話することができ、会話の内容はエンドツーエンドで暗号化されるため、プライバシーも守られます。グループ FaceTime は、メッセージ App のグループチャットから始めることができ、通話に途中から参加することもできます。赤毛、白髪、巻き毛の新しいキャラクター、スキンヘッドの新しい絵文字、より感情豊かな笑顔のほか、動物、スポーツ、食べ物を表す絵文字など、70 種類以上の絵文字が新たに追加されました。

これらの絵文字ファイル名に用いたファイルをmacOS 10.14.1以降のOS上で作成し、それ以前のバージョンのOSに持って行こうとするとトラブルが発生するのは当然のことでしょう。

ファイル名が原因であることは明らかなので(ふだんはScriptのファイル名に絵文字を使うことはありません)、自動で指定フォルダ以下の書類やフォルダをすべてスキャンして絵文字キャラクターを削除するという処理を書こうとして、その前段階として指定文字列中の絵文字を削除するAppleScriptを書いてみました。

いい感じに削除できていると思えば、削除できない文字もあったりで、まだ完全ではない印象です。p{Emoji_Presentation}で検出しているのですが、検出できない絵文字があるようで、、、、

もともと、NSString上で完結するように処理しようと試みていたものの、matchesInStringで絵文字を検出したあとの消し込みにてこずって、「じゃあ、1文字ずつ分解してチェックルーチンを通せばいいや」と、トーンダウンした経緯があります。

特定の絵文字だけ検出できないというのは納得できません。本Scriptはまだ実戦配備できないレベルだと思います。

下手をすると、全絵文字の全パターンを配列(リスト)に入れておいて、存在確認を行うことになるのかも?

AppleScript名:テキストから絵文字抽出(複数)して削除.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/11/03
—
–  Copyright © 2019 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use scripting additions

set a1Str to "where’s 😎the 😎😎emoji 😎?"
set b1Str to removeEmoji(a1Str) of me
–> "where’s the emoji ?"

set a2Str to "2200)🔄❎すべて❌伏せ字に(□に置き換え)"
set b2Str to removeEmoji(a2Str) of me
–> "2200)すべて伏せ字に(□に置き換え)"

set a3Str to "2251)1️⃣2️⃣3️⃣昇順(1–>9)で連番を振る"
set b3Str to removeEmoji(a3Str) of me
–> "2251)1️⃣2️⃣3️⃣昇順(1–>9)で連番を振る"

set a4Str to "2203)🔄❎⚙️🇯🇵簡易日本語形態素解析📚してそれっぽく❌伏せ字に(□に置き換え).scptd"
set b4Str to removeEmoji(a4Str) of me
–> "2203)⚙️簡易日本語形態素解析してそれっぽく伏せ字に(□に置き換え).scptd"

set emojiStr to "😀😃😄😁😆😅😂🤣☺️😊😇🙂🙃😉😌😍🥰😘😗😙😚😋😛😝😜🤪🤨🧐🤓😎🤩🥳😏😒😞😔😟😕🙁☹️😣😖😫😩🥺😢😭😤😡🤬🤯😳🥵🥶😱😨😨😰😥😓🤗🤔🤭🤫🤥😶😐😑😬🙄😯😦😧😮😲😴🤤😪😵🤐🥴🤢🤮🤧😷🤒🤕🤑🤠😈👿👹👺🤡💩👻💀☠️👽👾🤖🎃😺😸😹😻😼😽🙀😿😾🤲👐🙌👏🤝👍👎👊✊🤛🤜🤞✌️🤟🤘👌👈👉👆👇☝️✋🤚🖐🖖👋🤙💪🖕✍️🙏🦶🦵"
set eRes to removeEmoji(emojiStr) of me
–> "☺️☹️☠️✌️☝️🖐✍️"

set emojiStr to "☺️☹️☠️✌️☝️🖐✍️1️⃣2️⃣3️⃣⚙️"
set eRes to removeEmoji(emojiStr) of me
–> "☺️☹️☠️✌️☝️🖐✍️1️⃣2️⃣3️⃣⚙️"

on removeEmoji(aStr)
  script spdC
    property outList : {}
    
property cList : {}
  end script
  
  
set (cList of spdC) to characters of aStr
  
log (cList of spdC)
  
set (outList of spdC) to {}
  
  
repeat with i in (cList of spdC)
    set j to contents of i
    
set eRes to chkEmoji(j) of me
    
if eRes = false then
      set the end of (outList of spdC) to j
    end if
  end repeat
  
return retDelimedText((outList of spdC), "") of me
end removeEmoji

on chkEmoji(aStr)
  set aNSString to current application’s NSString’s stringWithString:aStr
  
set aReg to current application’s NSRegularExpression’s regularExpressionWithPattern:"\\p{Emoji_Presentation}" options:0 |error|:(missing value)
  
set cResList to (aReg’s matchesInString:(aNSString) options:0 range:(current application’s NSMakeRange(0, aNSString’s |length|()))) as list
  
if length of cResList = 0 then return false –指定文字列に絵文字が入っていない場合
  
return true –指定文字列に絵文字が入っている場合
end chkEmoji

on retDelimedText(aList, aDelim)
  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 Text | Tagged 10.14savvy 10.15savvy NSMakeRange NSRegularExpression NSString | Leave a comment

CotEditorのScript集、PowerPack & Basic Packをv2.0にアップデート

Posted on 10月 27, 2019 by Takaaki Naganoya

CotEditorの関連ScriptをまとめたScript Pack v2.0の配布を開始しました。無償、無保証、サポートなしで提供しています。CotEditor 3.8+macOS 10.14/10.15にて検証を行っています。

–> Download Page

基礎的なサンプルScriptの「Basic Pack」、強力なユーティリティScriptの「PowerPack」から構成され、今回アップデートしたのはPowerPackです。

PowerPackはCotEditorのScript Folder(~/Library/Application Scripts/com.coteditor.CotEditor)に入れればCotEditorのScript Menuに表示され、実行できるようになります。

Script Menuから実行すると、メニューバーにScript実行中のインジケーターが表示されます。

途中で停止したい場合には、⚙アイコンをクリックして表示されるメニューの×印ボタンをクリックすると、

実行がキャンセルされます。

さらに強化されたツールScript群:PowerPack

CotEditorのスクリプトメニューにインストールして使うためのScript群です。最大のアップデート内容は、メニュー内容の増加で見にくかった箇所を整理した点です。メニューにセパレータを入れて、おおまかな区分けを整理しています。v1.2で新規追加のScriptをわかりやすくしようと試みていましたが、メニュー内容が見にくくなったので廃止しました。


▲バージョンアップしてだんだんメニューが整理されてきました

アップデートしたものをご紹介いたします。

カウントレポート

「👀🔭🧼選択中のテキストの文字の種別ごとの構成比」を追加しました。長い文章の文字種判定を実行すると時間がかかるので、選択範囲のみ判定できるようにしたものです

🍎📜AppleScriptとして解釈


「📜AppleScript書類を読み込み、📄新規書類に展開」バンドル形式ではないAppleScript書類のソースコードを、CotEditorの新規書類に読み込みます
「📜🧼選択範囲をapplescript schemeの🌐URLに💙encodeして📄新規書類に展開」CotEditor上で編集中のAppleScriptの選択範囲をURLエンコードして、CotEditor新規書類に展開します

🧼🧼選択範囲を処理


「1️⃣2️⃣3️⃣行頭に番号を振る」選択中の行の先頭に連番を振ります
「🔄❎すべて❌伏せ字に」選択範囲の文字をすべて伏せ字にします
「🔄❎⚙️🇯🇵簡易日本語形態素解析📚してそれっぽく❌伏せ字に」選択範囲の日本語テキストを簡易形態素解析してそれっぽく伏せ字にします
「🔄❎⚙️🇬🇧英語簡易形態素解析📚してそれっぽく❌伏せ字に」同じく、選択範囲の英語のテキストをパースしてそれっぽく伏せ字にします(前置詞やbe動詞などを残してあとは伏せ字に)。まだ仕上がりがいまひとつです
「🔄✴️行頭にナカグロ(・)を入れる(箇条書き時の整形)」選択範囲の行頭にナカグロ(・)を入れます
「🔄✴️行頭のナカグロ(・)を削除する」行頭のナカグロ文字だけ削除します
「🔜⬇️行単位ソート(A→Z)」選択範囲の行を行単位で昇順ソートします
「🔙⬆️行単位ソート(Z→A)」選択範囲の行を行単位で逆順ソートします
「🔜🔃行単位で逆順に」選択範囲の行を行単位で現在と逆順に入れ替えます
「🔜🏞プロポーショナルフォントで🖥画面表示したピクセル数で行ソート」プロポーショナルフォントをオフスクリーン描画して、描画幅をもとにソートします
「🔄🎉行単位でランダム・シャッフル」行単位でシャッフルします

🈳青空文庫


「🈂️サンプル文章をオープン」同梱のサンプル文章「坊ちゃん」「こころ」「我輩は猫である」のうちのいずれかのテキストをオープンします

📝PDFから情報読み込み


「📝全ページの本文テキストを📗読み込む」指定のPDF本文テキストを新規書類に読み込みます
「📝指定ページの本文テキストを📗読み込む」指定のPDFの指定ページの本文テキストを新規書類に読み込みます
「🧾TOC(Table Of Contents)📗読み込み」指定のPDFのTOCテキストを新規書類に読み込みます
「🔗全ページの🌏URLリンクをまとめて📗新規書類に読み込む(http、https)」指定のPDFのURLリンクのうちプロトコルがhttp、httpsのURLを新規書類に読み込みます
「🔗全ページの🌏URLリンクをまとめて📗新規書類に読み込む(mailto)」指定のPDFのURLリンクのうちプロトコルがmailtoのURLを新規書類に読み込みます
「🔗全ページの🌏URLリンクをデコードして、それぞれ📗📗個別の📗📗新規書類に読み込む(applescript)」指定のPDFのURLリンクのうちプロトコルがapplescriptのURLをデコードして個別の新規書類に読み込みます
「🔗全ページの🌏URLリンクをデコードして、🧼選択語句を含むものをそれぞれ📗📗個別の📗📗新規書類に読み込む(applescript)」指定のPDFのURLリンクのうちプロトコルがapplescriptで、デコード内容にCotEditor上で選択中の語句を含むものを個別の新規書類に読み込みます

🎹iTunesまたはMusic


「🎹🖍現在の音楽トラックに歌詞として書き込む」CotEditorで選択範囲のテキストを、iTunes/Music上で選択中の音楽トラックの歌詞として書き込みます
「🎹👀現在の音楽トラックの歌詞を📗新規書類に読み込む」、iTunes/Music上で選択中の音楽トラックの歌詞をCotEditorの新規書類に読み込みます

🎲QRコード


「🎲💔QRコード画像をdecodeして📗新規書類に読み込み」QRコード画像をデコードして、CotEditorの新規書類に読み込みます
「🎲💙選択範囲をQRコードにencodeして🎆画像出力」CotEditor上で選択中のテキストをQRコードにエンコードしてデスクトップに画像出力します

🌇画像取り込み


「🔌💙base64 encodeして📃新規書類に読み込み」指定画像をbase64エンコードして新規書類に読み込みます
「)🔌💙base64 encodeして🏷img srcタグ🏷つきで📗新規書類に読み込み」指定画像をbase64エンコードして新規書類にimg srcタグつきで新規書類に読み込みます

📄⚙️ファイルの情報読み込み


「📄⚙️指定ファイルの🛍メタデータを📗新規書類に読み込み」指定ファイルのメタデータを新規書類に読み込みます

macOS 10.13上ではインストールできません

macOS 10.13上では配布中のZipファイルの展開時にエラーが出ることを確認していますが、macOS 10.13自体がバグの塊のようなバージョンなので、対処できるのかどうか、、、
–> DiskImageに入れて圧縮してみましたが、macOS 10.13上ではマウントしたDiskImageからのコピー時にエラーが出て(ファイル名をすべて変更しないと)コピー自体ができないようです

Posted in System | Tagged 10.14savvy 10.15savvy CotEditor | 2 Comments

指定画像をbase64エンコード文字列に変換

Posted on 10月 27, 2019 by Takaaki Naganoya

指定画像をbase64エンコーディング文字列に変換するAppleScriptです。

用途は、sdef(AppleScript用語辞書)に画像を突っ込む(ためのデータを作る)こと。それだけです。

ただ、あまりにでかい画像をbase64文字化して取得すると、スクリプトエディタが結果を表示したときに不安定になったり処理が返ってこなくなったりするので、文字列を取得する前にデータサイズを計算し、リサイズしてから文字列化するとか、他の形式(GIFなど)を用いてエンコードするなどのケアが必要になります。ねんのため。

元画像が何であっても、NSImageに読み込める画像なら(OSでサポートしている画像なら)読み込んで、PNG形式に変換したのちにBase64エンコード文字列に変換しています。


▲エンコードするにしても数10KBとかそのぐらいのファイルサイズの画像にしておかないと後がつらい


▲4K解像度の画像をbase64エンコードするとこんなに結果が巨大に

AppleScript名:指定画像をbase64エンコード文字列に変換.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/10/25
—
–  Copyright © 2019 Piyomaru Software, All Rights Reserved
—
property NSString : a reference to current application’s NSString
property NSImage : a reference to current application’s NSImage
property NSPNGFileType : a reference to current application’s NSPNGFileType
property NSBitmapImageRep : a reference to current application’s NSBitmapImageRep
property NSUTF8StringEncoding : a reference to current application’s NSUTF8StringEncoding
property NSDataBase64EncodingEndLineWithLineFeed : a reference to current application’s NSDataBase64EncodingEndLineWithLineFeed

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

set aFile to choose file of type {"public.image"}
set aStr to base64StringFromImageFile(aFile) of me

–Base64 Encode
on base64StringFromImageFile(aFile)
  set aPOSIX to POSIX path of aFile
  
set anImage to NSImage’s alloc()’s initWithContentsOfFile:aPOSIX
  
set imageRep to NSBitmapImageRep’s alloc()’s initWithData:(anImage’s TIFFRepresentation())
  
set aPNGdat to imageRep’s representationUsingType:(NSPNGFileType) |properties|:(missing value)
  
set base64Str to aPNGdat’s base64EncodedDataWithOptions:(NSDataBase64EncodingEndLineWithLineFeed)
  
set bStr to (NSString’s alloc()’s initWithData:base64Str encoding:(NSUTF8StringEncoding))
  
return bStr as string –or return NSString (delete as string) for speedy processing
end base64StringFromImageFile

★Click Here to Open This Script 

Posted in Image Text | Tagged 10.12savvy 10.13savvy 10.14savvy 10.15savvy NSBitmapImageRep NSDataBase64EncodingEndLineWithLineFeed NSImage NSPNGFileType NSString NSUTF8StringEncoding | Leave a comment

Pages書類の1ページ目の表の背景色を置換 v5

Posted on 10月 25, 2019 by Takaaki Naganoya

Pagesでオープン中の最前面の書類の1ページ目に存在する表オブジェクト中の背景色を置換するAppleScriptです。カラー選択のポップアップメニューUser Interfaceをpickup colorライブラリに分離したため、実行できる環境が増えました(Script Debugger上でも動くようになりました)。

–> Download Code-signed AppleScript applet with sample Pages data

Pages書類の「表オブジェクト」にAppleScriptからアクセスするためには、Pages上で表オブジェクトを選択した状態で、

「オブジェクトの配置」を「移動しない」に事前に設定しておく必要があります。

本AppleScriptを実行可能なランタイム環境は、スクリプトエディタ、アプレットの2つです。スクリプトメニューおよびScript Debuggerでは各GUI部品のクリックイベントを拾えないために、実行しても選択などが行えません。

のように、1ページのみのPages書類に表オブジェクトを入れて、「移動しない」設定にしてある状態で本AppleScriptを実行。

表のセル中の色をすべて取得して、ユニーク化してポップアップメニューから「変更元」の色を選択できます。

選択して、「OK」ボタンをクリック。ここで選択した色が置換されます。

選択した色をどの色に変更(置換)するのかを指定します。

グレーを選択。

AppleScript名:Pages書類の1ページ目の表の背景色を置換 v5
— Created 2017-07-15 by Takaaki Naganoya
— Modified 2019-10-25 by Takaaki Naganoya
— 2019 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"
use Bplus : script "BridgePlus" –https://www.macosxautomation.com/applescript/apps/BridgePlus.html
use pickLib : script "pickup color" –http://piyocast.com/as/asinyaye

–v1:First Version
–v2:Pick Up target cells by calculate every background color (35% speed up)
–v3:Draw cells by range (x20 speed up)
–v3.1:Bug Fix (retRangeFromPosList)
–v3.1.1:Bug Fix (retRangeFromPosList)
–v4:Two-way Simulation (Horizontal / Vertical scan), Corner-Rounded NSImage, Dynamic Color Naming
–v4.1:Correct Vertical Scan simulation (Sort list for vertical range evaluation, at first)
–v5: Use "pickup color" library, Auto color name suggestion function was removed

property NSArray : a reference to current application’s NSArray
property SMSForder : a reference to current application’s SMSForder

–初期化
load framework

–Pagesの1ページ目にある表の塗り色を取得
tell application "Pages"
  if (count of (every document)) = 0 then return
  
  
tell front document
    if (count of (every table)) = 0 then return
    
    
tell table 1
      set c1List to background color of every cell
      
set aProp to properties
      
set xCount to column count of aProp
    end tell
  end tell
end tell

–色データをユニーク化(重複削除)
set bList to uniquifyList(c1List) of me

–Convert 1D List to 2D List
set c3List to (SMSForder’s subarraysFrom:c1List groupedBy:xCount |error|:(missing value)) as list

–missing value(背景色なし)を除外する
set c2List to (SMSForder’s arrayByDeletingBlanksIn:(bList)) as list

–Popup Menuで置換色選択
set cRes to pickup color c2List main message "Select Target Color" color max max65535
if cRes = 0 then return

set fromCol to (contents of item cRes of c2List)

–カラーピッカーで置換色選択
set tCol to choose color default color fromCol

set d1 to current date

–実際に表の背景色を置換する
set hitList to findDataFrom2DList(fromCol, c3List) of me –データ上で当該色のセル情報を計算する

–Rangeを横スキャンと縦スキャンの2通りで試算(Two way Simulation)
set rList1 to retRangeFromPosListHorizontal(hitList) of me –横方向へのrange評価
set rList2 to retRangeFromPosListVertival(hitList) of me –縦方向へのrange評価

–Simulationの結果、要素数の少ない方(=処理時間の短い方=高速な方)を採用する
–log {"Simulation", (length of rList1), (length of rList2)}
if (length of rList1) < (length of rList2) then
  copy rList1 to rangeList
else
  copy rList2 to rangeList
end if

tell application "Pages"
  activate
  
tell front document
    tell table 1
      repeat with i in rangeList
        set j to contents of i
        
        
ignoring application responses –非同期実行モードで高速実行
          set background color of range j to tCol
        end ignoring
        
      end repeat
    end tell
  end tell
end tell

set d2 to current date
return d2 – d1

on uniquifyList(aList as list)
  set aArray to NSArray’s arrayWithArray:aList
  
set bArray to aArray’s valueForKeyPath:"@distinctUnionOfObjects.self"
  
return bArray as list
end uniquifyList

on findDataFrom2DList(anItem, aList as list)
  script spd
    property aList : {}
    
property resList : {}
  end script
  
  
set (aList of spd) to aList
  
set (resList of spd) to {}
  
  
set yCount to 1
  
  
repeat with i in (aList of spd)
    
    
set aResList to (Bplus’s indexesOfItem:anItem inList:i inverting:false) as list
    
    
set tmpList to {}
    
if aResList is not equal to {} then
      repeat with ii in aResList
        set jj to contents of ii
        
set the end of tmpList to {jj, yCount}
      end repeat
      
set (resList of spd) to (resList of spd) & tmpList
    end if
    
    
set yCount to yCount + 1
  end repeat
  
  
return (resList of spd) –return {{x, y}…..} item list (1-based)
end findDataFrom2DList

on retRangeFromPosListVertival(posList as list)
  script rangeSPD
    property posList2 : {}
  end script
  
  
–縦方向へのrange評価に都合がいいようにソート
  
set (posList2 of rangeSPD) to shellSortListAscending(posList, {1, 2}) of me
  
  
–先頭データをピックアップ
  
set firstData to first item of (posList2 of rangeSPD)
  
set (posList2 of rangeSPD) to rest of (posList2 of rangeSPD)
  
  
copy firstData to {curX1, curY1}
  
set tmpRangeStr to aNumToExcelColumn(curX1) of me & (curY1 as string) & ":"
  
  
set tmpRange to {}
  
set hitF to false
  
  
set outList to {}
  
  
repeat with i in (posList2 of rangeSPD)
    copy i to {tmpX, tmpY}
    
    
–log {"{curX1, curY1}", {curX1, curY1}}
    
–log {"{tmpX, tmpY}", {tmpX, tmpY}}
    
    
if (curX1 = tmpX) and (curY1 + 1 = tmpY) then
      –Y方向への連続値を拾っている最中
      
if hitF = false then
        –log "case 1a"
        
–log {"hitF", hitF}
        
set hitF to true
      else
        –log "case 1b"
        
–log {"hitF", hitF}
        
–横に連続しているブロックの途中
      end if
    else
      –直前の値と連続していない
      
if hitF = false then
        –log "case 2a"
        
–log {"hitF", hitF}
        
set tmpRangeStr to tmpRangeStr & aNumToExcelColumn(curX1) of me & (curY1 as string)
        
set the end of outList to tmpRangeStr
        
set tmpRangeStr to aNumToExcelColumn(tmpX) of me & (tmpY as string) & ":"
        
set hitF to false
      else
        –log "case 2b"
        
–log {"hitF", hitF}
        
–連続ブロックの末尾を拾った
        
set tmpRangeStr to tmpRangeStr & aNumToExcelColumn(curX1) of me & (curY1 as string)
        
set the end of outList to tmpRangeStr
        
set tmpRangeStr to aNumToExcelColumn(tmpX) of me & (tmpY as string) & ":"
        
set hitF to false
        
–log {"tmpRangeStr", tmpRangeStr}
      end if
    end if
    
    
copy {tmpX, tmpY} to {curX1, curY1}
  end repeat
  
  
–log {tmpRangeStr, hitF}
  
  
if (hitF = true) or (tmpRangeStr is not equal to "") then
    set tmpRangeStr to tmpRangeStr & aNumToExcelColumn(curX1) of me & (curY1 as string)
    
set the end of outList to tmpRangeStr
  end if
  
  
return outList
end retRangeFromPosListVertival

on retRangeFromPosListHorizontal(posList as list)
  script rangeSPD
    property posList2 : {}
  end script
  
  
copy posList to (posList2 of rangeSPD)
  
  
–先頭データをピックアップ
  
set firstData to first item of (posList2 of rangeSPD)
  
set (posList2 of rangeSPD) to rest of (posList2 of rangeSPD)
  
  
copy firstData to {curX1, curY1}
  
set tmpRangeStr to aNumToExcelColumn(curX1) of me & (curY1 as string) & ":"
  
  
set tmpRange to {}
  
set hitF to false
  
  
set outList to {}
  
  
repeat with i in (posList2 of rangeSPD)
    copy i to {tmpX, tmpY}
    
    
–log {"{curX1, curY1}", {curX1, curY1}}
    
–log {"{tmpX, tmpY}", {tmpX, tmpY}}
    
    
    
if (curX1 + 1 = tmpX) and (curY1 = tmpY) then
      –X方向への連続値を拾っている最中
      
if hitF = false then
        –log "case 1a"
        
–log {"hitF", hitF}
        
set hitF to true
      else
        –log "case 1b"
        
–log {"hitF", hitF}
        
–横に連続しているブロックの途中
      end if
    else
      –直前の値と連続していない
      
if hitF = false then
        –log "case 2a"
        
–log {"hitF", hitF}
        
set tmpRangeStr to tmpRangeStr & aNumToExcelColumn(curX1) of me & (curY1 as string)
        
set the end of outList to tmpRangeStr
        
set tmpRangeStr to aNumToExcelColumn(tmpX) of me & (tmpY as string) & ":"
        
set hitF to false
      else
        –log "case 2b"
        
–log {"hitF", hitF}
        
–連続ブロックの末尾を拾った
        
set tmpRangeStr to tmpRangeStr & aNumToExcelColumn(curX1) of me & (curY1 as string)
        
set the end of outList to tmpRangeStr
        
set tmpRangeStr to aNumToExcelColumn(tmpX) of me & (tmpY as string) & ":"
        
set hitF to false
        
–log {"tmpRangeStr", tmpRangeStr}
      end if
    end if
    
    
copy {tmpX, tmpY} to {curX1, curY1}
  end repeat
  
  
–log {tmpRangeStr, hitF}
  
  
if (hitF = true) or (tmpRangeStr is not equal to "") then
    set tmpRangeStr to tmpRangeStr & aNumToExcelColumn(curX1) of me & (curY1 as string)
    
set the end of outList to tmpRangeStr
  end if
  
  
return outList
end retRangeFromPosListHorizontal

–2008/05/01 By Takaaki Naganoya
–10進数数値をExcel 2004/2008的カラム表現にエンコードするサブルーチン を使いまわし
–1〜1351までの間であれば正しいエンコーディング結果を返す
on aNumToExcelColumn(origNum as integer)
  if origNum > 1351 then
    error "エラー:Excel 2004/2008的カラム表現(A1形式)への変換ルーチンにおいて、想定範囲外(1351以上)のパラメータが指定されました"
  end if
  
  
set upperDigitEncTable to {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "A"}
  
set lowerDigitEncTable to {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "A"}
  
  
set oNum to origNum
  
set nTh to 26
  
set stringLength to 4
  
  
–数字が1桁の場合の対応
  
if origNum < 27 then
    set aRes to (item origNum of upperDigitEncTable) as string
    
return aRes
  end if
  
  
  
if origNum > 702 then
    –3桁になる場合
    
set upupNum to oNum div 676 –整数除算–上の上の桁
    
set oNum to oNum – (upupNum * 676)
    
set upNum to oNum div 26 –整数除算–上の桁
    
set lowNum to oNum mod 26 – 1 –余剰計算–下の桁
    
    
–超つじつま合わせ処理
    
if lowNum = -1 then
      set upNum to upNum – 1
      
set lowNum to 25
    end if
    
    
set upupChar to (item upupNum of upperDigitEncTable) as string
    
set upChar to (item upNum of upperDigitEncTable) as string
    
set lowChar to (item (lowNum + 1) of lowerDigitEncTable) as string
    
set resText to upupChar & upChar & lowChar
    
  else
    –2桁の場合
    
set upNum to oNum div 26 –整数除算–上の桁
    
set lowNum to oNum mod 26 – 1 –余剰計算–下の桁
    
    
–超つじつま合わせ処理
    
if lowNum = -1 then
      set upNum to upNum – 1
      
set lowNum to 25
    end if
    
    
set upChar to (item upNum of upperDigitEncTable) as string
    
set lowChar to (item (lowNum + 1) of lowerDigitEncTable) as string
    
set resText to upChar & lowChar
    
  end if
  
  
return resText
end aNumToExcelColumn

–入れ子のリストを昇順ソート
on shellSortListAscending(a, keyItem)
  return sort2DList(a, keyItem, {true}) of me
end shellSortListAscending

–入れ子のリストを降順ソート
on shellSortListDecending(a, keyItem)
  return sort2DList(a, keyItem, {false}) of me
end shellSortListDecending

–2D Listをソート
on sort2DList(aList as list, sortIndexes as list, sortOrders as list)
  
  
–index値をAS流(アイテムが1はじまり)からCocoa流(アイテムが0はじまり)に変換
  
set newIndex to {}
  
repeat with i in sortIndexes
    set j to contents of i
    
set j to j – 1
    
set the end of newIndex to j
  end repeat
  
  
–Sort TypeのListを作成(あえて外部から指定する内容でもない)
  
set sortTypes to {}
  
repeat (length of sortIndexes) times
    set the end of sortTypes to "compare:"
  end repeat
  
  
–Sort
  
set resList to (SMSForder’s subarraysIn:(aList) sortedByIndexes:newIndex ascending:sortOrders sortTypes:sortTypes |error|:(missing value)) as list
  
  
return resList
end sort2DList

★Click Here to Open This Script 

Posted in Color dialog Script Libraries | Tagged 10.13savvy 10.14savvy 10.15savvy Pages | Leave a comment

sdef(AppleScript用語辞書)に画像やムービーを入れる

Posted on 10月 25, 2019 by Takaaki Naganoya

sdef(AppleScript用語辞書)に画像が入っているとわかりやすくてよさそうだと思っていました。ただ、その実例がどこにも見つかりません。

見つからない場合には、いろいろ考えればいいわけで、少し考えて試してみたらできてしまいました。

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

sdefはxml形式のファイルで、その中には基本的にAppleScriptのコマンドやオブジェクト、属性値や列挙値が定義されています。

ただ、それだけだとわかりづらいかも? という配慮から、HTML形式のドキュメントも入れられるようになっています。

最近のPiyomaru Softwareのライブラリでは、sdef内にサンプルScriptを「applescript://」URL Link入りで本Blogと同様に掲載しています。これだとsdefの容量が大きくなってしまいますが、すぐに利用できる用例が掲載されていないと意味がないと判断し、ライブラリを小分けにすることでバランスを取ろうと考えました。

ここまでで、ワンクリックですぐに試せるサンプルScript入りのAppleScript用語辞書は実現できました。全コマンド、全オブジェクトの定義に対してサンプルScriptが掲載されていれば、迷うこともないでしょう。

そこまで実現しても、やはり内容を画像で伝えたい場合もあるわけで、このHTML形式のドキュメントの中にimg srcタグで画像を指し示せればいいんじゃなかろうかと思っていました。

実際、いろいろパスの書き方を工夫してみたものの、なかなか画像表示できませんでした。その一方で、リンク先が間違っているという表示にはなっているものの、画像表示自体は行えそうな雰囲気のレンダリング結果にはなっていました。

当初、バンドル内の画像を相対パスで指し示したいと試行錯誤していたものの、自分が試した範囲内ではできませんでした。Web上の画像をURLで指し示せば表示されそうな気配はしていたものの、オフライン状態で作業した場合にでも画像は表示されてほしいところです。

そんなときに、画像をbase64エンコードしてimg srcタグの中に直接記述するという荒技を見つけ、そのとおりに書いてみたところ無事表示できたという寸法です。

オフライン時に表示されなくてよいのであれば、

のように、Web上の画像をリンク表示することもできるので、sdefのサイズを大きくしたくないが画像を大量に使いたいという場合にはこちらも検討に値することでしょう。

できないと思いつつ、iframeタグでYouTubeのムービーを埋め込んでみようと試してみましたが、表示されませんでした(iframeのフレーム自体はその大きさのボックスが存在しているもよう)。mpeg4のムービーをWeb上に置いてリンクしてみたらムービー再生できました。フルスクリーン再生も可能でした。

その他、sdefのあまり利用されていない機能は、

 ・ローカライズできる

というあたりでしょうか。日本語ユーザー向けに日本語のAppleScript用語辞書も書けるわけで、けっこう英語が読めない(英語読めないとプログラミング無理だと思わなくもないですが)人が多いようなので、いろいろ試してみたいところではあります(昔、Classic MacOS時代に、e.Typistという日本語OCRソフトウェアのAppleScript用語辞書が日本語で書かれていているのを見たことがあります)。

ただ、そこにパワーを割くぐらいならサンプルScriptを掲載しておけば、くどくど説明せずともサンプルのURLリンクをクリックするだけで実際にScriptを実行できるので、めったに使わない機能ではあります。


▲FineReader OCR ProのAppleScript用語辞書が日本語ローカライズされているのを発見しました。そこ日本語化するよりも、連続OCR実行ができないとか、「C++」などの指定できない定数を定義しているあたりを修正するほうがいいと思うのですが、、、、、、

Posted in sdef | Tagged 10.12savvy 10.13savvy 10.14savvy 10.15savvy | 1 Comment

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

Posted on 10月 23, 2019 by Takaaki Naganoya

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

—- >8 投稿ここから

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

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

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

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

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

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

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

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

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

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

★Click Here to Open This Script 

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

CotEditorの最前面のドキュメントの選択範囲を伏せ字に

Posted on 10月 22, 2019 by Takaaki Naganoya

CotEditorの最前面のドキュメントの選択範囲を、簡易形態素解析ルーチンeasyJparseを用いて、いい感じに伏せ字にするAppleScriptです。

–> Download makeSelectionToFuseji(Code-Signed AppleScript applet with libraries in its bundle, co-work with CotEditor)

easyJparseは日本語のコマンド解析用にでっちあげた作った超簡易形態素解析プログラムです。単語(形態素)ごとに分割しますが、品詞まではわかりません。コマンド解釈用ではあるものの、少し他の用途にも使えないかと思い、このような用途に使ってみました。

# 本Scriptは、CotEditor用のScript Pack v2.0に収録されています


▲CotEditorの選択範囲を伏せ字にする。形態素解析して単語化して、単語単位で伏せ字にするかの判断を実行

テキストエディタ上で伏せ字処理というのは、個人的によく使います。たいていは、オリジナルの文章に対して同様の分量の文章を作らなくてはならないようなケースで、文字数の感覚をつかむために使います。一種のダミーレイアウトのようなものです。

本スクリプトのような伏せ字処理については、ニーズがあるんだかないんだか不明なものですが、とりあえず掲載してみました。自分で使ってみたところ、たしかに面白いものの、実用性については未知数という印象です。

(minusList of parseSPD) に入れている語群は、どこかからか拾ってきたもののようではあるものの、すでに何か方向性を見失っているような気がしないではありません。

AppleScript名:選択範囲を伏せ字に(簡易形態素解析でそれっぽく).scptd
— Created 2018-09-26 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.5" — El Capitan (10.11) or later
use framework "Foundation"
use scripting additions
use jParser : script "easyJParse"

property NSArray : a reference to current application’s NSArray
property NSMutableSet : a reference to current application’s NSMutableSet
property NSSortDescriptor : a reference to current application’s NSSortDescriptor

property fuesejiChar : "□"

script parseSPD
  property pList : {}
  
property p2List : {}
  
property oneLine : {}
  
property outStr : ""
  
property minusList : {}
end script

–伏せ字化しない助詞などの単語リスト。名詞だけを残すように整備。単語(形態素)単位で照合する
set (minusList of parseSPD) to {"", " ", "ー", "あ", "で", "も", "に", "と", "の", "は", "へ", "さ", "が", "せ", "か", "た", "だ", "だっ", "ば", "つ", "な", "い", "き", "お", "ら", "る", "れ", "なっ", "それ", "これ", "あれ", "どれ", "この", "どの", "あの", "その", "まで", "こと", "もの", "いつ", "いく", "たち", "ただ", "たい", "そう", "いる", "よう", "れる", "ない", "なら", "なる", "なけれ", "から", "する", "たら", "たり", "だけ", "って", "られ", "的", "化", "いくら", "そんな", "どんな", "あんな", "者", "陰", "時", "事", "こんな", "つれ", "けど", "ああ", "ある", "あっ", "あり", "しかし", "きっと", "すっかり", "例えば", "たとえば", "さっぱり", "たとえ", "だろう", "かつ", "ところ", "まるで", "だが", "全て", "すべて", "なり", "いい", "つれ", "つけ", "ながら", "せいぜい", "そうそう", "さらに", "もっと", "まだ", "なく", "し", "を", "て", "いけ", "行く", "また", "まま", "まぁ", "『", "』", "、", "。", "。。", "……。", "【", "】", "「", "」", "(", ")", "最近", "今度", "中", "チカチカ", "グラグラ", "ふわふわ", "少し", "ついで", "より", "っぽい", "ぐらい", "何", "とき", "ため", "そっくり", "そして", "やがて", "じきに", "すぐ", "今", "次", "できる", "出来る", "いや", "そう", "おそらく", "いえ", "らしい", "とも", "ほぼ", "つい", "もう", "きっかけ", "ころ", "頃", "早々", "そこ", "どこ", "なんか", "じゃ", "くれ", "ください", "こそ", "あいつ", "だれ", "誰", "おぼしき", "らしき", "らしい", "しか", "でき", "よっ", "確か", "どう", "こう", "そう", "ああ", "くる", "ざま", "ごとく", "きれ", "はず", "さらに", "さらなる", "更なる", "など", "ごと", "とても", "たく", "いう", "とっ", "いっ", "えっ", "おっ", "ここ", "そこ", "どこ", "なかっ", "ごく", "やる", "ゆい", "ふと", "たび", "ほど", "もた", "よし", "ぜひ", "いら", "よい", "ま", "み", "む", "め", "も", "や", "けれど", "だけど", "したがっ", "すごく", "そもそも", "ほしい", "なれる", "すぎ", "もふもふ", "モフモフ", "さん", "おと", "とー", "えっと", "け", "っけ", "なん", "よ", "ね", "しっくり", "くれる", "くれた", "なぜ", "まあ", "まぁ", "ん", "なんて", "!」"}

set (pList of parseSPD) to {}
set (p2List of parseSPD) to {}
set (oneLine of parseSPD) to {}
set (outStr of parseSPD) to {}

tell application "CotEditor"
  tell front document
    –選択部分が存在しているかどうかチェック
    
set aCon to contents of selection
    
if aCon = "" then return
    
    
set (pList of parseSPD) to paragraphs of aCon
  end tell
end tell

–伏せ字にする対象単語を、助詞などを消し込むことでピックアップ
repeat with i in (pList of parseSPD)
  if length of i > 1 then
    –簡易形態素解析
    
set tempList to parseJ(i) of jParser
    
    
–簡易形態素解析したリストと助詞などのリストの差分を計算
    
set cList to clacListDiff(tempList, (minusList of parseSPD)) of me
    
    
set (oneLine of parseSPD) to {}
    
repeat with ii in tempList
      set aLen to length of ii
      
if ii is in cList then
        –伏せ字化する場合
        
set bCon to multipleChar(fuesejiChar, aLen) of me
        
      else
        –そのまま出力する場合
        
set bCon to contents of ii
      end if
      
set the end of (oneLine of parseSPD) to bCon
    end repeat
    
    
–1つの文章ぶんの単語を連結
    
set cStr to retDelimedText((oneLine of parseSPD), "") of me
  else
    set cStr to ""
  end if
  
  
set the end of (p2List of parseSPD) to cStr
  
end repeat

–すべての文章を連結して配列からテキストに
set (outStr of parseSPD) to retDelimedText((p2List of parseSPD), return) of me

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

–指定文字を指定回数繰り返して連結して出力
on multipleChar(aChar as string, aLen as integer)
  set aList to {}
  
repeat aLen times
    set the end of aList to aChar
  end repeat
  
  
return retDelimedText(aList, "") of me
end multipleChar

–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

–2つの1D Listの差分を計算
on clacListDiff(aList as list, bList as list)
  set aSet to NSMutableSet’s setWithArray:aList
  
set bSet to NSMutableSet’s setWithArray:bList
  
  
aSet’s minusSet:bSet –補集合
  
set aRes to aSet’s allObjects() as list
  
  
return aRes
end clacListDiff

★Click Here to Open This Script 

Posted in list Natural Language Processing Text | Tagged 10.12savvy 10.13savvy 10.14savvy 10.15savvy CotEditor NSArray NSMutableSet NSSortDescriptor | 1 Comment

Post navigation

  • Older posts
  • Newer posts

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

Google Search

Popular posts

  • 開発機としてM2 Mac miniが来たのでガチレビュー
  • macOS 15, Sequoia
  • 指定のWordファイルをPDFに書き出す
  • Pages本執筆中に、2つの書類モード切り替えに気がついた
  • Numbersで選択範囲のセルの前後の空白を削除
  • メキシカンハットの描画
  • Pixelmator Pro v3.6.4でAppleScriptからの操作時の挙動に違和感が
  • AdobeがInDesign v19.4からPOSIX pathを採用
  • AppleScriptによる並列処理
  • Safariで「プロファイル」機能を使うとAppleScriptの処理に影響
  • Cocoa Scripting Course 続刊計画
  • macOS 14.xでScript Menuの実行速度が大幅に下がるバグ
  • AppleScript入門③AppleScriptを使った「自動化」とは?
  • Keynote/Pagesで選択中の表カラムの幅を均等割
  • macOS 15でも変化したText to Speech環境
  • デフォルトインストールされたフォント名を取得するAppleScript
  • macOS 15 リモートApple Eventsにバグ?
  • AppleScript入門① AppleScriptってなんだろう?
  • macOS 14で変更になったOSバージョン取得APIの返り値
  • Keynoteで2階層のスライドのタイトルをまとめてテキスト化

Tags

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

カテゴリー

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

アーカイブ

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

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

メタ情報

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

Forum Posts

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

メタ情報

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