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

タグ: NSTextView

アラートダイアログでMarkdownをプレビュー v2

Posted on 8月 8, 2020 by Takaaki Naganoya

edama2さんから投稿していただいた、Markdown書類をダイアログ上でプレビューするScriptの第二弾です。

–> Download Script Bundle

WKWebViewではなくNSAttributedStringを使ってMarkdownを表示しています。
NSAttributedStringでhtmlが表示できるとわかってWKWebViewの代わりになるかな?と思ったんですが、javascriptは使えないので自前で実行し、NSAttributedStringに<hr>に相当するものがないのとWKWebViewとは描画結果が違うので、プレビューとして使うのはイマイチです。作っておいてなんですが…😢

本Scriptの見どころは2点。「Scriptバンドル内にJavaScriptのライブラリを突っ込んで呼び出しているところ」と、「Markdownを(HTML経由で)NSAttributedStringに変換してプレビューしている」ところです。

ひかえめな説明文とは裏腹に、ずいぶんと攻めているというか、野心的な実装です。

JavaScriptのライブラリをローカルに置く案についてはいろいろedama2さんと意見交換をしていたんですが、割とさらっと書いているところにショックを受けます。これだけでも、相当に試行錯誤が必要な内容なんですが、このレベルに追いつくためには相当の苦労が、、、

AppleScript名:アラートダイアログでMarkdownをプレビュー v2
use AppleScript
use framework "Foundation"
use scripting additions

on run
  my main()
end run

on main()
  set mes to "Markdownファイルを選択してください。"
  
set chooseItems to choose file of type {"net.daringfireball.markdown"} with prompt mes
  
  
#
  
set aScreen to current application’s NSScreen’s mainScreen()
  
set screenFrame to aScreen’s frame()
  
set aHeight to current application’s NSHeight(screenFrame)
  
set aWidth to current application’s NSWidth(screenFrame)
  
set aHeight to aHeight * 0.845
  
set aWidth to aWidth * 0.94 / 2
  
  
set paramObj to {}
  
set paramObj to paramObj & {myMessage:"Markdown preview"}
  
set paramObj to paramObj & {mySubMessage:"file : " & chooseItems’s POSIX path}
  
set paramObj to paramObj & {mdFile:chooseItems}
  
set paramObj to paramObj & {viewWidth:aWidth}
  
set paramObj to paramObj & {viewHeight:aHeight}
  
  
my performSelectorOnMainThread:"displayMarkdownPreview:" withObject:(paramObj) waitUntilDone:true
end main

# Markdownをダイアログで表示
on displayMarkdownPreview:paramObj
  set mesText to myMessage of paramObj as text
  
set infoText to mySubMessage of paramObj as text
  
set mdFile to (mdFile of paramObj) as alias
  
set viewWidth to (viewWidth of paramObj) as integer
  
set viewHeight to (viewHeight of paramObj) as integer
  
  
## MDを読み込む
  
set mdStr to (read mdFile as «class utf8») as text
  
  
## javascriptを読み込む
  
set mePath to path to me
  
set resPath to (mePath & "Contents:Resources:marked.min.js") as text
  
set jsStr to (read (resPath as alias) as «class utf8») as text
  
  
## javascriptでMarkdownをhtmlに変換
  
tell current application’s JSContext’s new()
    evaluateScript_(jsStr)
    
tell objectForKeyedSubscript_("marked")
      tell callWithArguments_({mdStr})
        set resultStr to toString()
      end tell
    end tell
  end tell
  
  
## HTMLを読み込む
  
set mePath to path to me
  
set resPath to (mePath & "Contents:Resources:index.html") as text
  
set htmlStr to (read (resPath as alias) as «class utf8») as text
  
  
## html内の文字を置き換え
  
set aString to current application’s NSString’s stringWithFormat_(htmlStr, resultStr) as text
  
log result
  
  
  
## NSAttributedString
  
set aString to current application’s NSString’s stringWithString:aString
  
set stringData to aString’s dataUsingEncoding:(current application’s NSUTF8StringEncoding)
  
  
set aValue to {current application’s NSHTMLTextDocumentType, current application’s NSUTF8StringEncoding}
  
set aKey to {current application’s NSDocumentTypeDocumentAttribute, current application’s NSCharacterEncodingDocumentAttribute}
  
set aOption to current application’s NSDictionary’s dictionaryWithObjects:aValue forKeys:aKey
  
  
tell current application’s NSAttributedString’s alloc()
    tell initWithHTML_options_documentAttributes_(stringData, aOption, missing value)
      set attributedString to it
    end tell
  end tell
  
log result
  
  
# Create a TextView with Scroll View
  
set frameSize to current application’s NSMakeRect(0, 0, viewWidth, viewHeight)
  
tell current application’s NSTextView’s alloc()
    tell initWithFrame_(frameSize)
      setEditable_(false)
      
tell textStorage()
        appendAttributedString_(attributedString)
      end tell
      
set aView to it
    end tell
  end tell
  
tell current application’s NSScrollView’s alloc()
    tell initWithFrame_(frameSize)
      setDocumentView_(aView)
      
set theView to it
    end tell
  end tell
  
  
  
## アイコンの指定
  
set aImage to current application’s NSWorkspace’s sharedWorkspace()’s iconForFileType:"net.daringfireball.markdown"
  
  
## set up alert
  
tell current application’s NSAlert’s new()
    addButtonWithTitle_("Close")
    
setAccessoryView_(theView)
    
setIcon_(aImage)
    
setInformativeText_(infoText)
    
setMessageText_(mesText)
    
tell |window|()
      setInitialFirstResponder_(theView)
    end tell
    
### show alert in modal loop
    
if runModal() is (current application’s NSAlertSecondButtonReturn) then return
  end tell
end displayMarkdownPreview:

★Click Here to Open This Script 

そして、本Scriptをよくよく見回してみると、NSAttributedStringになっているのでPDFに変換するのがとても簡単でした。WkWebView上に表示したWebコンテンツをPDF化しようと試みているものの、うまくできていません。Blocks構文を必要とする機能であるため(なんでこんなものまでBlocks(非同期実行)必要なんだろ?)、AppleScriptからの呼び出しができないためです。Xcode上で他の言語をまじえて組めば不可能ではない気もしますが……

CSSがWeb表示用のものなので、PDF出力時には割とゆったり目で密度の低いレイアウトになってしまうものの、このCSS指定を別のものにできればけっこうMarkdown→PDFの変換を行う部品として使えるレベルになってくるのではないでしょうか。それはそれで、Scriptバンドル内に入れたCSSを指定するとか、Web上のどこかに印刷用のCSSをホスティングしておくなどの方法が必要になることでしょう。

Posted in dialog JavaScript Markdown | Tagged 10.13savvy 10.14savvy 10.15savvy 11.0savvy JSContext NSAlert NSAlertSecondButtonReturn NSAttributedString NSCharacterEncodingDocumentAttribute NSDictionary NSDocumentTypeDocumentAttribute NSScreen NSScrollView NSString NSTextView NSUTF8StringEncoding NSWorkspace | Leave a comment

プログラムで作ったアラートダイアログ上のTextViewをフォーカスする

Posted on 4月 14, 2020 by Takaaki Naganoya

AppleScriptでダイナミックに(動的に)生成したアラートダイアログ上にテキストビューを生成し、そのテキストビュー上にテキスト入力用のキャレットを移動させる(フォーカスする)AppleScriptです。

Xcode上でAppleScriptでGUIアプリケーションを作っていて、文字サイズの大きなテキスト入力フィールドを動的に生成。さらに、テキスト入力フィールドにテキスト入力用のキャレットを移動させようとして、割と手こずっていました。

テキスト入力を受け付けるGUI部品に対して、入力フォーカスを与え、テキスト入力のキャレットが置かれた状態を再現するには、GUIの画面上からはマウスカーソルでクリック操作するとできます。同じ状態をプログラム側から作る場合にはFirstResponderにセットするという処理になります。

この、FirstResponderに指定することは理解でき、Xcode(Interface Builder)上で配置した部品に対して実行する処理は昔からやっています。NSTextFieldに強制的に入力フォーカスを置いた上でバーコードリーダーからのテキスト入力を受け付けるといった処理です。

一方、プログラムから動的に生成したGUI部品に対して、Cocoaが用意しているAPIのどれを用いて、どのように指定すべきなのかで困りました。

親WindowのFirstResponderにしてみたり、アラートウィンドウのFirstResponderにしてみたり、いろいろ試した末に、

parentWin's setInitialFirstResponder:aView

で、Alert DialogのWindowをparentWinに、alert dialog上のテキストビューをaViewに代入した状態で実行して、入力キャレットをテキストビュー上に移動できました。本Xcode Projectは上記の1行の記述の検証を行うためのテストプロジェクトです。

–> Download Xcode Project

AppleScript名:AppDelegate.applescript
—
— AppDelegate.applescript
— dialogCarret
—
— Created by Takaaki Naganoya on 2020/04/14.
— Copyright © 2020 Takaaki Naganoya. All rights reserved.
—

script AppDelegate
  property parent : class "NSObject"
  
  
property |NSURL| : a reference to current application’s |NSURL|
  
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 NSTextView : a reference to current application’s NSTextView
  
property NSScrollView : a reference to current application’s NSScrollView
  
property NSRunningApplication : a reference to current application’s NSRunningApplication
  
  
— IBOutlets
  
property theWindow : missing value
  
  
property returnCode : 0
  
property resStr : ""
  
  
  
on applicationWillFinishLaunching:aNotification
    —
  end applicationWillFinishLaunching:
  
  
on applicationShouldTerminate:sender
    return current application’s NSTerminateNow
  end applicationShouldTerminate:
  
  
on clicked:sender
    set tmpStr to "TEST"
    
set paramObj to {myMessage:"Input Text", mySubMessage:"", mes1:(tmpStr), mesWidth:400, mesHeight:200}
    
my performSelectorOnMainThread:"dispTextViewWithAlertdialog:" withObject:paramObj waitUntilDone:true
    
set aResText to (my resStr) as string
    
    
display dialog aResText
  end clicked:
  
  
on dispTextViewWithAlertdialog:paramObj
    –Receive Parameters
    
set aMainMes to (myMessage of paramObj) as string –Main Message
    
set aSubMes to (mySubMessage of paramObj) as string –Sub Message
    
set mesStr to (mes1 of paramObj) as string –Text Input field 1 Label
    
set aWidth to (mesWidth of paramObj) as integer –TextView width
    
set aHeight to (mesHeight of paramObj) as integer –TextView height
    
    
set vNum to system attribute "sys2"
    
if vNum > 13 then
      set apRes to retLightOrDark() of me
      
if apRes = true then
        set textColor to (current application’s NSColor’s cyanColor())
      else
        set textColor to (current application’s NSColor’s blackColor())
      end if
    else
      set textColor to (current application’s NSColor’s blackColor())
    end if
    
    
    
— Create a TextView with Scroll View
    
set aScroll to NSScrollView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aWidth, aHeight))
    
set aView to NSTextView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aWidth, aHeight))
    
aView’s setDelegate:me
    
aView’s setRichText:true
    
aView’s useAllLigatures:true
    
aView’s setTextColor:textColor
    
aView’s setFont:(current application’s NSFont’s systemFontOfSize:90.0)
    
set aColor to current application’s NSColor’s colorWithDeviceRed:0.0 green:0.0 blue:0.0 alpha:0.1
    
    
aView’s setBackgroundColor:aColor
    
aView’s setString:mesStr
    
aScroll’s setDocumentView:aView
    
aView’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
      
set parentWin to its |window|()
    end tell
    
    
parentWin’s setAlphaValue:0.8
    
–parentWin’s setOpaque:(false)
    
parentWin’s setLevel:(current application’s NSScreenSaverWindowLevel)
    
    
parentWin’s setInitialFirstResponder:aView —Place Input Carret to Alert Dialog
    
    
— 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
      —
    else
      set my resStr to aView’s |string|()
    end if
  end dispTextViewWithAlertdialog:
  
  
  
on doModal:aParam
    set (my returnCode) to aParam’s runModal()
  end doModal:
  
  
  
on retLightOrDark()
    return true
  end retLightOrDark
  
end script

★Click Here to Open This Script 

Posted in AppleScript Application on Xcode dialog How To | Tagged 10.13savvy 10.14savvy 10.15savvy NSAlert NSColor NSFont NSMakeRect NSRunningApplication NSScrollView NSTextView | Leave a comment

RoundWindow v2

Posted on 1月 12, 2020 by Takaaki Naganoya

Edama2さんと「無理だよねー」「そうそう、絶対無理〜」などとメールで言っていたら、Shane Stanleyから届いた「できるよ」という衝撃のメール。

スクリプトエディタ上で記述する通常のAppleScriptで、CocoaのCustom Class宣言と呼び出しができるとのこと。

自分で動作確認してみるまで、半信半疑でしたが、、、、できますねこれは、、、

–> Download Editable and Executable Script Bundle

冗談半分で思いついたことを試してみたらできてしまったり、冗談半分でできるわけないよねと念のために書いておいたことが世界の誰かの目に止まったりと、「冗談半分」ってけっこう重要なことだと思えてきました。

以下、Shane Stanleyの説明による、その書き換え手順です。

(1)Subclassファイル(複数可)をXcode上のプロジェクトで書くようなスタイルで書く

こういう(↑)スタイルですね。かならずscript宣言しつつ、parent属性を宣言しておくところがXcode上のAppleScriptアプリケーションのスタイルです。あとで動作確認して、アプリケーションの起動や終了に関するイベントハンドラを書いておいたのは無駄(実行されない)ではないかとも思われました。

(2)実行するメインのScriptのResourcesフォルダ内にSubclassファイルを入れる

普通、AppleScriptのファイルが入る/Contents/Resources/Scripts/でも、ライブラリを入れておく/Contents/Resources/Script Libraries/でもなく、/Contents/Resources/の直下に入れます。ファイル名はオリジナルのEdama2さんのものをそのまま採用していますが、割となんでもいいようです。Custom Classファイルは分割してもいいし、このサンプルのようにまとめてもいいんでしょう。

# 追加実験してみたところ、Resourcesフォルダ以下の/Scriptsや/Script Libraries/フォルダと重複しない名称の別フォルダ(例:/Classes/)に入れておいても大丈夫でした

(3)use framework “AppleScriptObjC”の宣言文を追加

見たことのない光景ですが、書くことについてはとくに障害はありません。AppKit.Frameworkもuse宣言しておいたほうがよかったかもしれません。

(4)メインスクリプトの実行時に以下の処理を実行

set theBundle to current application’s NSBundle’s bundleWithPath:pathToFolderWithScripts
theBundle’s loadAppleScriptObjectiveCScripts()

★Click Here to Open This Script 

試行錯誤して、上記の「pathToFolderWithScripts」にバンドル内の/Contents/Resources/を入れて実行すればよいことが理解できました。

以上の変更を加えて、ためしにスクリプトエディタ&Script Debugger上で実行してみたところ、改変前と変わりなく実行できてしまいました(冒頭のスクリーンショット)。

いや、これはめちゃくちゃすごいですよ!! 何がすごいって、CocoaのCustom Classをスクリプトライブラリ中に入れて呼び出せるということで、けっこう無茶な箱庭インタフェースが作れてしまう予感が、、、、。

そして、AppleScriptObjC(AppleScriptObjC.frameworkより)でスクリプトエディタの「.scpt」形式のファイルを読み込んで実行できてしまったということは、Xcode上のAppleScriptアプリケーション内のScriptもテキスト形式だけでなく、スクリプトエディタで編集できる.scpt形式のファイルを突っ込んで編集できる可能性が見えてきました。

ただ、テキスト形式になっていないと、Interface Builderとの連携のあたりで問題になりそうな気もします。

AppleScript名:customClassTest.scptd
—
–  Created by: Edama2 2020/01/10
–  Adviced by: Shane Stanley 2020/01/11
–  Modified by: Takaaki Naganoya 2020/01/12
—
use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use framework "AppleScriptObjC"
use scripting additions

property _clock_text_view : missing value –> 時計用の文字列
property _clock_timer : missing value –> 時計用のNSTimer

–Script Bundle内のResourcesフォルダを求める
set resourcePath to POSIX path of (path to me) & "Contents/Resources/"
set theBundle to current application’s NSBundle’s bundleWithPath:resourcePath
theBundle’s loadAppleScriptObjectiveCScripts()

my performSelectorOnMainThread:"raizeWindow:" withObject:(missing value) waitUntilDone:true

# ウィンドウを作成
on raizeWindow:aParam
  
  
# 時計用の文字を作成
  
tell current application’s NSTextView’s alloc()
    tell initWithFrame_(current application’s NSMakeRect(35, 120, 300, 40))
      setRichText_(true)
      
useAllLigatures_(true)
      
setTextColor_(current application’s NSColor’s whiteColor())
      
setFont_(current application’s NSFont’s fontWithName:"Arial-Black" |size|:48)
      
setBackgroundColor_(current application’s NSColor’s colorWithDeviceRed:0.0 green:0.0 blue:0.0 alpha:0.0)
      
setAlphaValue_(1.0)
      
setEditable_(false)
      
–setString_("00:00:00")
      
      
set my _clock_text_view to it
    end tell
  end tell
  
  
# 時計を更新するNSTimerを作成
  
set my _clock_timer to current application’s NSTimer’s scheduledTimerWithTimeInterval:1 target:me selector:"idleHandler:" userInfo:(missing value) repeats:true
  
  
# 丸いViewを作成
  
set aFrame to current application’s NSMakeRect(0, 0, 300, 300)
  
tell current application’s RoundView’s alloc()
    tell initWithFrame_(aFrame)
      setNeedsDisplay_(true)
      
setSubviews_({my _clock_text_view})
      
set customView to it
    end tell
  end tell
  
  
#スクリーンのサイズを調べる
  
set aScreen to current application’s NSScreen’s mainScreen()
  
  
# Window
  
set aBacking to current application’s NSWindowStyleMaskBorderless
  
–set aBacking to current application’s NSBorderlessWindowMask
  
set aDefer to current application’s NSBackingStoreBuffered
  
  
tell current application’s CustomWindow’s alloc()
    tell initWithContentRect_styleMask_backing_defer_screen_(aFrame, aBacking, aDefer, false, aScreen)
      –setTitle_(uniqueName) –>タイトル
      
setBackgroundColor_(current application’s NSColor’s clearColor()) — Grammar Police –>背景色
      
setContentView_(customView) –>内容ビューのセット
      
setDelegate_(me) –>デリゲート
      
setDisplaysWhenScreenProfileChanges_(true) –>スクリーンプロファイルが変更されたときウインドウの内容をアップデートするか
      
setHasShadow_(true) –>ウインドウに影があるか
      
setIgnoresMouseEvents_(false) –>マウスイベントを無視するか
      
–setLevel_((current application’s NSScreenSaverWindowLevel) + 1) –>ウインドウの前後関係の位置
      
setOpaque_(false) –>ウインドウを不透明にするか
      
setReleasedWhenClosed_(true) –>閉じたときにメモリを解放するか
      
      
#
      
|center|()
      
makeKeyAndOrderFront_(me) –>キーウインドウにして前面に持ってくる
      
–setFrame_display_(aFrame, true) –>表示
    end tell
  end tell
end raizeWindow:

#タイマー割り込み
on idleHandler:aSender
  set mesStr to time string of (current date)
  (
my _clock_text_view)’s setString:mesStr
end idleHandler:

★Click Here to Open This Script 

AppleScript名:CocoaAppletAppDelegate.scpt
script CocoaAppletAppDelegate
  property parent : class "NSObject"
  
  
on applicationWillFinishLaunching:aNotification
    —
  end applicationWillFinishLaunching:
  
  
  
on applicationShouldTerminate:sender
    return current application’s NSTerminateNow
  end applicationShouldTerminate:
  
end script

script CustomWindow
  property parent : class "NSWindow"
  
property canBecomeKeyWindow : true
  
  
property _initial_location : missing value
  
  
on mouseDown:theEvent
    set my _initial_location to theEvent’s locationInWindow()
  end mouseDown:
  
  
on mouseDragged:theEvent
    –set res to display dialog "mouseDragged" buttons {"OK"} default button "OK"
    
try
      set screenVisibleFrame to current application’s NSScreen’s mainScreen()’s visibleFrame()
      
set screenVisibleFrame to my myHandler(screenVisibleFrame)
      
set windowFrame to my frame()
      
set windowFrame to my myHandler(windowFrame)
      
set newOrigin to windowFrame’s origin
      
      
set currentLocation to theEvent’s locationInWindow()
      
set newOrigin’s x to (newOrigin’s x) + ((currentLocation’s x) – (_initial_location’s x))
      
set newOrigin’s y to (newOrigin’s y) + ((currentLocation’s y) – (_initial_location’s y))
      
      
set tmpY to ((newOrigin’s y) + (windowFrame’s |size|’s height))
      
set screenY to (screenVisibleFrame’s origin’s y) + (screenVisibleFrame’s |size|’s height)
      
if tmpY > screenY then
        set newOrigin’s y to (screenVisibleFrame’s origin’s y) + ((screenVisibleFrame’s |size|’s height) – (windowFrame’s |size|’s height))
      end if
      
      
my setFrameOrigin:newOrigin
    on error error_message number error_number
      set error_text to "Error: " & error_number & ". " & error_message
      
display dialog error_text buttons {"OK"} default button 1
      
return error_text
    end try
    
  end mouseDragged:
  
  
on myHandler(aFrame)
    if class of aFrame is list then
      set {{theX, theY}, {theWidth, theHeight}} to aFrame
      
set aFrame to {origin:{x:theX, y:theY}, |size|:{width:theWidth, height:theHeight}}
      
–set aFrame to current application’s NSMakeRect(theX, theY, theWidth, theHeight)
    end if
    
return aFrame
  end myHandler
end script

script RoundView
  property parent : class "NSView"
  
  
on drawRect:rect
    set aFrame to my frame()
    
set myColor to current application’s NSColor’s redColor()
    
    
tell current application’s NSBezierPath
      tell bezierPathWithOvalInRect_(aFrame)
        myColor’s |set|()
        
fill()
      end tell
    end tell
  end drawRect:
end script

★Click Here to Open This Script 

Posted in Custom Class GUI How To | Tagged 10.14savvy 10.15savvy NSBezierPath NSBundle NSColor NSFont NSScreen NSTextView NSTimer NSView NSWindow | Leave a comment

RoundWindow

Posted on 1月 10, 2020 by Takaaki Naganoya

本Scriptは、Edama2さんから投稿していただいたものです。Cocoa AppleScript AppletでCustom Classを宣言して作られた、丸いウィンドウ(透明ウィンドウの上に丸いグラフィックを描画)を表示して、タイマー割り込みで時計を表示するAppleScriptです。

–> Download Editable and Executable Applet

AppleScriptのランタイム環境はいくつかあり、それぞれに「できること」と「できないこと」、「手軽さ」などが異なります。

(1)スクリプトエディタ上で記述、実行する環境
一番セキュリティ上の制約が緩く、できることの多い環境です。

(2)Script Debugger上で記述、実行する環境
Cocoaのイベントやオブジェクトのログ表示などができる環境です。

(3)Applet環境
AppleScriptの実行ファイルです。

(4)Script Menu環境
macOS標準装備の、メニューからAppleScriptを実行できる環境です。

さらに、Cocoa Scriptingの機能に着目してみると、見え方が変わります。

本Scriptを記述している「Cocoa AppleScript Applet」環境(上の図の赤い部分)は、スクリプトエディタ上で記述する通常のAppleScriptと、Xcode上で記述するCocoaアプリケーションの中間的な性格を持つものです。スクリプトエディタ上で直接は動かせず、アプレット形式で動作させることになりますが、スクリプトエディタ上で動かすよりも、よりCocoaの機能が利用できます。

Cocoa AppleScript Appletでは、アプリケーション(Applet)起動や終了の最中で発生するイベントを利用できますし、本ScriptのようにCocoaのCustom Classを宣言できます。これは、普通のスクリプトエディタ上で記述する(本Blogの大部分のScriptのような)Scriptではできない真似です。
→ Shane Stanleyからツッコミが入って、手の込んだ作業を行うとできるとかで(テンプレートそのままでは無理)、後で実際に試してみます

タイトルは「丸いウィンドウと時計の表示」
NSWindowのカスタムクラスを使ったタイトルバーなしのドラッグで移動できる丸いウィンドウとオマケに時計を表示したものです。
初心者受けしそうなやつです。
問題はそこではなく、
XcodeやCocoa applescript appletから実行するASOCだとカスタムクラスが作れるけど、
ノーマルのapplescriptから実行するASOCではカスタムクラスが作れないということです。
表現がややこしいですが...。
ノーマルのapplescriptからカスタムクラスを作ると、ただのスクリプトオブジェクトにしかなりません。
誰かうまい解決方法を知っている人がいたら教えてください。

ちょうど、こういう資料をまとめていたので補足説明に役立ってしまいました。スクリプトエディタ上で記述する通常のAppleScriptでもCustom Cocoa Classが宣言できると便利そうですが、どんなもんでしょうか? 

Custom Classは便利なので使いたくなる一方、AppleScriptのインタプリタ上で実行するため、Objective-Cなどで書くのと同じような感覚で使うと「遅くて使えない」という話になると思いますが、このEdama2さんのサンプルぐらいの使いかたであれば、ちょうどいいんじゃないかというところです。

歴史的にみると、Cocoa-AppleScript Appletは、Xcode上で記述するCocoa-Applicationを簡略化してスクリプトエディタ上でCocoa Scriptingを手軽に使えるように手直しした「途中」の環境といえます。

Cocoa-AppleScript Appletは、GUIが手軽に作れるわけでもなく、スクリプトエディタ上で直接実行やログ表示ができるわけでもなありません。マスターしたところで最終到達点がCocoaアプリケーションほど高くなく、編集や習熟もしづらいことから「中途半端」「使えない」という評価になっていました(自分も使っていませんでした)。

その後、Cocoa-AppleScript Appletの機能要素をさらにダウンサイジングして、スクリプトエディタ上で手軽に記述・実行ができるように進化したのが現在・広くつかわれているCocoa Scripting環境です。

ただ、使いやすくなって広く使われるようになったはいいものの、「Xcodeを使うまでもないが、もうちょっとCocoaの機能が利用できないか?」という意見も出るようになり、Cocoa-AppleScript Appletを再評価してもいいんじゃないかと考えるようになってきてはいます。

ちなみに、本Cocoa-AppleScript AppletでCustom Classを宣言しているのと同じような書き方で、通常のCocoa Scriptingの環境で動かすような変更を加えたScriptもEdama2さんが試していますが、それは「動かない」ということで結論が出ています。

AppleScript名:CocoaAppletAppDelegate.scpt
script CocoaAppletAppDelegate
  property parent : class "NSObject"
  
  
property _clock_text_view : missing value –> 時計用の文字列
  
property _clock_timer : missing value –> 時計用のNSTimer
  
  
on applicationWillFinishLaunching:aNotification
    my raizeWindow()
  end applicationWillFinishLaunching:
  
  
on applicationShouldTerminate:sender
    my _clock_timer’s invalidate()
    
return current application’s NSTerminateNow
  end applicationShouldTerminate:
  
  
# ウィンドウを作成
  
on raizeWindow()
    
    
# 時計用の文字を作成
    
tell current application’s NSTextView’s alloc()
      tell initWithFrame_(current application’s NSMakeRect(35, 120, 300, 40))
        setRichText_(true)
        
useAllLigatures_(true)
        
setTextColor_(current application’s NSColor’s whiteColor())
        
setFont_(current application’s NSFont’s fontWithName:"Arial-Black" |size|:48)
        
setBackgroundColor_(current application’s NSColor’s colorWithDeviceRed:0.0 green:0.0 blue:0.0 alpha:0.0)
        
setAlphaValue_(1.0)
        
setEditable_(false)
        
–setString_("00:00:00")
        
        
set my _clock_text_view to it
      end tell
    end tell
    
    
# 時計を更新するNSTimerを作成
    
set my _clock_timer to current application’s NSTimer’s scheduledTimerWithTimeInterval:1 target:me selector:"idleHandler:" userInfo:(missing value) repeats:true
    
    
    
# 丸いViewを作成
    
set aFrame to current application’s NSMakeRect(0, 0, 300, 300)
    
tell current application’s RoundView’s alloc()
      tell initWithFrame_(aFrame)
        setNeedsDisplay_(true)
        
setSubviews_({my _clock_text_view})
        
set customView to it
      end tell
    end tell
    
    
#スクリーンのサイズを調べる
    
set aScreen to current application’s NSScreen’s mainScreen()
    
    
# Window
    
set aBacking to current application’s NSWindowStyleMaskBorderless
    
–set aBacking to current application’s NSBorderlessWindowMask
    
set aDefer to current application’s NSBackingStoreBuffered
    
tell current application’s CustomWindow’s alloc()
      tell initWithContentRect_styleMask_backing_defer_screen_(aFrame, aBacking, aDefer, false, aScreen)
        –setTitle_(uniqueName) –>タイトル
        
setBackgroundColor_(current application’s NSColor’s clearColor()) –>背景色
        
setContentView_(customView) –>内容ビューのセット
        
setDelegate_(me) –>デリゲート
        
setDisplaysWhenScreenProfileChanges_(true) –>スクリーンプロファイルが変更されたときウインドウの内容をアップデートするか
        
setHasShadow_(true) –>ウインドウに影があるか
        
setIgnoresMouseEvents_(false) –>マウスイベントを無視するか
        
–setLevel_((current application’s NSScreenSaverWindowLevel) + 1) –>ウインドウの前後関係の位置
        
setOpaque_(false) –>ウインドウを不透明にするか
        
setReleasedWhenClosed_(true) –>閉じたときにメモリを解放するか
        
        
#
        
|center|()
        
makeKeyAndOrderFront_(me) –>キーウインドウにして前面に持ってくる
        
–setFrame_display_(aFrame, true) –>表示
      end tell
    end tell
  end raizeWindow
  
  
#タイマー割り込み
  
on idleHandler:aSender
    set mesStr to time string of (current date)
    (
my _clock_text_view)’s setString:mesStr
  end idleHandler:
end script

script CustomWindow
  property parent : class "NSWindow"
  
property canBecomeKeyWindow : true
  
  
property _initial_location : missing value
  
  
on mouseDown:theEvent
    set my _initial_location to theEvent’s locationInWindow()
  end mouseDown:
  
  
on mouseDragged:theEvent
    –set res to display dialog "mouseDragged" buttons {"OK"} default button "OK"
    
try
      set screenVisibleFrame to current application’s NSScreen’s mainScreen()’s visibleFrame()
      
set screenVisibleFrame to my myHandler(screenVisibleFrame)
      
set windowFrame to my frame()
      
set windowFrame to my myHandler(windowFrame)
      
set newOrigin to windowFrame’s origin
      
      
set currentLocation to theEvent’s locationInWindow()
      
set newOrigin’s x to (newOrigin’s x) + ((currentLocation’s x) – (_initial_location’s x))
      
set newOrigin’s y to (newOrigin’s y) + ((currentLocation’s y) – (_initial_location’s y))
      
      
set tmpY to ((newOrigin’s y) + (windowFrame’s |size|’s height))
      
set screenY to (screenVisibleFrame’s origin’s y) + (screenVisibleFrame’s |size|’s height)
      
if tmpY > screenY then
        set newOrigin’s y to (screenVisibleFrame’s origin’s y) + ((screenVisibleFrame’s |size|’s height) – (windowFrame’s |size|’s height))
      end if
      
      
my setFrameOrigin:newOrigin
    on error error_message number error_number
      set error_text to "Error: " & error_number & ". " & error_message
      
display dialog error_text buttons {"OK"} default button 1
      
return error_text
    end try
    
  end mouseDragged:
  
  
on myHandler(aFrame)
    if class of aFrame is list then
      set {{theX, theY}, {theWidth, theHeight}} to aFrame
      
set aFrame to {origin:{x:theX, y:theY}, |size|:{width:theWidth, height:theHeight}}
      
–set aFrame to current application’s NSMakeRect(theX, theY, theWidth, theHeight)
    end if
    
return aFrame
  end myHandler
end script

script RoundView
  property parent : class "NSView"
  
  
on drawRect:rect
    set aFrame to my frame()
    
set myColor to current application’s NSColor’s redColor()
    
    
tell current application’s NSBezierPath
      tell bezierPathWithOvalInRect_(aFrame)
        myColor’s |set|()
        
fill()
      end tell
    end tell
  end drawRect:
end script

★Click Here to Open This Script 

Posted in GUI | Tagged 10.14savvy 10.15savvy NSBezierPath NSColor NSScreen NSTextView NSTimer NSView NSWindow | Leave a comment

display text fields Library v1.3

Posted on 12月 31, 2019 by Takaaki Naganoya

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

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

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

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

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

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

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

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

AppleScript名:文字列で指定したAppleScriptの実行結果をテキストで取得する v2.scpt
— Created 2016-01-08 by Takaaki Naganoya
— 2016 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "OSAKit"
use framework "AppKit"
use tfLib : script "display text fields"

property OSAScript : a reference to current application’s OSAScript
property NSTextView : a reference to current application’s NSTextView
property OSAScriptView : a reference to current application’s OSAScriptView
property OSAScriptController : a reference to current application’s OSAScriptController

property myRes : ""

–OSのメジャーバージョンを数値で取得
set osVer to system attribute "sys2"

if osVer ≥ 15 then
  set srcStr to "tell application \"Music\"
  set aSel to first item of selection
  set aRes to (properties of aSel)
end tell"
else
  set srcStr to "tell application \"iTunes\"
  set aSel to first item of selection
  set aRes to (properties of aSel)
end tell"
end if

my performSelectorOnMainThread:"getResultStringFromScript:" withObject:(srcStr) waitUntilDone:true

set aRes to getListFromText(myRes) of me

set aList to {}
set bList to {}
set aLen to length of aRes

repeat with i from 1 to aLen
  set {aCon, bCon} to contents of item i of aRes
  
set the end of aList to aCon
  
set the end of bList to bCon
end repeat

confirm text fields main message "Track Info" sub message "Properties about selected track" key list aList value list bList

–Get AppleScript’s Result as string
on getResultStringFromScript:paramObj
  set srcStr to paramObj as string
  
set myRes to ""
  
  
set targX to 500 –View Width
  
set targY to 200 –View Height
  
  
set osaCon to OSAScriptController’s alloc()’s init()
  
set osaView to OSAScriptView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, targX, targY))
  
  
set resView to NSTextView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, targX, targY))
  
resView’s setRichText:true
  
resView’s useAllLigatures:true
  
  
osaCon’s setScriptView:osaView
  
osaCon’s setResultView:resView
  
  
osaView’s setString:srcStr
  
osaCon’s runScript:(missing value)
  
  
set myRes to resView’s |string|() as string
end getResultStringFromScript:

–スクリプトエディタのresult欄に返ってきたテキストをリストに変える
on getListFromText(aText)
  
  
script getListFromTextO
    property aaText : ""
    
property gList : {}
    
property outList : {}
    
property aG : ""
    
property valList : {}
  end script
  
  
copy aText to (aaText of getListFromTextO)
  
  
set (gList of getListFromTextO) to {}
  
set (outList of getListFromTextO) to {}
  
set (aG of getListFromTextO) to ""
  
set (valList of getListFromTextO) to {}
  
  
if (aaText of getListFromTextO) does not start with "{" and (aaText of getListFromTextO) does not end with "}" then
    return {}
  end if
  
  
set aLen to length of (aaText of getListFromTextO)
  
set (aG of getListFromTextO) to text 2 thru -2 of (aaText of getListFromTextO)
  
set (gList of getListFromTextO) to characters of (aG of getListFromTextO)
  
  
  
set sPos to 2 –1文字目は\"{\"なので2文字目からスキャンを開始する
  
set ePos to 2
  
  
set imdF to false –Immediate Data Flag(文字列中を示すダブルクォート内の場合にはtrueになる)
  
set listF to 0 –stacking段数が入る
  
  
set attrF to true –属性ラベルスキャン時にtrue、データ末尾スキャン時にfalse
  
  
  
repeat with i in (gList of getListFromTextO)
    
    
set j to contents of i
    
    
if attrF = true and imdF = false and listF = 0 then
      
      
–属性値部分の末尾検出
      
if j = ":" then
        if text sPos thru sPos of (aaText of getListFromTextO) = " " then
          set sPos to sPos + 1
        end if
        
set anOut to text sPos thru ePos of (aaText of getListFromTextO)
        
set sPos to ePos + 1
        
set the end of (valList of getListFromTextO) to anOut
        
set attrF to false –データのスキャンを開始する
        
set imdF to false
        
set listF to 0
      end if
      
    else if imdF = false and listF = 0 and j = "," then
      
      
–データ部分の末尾検出
      
set anOut to text sPos thru (ePos – 1) of (aaText of getListFromTextO)
      
set sPos to ePos + 1
      
set the end of (valList of getListFromTextO) to anOut
      
set the end of (outList of getListFromTextO) to (valList of getListFromTextO)
      
set (valList of getListFromTextO) to {}
      
      
set attrF to true –次が属性値ラベルであることを宣言
      
set imdF to false
      
set listF to 0
      
    else if j = "{" then
      if imdF = false then
        set listF to listF + 1 –1段スタックにpush
      end if
    else if j = "}" then
      if imdF = false then
        set listF to listF – 1 –1段スタックからpop
      end if
    else if j = "\"" then
      if imdF = true then
        set imdF to false
      else
        set imdF to true
      end if
    end if
    
    
set ePos to ePos + 1
    
  end repeat
  
  
–ラストのデータ部分を出力
  
try
    set the end of (valList of getListFromTextO) to text sPos thru (ePos – 1) of (aaText of getListFromTextO)
    
set the end of (outList of getListFromTextO) to (valList of getListFromTextO)
  on error
    false
  end try
  
  
return contents of (outList of getListFromTextO)
  
end getListFromText

★Click Here to Open This Script 

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

指定のフォントとサイズに該当するテキストを抽出する v3

Posted on 12月 1, 2019 by Takaaki Naganoya

指定のRTFファイルから書式情報を取得し、フォント名とフォントサイズのペアをスタイルを反映させたポップアップメニューで選択。RTFの内容を解析したのち、ダイアログが表示されます(ここの所要時間は読ませるRTFのサイズ次第)。ポップアップメニューで書式を選ぶと、すぐさま抽出した箇所をすべてまとめて表示します。

–> Watch Demo Movie

–> Download Script Bundle with Sample data

ダイアログ表示前に書式ごとの抽出を完了し、個別のTabViewに抽出後の文字データを展開しておくので、ポップアップメニューから選択すると、展開ずみのデータを入れてあるTabViewに表示を切り替えるだけ。切り替え時に計算は行わないため、すぐに抽出ずみの文字データが表示されるという寸法です。

今回は短いサンプルデータを処理してみましたが、サンプル抽出時にあらかじめ範囲指定するなどして、データ処理規模を限定することで処理時間を稼ぐこともできることでしょう。

テキストエディットでオープン中のRTF書類のパスを取得して、それを処理対象にしてもいいでしょう。

ただし、やっつけで作ったのでスクリプトエディタ上でCommand-Control-Rで実行しないと動きません(メインスレッド実行をプログラムで強制しても、途中でクラッシュしてしまいます)。それほど時間もかけずに作ったやっつけプログラムなので、あまり原因追求も行えずそのままです。

AppleScript名:アラートダイアログ+Tab View v3.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/09/16
—
–  Copyright © 2019 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"
use rtfLib : script "readStyledTextLib"
use parseLib : script "parseAttrLib"

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 NSMenu : a reference to current application’s NSMenu
property NSArray : a reference to current application’s NSArray
property NSTabView : a reference to current application’s NSTabView
property NSPredicate : a reference to current application’s NSPredicate
property NSTextView : a reference to current application’s NSTextView
property NSMenuItem : a reference to current application’s NSMenuItem
property NSTabViewItem : a reference to current application’s NSTabViewItem
property NSPopUpButton : a reference to current application’s NSPopUpButton
property 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 NSLigatureAttributeName : a reference to current application’s NSLigatureAttributeName
property NSMutableAttributedString : a reference to current application’s NSMutableAttributedString
property NSStrokeWidthAttributeName : a reference to current application’s NSStrokeWidthAttributeName
property NSUnderlineStyleAttributeName : a reference to current application’s NSUnderlineStyleAttributeName
property NSForegroundColorAttributeName : a reference to current application’s NSForegroundColorAttributeName

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

property returnCode : 0

property aTabV : missing value
property selectedNum : {}

set aFile to choose file of type {"public.rtf"}

set aStyledStr to readRTFfile(aFile) of rtfLib
set paramObj to {myMessage:"Select Style", mySubMessage:"Select style you want to filter", viewWidth:800, viewHeight:400, myStyledStr:aStyledStr}

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

on dispTabViewWithAlertdialog:paramObj
  –Receive Parameters
  
set aMainMes to (myMessage of paramObj) as string –Main Message
  
set aSubMes to (mySubMessage of paramObj) as string –Sub Message
  
set aWidth to (viewWidth of paramObj) as integer –TextView width
  
set aHeight to (viewHeight of paramObj) as integer –TextView height
  
set aStyledStr to (myStyledStr of paramObj)
  
  
set attrResTmp to getAttributeRunsFromAttrString(aStyledStr) of parseLib
  
set attrList to attributes of attrResTmp
  
set menuStyle to menuList of attrResTmp
  
  
set selectedNum to {}
  
  
set aView to NSView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aWidth, aHeight))
  
  
–Ppopup Buttonをつくる
  
set a1Button to NSPopUpButton’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, aHeight – 20, 400, 20)) pullsDown:false
  
a1Button’s removeAllItems()
  
  
–WYSIWHG popup menuをつくる
  
set a1Menu to NSMenu’s alloc()’s init()
  
repeat with i from 1 to (length of menuStyle)
    set {tmpFont, tmpSize} to contents of item i of menuStyle
    
set aTitle to (tmpFont & " " & tmpSize as string) & " point"
    
set aMenuItem to (NSMenuItem’s alloc()’s initWithTitle:aTitle action:"actionHandler:" keyEquivalent:"")
    
    
set attributedTitle to makeRTFfromParameters(aTitle, tmpFont, tmpSize, NSColor’s blackColor()) of me
    
    (
aMenuItem’s setEnabled:true)
    (
aMenuItem’s setTarget:me)
    (
aMenuItem’s setTag:(i as string))
    (
aMenuItem’s setAttributedTitle:(attributedTitle))
    (
a1Menu’s addItem:aMenuItem)
  end repeat
  
  
–Ppopup Buttonにmenuをつける
  
a1Button’s setMenu:a1Menu
  
  
–Make Tab View
  
set aTabV to NSTabView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aWidth, aHeight – 30))
  
aTabV’s setTabViewType:(TabPosition)
  
  
  
–TabViewに中身を入れる
  
repeat with i from 1 to (length of menuStyle)
    set {tmpFont, tmpSize} to contents of item i of menuStyle
    
set tmpKey to (tmpFont as string) & "/" & (tmpSize as string)
    
set tmpArry to filterRecListByLabel1(attrList, "styleKey2 == ’" & tmpKey & "’") of me
    
set tmpStr to (tmpArry’s valueForKeyPath:"stringVal") as list
    
    
set aTVItem to (NSTabViewItem’s alloc()’s initWithIdentifier:(i as string))
    (
aTVItem’s setLabel:(i as string))
    
    
    
set aTextView to (NSTextView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aWidth – 10, aHeight – 10)))
    (
aTextView’s setRichText:true)
    
set tmpAttr to makeRTFfromParameters(tmpStr as string, tmpFont, tmpSize, NSColor’s blackColor()) of me
    (
aTextView’s textStorage()’s appendAttributedString:tmpAttr)
    
    (
aTVItem’s setView:aTextView)
    
    (
aTabV’s addTabViewItem:aTVItem)
  end repeat
  
  
  
aView’s setSubviews:{a1Button, aTabV}
  
aView’s setNeedsDisplay:true
  
  
  
— set up alert
  
set theAlert to NSAlert’s alloc()’s init()
  
tell theAlert
    –for Messages
    
its setMessageText:(aMainMes)
    
its setInformativeText:(aSubMes)
    
    
–for Buttons
    
its addButtonWithTitle:"OK"
    
its addButtonWithTitle:"Cancel"
    
    
–Add Accessory View
    
its setAccessoryView:(aView)
    
    
–for Help Button
    
its setShowsHelp:(true)
    
its setDelegate:(me)
  end tell
  
  
  
— show alert in modal loop
  
NSRunningApplication’s currentApplication()’s activateWithOptions:0
  
my performSelectorOnMainThread:"doModal:" withObject:(theAlert) waitUntilDone:true
  
if (my returnCode as number) = 1001 then error number -128
  
  
set selectedNum to contents of item ((a1Button’s indexOfSelectedItem()) + 1) of menuStyle
end dispTabViewWithAlertdialog:

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

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

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

–書式つきテキストを組み立てる
on makeRTFfromParameters(aStr as string, aFontName as string, aFontSize as real, aColor)
  –フォント
  
set aVal1 to NSFont’s fontWithName:(aFontName) |size|:aFontSize
  
set aKey1 to (NSFontAttributeName)
  
  
–色
  
set aVal2 to aColor
  
set aKey2 to (NSForegroundColorAttributeName)
  
  
–カーニング
  
set aVal3 to 0.0
  
set akey3 to (NSKernAttributeName)
  
  
–アンダーライン
  
set aVal4 to 0
  
set akey4 to (NSUnderlineStyleAttributeName)
  
  
–リガチャ
  
–set aVal5 to 2 –全てのリガチャを有効にする
  
–set akey5 to ( NSLigatureAttributeName)
  
  
–枠線(アウトライン)
  
–set aVal6 to outlineNum
  
–set akey6 to ( NSStrokeWidthAttributeName)
  
  
  
set keyList to {aKey1, aKey2, akey3, akey4}
  
set valList to {aVal1, aVal2, aVal3, aVal4}
  
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 filterRecListByLabel1(aRecList as list, aPredicate as string)
  set aArray to NSArray’s arrayWithArray:aRecList
  
set aPredicate to NSPredicate’s predicateWithFormat:aPredicate
  
set filteredArray to aArray’s filteredArrayUsingPredicate:aPredicate
  
set bList to filteredArray
  
return bList
end filterRecListByLabel1

★Click Here to Open This Script 

Posted in Color dialog Font GUI Require Control-Command-R to run RTF | Tagged 10.14savvy 10.15savvy NSAlert NSArray NSColor NSFont NSFontAttributeName NSForegroundColorAttributeName NSKernAttributeName NSLigatureAttributeName NSMenu NSMenuItem NSMutableAttributedString NSMutableDictionary NSPopUpButton NSPredicate NSRunningApplication NSStrokeWidthAttributeName NSTabView NSTabViewItem NSTextView NSUnderlineStyleAttributeName NSView | 1 Comment

透明ウィンドウで時計表示

Posted on 10月 2, 2019 by Takaaki Naganoya

透明のNSTextView+NSWindowで時計を表示するAppleScriptです。ありものを組み合わせて作ってみました。

テキストビュー+ボタンをつくる ScriptにTimerを組み合わせたぐらいです。macOS標準装備のスクリプトエディタ上でそのまま動きますし、Script Debugger上でも動作確認ずみです。

この手のプログラムは初心者が割と作りたくなるものの、作ってもそれほど役に立たない上に、「まあ、こんなもんか」という程度にしかなりません。初心者向けといえば初心者向けですが、記述量がそれほど少なくないのが困りものです(Xcode上でAppleScriptでCocoa-Appを書いたほうがずっと短く書けることでしょう)。

それもこれも、実際に動かしてみないとわからないことでしょう。Safariで表示中の表だけCSVに書き出すScriptなどと比べると、ものすごく面白くありません。

AppleScript名:テキストビュー+ボタンを作成(フォント指定)_+Timer
— Created 2019-10-02 by Takaaki Naganoya
— 2019 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"

property NSFont : a reference to current application’s NSFont
property NSColor : a reference to current application’s NSColor
property NSTimer : a reference to current application’s NSTimer
property NSScreen : a reference to current application’s NSScreen
property NSButton : a reference to current application’s NSButton
property NSWindow : a reference to current application’s NSWindow
property NSSplitView : a reference to current application’s NSSplitView
property NSTextView : a reference to current application’s NSTextView
property NSWindowController : a reference to current application’s NSWindowController
property NSTitledWindowMask : a reference to current application’s NSTitledWindowMask
property NSFloatingWindowLevel : a reference to current application’s NSFloatingWindowLevel
property NSBackingStoreBuffered : a reference to current application’s NSBackingStoreBuffered

property windisp : false
property aView : missing value

set aFontName to "Arial-Black"
set aWidth to 350
set aHeight to 120
set aTitle to "Clock Test" –Window Title
set aButtonMSG to "OK" –Button Title

set aRes to checkExistenceOfFont(aFontName) of me
if aRes = false then
  display dialog "There is no <" & aFontName & "> font. Select another one." –No font
  
return
end if
set dispStr to ""

set paramObj to {myWidth:aWidth, myHeight:aHeight, myTitle:aTitle, myBMes:aButtonMSG, myTimeOut:180, myFontID:aFontName, myFontSize:48}
–my dispTextView:aRecObj
my performSelectorOnMainThread:"dispTextView:" withObject:paramObj waitUntilDone:true

on dispTextView:aRecObj
  set aWidth to myWidth of aRecObj as integer
  
set aHeight to myHeight of aRecObj as integer
  
set aTitle to myTitle of aRecObj as string
  
set aButtonMSG to myBMes of aRecObj as string
  
set timeOutSecs to myTimeOut of aRecObj as integer
  
set fontID to myFontID of aRecObj as string
  
set fontSize to myFontSize of aRecObj as integer
  
  
set dispStr to ""
  
  
–Make Timer
  
set aTimer to NSTimer’s scheduledTimerWithTimeInterval:1 target:me selector:"idleHandler:" userInfo:(missing value) repeats:true
  
  
— Text View Background color
  
set aColor to NSColor’s colorWithDeviceRed:0.0 green:0.0 blue:0.0 alpha:0.0
  
set (my windisp) to true
  
  
–Text View+Scroll Viewをつくる
  
set aView to NSTextView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aWidth, aHeight))
  
aView’s setRichText:true
  
aView’s useAllLigatures:true
  
aView’s setTextColor:(NSColor’s magentaColor())
  
aView’s setFont:(NSFont’s fontWithName:fontID |size|:fontSize)
  
aView’s setBackgroundColor:aColor
  
aView’s setAlphaValue:1.0
  
aView’s setEditable:false
  
–aView’s enclosingScrollView()’s setHasVerticalScroller:true
  
  
–Buttonをつくる
  
set bButton to (NSButton’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aWidth, 40)))
  
bButton’s setTitle:aButtonMSG
  
bButton’s setTarget:me
  
bButton’s setAction:("clicked:")
  
  
–SplitViewをつくる
  
set aSplitV to NSSplitView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aHeight, aWidth))
  
aSplitV’s setVertical:false
  
  
aSplitV’s addSubview:aView
  
aSplitV’s addSubview:bButton
  
aSplitV’s setNeedsDisplay:true
  
  
–WindowとWindow Controllerをつくる
  
set aWin to makeWinWithView(aSplitV, aWidth, aHeight, aTitle, 1.0)
  
aWin’s makeKeyAndOrderFront:(missing value)
  
set wController to NSWindowController’s alloc()
  
wController’s initWithWindow:aWin
  
aWin’s makeFirstResponder:aView
  
aView’s setString:dispStr
  
wController’s showWindow:me
  
  
set aCount to timeOutSecs * 10 –timeout seconds * 10
  
repeat aCount times
    if (my windisp) = false then
      exit repeat
    end if
    
delay 0.1
    
set aCount to aCount – 1
  end repeat
  
  
aTimer’s invalidate() –Stop Timer
  
my closeWin:aWin
  
end dispTextView:

–Button Clicked Event Handler
on clicked:aSender
  set (my windisp) to false
end clicked:

–make Window for Input
on makeWinWithView(aView, aWinWidth, aWinHeight, aTitle, alphaV)
  set aScreen to NSScreen’s mainScreen()
  
set aFrame to {{0, 0}, {aWinWidth, aWinHeight}}
  
set aBacking to NSTitledWindowMask –NSBorderlessWindowMask
  
set aDefer to NSBackingStoreBuffered
  
  
— Window
  
set aWin to NSWindow’s alloc()
  (
aWin’s initWithContentRect:aFrame styleMask:aBacking backing:aDefer defer:false screen:aScreen)
  
aWin’s setBackgroundColor:(NSColor’s clearColor())
  
  
aWin’s setTitle:aTitle
  
aWin’s setDelegate:me
  
aWin’s setDisplaysWhenScreenProfileChanges:true
  
aWin’s setHasShadow:true
  
aWin’s setIgnoresMouseEvents:false
  
aWin’s setLevel:(NSFloatingWindowLevel)
  
aWin’s setOpaque:false
  
aWin’s setAlphaValue:alphaV –append
  
aWin’s setReleasedWhenClosed:true
  
aWin’s |center|()
  
–aWin’s makeKeyAndOrderFront:(me)
  
  
— Set Custom View
  
aWin’s setContentView:aView
  
  
return aWin
end makeWinWithView

–close win
on closeWin:aWindow
  aWindow’s |close|()
end closeWin:

–指定PostScript名称のフォントがコンピューター上に存在するかどうかチェック
on checkExistenceOfFont(fontName as string)
  if fontName = "" then return false
  
set aFont to NSFont’s fontWithName:fontName |size|:9.0
  
if aFont = missing value then
    return false
  else
    return true
  end if
end checkExistenceOfFont

–タイマー割り込み
on idleHandler:aSender
  set mesStr to time string of (current date)
  
aView’s setString:mesStr
end idleHandler:

★Click Here to Open This Script 

Posted in Color dialog | Tagged 10.12savvy 10.13savvy 10.14savvy NSBackingStoreBuffered NSButton NSColor NSFloatingWindowLevel NSFont NSScreen NSSplitView NSTextView NSTimer NSTitledWindowMask NSWindow NSWindowController | 6 Comments

アラートダイアログ上にTexViewを表示_ヘルプ付き_半透明_Float_SuppressionButtonつき

Posted on 7月 10, 2019 by Takaaki Naganoya

アラートダイアログ上にTextViewを表示して、指定のテキストを閲覧するAppleScriptです。

Xcode上でNSAlert.hを調べ、アラートダイアログに指定できる各種オプションを指定してみました。NSWindowLevelの変更は効いていないみたいですけれども。

AppleScript名:アラートダイアログ上にTexViewを表示_ヘルプ付き_半透明_Float_SuppressionButtonつき
— Created 2019-07-09 by Takaaki Naganoya
— 2019 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"

property |NSURL| : a reference to current application’s |NSURL|
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 NSTextView : a reference to current application’s NSTextView
property NSScrollView : a reference to current application’s NSScrollView
property NSUserDefaults : a reference to current application’s NSUserDefaults
property NSRunningApplication : a reference to current application’s NSRunningApplication
property NSModalPanelWindowLevel : a reference to current application’s NSModalPanelWindowLevel

property returnCode : 0
property supState : false

set asStr to do shell script "cal 2019"
set paramObj to {myMessage:"Main Message", mySubMessage:"Sub information", mes1:(asStr), mesWidth:450, mesHeight:200, fontName:"Courier", fontSize:11.0, suppressionMes:"Some Option"}

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

return (my supState)

on dispTextViewWithAlertdialog:paramObj
  –Receive Parameters
  
set aMainMes to (myMessage of paramObj) as string –Main Message
  
set aSubMes to (mySubMessage of paramObj) as string –Sub Message
  
set mesStr to (mes1 of paramObj) as string –Text Input field 1 Label
  
set aWidth to (mesWidth of paramObj) as integer –TextView width
  
set aHeight to (mesHeight of paramObj) as integer –TextView height
  
set aFontName to (fontName of paramObj) as string –TextView font name
  
set aFontSize to (fontSize of paramObj) as real –TextView font size
  
set aSupMes to (suppressionMes of paramObj) as string –Suppression Button Titile
  
  
–Detect Dark Mode
  
set dMode to retLIghtOrDark() of me
  
if dMode = true then
    set tvCol to 1
    
set tvAlpha to 0.8
    
set bCol to 0.1
    
set bAlpha to 0.8
    
set contentCol to (NSColor’s cyanColor())
  else
    set tvCol to 0
    
set tvAlpha to 0.1
    
set bCol to 1
    
set bAlpha to 0.5
    
set contentCol to (NSColor’s grayColor())
  end if
  
  
— Create a TextView with Scroll View
  
set aScroll to NSScrollView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aWidth, aHeight))
  
set aView to NSTextView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aWidth, aHeight))
  
set aColor to NSColor’s colorWithDeviceRed:0.0 green:0.0 blue:0.0 alpha:(tvAlpha)
  
  
aView’s setRichText:true
  
aView’s useAllLigatures:true
  
aView’s setTextColor:(contentCol)
  
aView’s setFont:(NSFont’s fontWithName:aFontName |size|:aFontSize)
  
  
aView’s setDrawsBackground:false
  
  
  
aView’s setBackgroundColor:aColor
  
aView’s setOpaque:(false)
  
aView’s setString:mesStr
  
aScroll’s setDocumentView:aView
  
–aScroll’s setBorderType:(current application’s NSBezelBorder)
  
–aScroll’s setBorderType:(current application’s NSGrooveBorder)
  
–aScroll’s setBorderType:(current application’s NSLineBorder)
  
aScroll’s setBorderType:(current application’s NSNoBorder)
  
  
–Ruler
  
–aScroll’s setHasHorizontalRuler:(true)
  
–aScroll’s setRulersVisible:(true)
  
  
aView’s enclosingScrollView()’s setHasVerticalScroller:true
  
  
set anImage to current application’s NSImage’s imageNamed:(current application’s NSImageNameComputer)
  
  
— set up alert
  
set theAlert to NSAlert’s alloc()’s init()
  
tell theAlert
    its setIcon:(anImage)
    
    
–for Messages
    
its setMessageText:(aMainMes)
    
its setInformativeText:(aSubMes)
    
    
–for Buttons
    
its addButtonWithTitle:"OK"
    
its addButtonWithTitle:"Cancel"
    
    
–Add Accessory View
    
its setAccessoryView:(aScroll)
    
    
–for Help Button
    
its setShowsHelp:(true)
    
its setDelegate:(me)
    
    
its setAlertStyle:0 —-0…2
    
    
its setShowsSuppressionButton:(true) –「今後このメッセージを表示しない」チェックボックスを表示
    
    
set suppressionB to its suppressionButton
    
set myWindow to its |window|
  end tell
  
  
myWindow’s setOpaque:(false)
  
myWindow’s setBackgroundColor:(NSColor’s colorWithCalibratedWhite:(bCol) alpha:(bAlpha))
  
myWindow’s setLevel:(NSModalPanelWindowLevel)
  
  
suppressionB’s setTitle:(aSupMes)
  
suppressionB’s setState:(true) —default state
  
  
— 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 supState to (suppressionB’s state) as boolean
end dispTextViewWithAlertdialog:

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

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

–ダークモードの判定。ダークモード時:true、ライトモード時:falseが返る。System Eventsを使っていないのは、macOS 10.14以降対策(承認を取得しなくてもいいように)
on retLIghtOrDark()
  set curMode to (current application’s NSUserDefaults’s standardUserDefaults()’s stringForKey:"AppleInterfaceStyle") as string
  
return (curMode = "Dark") as boolean
end retLIghtOrDark

★Click Here to Open This Script 

Posted in Color dialog Font GUI Icon Image | Tagged 10.12savvy 10.13savvy 10.14savvy NSAlert NSColor NSFont NSModalPanelWindowLevel NSRunningApplication NSScrollView NSTextView NSURL NSUserDefaults | Leave a comment

アラートダイアログ上にTexViewを表示_ヘルプ付き_半透明

Posted on 7月 8, 2019 by Takaaki Naganoya

アラートダイアログ上にTextViewを表示して、指定のテキストを閲覧するAppleScriptです。

# 前バージョンの「自分のソースコード」表示というのは意味不明だったので、プロセス一覧を取得してみました

ヘルプボタン(?)を付け、アラートダイアログのウィンドウ背景を半透明に設定。そのままでは配色の都合上Dark Mode/Light Modeの切り替え時に読みづらい文字なども出てきたため、モード判定を行って表示色などを変更しています。

アプレット書き出ししたときに、スクロールビューがマウスのスクロールホイールの操作に追従したスクロールを行ってくれないので、そのあたり何か追加でNSScrollViewに設定を行う必要があるのだろうかと。


▲スクリプトエディタ上で実行@macOS 10.14.5。左がLight Mode、右がDark Mode(以下同様)


▲ヘルプボタンをクリックしたところ。本当にアンカーを指定して指定のヘルプコンテンツを表示させることもできる模様。そのための基礎的な試験


▲AppleScriptアプレット書き出しして実行したところ


▲Script Debugger上で実行@macOS 10.14.5。Dark Modeに対応できていない(次バージョンで対応することでしょう)


▲Script DebuggerからAppleScript Applet (Enhanced)で書き出して実行したところ。マウスのスクロールホイールの操作を受け付けて文字がスクロールする

AppleScript名:アラートダイアログ上にTexViewを表示_ヘルプ付き_半透明
— Created 2019-07-08 by Takaaki Naganoya
— 2019 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"

property |NSURL| : a reference to current application’s |NSURL|
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 NSTextView : a reference to current application’s NSTextView
property NSScrollView : a reference to current application’s NSScrollView
property NSRunningApplication : a reference to current application’s NSRunningApplication

property returnCode : 0

–Get Self Source Code (a kind of joke)
set asStr to do shell script "ps -ax"
set paramObj to {myMessage:"Main Message", mySubMessage:"Sub information", mes1:(asStr), mesWidth:400, mesHeight:200, fontName:"HiraginoSans-W3", fontSize:11.0}

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

on dispTextViewWithAlertdialog:paramObj
  –Receive Parameters
  
set aMainMes to (myMessage of paramObj) as string –Main Message
  
set aSubMes to (mySubMessage of paramObj) as string –Sub Message
  
set mesStr to (mes1 of paramObj) as string –Text Input field 1 Label
  
set aWidth to (mesWidth of paramObj) as integer –TextView width
  
set aHeight to (mesHeight of paramObj) as integer –TextView height
  
set aFontName to (fontName of paramObj) as string –TextView font name
  
set aFontSize to (fontSize of paramObj) as real –TextView font size
  
  
–Detect Dark Mode
  
set dMode to retLIghtOrDark() of me
  
if dMode = true then
    set tvCol to 1
    
set tvAlpha to 0.8
    
set bCol to 0.1
    
set bAlpha to 0.8
  else
    set tvCol to 1
    
set tvAlpha to 1.0
    
set bCol to 1
    
set bAlpha to 0.7
  end if
  
  
— Create a TextView with Scroll View
  
set aScroll to NSScrollView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aWidth, aHeight))
  
set aView to NSTextView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aWidth, aHeight))
  
aView’s setRichText:true
  
aView’s useAllLigatures:true
  
aView’s setTextColor:(NSColor’s cyanColor()) –cyanColor
  
aView’s setFont:(NSFont’s fontWithName:aFontName |size|:aFontSize)
  
set aColor to NSColor’s colorWithDeviceRed:0.0 green:0.0 blue:0.0 alpha:(tvAlpha)
  
aView’s setBackgroundColor:aColor
  
aView’s setOpaque:(false)
  
aView’s setString:mesStr
  
aScroll’s setDocumentView:aView
  
aView’s enclosingScrollView()’s setHasVerticalScroller:true
  
  
— set up alert
  
set theAlert to NSAlert’s alloc()’s init()
  
tell theAlert
    –for Messages
    
its setMessageText:(aMainMes)
    
its setInformativeText:(aSubMes)
    
    
–for Buttons
    
its addButtonWithTitle:"OK"
    
its addButtonWithTitle:"Cancel"
    
    
–Add Accessory View
    
its setAccessoryView:(aScroll)
    
    
–for Help Button
    
its setShowsHelp:(true)
    
its setDelegate:(me)
    
    
set myWindow to its |window|
  end tell
  
  
myWindow’s setOpaque:(false)
  
myWindow’s setBackgroundColor:(NSColor’s colorWithCalibratedWhite:(bCol) alpha:(bAlpha))
  
  
— 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 dispTextViewWithAlertdialog:

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

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

–ダークモードの判定。ダークモード時:true、ライトモード時:falseが返る
on retLIghtOrDark()
  set curMode to (current application’s NSUserDefaults’s standardUserDefaults()’s stringForKey:"AppleInterfaceStyle") as string
  
return (curMode = "Dark") as boolean
end retLIghtOrDark

★Click Here to Open This Script 

Posted in Color dialog GUI | Tagged 10.11savvy 10.12savvy 10.13savvy 10.14savvy NSAlert NSColor NSFont NSRunningApplication NSScrollView NSTextView NSURL NSView | Leave a comment

アラートダイアログ上にTextViewを表示

Posted on 7月 8, 2019 by Takaaki Naganoya

アラートダイアログ上にTextViewを表示して、指定のテキストを閲覧するAppleScriptです。

とくにこれといって何か表示するものを思いつかなかったので、自分自身のソースコードを取得して表示しています。スクリプトエディタやScript Debugger上で実行した場合には自分自身のソースコードをテキストビュー上で表示します。

読み取り専用のスクリプトやアプレットで実行している場合にはソースコードを取得できません。何か適宜自分で表示させたいテキストを与えてみてください。

AppleScript名:アラートダイアログ上にTexViewを表示
— Created 2019-07-02 by Takaaki Naganoya
— 2019 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"
use framework "OSAKit"

property |NSURL| : a reference to current application’s |NSURL|
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 NSTextView : a reference to current application’s NSTextView
property NSScrollView : a reference to current application’s NSScrollView
property NSRunningApplication : a reference to current application’s NSRunningApplication
property OSAScript : a reference to current application’s OSAScript

property returnCode : 0

–Get Self Source Code (a kind of joke)
set mePath to path to me
set asStr to getASsourceFor(mePath) of me

set paramObj to {myMessage:"Main Message", mySubMessage:"Sub information", mes1:(asStr), mesWidth:400, mesHeight:200, fontName:"HiraginoSans-W3", fontSize:11.0}

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

on dispTextViewWithAlertdialog:paramObj
  –Receive Parameters
  
set aMainMes to (myMessage of paramObj) as string –Main Message
  
set aSubMes to (mySubMessage of paramObj) as string –Sub Message
  
set mesStr to (mes1 of paramObj) as string –Text Input field 1 Label
  
set aWidth to (mesWidth of paramObj) as integer –TextView width
  
set aHeight to (mesHeight of paramObj) as integer –TextView height
  
set aFontName to (fontName of paramObj) as string –TextView font name
  
set aFontSize to (fontSize of paramObj) as real –TextView font size
  
  
— Create a TextView with Scroll View
  
set aScroll to NSScrollView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aWidth, aHeight))
  
set aView to NSTextView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aWidth, aHeight))
  
aView’s setRichText:true
  
aView’s useAllLigatures:true
  
aView’s setTextColor:(current application’s NSColor’s cyanColor()) –cyanColor
  
aView’s setFont:(current application’s NSFont’s fontWithName:aFontName |size|:aFontSize)
  
set aColor to current application’s NSColor’s colorWithDeviceRed:0.0 green:0.0 blue:0.0 alpha:0.5
  
aView’s setBackgroundColor:aColor
  
aView’s setString:mesStr
  
aScroll’s setDocumentView:aView
  
aView’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
end dispTextViewWithAlertdialog:

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

–指定AppleScriptファイルのソースコードを取得する(実行専用Scriptからは取得できない)
— Original Created 2014-02-23 Shane Stanley
on getASsourceFor(anAlias as {alias, string})
  set aURL to |NSURL|’s fileURLWithPath:(POSIX path of anAlias)
  
set theScript to OSAScript’s alloc()’s initWithContentsOfURL:aURL |error|:(missing value)
  
  
if theScript is equal to missing value then
    error "Compile Error" — handle error
  else
    set sourceText to theScript’s source()
  end if
  
  
return sourceText as string
end getASsourceFor

★Click Here to Open This Script 

Posted in Color file File path Font GUI Text URL | Tagged 10.11savvy 10.12savvy 10.13savvy 10.14savvy NSAlert NSColor NSFont NSRunningApplication NSScrollView NSTextView NSURL OSAScript | Leave a comment

テキストから数値を抽出して度数分布集計 v3

Posted on 6月 29, 2019 by Takaaki Naganoya

CotEditorで編集中の最前面の書類の本文中から指定桁の数値を抽出して登場回数で度数分布の集計を行うAppleScriptです。

初版では、集計対象の数値を桁数で指定するという(使うのに)無茶な仕様になっていたので、この頭の悪い仕様に作った本人もめまいがしていました。

わざわざAppleScriptを使うのは、他のどの環境でも追いつけない高度な処理を行うことに意義があると思っています。

そこで、

 (1)数字部分をあらかじめ抽出して事前に集計(分布および最小値、最大値を計算)
 (2)事前集計結果をグラフ表示
 (3)集計対象の数字の範囲を最小値〜最大値までの間で指定できるように
 (4)パラメータの入力、および事前集計結果の表示を自前で作成したアラートダイアログで表示

といった変更を加えてみました。初版では「数字の桁数」というご無体な指定で数字を抽出していましたが、最初に最大値を計算しておいたことで、最大値の桁数ですべて数値を抽出し、最小値・最大値の間に収まる数値のみを抽出して度数分布を再計算しています(言うほど計算結果が変わってきたりはしないんですけど ^ー^;;)。

このぐらい行えば、安心して見られる感じでしょうか。

追記:
4.11といった文字が「4」と「11」に分離して認識されるようだったので数値として認識するCharacter setに「.」(小数点)および「,」(桁数区切り)を追加してみました。想定していた部分はうまくクリアしたものの、「REV.」の部分の「.」も認識して「0.411」のような数値として認識したようです。

このあたりに課題を残しつつも、全体として見ると当初からノイズとして除去する対象として考えていた箇所でもあったため、そんなもんだろうかと。

アラートダイアログに表示するテスト集計結果の文字が小さかったので、少し大きくしてみました。フォントについては「ヒラギノ角ゴシック W1」(PostScript名は「HiraginoSans-W1」)を指定しています。このあたりは好みに応じて変更してみるとよいでしょう。

巨大なテキスト(青空文庫の小説1作文まるごととか)を対象に処理していないので(画面キャプチャ掲載している程度のサイズ)そういう配慮は行っていません。仕事だと考慮しないでもないですが、必要と思われた処理をとりあえず組んでみた程度なので、そういうものだとお考えください。

–> Download Applet With Libraries (mainly for macOS 10.14 or later)

AppleScript名:テキストから数値を抽出して度数分布集計 v3.1
— Created 2019-06-29 by Takaaki Naganoya
— 2019 Piyomaru Software
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
use framework "AppKit"
use bPlus : script "BridgePlus" –https://www.macosxautomation.com/applescript/apps/BridgePlus.html

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 NSTextField : a reference to current application’s NSTextField
property NSTextView : a reference to current application’s NSTextView
property NSScrollView : a reference to current application’s NSScrollView
property NSRunningApplication : a reference to current application’s NSRunningApplication

–property theResult : 0
property returnCode : 0
property segRes : missing value

set segRes to missing value

tell application "CotEditor"
  if (count every document) = 0 then return –No Document
  
  
tell front document
    set aText to contents of it
    
set lineTerm to (line ending)
  end tell
  
  
–改行コードの選択(ドキュメントの状態から取得)
  
if lineTerm = LF then
    set aRet to ASCII character 10 –To avoid keyword conflict (string)
  else if lineTerm = CR then
    set aRet to ASCII character 13
  else if lineTerm = CRLF then
    set aRet to (ASCII character 13) & (ASCII character 10)
  else
    set aRet to ASCII character 10
  end if
end tell

–事前にテキストから自動で数値部分を抽出して分析
set cArray to extractNumberFromText(aText) of me
set aRes to (cArray’s valueForKeyPath:"@max.self")’s intValue()
set bRes to (cArray’s valueForKeyPath:"@min.self")’s intValue()
set cRes to (cArray’s valueForKeyPath:"@count")’s intValue()

–事前に数字の分布シミュレーションを計算
set tmpLen to count every character of (aRes as string)
set theList to my findPattern:("[0-9]{" & tmpLen & "}") inString:aText
set sampleStr to calculateNumFreq(cArray, "■", aRet, bRes, aRes, true) of me

set sampleStr to return & return & "テスト集計結果:" & return & return & sampleStr

–テキストからの数値抽出時のパラメータ取得
set paramObj to {myMessage:"テキスト内の数値の度数分布集計", mySubMessage:"集計対象の数値の範囲と、集計時のグラフ生成時の構成文字を指定してください", mes1:"最小値(min.)", mes1Default:(bRes as string), mes2:"最大値(max.)", mes2Default:(aRes as string), mes3:"出力文字", mes3Default:"絆", aSample:sampleStr}

–set segRes to my inputParametersFromAlertDialog:paramObj–for debugging
my performSelectorOnMainThread:"inputParametersFromAlertDialog:" withObject:(paramObj) waitUntilDone:true
if segRes = missing value then return –Cancel

–度数分布計算
set tmpLen to count every character of ((a2Res of segRes) as string)
set theList to my findPattern:("[0-9]{" & tmpLen & "}") inString:aText
set outStr to calculateNumFreq(cArray, a3Res of segRes, aRet, a1Res of segRes, a2Res of segRes, false) of me

–テキストエディタへの集計結果出力
tell application "CotEditor"
  tell front document
    set contents of it to (aText & aRet & aRet & "集計結果:" & aRet & aRet & outStr & aRet)
  end tell
end tell

on inputParametersFromAlertDialog:paramObj
  –Receive Parameters
  
set aMainMes to (myMessage of paramObj) as string –Main Message
  
set aSubMes to (mySubMessage of paramObj) as string –Sub Message
  
set mes1Label to (mes1 of paramObj) as string –Text Input field 1 Label
  
set mes2Label to (mes2 of paramObj) as string –Text Input field 2 Label
  
set mes3Label to (mes3 of paramObj) as string –Text Input field 3 Label
  
set aTextInputString to (mes1Default of paramObj) as string –Text Input field 1 Default value
  
set bTextInputString to (mes2Default of paramObj) as string –Text Input field 2 Default value
  
set cTextInputString to (mes3Default of paramObj) as string –Text Input field 2 Default value
  
set sampleString to (aSample of paramObj) as string
  
  
— Create a view
  
set theView to NSView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, 500, 400))
  
  
— create two input field and their labels pairs
  
–NSTextFields for Input
  
set aTextInput to makeNSTextField(100, 70, 140, 20, true, (aTextInputString), true, true) of me
  
set bTextInput to makeNSTextField(100, 35, 140, 20, true, (bTextInputString), true, true) of me
  
set cTextInput to makeNSTextField(100, 0, 140, 20, true, (cTextInputString), true, true) of me
  
  
–Labels
  
set a1TF to makeNSTextField(0, 70, 100, 20, false, (mes1Label), false, false) of me
  
set a2TF to makeNSTextField(0, 35, 100, 20, false, (mes2Label), false, false) of me
  
set a3TF to makeNSTextField(0, 0, 100, 20, false, (mes3Label), false, false) of me
  
  
–Sample Text View
  
set aColor to NSColor’s colorWithDeviceRed:0.0 green:0.0 blue:0.0 alpha:0.9
  
set tvScroll to NSScrollView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 120, 500, 300))
  
set tvView to NSTextView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 120, 500, 380))
  
tvView’s setRichText:true
  
tvView’s useAllLigatures:true
  
tvView’s setTextColor:(NSColor’s cyanColor()) —
  
tvView’s setFont:(current application’s NSFont’s fontWithName:"HiraginoSans-W1" |size|:16.0)
  
tvView’s setBackgroundColor:aColor
  
tvView’s setEditable:false
  
  
tvScroll’s setDocumentView:tvView
  
tvView’s enclosingScrollView()’s setHasVerticalScroller:true
  
tvView’s setString:(sampleString)
  
  
  
theView’s setSubviews:{a1TF, aTextInput, a2TF, bTextInput, a3TF, cTextInput, tvScroll}
  
  
— 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
  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
    set my segRes to missing value
  else
    set s1Val to (aTextInput’s integerValue()) as integer
    
set s2Val to (bTextInput’s integerValue()) as integer
    
set s3Val to (cTextInput’s stringValue()) as string
    
    
–return {a1Res:s1Val, a2Res:s2Val, a3Res:s3Val}–old version’s way to return values
    
set my segRes to {a1Res:s1Val, a2Res:s2Val, a3Res:s3Val}
  end if
end inputParametersFromAlertDialog:

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

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 Arrayで返す
on extractNumberFromText(aText)
  set aStr to current application’s NSString’s stringWithString:aText
  
–set nonDigitCharacterSet to (current application’s NSCharacterSet’s decimalDigitCharacterSet())’s invertedSet()
  
set nonDigitCharacterSet to (current application’s NSCharacterSet’s characterSetWithCharactersInString:"0123456789.,")’s invertedSet()
  
set bArray to (aStr’s componentsSeparatedByCharactersInSet:nonDigitCharacterSet)
  
  
–Sweep Blank Items
  
load framework –BridgePlus
  
set cArray to (current application’s SMSForder’s arrayByDeletingBlanksIn:(bArray))’s valueForKey:"intValue"
  
return cArray –return as NSArray
end extractNumberFromText

–正規表現でテキスト中から指定パターンに該当する箇所を抽出してリストで返す
on findPattern:thePattern inString:theString
  set theOptions to ((current application’s NSRegularExpressionDotMatchesLineSeparators) as integer) + ((current application’s NSRegularExpressionAnchorsMatchLines) as integer)
  
set theRegEx to current application’s NSRegularExpression’s regularExpressionWithPattern:thePattern options:theOptions |error|:(missing value)
  
set theFinds to theRegEx’s matchesInString:theString options:0 range:{location:0, |length|:length of theString}
  
set theFinds to theFinds as list — so we can loop through
  
set theResult to {} — we will add to this
  
set theNSString to current application’s NSString’s stringWithString:theString
  
repeat with i from 1 to count of items of theFinds
    set theRange to (item i of theFinds)’s range()
    
set end of theResult to (theNSString’s substringWithRange:theRange) as integer
  end repeat
  
return theResult
end findPattern:inString:

–1D Listをユニーク化してソート
on uniquifyAndSort1DList(theList as list, aBool as boolean)
  set aArray to current application’s NSArray’s arrayWithArray:theList
  
set bArray to aArray’s valueForKeyPath:"@distinctUnionOfObjects.self"
  
set aDdesc to current application’s NSSortDescriptor’s sortDescriptorWithKey:"self" ascending:aBool selector:"compare:"
  
set cArray to bArray’s sortedArrayUsingDescriptors:{aDdesc}
  
  
set bList to cArray as list
  
return bList
end uniquifyAndSort1DList

–度数分布集計して文字グラフ出力
on calculateNumFreq(theList, outChar, aLineTerminator, aMin, aMax, zeroPaddingF)
  set theCountedSet to current application’s NSCountedSet’s alloc()’s initWithArray:theList
  
set newArray to current application’s NSMutableArray’s new()
  
  
set kList to uniquifyAndSort1DList(theList, false) of me –降順ソート
  
set maxDigit to (count every character of (aMax as string))
  
  
repeat with i in kList
    if (i ≥ aMin) and (i ≤ aMax) then
      (newArray’s addObject:{theKey:i, theCount:(theCountedSet’s countForObject:i)})
    end if
  end repeat
  
  
set outStr to ""
  
  
repeat with i in newArray as list
    set j to (current application’s NSDictionary’s dictionaryWithDictionary:i)
    
set tmpStr to (j’s valueForKey:"theKey")
    
    
if zeroPaddingF = true then
      –Zero Pagging
      
set keyNumStr to numToZeroPaddingStr(tmpStr, maxDigit, "0") of me
    else
      –No Padding
      
copy (tmpStr as string) to keyNumStr
    end if
    
    
set outStr to outStr & keyNumStr & ":"
    
    
set aNum to (j’s valueForKey:"theCount")
    
repeat aNum times
      set outStr to outStr & outChar
    end repeat
    
    
set outStr to outStr & aLineTerminator
  end repeat
end calculateNumFreq

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

★Click Here to Open This Script 

Posted in list regexp Sort Text | Tagged 10.12savvy 10.13savvy 10.14savvy CotEditor NSAlert NSColor NSRunningApplication NSScrollView NSTextField NSTextView NSView | 1 Comment

ASの実行結果をNumbersの表に出力する

Posted on 4月 5, 2019 by Takaaki Naganoya

文字列で与えたAppleScriptを実行し、その実行結果をテキストで取得したうえにラベルと値に分割してNumbersの「表」に組み立てるAppleScriptです。

仕様書の作成とかテストデータの評価とかそういう仕事を行うさいに、プログラムコード(AppleScriptが出力するrecordとかlistとか)が読めない人向けに確認してもらうために作成したものです。

Numbersに出力すること自体にはさほど意味はありませんが(ExcelでもREST API経由でGoogle Spread Sheetに出力したっていいわけで)、とりあえずプログラムの結果出力になじみのない方々に計算結果を見ていただくためのものです。

AppleScriptの実行結果をスクリプトエディタではなくOSAScriptControllerなどから受け取る部品などが揃ってきたので、こういう加工も割とすぐにできていい感じです。

ちなみに、Numbersの表のセルに対して直接AppleScriptからデータを突っ込んでいますが、これはあらかじめ出力するデータ数が少ないことが見込まれているためです。多い場合(100件前後がひとつの基準に)には、CSVファイルに書き出してNumbersにオープンさせることになるでしょう。

例によって、Numbersの表セルに対してデータを突っ込むさいには非同期モードで実行して速度を稼いでいます。

AppleScript名:ASの実行結果をNumbersの表に出力する
— Created 2019/04/05 by Takaaki Naganoya
— 2019 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "OSAKit"
use framework "AppKit"
use bLus : script "BridgePlus"

property NSString : a reference to current application’s NSString
property NSThread : a reference to current application’s NSThread
property OSAScript : a reference to current application’s OSAScript
property NSTextView : a reference to current application’s NSTextView
property OSAScriptView : a reference to current application’s OSAScriptView
property OSAScriptController : a reference to current application’s OSAScriptController

property SMSForder : a reference to current application’s SMSForder

property theResult : "" –result

set origStr to "
tell application \"Numbers\"
  tell front document
    properties
  end tell
end tell
"

my performSelectorOnMainThread:"execASandReturnString:" withObject:origStr waitUntilDone:true
set aStr to (my theResult)

set aList to my getListFromText:aStr

makeNewNumbersDocumentAndTable(length of aList, 2) of me
fillCurrentTable(aList) of me

–リストに入れたレコードを、指定の属性ラベルの値で抽出
on filterRecListByLabel(aRecList as list, aPredicate as string)
  –ListからNSArrayへの型変換
  
set aArray to current application’s NSArray’s arrayWithArray:aRecList
  
  
–抽出
  
set aPredicate to current application’s NSPredicate’s predicateWithFormat:aPredicate
  
set filteredArray to aArray’s filteredArrayUsingPredicate:aPredicate
  
  
–NSArrayからListに型変換して返す
  
set bList to filteredArray as list
  
return bList
end filterRecListByLabel

–リストに入れたレコードを、指定の属性ラベルの値で抽出。値が別途指定のリストの中に存在していることが条件
on filterRecList:(aRecList as list) byLabel:(aPredicate as string) andSublist:(aSubList as list)
  –ListからNSArrayへの型変換
  
set aArray to current application’s NSArray’s arrayWithArray:aRecList
  
set aSubArray to current application’s NSArray’s arrayWithArray:aSubList
  
  
–抽出
  
set aPredicate to current application’s NSPredicate’s predicateWithFormat_(aPredicate, aSubArray)
  
set filteredArray to aArray’s filteredArrayUsingPredicate:aPredicate
  
  
–NSArrayからListに型変換して返す
  
set bList to filteredArray as list
  
return bList
end filterRecList:byLabel:andSublist:

–listの共通項を返す
on getSameItemsInLists:(aList as list) withList:(bList as list)
  
  
–ASオブジェクトをCocoaオブジェクトに変換
  
set aArray to current application’s NSArray’s arrayWithArray:aList
  
set bArray to current application’s NSArray’s arrayWithArray:bList
  
  
— まとめる
  
set allSet to current application’s NSMutableSet’s setWithArray:aArray
  
allSet’s addObjectsFromArray:bArray
  
  
–重複する要素のみ抜き出す
  
set duplicateSet to current application’s NSMutableSet’s setWithArray:aArray
  
duplicateSet’s intersectSet:(current application’s NSSet’s setWithArray:bArray)
  
  
–重複部分だけを返す
  
set resArray to duplicateSet’s allObjects()
  
  
set resList to resArray as list
  
  
return resList
end getSameItemsInLists:withList:

–スクリプトエディタのresult欄に返ってきたテキストをリストに変える
on getListFromText:aText
  
  
script getListFromTextO
    property aaText : ""
    
property gList : {}
    
property outList : {}
    
property aG : ""
    
property valList : {}
  end script
  
  
copy aText to (aaText of getListFromTextO)
  
  
set (gList of getListFromTextO) to {}
  
set (outList of getListFromTextO) to {}
  
set (aG of getListFromTextO) to ""
  
set (valList of getListFromTextO) to {}
  
  
if (aaText of getListFromTextO) does not start with "{" and (aaText of getListFromTextO) does not end with "}" then
    return {}
  end if
  
  
set aLen to length of (aaText of getListFromTextO)
  
set (aG of getListFromTextO) to text 2 thru -2 of (aaText of getListFromTextO)
  
set (gList of getListFromTextO) to characters of (aG of getListFromTextO)
  
  
  
set sPos to 2 –1文字目は\"{\"なので2文字目からスキャンを開始する
  
set ePos to 2
  
  
set imdF to false –Immediate Data Flag(文字列中を示すダブルクォート内の場合にはtrueになる)
  
set listF to 0 –stacking段数が入る
  
  
set attrF to true –属性ラベルスキャン時にtrue、データ末尾スキャン時にfalse
  
  
  
repeat with i in (gList of getListFromTextO)
    
    
set j to contents of i
    
    
if attrF = true and imdF = false and listF = 0 then
      
      
–属性値部分の末尾検出
      
if j = ":" then
        if text sPos thru sPos of (aaText of getListFromTextO) = " " then
          set sPos to sPos + 1
        end if
        
set anOut to text sPos thru ePos of (aaText of getListFromTextO)
        
set sPos to ePos + 1
        
set the end of (valList of getListFromTextO) to anOut
        
set attrF to false –データのスキャンを開始する
        
set imdF to false
        
set listF to 0
      end if
      
    else if imdF = false and listF = 0 and j = "," then
      
      
–データ部分の末尾検出
      
set anOut to text sPos thru (ePos – 1) of (aaText of getListFromTextO)
      
set sPos to ePos + 1
      
set the end of (valList of getListFromTextO) to anOut
      
set the end of (outList of getListFromTextO) to (valList of getListFromTextO)
      
set (valList of getListFromTextO) to {}
      
      
set attrF to true –次が属性値ラベルであることを宣言
      
set imdF to false
      
set listF to 0
      
    else if j = "{" then
      if imdF = false then
        set listF to listF + 1 –1段スタックにpush
      end if
    else if j = "}" then
      if imdF = false then
        set listF to listF – 1 –1段スタックからpop
      end if
    else if j = "\"" then
      if imdF = true then
        set imdF to false
      else
        set imdF to true
      end if
    end if
    
    
set ePos to ePos + 1
    
  end repeat
  
  
–ラストのデータ部分を出力
  
try
    set the end of (valList of getListFromTextO) to text sPos thru (ePos – 1) of (aaText of getListFromTextO)
    
set the end of (outList of getListFromTextO) to (valList of getListFromTextO)
  on error
    return false
  end try
  
  
return contents of (outList of getListFromTextO)
end getListFromText:

on execASandReturnString:(srcStr as string)
  
  
set targX to 500 –View Width
  
set targY to 200 –View Height
  
  
  
if srcStr = missing value or srcStr = "" then
    –Error
    
display dialog "Error in reading script source…." buttons {"OK"} default button 1 with icon 1
    
return
  end if
  
  
–Make AppleScript Controller & Script Editor View
  
set osaCon to OSAScriptController’s alloc()’s init()
  
set osaView to OSAScriptView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, targX, targY))
  
  
–Make Result View
  
set resView to NSTextView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, targX, targY))
  
resView’s setRichText:true
  
resView’s useAllLigatures:true
  
  
–Connect OSAScriptController to Editor View & Result View
  
osaCon’s setScriptView:osaView
  
osaCon’s setResultView:resView
  
  
–Set AppleScript Source to Editor View & Execute it
  
osaView’s setString:srcStr
  
osaCon’s runScript:(missing value)
  
  
–Get AppleScript’s Result as string
  
set aRes to resView’s |string|() as list of string or string –as anything
  
  
set my theResult to aRes –Return the result as string
  
end execASandReturnString:

on fillCurrentTable(aList)
  set aLen to length of aList
  
set aWidth to length of first item of aList
  
  
tell application "Numbers"
    tell front document
      tell active sheet
        tell table 1
          repeat with i from 1 to aLen
            tell row (i + 1)
              set aRowList to contents of item i of aList
              
repeat with ii from 1 to aWidth
                tell cell ii
                  set aTmpData to contents of item ii of aRowList
                  
ignoring application responses
                    set value to aTmpData
                  end ignoring
                end tell
              end repeat
            end tell
          end repeat
        end tell
      end tell
    end tell
  end tell
end fillCurrentTable

on makeNewNumbersDocumentAndTable(aHeight, aWidth)
  tell application "Numbers"
    make new document
    
    
tell front document
      tell active sheet
        delete every table
      end tell
    end tell
    
    
tell front document
      tell active sheet
        set tRes to make new table with properties {row count:aHeight, column count:aWidth}
        
return tRes
      end tell
    end tell
  end tell
end makeNewNumbersDocumentAndTable

★Click Here to Open This Script 

Posted in OSA Record | Tagged 10.12savvy 10.13savvy 10.14savvy NSString NSTextView NSThread Numbers OSAScript OSAScriptController OSAScriptView | Leave a comment

WebView+ボタンを作成 v3(URLから読み込み)

Posted on 11月 28, 2018 by Takaaki Naganoya

WkWebViewを動的に生成して、YouTube上の指定ムービーを再生するAppleScriptです。

# AppleScriptでは、Webブラウザに命令を出せば数行のコマンドで簡単に任意のURLのWebコンテンツを表示させられますが、本ScriptはAppleScriptから他のアプリケーションを介さずに直接Cocoaの機能を呼び出して自前でWebコンテンツを表示させるものです

NSWindow+NSSplitView+WKWebViewを作成して、Webサーバー上の内容を表示します。WkWebViewでWebの内容を表示させるのにかなり苦労しましたが、Objective-Cのサンプル数本を比較してテストし実現しました。

WkWebViewでコンテンツを表示するのにこんなに大変だと思いませんでしたが、これができるようになったおかげで、AppleScriptの処理結果のURLを(Webブラウザを利用せずに)プレビューできます。

グラフ描画のプログラムがJavaScript+WebViewで作られているケースが多々あるため、凝ったインタラクティブなグラフの表示を行ったり画像やPDFに出力できるようにもなったわけで、たいへんけっこうなことです。


▲Auto StartでYouTube上のムービーの再生を開始する

まだ解決できていないのは、YouTubeのムービー再生が始まるとウィンドウをクローズしてAppleScriptの実行が終了していても再生中の音声が停止しないあたりでしょうか。メモリ上からWebブラウザのオブジェクトを明示的にパージする方法についてはまだ実装できていません。

あと、Script Debugger上で動かすと、WkWebView上のコンテンツの操作(YouTube映像の再生コントロールとか)ができなくなります。ねんのため。

AppleScript名:WebView+ボタンを作成 v3(URLから読み込み)
— Created 2018-11-27 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"
use framework "WebKit"

property |NSURL| : a reference to current application’s |NSURL|
property NSColor : a reference to current application’s NSColor
property NSString : a reference to current application’s NSString
property NSScreen : a reference to current application’s NSScreen
property NSButton : a reference to current application’s NSButton
property NSWindow : a reference to current application’s NSWindow
property NSSplitView : a reference to current application’s NSSplitView
property NSTextView : a reference to current application’s NSTextView
property NSScrollView : a reference to current application’s NSScrollView
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 NSMutableString : a reference to current application’s NSMutableString
property NSWindowController : a reference to current application’s NSWindowController
property NSTitledWindowMask : a reference to current application’s NSTitledWindowMask
property NSRoundedBezelStyle : a reference to current application’s NSRoundedBezelStyle
property NSUTF8StringEncoding : a reference to current application’s NSUTF8StringEncoding
property NSBackingStoreBuffered : a reference to current application’s NSBackingStoreBuffered
property WKUserContentController : a reference to current application’s WKUserContentController
property NSMomentaryLightButton : a reference to current application’s NSMomentaryLightButton
property WKWebViewConfiguration : a reference to current application’s WKWebViewConfiguration
property NSScreenSaverWindowLevel : a reference to current application’s NSScreenSaverWindowLevel
property WKUserScriptInjectionTimeAtDocumentEnd : a reference to current application’s WKUserScriptInjectionTimeAtDocumentEnd

property windisp : false
property wController : false

set aWidth to 1100
set aHeight to 600

set aTitle to "WkWebView test"
set aButtonMSG to "OK"
–set aURL to "https://www.youtube.com/watch?v=GP_tVXTYdmY&autoplay=1&hd=1"
set aURL to "https://www.youtube.com/embed/GP_tVXTYdmY?autoplay=1&hd=1"

set paramObj to {aWidth, aHeight, aTitle, aURL, aButtonMSG, "600"}
my performSelectorOnMainThread:"dispWebView:" withObject:(paramObj) waitUntilDone:true

on dispWebView:paramObj
  set my windisp to false
  
copy (paramObj as list) to {aWidth, aHeight, aTitle, tmpURL, aButtonMSG, timeOutSecs}
  
  
set (my windisp) to true
  
  
set aWidth to aWidth as integer
  
set aHeight to aHeight as integer
  
set tmpURL to tmpURL as string
  
  
–WebViewをつくる
  
set aConf to WKWebViewConfiguration’s alloc()’s init()
  
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
  
  
set bURL to |NSURL|’s URLWithString:tmpURL
  
set aReq to NSURLRequest’s requestWithURL:bURL
  
aWebView’s loadRequest:aReq
  
  
  
–Buttonをつくる
  
set bButton to (NSButton’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aWidth, 40)))
  
bButton’s setTitle:aButtonMSG
  
bButton’s setTarget:me
  
bButton’s setAction:("clicked:")
  
bButton’s setKeyEquivalent:(return)
  
  
–SplitViewをつくる
  
set aSplitV to NSSplitView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aWidth, aHeight))
  
aSplitV’s setVertical:false
  
  
aSplitV’s addSubview:aWebView
  
aSplitV’s addSubview:bButton
  
aSplitV’s setNeedsDisplay:true
  
  
set aWin to makeWinWithView(aSplitV, aWidth, aHeight, aTitle, 1.0)
  
  
–NSWindowControllerを作ってみた
  
set my wController to NSWindowController’s alloc()
  
my (wController’s initWithWindow:aWin)
  
  
my (wController’s showWindow:me)
  
  
set aCount to (timeOutSecs as string as number) * 10 –timeout seconds * 10
  
repeat aCount times
    if (my windisp) = false then
      exit repeat
    end if
    
delay 0.1
  end repeat
  
  
–Purge Web Objects (not success)
  
set aWebView to ""
  
set userContentController to ""
  
set aConf to ""
  
set userScript to ""
  
set my wController to ""
  
  
my closeWin:bButton
end dispWebView:

–Button Clicked Event Handler
on clicked:aSender
  set (my windisp) to false
  
my closeWin:aSender
end clicked:

–make Window for Input
on makeWinWithView(aView, aWinWidth, aWinHeight, aTitle, alphaV)
  set aScreen to NSScreen’s mainScreen()
  
set aFrame to {{0, 0}, {aWinWidth, aWinHeight}}
  
set aBacking to NSTitledWindowMask –NSBorderlessWindowMask
  
set aDefer to NSBackingStoreBuffered
  
  
— Window
  
set aWin to NSWindow’s alloc()
  (
aWin’s initWithContentRect:aFrame styleMask:aBacking backing:aDefer defer:false screen:aScreen)
  
  
aWin’s setTitle:aTitle
  
aWin’s setDelegate:me
  
aWin’s setDisplaysWhenScreenProfileChanges:true
  
aWin’s setHasShadow:true
  
aWin’s setIgnoresMouseEvents:false
  
aWin’s setLevel:(NSScreenSaverWindowLevel)
  
aWin’s setOpaque:false
  
aWin’s setAlphaValue:alphaV –append
  
aWin’s setReleasedWhenClosed:true
  
aWin’s |center|()
  
  
— Set Custom View
  
aWin’s setContentView:aView
  
  
return aWin
end makeWinWithView

–close win
on closeWin:aSender
  set tmpWindow to aSender’s |window|()
  
  
repeat with n from 10 to 1 by -1
    (tmpWindow’s setAlphaValue:n / 10)
    
delay 0.02
  end repeat
  
  
my wController’s |close|()
end closeWin:

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

★Click Here to Open This Script 

Posted in Internet URL | Tagged 10.12savvy 10.13savvy 10.14savvy NSButton NSMomentaryLightButton NSMutableString NSScreen NSScrollView NSSplitView NSString NSTextView NSURL NSURLRequest NSWindow NSWindowController WKUserContentController WKUserScript WKWebView WKWebViewConfiguration | 1 Comment

テキストビュー+ボタンを作成 v2

Posted on 11月 3, 2018 by Takaaki Naganoya

Window+TextView+Buttonを作成してボタンのクリックを受け付けるAppleScriptです。

ちょっとしたログ表示などのために作成したものです。


▲通常(ライト)モード@macOS 10.12.6、ダークモード@10.14.1

オリジナルはスクリプトエディタ上でCommand+Control+Rの「フォアグラウンドで実行」を実行する必要があったのですが、

本バージョンでは強制的にメインスレッド実行を行うことで、この操作は不要になっています。

ただ、ランタイム環境ごとに「ボタンをクリックできない」という現象に遭遇。他のいろいろなランタイムでも試しておく必要を感じます。

ランタイム環境 スクリプトエディタ アプレット スクリプトメニュー osascript Script Debugger
macOS 10.12 OK OK クリックできない クリックできない クリックできない
macOS 10.13 OK OK クリックできない クリックできない クリックできない
macOS 10.14 OK OK クリックできない クリックできない クリックできない

macOS 10.12.6、10.13.6、10.14.1で動作確認してみましたが、傾向は同じです。Script Debugger上でクリックを受け付けないのはかなり問題が、、、、

AppleScript名:テキストビュー+ボタンを作成 v2
— Created 2015-12-11 by Takaaki Naganoya
— 2015 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"

property NSColor : a reference to current application’s NSColor
property NSScreen : a reference to current application’s NSScreen
property NSButton : a reference to current application’s NSButton
property NSWindow : a reference to current application’s NSWindow
property NSSplitView : a reference to current application’s NSSplitView
property NSTextView : a reference to current application’s NSTextView
property NSScrollView : a reference to current application’s NSScrollView
property NSMutableString : a reference to current application’s NSMutableString
property NSWindowController : a reference to current application’s NSWindowController
property NSTitledWindowMask : a reference to current application’s NSTitledWindowMask
property NSRoundedBezelStyle : a reference to current application’s NSRoundedBezelStyle
property NSNormalWindowLevel : a reference to current application’s NSNormalWindowLevel
property NSBackingStoreBuffered : a reference to current application’s NSBackingStoreBuffered
property NSMomentaryLightButton : a reference to current application’s NSMomentaryLightButton

property windisp : false
property wController : false

set aWidth to 600
set aHeight to 500

set aTitle to "テキストビューのじっけん/TextView Test"
set outText to "ぴよまるソフトウェア / Piyomaru Software "
set aButtonMSG to "OK"

–表示用テキストの作成
set dispStr to NSMutableString’s alloc()’s init()
repeat with i from 1 to 100
  set bStr to (NSMutableString’s stringWithString:(outText & (i as string) & return))
  
set dispStr to (bStr’s stringByAppendingString:dispStr)
end repeat

set paramObj to {aWidth, aHeight, aTitle, dispStr, aButtonMSG, "10"}
my performSelectorOnMainThread:"dispTextView:" withObject:(paramObj) waitUntilDone:true

on dispTextView:paramObj
  set my windisp to false
  
copy paramObj to {aWidth, aHeight, aTitle, dispStr, aButtonMSG, timeOutSecs}
  
  
set aColor to NSColor’s colorWithDeviceRed:0.0 green:0.0 blue:0.0 alpha:0.9
  
set (my windisp) to true
  
  
–Text View+Scroll Viewをつくる
  
set aScroll to NSScrollView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aWidth, aHeight))
  
set aView to NSTextView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aWidth, aHeight))
  
aView’s setRichText:true
  
aView’s useAllLigatures:true
  
aView’s setTextColor:(NSColor’s cyanColor()) —
  
aView’s setBackgroundColor:aColor
  
aView’s setEditable:false
  
  
aScroll’s setDocumentView:aView
  
aView’s enclosingScrollView()’s setHasVerticalScroller:true
  
  
  
–Buttonをつくる
  
set bButton to (NSButton’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aWidth, 40)))
  
–bButton’s setButtonType:( NSMomentaryLightButton)
  
–bButton’s setBezelStyle:( NSRoundedBezelStyle)
  
bButton’s setTitle:aButtonMSG
  
bButton’s setTarget:me
  
bButton’s setAction:("clicked:")
  
bButton’s setKeyEquivalent:(return)
  
  
–SplitViewをつくる
  
set aSplitV to NSSplitView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aHeight, aWidth))
  
aSplitV’s setVertical:false
  
  
aSplitV’s addSubview:aScroll
  
aSplitV’s addSubview:bButton
  
aSplitV’s setNeedsDisplay:true
  
  
set aWin to makeWinWithView(aSplitV, aWidth, aHeight, aTitle, 0.9)
  
aView’s setString:dispStr
  
  
–NSWindowControllerを作ってみた
  
set my wController to NSWindowController’s alloc()
  
my (wController’s initWithWindow:aWin)
  
  
my (wController’s showWindow:me)
  
  
set aCount to (timeOutSecs as string as number) * 10 –timeout seconds * 10
  
repeat aCount times
    if (my windisp) = false then
      exit repeat
    end if
    
delay 0.1
  end repeat
  
  
my closeWin:bButton
end dispTextView:

–Button Clicked Event Handler
on clicked:aSender
  set (my windisp) to false
  
my closeWin:aSender
end clicked:

–make Window for Input
on makeWinWithView(aView, aWinWidth, aWinHeight, aTitle, alphaV)
  set aScreen to NSScreen’s mainScreen()
  
set aFrame to {{0, 0}, {aWinWidth, aWinHeight}}
  
set aBacking to NSTitledWindowMask –NSBorderlessWindowMask
  
set aDefer to NSBackingStoreBuffered
  
  
— Window
  
set aWin to NSWindow’s alloc()
  (
aWin’s initWithContentRect:aFrame styleMask:aBacking backing:aDefer defer:false screen:aScreen)
  
  
aWin’s setTitle:aTitle
  
aWin’s setDelegate:me
  
aWin’s setDisplaysWhenScreenProfileChanges:true
  
aWin’s setHasShadow:true
  
aWin’s setIgnoresMouseEvents:false
  
aWin’s setLevel:(NSNormalWindowLevel)
  
aWin’s setOpaque:false
  
aWin’s setAlphaValue:alphaV –append
  
aWin’s setReleasedWhenClosed:true
  
aWin’s |center|()
  
  
— Set Custom View
  
aWin’s setContentView:aView
  
  
return aWin
end makeWinWithView

–close win
on closeWin:aSender
  set tmpWindow to aSender’s |window|()
  
  
repeat with n from 10 to 1 by -1
    (tmpWindow’s setAlphaValue:n / 10)
    
delay 0.02
  end repeat
  
  
my wController’s |close|()
end closeWin:

★Click Here to Open This Script 

Posted in GUI | Tagged 10.11savvy 10.12savvy 10.13savvy 10.14savvy NSButton NSColor NSMutableString NSScreen NSScrollView NSSplitView NSTextView NSWindow NSWindowController | 1 Comment

WordPressの指定IDの記事にリンクされているapplescriptからCocoa Classのproperty宣言を抽出 v3

Posted on 8月 5, 2018 by Takaaki Naganoya

本BlogのようなWordPressで運用されており、AppleScriptのURLリンクを記事に埋め込んでいるWordPressに対して、XML-RPC経由で指定IDの記事本文を取得し、埋め込まれているURLリンクからAppleScriptのソースコードを取得して、メモリー上でコンパイルして書式つきテキストに変換し、AppleScript構文書式をもとにpropertyラベルを抽出、そのうちCocoa Classのみをリストで取得するAppleScriptです。

本Blogに投稿した記事から宣言しているCocoa Classを抽出し、自動でタグ付けするために準備したものです。1記事に対して複数のAppleScriptが掲載されている場合にも対応しています。

HTMLReader.frameworkを用いてBlog本文からのリンク抽出、リンクURL抽出を行っています。

–> HTMLReader.framework(To ~/Library/Frameworks/)

本Sample Scriptで指定したIDの記事のproperty部分はこのようになっており、

本Scriptの実行によって抽出されたCocoa Class(単なる変数的なproperty項目や、Enumは対象外のため排除)は、

–> {“NSString”, “NSArray”, “OSAScript”, “NSPredicate”, “OSALanguage”, “NSDictionary”, “OSALanguageInstance”, “NSBundle”, “NSUnarchiver”}

のようになります。自分の環境でMacBook Proを有線ネットワーク接続した状態で、3.3〜3.4秒程度かかっています。大量の記事を処理する場合には本AppleScriptの並列処理を行うと処理時間の大幅な短縮が期待できます(MacのCPUがサーマルスロットリングで速度低下しなければ)。

また、負荷が集中している特定コアの動作周波数を上げ、他のコアの動作周波数を落とすTurbo Boostが有効な状態で並列処理を実行すると、並列処理を行う意義そのものが低下してしまうため、Turbo-Boost-Switcherのようなツールの併用が必要と思われます。

AppleScript名:WordPressの指定IDの記事にリンクされているapplescriptからCocoa Classのproperty宣言を抽出 v3
— Created 2018-07-30 by Takaaki Naganoya
— Modified 2018-08-05 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"
use framework "OSAKit"
use framework "HTMLReader" –https://github.com/nolanw/HTMLReader

property |NSURL| : a reference to current application’s |NSURL|
property NSArray : a reference to current application’s NSArray
property NSString : a reference to current application’s NSString
property NSBundle : a reference to current application’s NSBundle
property NSThread : a reference to current application’s NSThread
property OSAScript : a reference to current application’s OSAScript
property NSPredicate : a reference to current application’s NSPredicate
property NSTextView : a reference to current application’s NSTextView
property NSDictionary : a reference to current application’s NSDictionary
property NSUnarchiver : a reference to current application’s NSUnarchiver
property OSALanguage : a reference to current application’s OSALanguage
property OSAScriptView : a reference to current application’s OSAScriptView
property NSMutableArray : a reference to current application’s NSMutableArray
property OSAScriptController : a reference to current application’s OSAScriptController
property NSMutableDictionary : a reference to current application’s NSMutableDictionary
property OSALanguageInstance : a reference to current application’s OSALanguageInstance
property NSUTF8StringEncoding : a reference to current application’s NSUTF8StringEncoding

set postID to 3864
set {myUser, myPass} to getAcountData() of me
set aURL to "http://piyocast.com/as/xmlrpc.php"
set cocoaClassList to getCocoaPropListFromPost(aURL, postID, myUser, myPass) of me
–>  {"NSString", "NSBundle", "NSPredicate", "NSDictionary", "NSMutableArray", "NSMutableDictionary"}

–指定Blogの指定IDの記事にURLリンクされているAppleScriptから、Cocoa Classのpropertyのみ取得する
on getCocoaPropListFromPost(aURL, postID, myUser, myPass)
  –AppleScriptの構文色分け設定ファイルを読み込んで、重複色のチェックを実施  
  
set cList to getAppleScriptSourceColors() of me
  
set cRes to chkASLexicalFormatColorConfliction(cList) of me –構文色分けの重複色チェック
  
if cRes = false then error "There is some duplicate(s) color among AppleScript’s lexical color settings"
  
  
–WordPressの指定Post IDの記事を取得してリンクされているURLからURL Schemeでフィルタして、リンクされているAppleScriptのソースを取得
  
set aScheme to "applescript://"
  
set sourceList to getASSouceLinkedInWordPressPost(postID, aURL, aScheme, myUser, myPass) of me
  
  
–AppleScriptのソースをRAM上でコンパイル(構文確認)して、構文色分けしたRTFを取得。RTFの書式情報をparseしてattribute runsと同様のrecordを生成
  
–構文色分けをもとにproperty項目を抽出し、Cocoa Classに該当するもののみを抽出
  
set outList to {}
  
repeat with i in sourceList
    set j to contents of i
    
set anAttrStr to compileASandReturnAttributedString(j) of me
    
set attrRes to getAttributeRunsFromAttrString(anAttrStr) of me
    
set propNames to getPropertyNamesCocoaOnly(cList, attrRes) of me
    
    
if propNames is not equal to {} then
      set outList to outList & propNames
    end if
  end repeat
  
  
–1D Listのユニーク化(重複要素の排除)
  
set aArray to NSArray’s arrayWithArray:outList
  
set bArray to aArray’s valueForKeyPath:"@distinctUnionOfObjects.self"
  
set bList to bArray as list of string or string –as anything
  
  
return bList
end getCocoaPropListFromPost

–Property名称を取得する
on getPropertyNamesCocoaOnly(cList, aRec)
  script spdHnd
    property aRec : {}
  end script
  
  
set (aRec of spdHnd) to aRec
  
  
set targAttr to contents of item 7 of cList –ハンドラあるいは変数
  
set tmpCoStr to ((redValue of targAttr) as string) & " " & ((greenValue of targAttr) as string) & " " & ((blueValue of targAttr) as string)
  
  
set ontoColItem to contents of item 3 of cList –スクリプティング予約語(on/to)
  
set ontoCoStr to ((redValue of ontoColItem) as string) & " " & ((greenValue of ontoColItem) as string) & " " & ((blueValue of ontoColItem) as string)
  
  
  
–変数あるいはハンドラ名称をリストアップ(variables & handler)
  
set tmp1Array to NSArray’s arrayWithArray:(aRec of spdHnd)
  
set thePred0 to NSPredicate’s predicateWithFormat_("colorStr == %@", tmpCoStr)
  
set dArray to (tmp1Array’s filteredArrayUsingPredicate:thePred0) as list
  
  
–改行を含むデータをリストアップ(text data contains return)
  
set thePred1 to NSPredicate’s predicateWithFormat_("stringVal CONTAINS %@", return)
  
set eArray to ((tmp1Array’s filteredArrayUsingPredicate:thePred1)’s valueForKeyPath:"itemIndex") as list
  
  
set the beginning of eArray to 0 –ハンドラ宣言部がTopに来る場合に備える
  
  
–"property"(プロパティ宣言)の項目をリストアップ 文字と色で抽出
  
set thePred2 to NSPredicate’s predicateWithFormat_("stringVal == %@ && colorStr == %@ ", "property", ontoCoStr)
  
set fArray to ((tmp1Array’s filteredArrayUsingPredicate:thePred2)’s valueForKeyPath:"itemIndex") as list
  
  
set handlerList to {}
  
  
–property ではじまるハンドラの抽出
  
repeat with i in eArray –改行を含むテキストのアイテム番号リスト
    set j to (contents of i) as integer
    
repeat with ii in fArray –"on"の項目リスト
      set jj to (contents of ii) as integer
      
      
set handlerStr to missing value
      
      
if (j + 1) = jj then
        set handlerStr to stringVal of (item (jj + 2) of ((aRec of spdHnd) as list))
      else if (j + 2) = jj then
        set handlerStr to stringVal of (item (jj + 2) of ((aRec of spdHnd) as list))
      end if
      
      
set tmpStr to repChar(handlerStr, "|", "") of me
      
      
if tmpStr is not in {"error", missing value} and tmpStr is not in handlerList then
        –抽出したProperty宣言がCocoa Classのものかどうか判定
        
if searchClassInFrameworks(tmpStr) of me is not equal to false then
          set the end of handlerList to tmpStr
        end if
      end if
      
    end repeat
  end repeat
  
  
return handlerList
end getPropertyNamesCocoaOnly

–RAM上にスクリプトエディタと同じ部品を組み立て(非表示)、AppleScriptのソーステキストからObjectを生成し、Attributed Stringデータを返す
on compileASandReturnAttributedString(theSource as string)
  set targX to 1024 –View Width
  
set targY to 2048 –View Height
  
  
set osaCon to current application’s OSAScriptController’s alloc()’s init()
  
set osaView to current application’s OSAScriptView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, targX, targY))
  
  
set resView to NSTextView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, targX, targY))
  
resView’s setRichText:true
  
resView’s useAllLigatures:true
  
  
osaCon’s setScriptView:osaView
  
osaCon’s setLanguage:(OSALanguage’s languageForName:"AppleScript")
  
osaCon’s setResultView:resView
  
  
osaView’s setString:theSource
  
osaCon’s compileScript:(missing value) –Compile(構文確認)
  
  
set aRes to (osaView’s attributedString())
  
  
return aRes
end compileASandReturnAttributedString

–Attributed StringをDictionary化
on getAttributeRunsFromAttrString(theStyledText)
  script aSpd
    property styleList : {}
  end script
  
  
set (styleList of aSpd) to {} —for output
  
  
set thePureString to theStyledText’s |string|() –pure string from theStyledText
  
  
set theLength to theStyledText’s |length|()
  
set startIndex to 0
  
set itemCount to 1
  
  
repeat until (startIndex = theLength)
    set {theAtts, theRange} to theStyledText’s attributesAtIndex:startIndex longestEffectiveRange:(reference) inRange:{startIndex, theLength – startIndex}
    
    
–String  
    
set aText to (thePureString’s substringWithRange:theRange) as string
    
    
–Color
    
set aColor to (theAtts’s valueForKeyPath:"NSColor")
    
if aColor is not equal to missing value then
      set aSpace to aColor’s colorSpace()
      
      
set aRed to (aColor’s redComponent()) * 255
      
set aGreen to (aColor’s greenComponent()) * 255
      
set aBlue to (aColor’s blueComponent()) * 255
      
      
set colList to {aRed as integer, aGreen as integer, aBlue as integer} –for comparison
      
set colStrForFind to (aRed as integer as string) & " " & (aGreen as integer as string) & " " & (aBlue as integer as string) –for filtering
    else
      set colList to {0, 0, 0}
      
set colStrForFind to "0 0 0"
    end if
    
    
–Font
    
set aFont to (theAtts’s valueForKeyPath:"NSFont")
    
if aFont is not equal to missing value then
      set aDFontName to aFont’s displayName()
      
set aDFontSize to aFont’s pointSize()
    end if
    
    
set the end of (styleList of aSpd) to {stringVal:aText, colorStr:colStrForFind, colorVal:colList, fontName:aDFontName as string, fontSize:aDFontSize, itemIndex:itemCount}
    
set startIndex to current application’s NSMaxRange(theRange)
    
    
set itemCount to itemCount + 1
  end repeat
  
  
return (styleList of aSpd)
  
end getAttributeRunsFromAttrString

–指定クラスがいずれかのCocoa Frameworkに所属しているかを検索
on searchClassInFrameworks(aTarget)
  set aClass to current application’s NSClassFromString(aTarget)
  
if aClass = missing value then return false
  
set theComponenents to (NSBundle’s bundleForClass:aClass)’s bundleURL’s pathComponents()
  
set thePred to NSPredicate’s predicateWithFormat:"pathExtension == ’framework’"
  
set aRes to (theComponenents’s filteredArrayUsingPredicate:thePred)’s firstObject() as list of string or string
  
return aRes
end searchClassInFrameworks

–指定Post IDのWordPress記事から、指定SchemeのURLを抽出し、AS Sourceをdecodeしてproperty行のみ抽出
on getASSouceLinkedInWordPressPost(postID, aURL, aScheme, myUser, myPass)
  –call xmlrpc命令に対するURLの間接指定を有効にするために、AppleScriptの構文解釈機能をダミーURLでだます
  
using terms from application "http://piyocast.com/as/xmlrpc.php" –URLと判定されればなんでもいい
    tell application aURL
      set wRes to (call xmlrpc {method name:"wp.getPost", parameters:{"1", myUser, myPass, postID as string}})
    end tell
  end using terms from
  
  
set aBody to post_content of wRes –Blog本文
  
  
–記事中でリンクしているURLを取得し、指定のURL Schemeでフィルタする
  
set urlList to filterURLLinksByScheme(aBody, aScheme) of me
  
  
set propList to {}
  
  
repeat with i in urlList
    set j to contents of i
    
set urlRec to parseQueryDictFromURLString(j) of me
    
set tmpScript to (urlRec’s |script|) as string –Get AppleScript Source
    
    
set propList to propList & tmpScript
  end repeat
  
  
return propList
end getASSouceLinkedInWordPressPost

on parseQueryDictFromURLString(aURLStr as string)
  if aURLStr = "" then error "No URL String"
  
  
set aURL to |NSURL|’s URLWithString:aURLStr
  
set aQuery to aURL’s query() –Get Query string part from URL
  
if aQuery’s |length|() = 0 then return false
  
  
set aDict to NSMutableDictionary’s alloc()’s init()
  
set aParamList to (aQuery’s componentsSeparatedByString:"&") as list
  
  
repeat with i in aParamList
    set j to contents of i
    
if length of j > 0 then
      set tmpStr to (NSString’s stringWithString:j)
      
set eList to (tmpStr’s componentsSeparatedByString:"=")
      
set anElement to (eList’s firstObject()’s stringByReplacingPercentEscapesUsingEncoding:(NSUTF8StringEncoding))
      
set aValStr to (eList’s lastObject()’s stringByReplacingPercentEscapesUsingEncoding:(NSUTF8StringEncoding))
      (
aDict’s setObject:aValStr forKey:anElement)
    end if
  end repeat
  
  
return aDict
end parseQueryDictFromURLString

–指定のHTML文字列から、Link URLを抽出し、schemeで再抽出する
on filterURLLinksByScheme(aBody, aScheme)
  set conType to "text/html"
  
  
–HTML文字列をいったんNSDataにしているのは、HTMLReader.frameworkの仕様のため
  
set aData to (current application’s NSString’s stringWithString:aBody)’s dataUsingEncoding:(current application’s NSUTF8StringEncoding)
  
set aHTML to current application’s HTMLDocument’s documentWithData:aData contentTypeHeader:conType
  
  
set aTextArray to ((aHTML’s nodesMatchingSelector:"a")’s textContent) as list –リンク文字
  
set aLinkList to ((aHTML’s nodesMatchingSelector:"a")’s attributes’s valueForKeyPath:"href") as list –URL文字列
  
  
set outList to {}
  
repeat with i in aLinkList
    set j to contents of i
    
if j begins with aScheme then
      set the end of outList to j
    end if
  end repeat
  
  
return outList
end filterURLLinksByScheme

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

–AppleScriptの構文色分けのカラー値をRGBで取得する
on getAppleScriptSourceColors()
  — get the plist info as a dictionary
  
set thePath to NSString’s stringWithString:"~/Library/Preferences/com.apple.applescript.plist"
  
set thePath to thePath’s stringByExpandingTildeInPath()
  
set theInfo to NSDictionary’s dictionaryWithContentsOfFile:thePath
  
  
— extract relevant part and loop through
  
set theArray to (theInfo’s valueForKey:"AppleScriptSourceAttributes") as list
  
  
set colList to {}
  
  
repeat with i from 1 to count of theArray
    set anEntry to item i of theArray
    
    
set colorData to NSColor of anEntry
    
set theColor to (NSUnarchiver’s unarchiveObjectWithData:colorData)
    
    
set {rVal, gVal, bVal} to retColListFromNSColor(theColor, 255) of me
    
    
set fontData to NSFont of anEntry
    
set theFont to (NSUnarchiver’s unarchiveObjectWithData:fontData)
    
    
set aFontName to theFont’s displayName() as text
    
set aFontSize to theFont’s pointSize()
    
    
set aColRec to {redValue:rVal, greenValue:gVal, blueValue:bVal, fontName:aFontName, fontSize:aFontSize}
    
    
set the end of colList to aColRec
  end repeat
  
  
return colList
end getAppleScriptSourceColors

–NSColorからRGBの値を取り出す
on retColListFromNSColor(aCol, aMAX as integer)
  set aRed to round ((aCol’s redComponent()) * aMAX) rounding as taught in school
  
set aGreen to round ((aCol’s greenComponent()) * aMAX) rounding as taught in school
  
set aBlue to round ((aCol’s blueComponent()) * aMAX) rounding as taught in school
  
  
if aRed > aMAX then set aRed to aMAX
  
if aGreen > aMAX then set aGreen to aMAX
  
if aBlue > aMAX then set aBlue to aMAX
  
  
return {aRed, aGreen, aBlue}
end retColListFromNSColor

–AS書式で配色に重複がないかどうかチェック
on chkASLexicalFormatColorConfliction(aList)
  set anArray to current application’s NSArray’s arrayWithArray:aList
  
set bList to (anArray’s valueForKeyPath:"redValue.stringValue") as list
  
set cList to (anArray’s valueForKeyPath:"greenValue.stringValue") as list
  
set dList to (anArray’s valueForKeyPath:"blueValue.stringValue") as list
  
  
set colStrList to {}
  
repeat with i from 1 to (length of bList)
    set bItem to contents of item i of bList
    
set cItem to contents of item i of cList
    
set dItem to contents of item i of dList
    
set the end of colStrList to bItem & " " & cItem & " " & dItem
  end repeat
  
  
set aRes to returnDuplicatesOnly(colStrList) of me
  
if aRes is equal to {} then
    return true –重複が存在しなかった場合
  else
    return false –重複があった場合
  end if
end chkASLexicalFormatColorConfliction

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

on getAcountData()
  return {"xxxxxxxx_xx", "XXXXXXXXXXXXXXXXXXXXXXXX"} –user name, password
end getAcountData

★Click Here to Open This Script 

Posted in list OSA RTF Text URL XML-RPC | Tagged 10.11savvy 10.12savvy 10.13savvy NSArray NSBundle NSDictionary NSMutableArray NSMutableDictionary NSPredicate NSString NSTextView NSThread NSUnarchiver OSALanguage OSALanguageInstance OSAScript OSAScriptController OSAScriptView | Leave a comment

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

Google Search

Popular posts

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

Tags

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

カテゴリー

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

アーカイブ

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

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

メタ情報

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

Forum Posts

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

メタ情報

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