Menu

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

AppleScriptの穴

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

タグ: 10.14savvy

アラートダイアログ上にd3-cloudを用いてワードクラウドを表示

Posted on 6月 14, 2020 by Takaaki Naganoya

d3-cloudを用いてワードクラウドを表示するAppleScriptです。

本AppleScriptでは、

 {|word|:"NSString", |count|:97}

のように、登場単語、登場回数のように集計ずみのデータをJSONに変換してワードクラウド表示させています。この(AppleScriptの予約語にかぶりまくりな)属性ラベルはd3-cloud側の仕様です。

以前に作った「Tag CloudっぽいRTFの作成」のデータを用いて(属性ラベルを置換して)表示させたものがこちら(↑)。

Tag/Word Cloud関連のJavaScriptについては前から気になって調べてはいたのですが、「ローカルにデータを持つスクリプトが多い」「d3-cloud自体をローカルにインストールさせる例が多い」(実行速度などの問題で?)という状況で、ありもののスクリプトをこのアラートダイアログ上にはりつけたWkWebViewの「箱庭環境」で追加スクリプトのインストールなしで動くように書き換えるのに少々手間取りました。

CDNにホスティングされているd3-cloudを呼び出すことで、ローカルにd3-cloudをインストールせずに実行していますが、将来的にこれが変更・廃止された場合には別のWeb上のどこかにホスティングされているd3-cloudを呼び出すことになります。

ローカルにあるテキストコンテンツ(CotEditorで編集中の文章とか、Pagesで作成中のワープロ文章とか、Keynoteで作成中のプレゼン資料の内容とか)を分析して頻出単語を取り出し、タグクラウドといいますかワードクラウドで表示して全体の見通しをつけるというScriptは作りたいと思っていました。

AppleScript名:アラートダイアログ上にd3-cloudを用いてワードクラウドを表示.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2020/06/13
—
–  Copyright © 2020 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use framework "AppKit"
use framework "WebKit"
use scripting additions

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

property returnCode : 0

set aRecArray to {{|word|:"NSString", |count|:97}, {|word|:"NSURL", |count|:78}, {|word|:"Keynote", |count|:52}, {|word|:"NSMutableArray", |count|:51}, {|word|:"NSAlert", |count|:50}, {|word|:"NSRunningApplication", |count|:49}, {|word|:"NSArray", |count|:48}, {|word|:"CotEditor", |count|:44}, {|word|:"NSColor", |count|:44}, {|word|:"Finder", |count|:41}, {|word|:"NSImage", |count|:39}, {|word|:"Numbers", |count|:38}, {|word|:"NSPredicate", |count|:34}, {|word|:"NSView", |count|:32}, {|word|:"NSButton", |count|:28}, {|word|:"Safari", |count|:28}, {|word|:"NSScreen", |count|:27}, {|word|:"iTunes", |count|:25}, {|word|:"NSUTF8StringEncoding", |count|:24}, {|word|:"NSDictionary", |count|:22}, {|word|:"NSScrollView", |count|:21}, {|word|:"NSBitmapImageRep", |count|:20}, {|word|:"NSFileManager", |count|:20}, {|word|:"NSMutableDictionary", |count|:19}, {|word|:"NSURLRequest", |count|:18}, {|word|:"NSUUID", |count|:18}, {|word|:"NSWindow", |count|:17}, {|word|:"NSBezierPath", |count|:16}, {|word|:"NSFont", |count|:16}, {|word|:"WKWebView", |count|:16}, {|word|:"WKWebViewConfiguration", |count|:16}, {|word|:"NSWorkspace", |count|:15}, {|word|:"Pages", |count|:15}, {|word|:"Script Editor", |count|:15}, {|word|:"System Events", |count|:15}, {|word|:"WKUserContentController", |count|:15}, {|word|:"WKUserScript", |count|:15}, {|word|:"NSAlertSecondButtonReturn", |count|:14}, {|word|:"NSJSONSerialization", |count|:14}, {|word|:"NSSortDescriptor", |count|:14}}
set jsonStr to array2DToJSONArray(aRecArray) of me

–https://qiita.com/january108/items/5388799531c1ace8324e
set myStr to "<!DOCTYPE HTML>
<html lang=\"en\">
<head>
<meta charset=\"UTF-8\">
<title>D3 Word Clouds</title>
<meta name=\"author\" content=\"d4i\"/>
</head>
<body>
<script src=\"http://d3js.org/d3.v3.min.js\" charset=\"utf-8\"></script>
<script src=\"https://cdnjs.cloudflare.com/ajax/libs/d3-cloud/1.2.5/d3.layout.cloud.min.js\"></script>

<script>
  var data = %@;
var width = 600,
height = 400,
fill = d3.scale.category20(),
maxcount = d3.max(data, function(d){ return d.count; } ),
wordcount = data.map(function(d) { return {text: d.word, size: d.count / maxcount * 100}; });

d3.layout.cloud().size([width, height])
.words(wordcount)
.padding(5)
.rotate(function() { return ~~(Math.random() * 2) * 90; })
.font(\"Impact\")
.fontSize(function(d) { return d.size; })
.on(\"end\", draw)
.start();

function draw(words) {
d3.select(\"body\").append(\"svg\")
.attr({
\"width\": width,
\"height\": height
})
.append(\"g\")
.attr(\"transform\", \"translate(\" + [ width >> 1, height >> 1 ] + \")\")
.selectAll(\"text\")
.data(words)
.enter()
.append(\"text\")
.style({
\"font-size\": function(d) { return d.size + \"px\"; },
\"font-family\": \"Impact\",
\"fill\": function(d, i) { return fill(i); }
})
.attr({
\"text-anchor\": \"middle\",
\"transform\": function(d) { return \"translate(\" + [d.x, d.y] + \")rotate(\" + d.rotate + \")\"; }
})
.text(function(d) { return d.text; });
}
</script>
</body>
</html>"

set aString to current application’s NSString’s stringWithFormat_(myStr, jsonStr) as string

set paramObj to {myMessage:"D3 Test", mySubMessage:"This is a d3-cloud word cloud test", htmlStr:aString}
–my browseStrWebContents:paramObj–for debug
my performSelectorOnMainThread:"browseStrWebContents:" withObject:(paramObj) waitUntilDone:true

on browseStrWebContents:paramObj
  set aMainMes to myMessage of paramObj
  
set aSubMes to mySubMessage of paramObj
  
set htmlString to (htmlStr of paramObj)
  
  
set aWidth to 620
  
set aHeight to 420
  
  
–WebViewをつくる
  
set aConf to WKWebViewConfiguration’s alloc()’s init()
  
  
–指定HTML内のJavaScriptをFetch
  
set jsSource to pickUpFromToStr(htmlString, "<script>", "</script>") of me
  
  
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)) configuration:aConf
  
aWebView’s setNavigationDelegate:me
  
aWebView’s setUIDelegate:me
  
aWebView’s setTranslatesAutoresizingMaskIntoConstraints:true
  
using terms from scripting additions
    set bURL to |NSURL|’s fileURLWithPath:(POSIX path of (path to me))
  end using terms from
  
aWebView’s loadHTMLString:htmlString baseURL:(bURL)
  
  
— set up alert  
  
set theAlert to NSAlert’s alloc()’s init()
  
tell theAlert
    its setMessageText:aMainMes
    
its setInformativeText:aSubMes
    
its addButtonWithTitle:"OK"
    
–its addButtonWithTitle:"Cancel"
    
its setAccessoryView:aWebView
    
    
set myWindow to its |window|
  end tell
  
  
— show alert in modal loop
  
NSRunningApplication’s currentApplication()’s activateWithOptions:0
  
my performSelectorOnMainThread:"doModal:" withObject:(theAlert) waitUntilDone:true
  
  
–Stop Web View Action
  
set bURL to |NSURL|’s URLWithString:"about:blank"
  
set bReq to NSURLRequest’s requestWithURL:bURL
  
aWebView’s loadRequest:bReq
  
  
if (my returnCode as number) = 1001 then error number -128
end browseStrWebContents:

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

on viewDidLoad:aNotification
  return true
end viewDidLoad:

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

on pickUpFromToStr(aStr as string, s1Str as string, s2Str as string)
  set a1Offset to offset of s1Str in aStr
  
if a1Offset = 0 then return false
  
set bStr to text (a1Offset + (length of s1Str)) thru -1 of aStr
  
set a2Offset to offset of s2Str in bStr
  
if a2Offset = 0 then return false
  
set cStr to text 1 thru (a2Offset – (length of s2Str)) of bStr
  
return cStr as string
end pickUpFromToStr

–リストを任意のデリミタ付きでテキストに
on retArrowText(aList, aDelim)
  set aText to ""
  
set curDelim to AppleScript’s text item delimiters
  
set AppleScript’s text item delimiters to aDelim
  
set aText to aList as text
  
set AppleScript’s text item delimiters to curDelim
  
return aText
end retArrowText

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

on parseByDelim(aData, aDelim)
  set curDelim to AppleScript’s text item delimiters
  
set AppleScript’s text item delimiters to aDelim
  
set dList to text items of aData
  
set AppleScript’s text item delimiters to curDelim
  
return dList
end parseByDelim

★Click Here to Open This Script 

Posted in dialog JSON Tag | Tagged 10.13savvy 10.14savvy 10.15savvy NSAlert NSButton NSJSONSerialization NSMutableArray NSRunningApplication NSString NSURL NSURLRequest NSUTF8StringEncoding WKUserContentController WKUserScript WKUserScriptInjectionTimeAtDocumentEnd WKWebView WKWebViewConfiguration | Leave a comment

アラートダイアログ上にWebViewで3Dコンテンツを表示(WebGL+three.js)

Posted on 6月 13, 2020 by Takaaki Naganoya

アラートダイアログ上にさまざまなGUI部品を配置してUIを作成する「箱庭UI」シリーズ、WkWebViewを配置してWeb GL+three.jsによる3Dアニメーションコンテンツを表示するAppleScriptです。

# macOS 10.14.6上のWkWebViewで途中のアップデートから、mouse dragのイベントが取れなくなっています。macOS 10.15および11.0では問題なくmouse dragのイベントを取得できているのですが、、、、。ちなみに、Safariで表示させた場合には問題ありません。同様にWkWebViewを使っているとおぼしきFileMaker Pro v19のWebViewerも同様にドラッグ操作が抜けるので、自分が間抜けなせいではないと思いま

# macOS 13.3beta上では、SafariでもWkWebViewでもWebGL+three.jsで作られているこの内容を表示できません。全世界のデベロッパーがWkWebView上でWebGL+three.jsのコンテンツが動かない(表示できない)ことを確認しています。
→ 最新のmacOSで動くバージョンを掲載アラートダイアログ上にWebViewで3Dコンテンツを表示(WebGL+three.js)v3

多項目選択メニュー部品のようであり、画面下部にあるTABLE(少しデータをいじくってPIYOMARU表示)、SPHERE、HELIX、GRIDのボタンから表示メニュー形態を選択可能になっています。操作は、マウスのドラッグとマウスのスクロール(トラックパッドでもスクロール操作を)です。


▲TABLE 表示


▲SPHERE 表示


▲HELIX 表示


▲GRID 表示

ひととおり、最初のTABLE表示部分の部品表示座標データをいじくって、表示色をいろいろ変更してみて、表示データをAppleScript側のリスト変数で与えるところまでやりかけて、リストからJSON文字列に問題なく変換できているものの、実際にHTMLコンテンツに合成して再生まで行くと何も表示されないという状況です。何も考えずに横長のデータを生成したので、そのあたり横幅に制限があったりするのかもしれません。

球体にDOM要素をテクスチャマッピングするSPHERE表示では、データ数が想定どおりの個数ないと球体の表示が成立しないため、そのあたりにデモプログラムっぽさが垣間見えます。

現状、ただ表示するだけで項目選択などは行えない状況ですが、これを強化して項目選択UIとして育てていくのか、Xcode上のアプリケーションに統合する方向でブラッシュアップするのか、いろいろ協議した結果、現状で既存の選択UIより高い実用性を確保できない、という結論に至ったため「AppleScriptでここまでやってみた」という技術的なデモンストレーションとしてBlog上で公開しておくぐらいのものだろうという話に。

その後、FileMaker ProのWebViewer上で内容可変+クリック受信機能つきの3D Rotationメニューを実装できるところまで内容の解析ができました。

AppleScript名:アラートダイアログ上にWebViewで3Dコンテンツを表示(WebGL+three.js).scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2020/06/13
—
–  Copyright © 2020 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use framework "AppKit"
use framework "WebKit"
use scripting additions

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

property returnCode : 0

–https://www.cresco.co.jp/blog/entry/7427/
— By sgi-chang @ UX Design Center
set myStr to "<!DOCTYPE html>
<html>

<head>
<title>three.js css3d – cresco xmas inspired by periodic table</title>
<meta charset=\"utf-8\">
<meta name=\"viewport\" content=\"width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0\">
<link type=\"text/css\" rel=\"stylesheet\" href=\"https://threejs.org/examples/main.css\">
<style>
a {
color: #8ff;
}

#menu {
position: absolute;
bottom: 20px;
width: 100%;
text-align: center;
}

.element {
width: 120px;
height: 160px;
box-shadow: 0px 0px 12px rgba(0, 255, 255, 0.5);
border: 1px solid rgba(127, 255, 255, 0.25);
font-family: Helvetica, sans-serif;
text-align: center;
line-height: normal;
cursor: default;
}

.element:hover {
box-shadow: 0px 0px 12px rgba(0, 255, 255, 0.75);
border: 1px solid rgba(127, 255, 255, 0.75);
}

.element .number {
position: absolute;
top: 20px;
right: 20px;
font-size: 12px;
color: rgba(127, 255, 255, 0.75);
}

.element .symbol {
position: absolute;
top: 40px;
left: 0px;
right: 0px;
font-size: 60px;
font-weight: bold;
color: rgba(255, 255, 255, 0.75);
text-shadow: 0 0 10px rgba(0, 255, 255, 0.95);
}

.element .details {
position: absolute;
bottom: 15px;
left: 0px;
right: 0px;
font-size: 12px;
color: rgba(127, 255, 255, 0.75);
}

button {
color: rgba(127, 255, 255, 0.75);
background: transparent;
outline: 1px solid rgba(127, 255, 255, 0.75);
border: 0px;
padding: 5px 10px;
cursor: pointer;
}

button:hover {
background-color: rgba(0, 255, 255, 0.5);
}

button:active {
color: #000000;
background-color: rgba(0, 255, 255, 0.75);
}
</style>
</head>

<body>
<script src=\"https://threejs.org/examples/jsm/libs/tween.module.min.js\"></script>
<script src=\"https://threejs.org/examples/jsm/controls/TrackballControls.js\"></script>
<script src=\"https://threejs.org/examples/jsm/renderers/CSS3DRenderer.js\"></script>

<div id=\"info\"><a href=\"http://piyocast.com/as\" target=\"_blank\">AppleScript 3D UI Demonstration</a> By Piyomaru Software</div>
<div id=\"container\"></div>
<div id=\"menu\">
<button id=\"table\">TABLE</button>
<button id=\"sphere\">SPHERE</button>
<button id=\"helix\">HELIX</button>
<button id=\"grid\">GRID</button>
</div>

<!– <script> –>
<script type=\"module\">
import * as THREE from ’https://threejs.org/build/three.module.js’;
import { TWEEN } from ’https://threejs.org/examples/jsm/libs/tween.module.min.js’;
import { TrackballControls } from ’https://threejs.org/examples/jsm/controls/TrackballControls.js’;
import { CSS3DRenderer, CSS3DObject } from ’https://threejs.org/examples/jsm/renderers/CSS3DRenderer.js’;
    
var table = [
\"P\", \"Hydrogen\", \"1.00794\", 1, 1,
\"P\", \"Helium\", \"4.002602\", 1, 2,
\"P\", \"Lithium\", \"6.941\", 1, 3,
\"P\", \"Beryllium\", \"9.012182\", 1, 4,
\"P\", \"Boron\", \"10.811\", 1, 5,
\"P\", \"Carbon\", \"12.0107\", 2, 1,
\"P\", \"Nitrogen\", \"14.0067\", 2, 3,
\"P\", \"Oxygen\", \"15.9994\", 3, 1,
\"P\", \"Fluorine\", \"18.9984032\", 3, 3,
\"P\", \"Flerovium\", \"(289)\", 4, 2,
\"I\", \"Moscovium\", \"(290)\", 6, 1,
\"I\", \"Livermorium\", \"(293)\", 6, 2,
\"I\", \"Tennessine\", \"(294)\", 6, 3,
\"I\", \"Titanium\", \"47.867\", 6, 4,
\"I\", \"Vanadium\", \"50.9415\", 6, 5,
\"Y\", \"Chromium\", \"51.9961\", 8, 1,
\"Y\", \"Manganese\", \"54.938045\", 9, 2,
\"Y\", \"Iron\", \"55.845\", 10, 3,
\"Y\", \"Cobalt\", \"58.933195\", 10, 4,
\"Y\", \"Nickel\", \"58.6934\", 10, 5,
\"Y\", \"Copper\", \"63.546\", 11, 2,
\"Y\", \"Zinc\", \"65.38\", 12, 1,
\"O\", \"Gallium\", \"69.723\", 14, 1,
\"O\", \"Copernicium\", \"(285)\", 14, 2,
\"O\", \"Nihonium\", \"(286)\", 14, 3,
\"O\", \"Oganesson\", \"(294)\", 14, 4,
\"O\", \"Neon\", \"20.1797\", 14, 5,
\"O\", \"Sodium\", \"22.98976…\", 15, 1,
\"O\", \"Magnesium\", \"24.305\", 15, 5,
\"O\", \"Aluminium\", \"26.9815386\", 16, 1,
\"O\", \"Silicon\", \"28.0855\", 16, 5,
\"O\", \"Phosphorus\", \"30.973762\", 17, 1,
\"O\", \"Sulfur\", \"32.065\", 17, 2,
\"O\", \"Chlorine\", \"35.453\", 17, 3,
\"O\", \"Argon\", \"39.948\", 17, 4,
\"O\", \"Potassium\", \"39.948\", 17, 5,
\"M\", \"Calcium\", \"40.078\", 1, 7,
\"M\", \"Scandium\", \"44.955912\", 1, 8,
\"M\", \"Roentgenium\", \"(280)\", 1, 9,
\"M\", \"Germanium\", \"72.63\", 1, 10,
\"M\", \"Lead\", \"207.2\", 1, 11,      
\"M\", \"Arsenic\", \"74.9216\", 2, 8,
\"M\", \"Selenium\", \"78.96\", 3, 9,
\"M\", \"Bromine\", \"79.904\", 3, 10,
\"M\", \"Krypton\", \"83.798\", 4, 8,
\"M\", \"Rubidium\", \"85.4678\", 5, 7,
\"M\", \"Strontium\", \"87.62\", 5, 8,
\"M\", \"Yttrium\", \"88.90585\", 5, 9,
\"M\", \"Zirconium\", \"91.224\", 5, 10,
\"M\", \"Niobium\", \"92.90628\", 5, 11,
\"A\", \"Molybdenum\", \"95.96\", 7,8,
\"A\", \"Technetium\", \"(98)\", 7, 9,
\"A\", \"Ruthenium\", \"101.07\", 7, 10,
\"A\", \"Rhodium\", \"102.9055\",7, 11,
\"A\", \"Palladium\", \"106.42\", 8, 7,
\"A\", \"Silver\", \"107.8682\", 8,9,
\"A\", \"Cadmium\", \"112.411\", 9, 7,
\"A\", \"Indium\", \"114.818\", 9, 9,
\"A\", \"Tin\", \"118.71\", 10, 8,
\"A\", \"Antimony\", \"121.76\", 10, 9,
\"A\", \"Gadolinium\", \"157.25\", 10, 10,
\"A\", \"Terbium\", \"158.92535\", 10, 11,
\"R\", \"Dysprosium\", \"162.5\", 12, 7,
\"R\", \"Holmium\", \"164.93032\", 12, 8,
\"R\", \"Erbium\", \"167.259\", 12, 9,
\"R\", \"Thulium\", \"168.93421\", 12, 10,
\"R\", \"Ytterbium\", \"173.054\", 12, 11,
\"R\", \"Lutetium\", \"174.9668\", 13, 7,
\"R\", \"Hafnium\", \"178.49\", 13, 9,
\"R\", \"Samarium\", \"150.36\", 14, 7,
\"R\", \"Europium\", \"151.964\", 14, 9,
\"R\", \"Tantalum\", \"180.94788\", 15, 8,
\"R\", \"Tungsten\", \"183.84\", 15, 10,
\"R\", \"Rhenium\", \"186.207\", 15, 11,
\"U\", \"Osmium\", \"190.23\", 17, 7,
\"U\", \"Iridium\", \"192.217\", 17,8,
\"U\", \"Platinum\", \"195.084\", 17, 9,
\"U\", \"Gold\", \"196.966569\", 17, 10,
\"U\", \"Mercury\", \"200.59\", 18, 11,
\"U\", \"Thallium\", \"204.3833\", 19, 11,
\"U\", \"Bismuth\", \"208.9804\", 20, 7,
\"U\", \"Polonium\", \"(209)\", 20, 8,
\"U\", \"Astatine\", \"(210)\", 20, 9,
\"U\", \"Francium\", \"(223)\", 20, 10,
\"U\", \"Radium\", \"(226)\", 22, 9,
\"U\", \"Actinium\", \"(227)\", 22, 10,
\"U\", \"Thorium\", \"232.03806\", 22, 11,
\"A\", \"Protactinium\", \"231.0588\", 22, 7,
\"A\", \"Uranium\", \"238.02891\", 23, 9,
\"A\", \"Neptunium\", \"(237)\", 23, 8,
\"A\", \"Plutonium\", \"(244)\", 23, 9,
\"A\", \"Americium\", \"(243)\", 23, 10,
\"A\", \"Curium\", \"(247)\", 23, 11,
\"S\", \"Berkelium\", \"(247)\", 24, 7,
\"S\", \"Californium\", \"(251)\", 24, 8,
\"S\", \"Einstenium\", \"(252)\", 24, 9,
\"S\", \"Fermium\", \"(257)\", 24, 11,
\"S\", \"Mendelevium\", \"(258)\", 25, 7,
\"S\", \"Nobelium\", \"(259)\", 25, 9,
\"S\", \"Lawrencium\", \"(262)\", 25, 11,
\"S\", \"Rutherfordium\", \"(267)\", 26, 7,
\"S\", \"Dubnium\", \"(268)\", 26, 9,
\"S\", \"Seaborgium\", \"(271)\", 26, 10,
\"S\", \"Bohrium\", \"(272)\", 26, 11,
\"A\", \"Hassium\", \"(270)\", 27, 8,
\"B\", \"Meitnerium\", \"(276)\", 27, 9,
\"C\", \"Darmstadium\", \"(281)\", 27, 8,
\"D\", \"Tellurium\", \"127.6\", 27, 9,
\"E\", \"Iodine\", \"126.90447\", 27, 10,
\"F\", \"Xenon\", \"131.293\", 28, 9,
\"G\", \"Caesium\", \"132.9054\", 28, 10,
\"H\", \"Barium\", \"132.9054\", 28, 11,
\"I\", \"Lanthanum\", \"138.90547\", 29, 8,
\"J\", \"Cerium\", \"140.116\", 29, 9,
\"K\", \"Praseodymium\", \"140.90765\", 29, 10,
\"L\", \"Neodymium\", \"144.242\", 29, 8,
\"M\", \"Promethium\", \"(145)\", 29, 9,
  \"PS\", \"Piyomaru Software\", \"(PiyoPiyo)\", 29, 10,  
  \"AS\", \"AppleScript\", \"(osalang)\", 29, 11,  
];

var camera, scene, renderer;
var controls;
var objects = [];
var targets = { table: [], sphere: [], helix: [], grid: [] };
init();
animate();
    
function init() {
camera = new THREE.PerspectiveCamera(40, window.innerWidth / window.innerHeight, 1, 10000);
camera.position.z = 3000;
scene = new THREE.Scene();
      
// table
for (var i = 0; i < table.length; i += 5) {
      
var element = document.createElement(’div’);
element.className = ’element’;

     //element.style.backgroundColor = ’rgba(128,0,64,’ + ( Math.random() * 0.5 + 0.25 ) + ’)’;
    //element.style.backgroundColor = ’rgba(64,0,128,’ + ( Math.random() * 0.5 + 0.25 ) + ’)’;
//element.style.backgroundColor = ’rgba(0,0,0,’ + ( Math.random() * 0.5 + 0.25 ) + ’)’;
element.style.backgroundColor = ’rgba(0,127,127,’ + ( Math.random() * 0.5 + 0.25 ) + ’)’;
//element.style.backgroundColor = ’rgba(18,77,174,’ + (Math.random() * 0.5 + 0.25) + ’)’;

var number = document.createElement(’div’);
number.className = ’number’;
number.textContent = (i / 5) + 1;
element.appendChild(number);
var symbol = document.createElement(’div’);
symbol.className = ’symbol’;
symbol.textContent = table[i];
element.appendChild(symbol);
var details = document.createElement(’div’);
details.className = ’details’;
details.innerHTML = table[i + 1] + ’<br>’ + table[i + 2];
element.appendChild(details);
var object = new CSS3DObject(element);
object.position.x = Math.random() * 4000 – 2000;
object.position.y = Math.random() * 4000 – 2000;
object.position.z = Math.random() * 4000 – 2000;
scene.add(object);
objects.push(object);
//
var object = new THREE.Object3D();
object.position.x = (table[i + 3] * 140) – 1330;
object.position.y = – (table[i + 4] * 180) + 990;
targets.table.push(object);
}
      
// sphere
var vector = new THREE.Vector3();
for (var i = 0, l = objects.length; i < l; i++) {
var phi = Math.acos(- 1 + (2 * i) / l);
var theta = Math.sqrt(l * Math.PI) * phi;
var object = new THREE.Object3D();
object.position.setFromSphericalCoords(800, phi, theta);
vector.copy(object.position).multiplyScalar(2);
object.lookAt(vector);
targets.sphere.push(object);
}
      
// helix
var vector = new THREE.Vector3();
for (var i = 0, l = objects.length; i < l; i++) {
var theta = i * 0.175 + Math.PI;
var y = – (i * 8) + 450;
var object = new THREE.Object3D();
object.position.setFromCylindricalCoords(900, theta, y);
vector.x = object.position.x * 2;
vector.y = object.position.y;
vector.z = object.position.z * 2;
object.lookAt(vector);
targets.helix.push(object);
}
      
// grid
for (var i = 0; i < objects.length; i++) {
var object = new THREE.Object3D();
object.position.x = ((i % 5) * 400) – 800;
object.position.y = (- (Math.floor(i / 5) % 5) * 400) + 800;
object.position.z = (Math.floor(i / 25)) * 1000 – 2000;
targets.grid.push(object);
}
      
//
renderer = new CSS3DRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.getElementById(’container’).appendChild(renderer.domElement);
      
//
controls = new TrackballControls(camera, renderer.domElement);
controls.minDistance = 500;
controls.maxDistance = 6000;
controls.addEventListener(’change’, render);
      
var button = document.getElementById(’table’);
button.addEventListener(’click’, function () {
transform(targets.table, 2000);
}, false);
      
var button = document.getElementById(’sphere’);
button.addEventListener(’click’, function () {
transform(targets.sphere, 2000);
}, false);
      
var button = document.getElementById(’helix’);
button.addEventListener(’click’, function () {
transform(targets.helix, 2000);
}, false);
      
var button = document.getElementById(’grid’);
button.addEventListener(’click’, function () {
transform(targets.grid, 2000);
}, false);
      
transform(targets.table, 2000);
//
window.addEventListener(’resize’, onWindowResize, false);
}
    
function transform(targets, duration) {
TWEEN.removeAll();
for (var i = 0; i < objects.length; i++) {
var object = objects[i];
var target = targets[i];
new TWEEN.Tween(object.position)
.to({ x: target.position.x, y: target.position.y, z: target.position.z }, Math.random() * duration + duration)
.easing(TWEEN.Easing.Exponential.InOut)
.start();
new TWEEN.Tween(object.rotation)
.to({ x: target.rotation.x, y: target.rotation.y, z: target.rotation.z }, Math.random() * duration + duration)
.easing(TWEEN.Easing.Exponential.InOut)
.start();
}
new TWEEN.Tween(this)
.to({}, duration * 2)
.onUpdate(render)
.start();
}
    
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
render();
}
    
function animate() {
requestAnimationFrame(animate);
TWEEN.update();
controls.update();
}
    
function render() {
renderer.render(scene, camera);
}
</script>
</body>

</html>"

set paramObj to {myMessage:"WebGL & three.js Test", mySubMessage:"This is a WebGL UI using charts.js", htmlStr:myStr}
–my browseStrWebContents:paramObj–for debug
my performSelectorOnMainThread:"browseStrWebContents:" withObject:(paramObj) waitUntilDone:true

on browseStrWebContents:paramObj
  set aMainMes to myMessage of paramObj
  
set aSubMes to mySubMessage of paramObj
  
set htmlString to (htmlStr of paramObj)
  
  
set aWidth to 1600
  
set aHeight to 950
  
  
–WebViewをつくる
  
set aConf to WKWebViewConfiguration’s alloc()’s init()
  
  
–指定HTML内のJavaScriptをFetch
  
set jsSource to pickUpFromToStr(htmlString, "<script src", "</script>") of me
  
  
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)) configuration:aConf
  
aWebView’s setNavigationDelegate:me
  
aWebView’s setUIDelegate:me
  
aWebView’s setTranslatesAutoresizingMaskIntoConstraints:true
  
using terms from scripting additions
    set bURL to |NSURL|’s fileURLWithPath:(POSIX path of (path to me))
  end using terms from
  
aWebView’s loadHTMLString:htmlString baseURL:(bURL)
  
  
— set up alert  
  
set theAlert to NSAlert’s alloc()’s init()
  
tell theAlert
    its setMessageText:aMainMes
    
its setInformativeText:aSubMes
    
its addButtonWithTitle:"OK"
    
–its addButtonWithTitle:"Cancel"
    
its setAccessoryView:aWebView
    
    
set myWindow to its |window|
  end tell
  
  
— show alert in modal loop
  
NSRunningApplication’s currentApplication()’s activateWithOptions:0
  
my performSelectorOnMainThread:"doModal:" withObject:(theAlert) waitUntilDone:true
  
  
–Stop Web View Action
  
set bURL to |NSURL|’s URLWithString:"about:blank"
  
set bReq to NSURLRequest’s requestWithURL:bURL
  
aWebView’s loadRequest:bReq
  
  
if (my returnCode as number) = 1001 then error number -128
end browseStrWebContents:

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

on viewDidLoad:aNotification
  return true
end viewDidLoad:

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

on pickUpFromToStr(aStr as string, s1Str as string, s2Str as string)
  set a1Offset to offset of s1Str in aStr
  
if a1Offset = 0 then return false
  
set bStr to text (a1Offset + (length of s1Str)) thru -1 of aStr
  
set a2Offset to offset of s2Str in bStr
  
if a2Offset = 0 then return false
  
set cStr to text 1 thru (a2Offset – (length of s2Str)) of bStr
  
return cStr as string
end pickUpFromToStr

–リストを任意のデリミタ付きでテキストに
on retArrowText(aList, aDelim)
  set aText to ""
  
set curDelim to AppleScript’s text item delimiters
  
set AppleScript’s text item delimiters to aDelim
  
set aText to aList as text
  
set AppleScript’s text item delimiters to curDelim
  
return aText
end retArrowText

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

on parseByDelim(aData, aDelim)
  set curDelim to AppleScript’s text item delimiters
  
set AppleScript’s text item delimiters to aDelim
  
set dList to text items of aData
  
set AppleScript’s text item delimiters to curDelim
  
return dList
end parseByDelim

★Click Here to Open This Script 

Posted in 3D Animation dialog JSON | Tagged 10.13savvy 10.14savvy 10.15savvy | Leave a comment

Pagesでテキストアイテムか本文テキストから最大文字サイズのテキストを返す

Posted on 6月 12, 2020 by Takaaki Naganoya

Pagesでオープン中の最前面の書類から、最大文字サイズのテキスト(文字ボックス/本文テキスト)を抽出するAppleScriptです。

Pagesでは、本文にテキストをベタ打ちしつつ、文字スタイルを適用していくワープロ的な作り方と、ボックスでテキストアイテムを配置して文字を入れていくDTP的な(?)作り方の2通りがあります(混在できます)。

両方取得して文字サイズが大きい方を採用します。

AppleScript名:テキストアイテムか本文テキストから最大文字サイズのテキストを返す.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2020/06/12
—
–  Copyright © 2020 Piyomaru Software, All Rights Reserved
—

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

property NSMutableArray : a reference to current application’s NSMutableArray

set aRes to getMaxTextFromTextItemsAndBodText() of me
–> {"テクノロジーが色彩(カラー)を決定している例は?"}–本文縦組みテキスト
–> {"AppleScript"}–テキストボックス組みテキスト

on getMaxTextFromTextItemsAndBodText()
  set aRes to getMaxTextFromTextItems() of me
  
set bRes to getMaxTextFromBodyText() of me
  
  
set aMax to maxSize of aRes
  
set bMax to maxSize of bRes
  
  
if aMax > bMax then
    return maxTextList of aRes
  else
    return maxTextList of bRes
  end if
end getMaxTextFromTextItemsAndBodText

on getMaxTextFromTextItems()
  tell application "Pages"
    tell front document
      set tmpList to every text item
      
if length of tmpList > 0 then
        set szList to size of object text of every text item
        
set aMaxPoint to calcMax(szList) of me –最大の文字サイズを取得
        
        
–文字サイズが最大のテキストアイテムを抽出
        
set resList to object text of every text item whose size of object text is aMaxPoint
      else
        set aMaxPoint to 0
        
set resList to {}
      end if
      
return {maxSize:aMaxPoint, maxTextList:resList}
    end tell
  end tell
end getMaxTextFromTextItems

–本文テキストから最大文字サイズのテキストを取得する
on getMaxTextFromBodyText()
  tell application "Pages"
    tell front document
      tell body text
        set tmpP to every paragraph
        
if tmpP = {""} then
          return {maxSize:0, maxTextList:{}}
        end if
        
        
–フォントサイズのみパラグラフ単位に取得
        
set szList to size of every paragraph
        
set aMaxPoint to calcMax(szList) of me –最大の文字サイズを取得
        
        
–文字サイズが最大のパラグラフを抽出
        
set resList to every paragraph whose size is aMaxPoint
        
–> {"テクノロジーが色彩(カラー)を決定している例は?"}
        
        
return {maxSize:aMaxPoint, maxTextList:resList}
      end tell
    end tell
  end tell
end getMaxTextFromBodyText

on calcMax(aList as list)
  set nArray to (NSMutableArray’s arrayWithArray:aList)
  
set maxRes to (nArray’s valueForKeyPath:"@max.self")’s doubleValue()
  
return maxRes
end calcMax

★Click Here to Open This Script 

Posted in list | Tagged 10.14savvy 10.15savvy Pages | Leave a comment

Pagesで最前面の書類中のテキストアイテムの文字サイズが最大のもののテキストを求める

Posted on 6月 12, 2020 by Takaaki Naganoya

Pagesでオープン中の最前面の書類から、最大文字サイズのテキストアイテム(文字ボックス)のテキストを抽出するAppleScriptです。

Pagesでは、本文にテキストをベタ打ちしつつ、文字スタイルを適用していくワープロ的な作り方と、ボックスでテキストアイテムを配置して文字を入れていくDTP的な(?)作り方の2通りがあります(混在できます)。

ここでは、ボックスでテキストアイテムを配置して作っています。

AppleScript名:最前面の書類中のテキストアイテムの文字サイズが最大のもののテキストを求める.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2020/06/12
—
–  Copyright © 2020 Piyomaru Software, All Rights Reserved
—

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

property NSMutableArray : a reference to current application’s NSMutableArray

tell application "Pages"
  tell front document
    set tmpList to every text item
    
if length of tmpList = 0 then return –テキストアイテムがない場合には処理終了
    
    
set szList to size of object text of every text item
    
set aMaxPoint to calcMax(szList) of me –最大の文字サイズを取得
    
    
–文字サイズが最大のテキストアイテムを抽出
    
set resList to object text of every text item whose size of object text is aMaxPoint
    
–> {"AppleScript"}
  end tell
end tell

on calcMax(aList as list)
  set nArray to (NSMutableArray’s arrayWithArray:aList)
  
set maxRes to (nArray’s valueForKeyPath:"@max.self")’s doubleValue()
  
return maxRes
end calcMax

★Click Here to Open This Script 

Posted in list | Tagged 10.14savvy 10.15savvy NSMutableArray Pages | Leave a comment

Pagesで書類中の最大文字サイズのパラグラフのテキストを抽出

Posted on 6月 12, 2020 by Takaaki Naganoya

Pagesでオープン中の最前面の書類から、最大文字サイズのパラグラフ(段落)のテキストを抽出するAppleScriptです。

Pages v10.0で縦組みのテキスト中心の書類を作っていて、そのタイトルに該当する部分のテキストを抽出したいと考えておりました。

Pagesでは、本文にテキストをベタ打ちしつつ、文字スタイルを適用していくワープロ的な作り方と、ボックスでテキストアイテムを配置して文字を入れていくDTP的な(?)作り方の2通りがあります(混在できます)。

ここでは、本文テキストベタ打ちで作っています。

本来であれば、各パラグラフに指定されたスタイルの名称を取得して、スタイル名が「タイトル」だったらタイトルと判定するのが他のアプリケーションでの処理ですが、Pagesにはスタイル名を取得する機能はありません。

そこで、書類中の全パラグラフの文字サイズを取得し、その最大値を求め、最大値の文字サイズを持つパラグラフを求めるようにしてみました。

こういう(↑)文字ボックスを配置して作成した書類では、本Scriptのアプローチではタイトルを取得できません。

AppleScript名:書類中の最大文字サイズのパラグラフのテキストを抽出.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2020/06/12
—
–  Copyright © 2020 Piyomaru Software, All Rights Reserved
—

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

property NSMutableArray : a reference to current application’s NSMutableArray

tell application "Pages"
  tell front document
    tell body text
      –フォントサイズのみパラグラフ単位に取得
      
set szList to size of every paragraph
      
set aMaxPoint to calcMax(szList) of me –最大の文字サイズを取得
      
      
–文字サイズが最大のパラグラフを抽出
      
set resList to every paragraph whose size is aMaxPoint
      
–> {"テクノロジーが色彩(カラー)を決定している例は?"}
    end tell
  end tell
end tell

on calcMax(aList as list)
  set nArray to (NSMutableArray’s arrayWithArray:aList)
  
set maxRes to (nArray’s valueForKeyPath:"@max.self")’s doubleValue()
  
return maxRes
end calcMax

★Click Here to Open This Script 

Posted in list | Tagged 10.14savvy 10.15savvy NSMutableArray Pages | Leave a comment

Automator Actionを実行 v3

Posted on 6月 7, 2020 by Takaaki Naganoya

指定のAutomator Actionをパラメータ指定つきで実行するAppleScriptです。

Automatorは、登場当初から「なにこれ、仕様がダメダメじゃん」という感想しかありませんでした。

各Actionをキーワード検索できる仕様になっているものの、検索キーワードが固定で、ゆらぎを許容しない狂気の仕様。

その割に、ものによっては「写真」だったり「画像」だったりと、検索キーワードがゆらぎまくっています。とくに日本語などという同義語がたくさん存在する系の言語では、その苦痛は尋常なものではありません。

# フィードバックしたものの、Apple側が聞く耳持たない感じだったのでVersion 1.0で見捨てました

おまけに、まとまった処理を書こうとすると、途中の処理をつなぐActionがごっそり存在せず、あとはひたすら普通にAppleScriptを書くことに。気がつくと、スクリプトエディタで書いたほうがはるかに速い……とまあ、自分とAutomatorの相性は最悪です。

とはいえ、この先何があるかわかりません。Automatorにしかない機能を呼び出さないと実現できない(奇特な)処理に遭遇するかもしれません。Automator Actionを呼び出す方法についても、一応経験を積んでおくべきでしょう。

AMWorkflow経由でAutomator Actionを呼び出したとき、指定できるパラメータはAction自体のURLと、inputパラメータ。

inputパラメータについては、指定したものがそのままAutomator Action側に伝えられるようです。

Automator Action側のinputにこのinputパラメータの内容が伝えられるようです。一方のparametersパラメータについては、

{|temporary items path|:"/var/folders/h4/...../1/com.apple.Automator.RunScript", ignoresInput:false, source:"on run {input, parameters}
	set aClass to convToStr(input)
	display dialog aClass as string
....

のような内容になっていました。

若干間違っていたのと、AMWorkflowを呼び出すのにメインスレッド実行を強制する必要はなかったので修正版を掲載しておきます。

AppleScript名:Automator Actionを実行 v3.1
–Original By Shane Stanley 2020/1/28
–https://www.macscripter.net/viewtopic.php?id=47364
–Modified by Takaaki Naganoya 2020/6/4
–Error reported by hiro 2020/6/10
use AppleScript version "2.5" — macOS 10.11 or later
use framework "Foundation"
use framework "Automator"
use scripting additions

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

set thePath to POSIX path of (choose file of type {"com.apple.automator-workflow"})
set {theResult, theError} to runWorkflow(thePath, "AAA") of me
–> {<NSAppleEventDescriptor: ’utxt’("OK")>, missing value}

on runWorkflow(thePath, theInput)
  set theURL to |NSURL|’s fileURLWithPath:thePath
  
set {theResult, theError} to AMWorkflow’s runWorkflowAtURL:(theURL) withInput:theInput |error|:(reference)
  
return {theResult, theError}
end runWorkflow

★Click Here to Open This Script 

Posted in URL | Tagged 10.13savvy 10.14savvy 10.15savvy AMWorkflow Automator NSURL | 3 Comments

PDFにウォーターマーク画像を重ね合わせる2

Posted on 6月 4, 2020 by Takaaki Naganoya

指定のPDFにウォーターマークのPDFを重ね合わせるAppleScriptです。

これまでにもいろいろ試してきたのですが、不可能ではないものの、再配布が難しかったりアプリケーションに依存していたりで、決定版とはなっていませんでした。

macscripter.netにpeavine氏が投稿したScriptが元になっています。同氏のScriptではcpdfというコマンドラインツールが用いられており、これがなかなかいい感じです。実行時には、cpdfが/usr/local/binに入っている必要があります。Script Bundleの中に入れて呼び出してもよさそうです。

いい感じではあるものの、商用利用は許可されていないとのこと(要、購入)なので、商用利用時にはライセンスを購入すべきでしょう。再配布もできない雰囲気なので、自分のアプリケーション内に入れて呼び出すとかいうのは無理です。

ファイルの複数選択に、自分で作った「choosePathLib」を用いています。NSPathControlにドラッグ&ドロップできるファイル種別を限定できるように作っておけばよかった、と反省しまくりました。

Watermark画像をPDFに重ね合わせる処理については、こういう外部ツールを併用しないでAppleScriptだけで済めばベストですが、、、、


▲オリジナルPDF


▲WatermarkのPDF。背景色に透明を指定している


▲処理対象ファイル選択


▲処理後のPDF。Watermarkが各ページに重ね合わされていることがわかる


▲処理後のPDFにはPDF Creator情報にcpdfのCopyrightが記入される

AppleScript名:PDFにウォーターマーク画像を重ね合わせる2
—
–  Created by: peavine @macscripter.net
–  Created on: 2020/06/04
–  Modified by: Takaaki Naganoya @ Piyomaru Software
–  cpdf
–  https://community.coherentpdf.com

use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use scripting additions
use pLib : script "choosePathLib" –http://piyocast.com/as/asinyaye

set mesList to {"Logo PDF", "Source PDF"}
set defaultLocList to {"~/Movies", "~/Desktop"}

set cRes to choose multiple path main message "Drag & Drop to set target" sub message "" with titles mesList with default locations defaultLocList dialog width 800

set outFile to POSIX path of (choose file name with prompt "Select Output PDF File name")

copy cRes to {logoFile, sourceFile}

set logoFile to POSIX path of logoFile
set sourceFile to POSIX path of sourceFile

–check file extension = file type
if logoFile does not end with ".pdf" then error "Logo path is not pdf"
if sourceFile does not end with ".pdf" then error "Source file is not pdf"
if outFile does not end with ".pdf" then error "output path is not pdf"

try
  do shell script "/usr/local/bin/cpdf -stamp-on " & quoted form of logoFile & " -center " & quoted form of sourceFile & " -o " & quoted form of outFile
end try

★Click Here to Open This Script 

Posted in dialog file PDF | Tagged 10.13savvy 10.14savvy 10.15savvy | Leave a comment

アラートダイアログ上にWebViewでGoogle Chartを表示(Column Chart)

Posted on 6月 3, 2020 by Takaaki Naganoya

アラートダイアログ上にWkWebViewを配置し、Google Chartsを用いてカラムチャート(縦棒グラフ)を表示するAppleScriptです。

大枠はAppleScriptで、Cocoaの機能を活用してWkWebViewを動的に生成し、その中にJavaScript入りのHTMLを文字列で作って表示させ、WkWebView上でマウスカーソルの挙動に合わせて表示させる(このあたりはGoogle Chartsの機能)という、3階建ぐらいの構造のScriptです。

AppleScriptの配列変数(リスト型変数)をJavaScriptで扱えるJSON形式に変換して、HTML+JavaScriptのテンプレートにはめこんで、WkWebViewに表示させてグラフ描画実行を行なっています。表示データをAppleScriptのデータ(リスト型変数)で与えられる点がチャームポイントです。

AppleScript名:アラートダイアログ上にWebViewでGoogle Chartを表示(Column Chart).scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2020/05/30
—
–  Copyright © 2020 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use framework "AppKit"
use framework "WebKit"
use scripting additions

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

property returnCode : 0

set aList to {{"Year", "Sales", "Expenses", "Profit"}, ¬
  {"2014", 1000, 400, 200}, ¬
  {
"2015", 1170, 460, 250}, ¬
  {
"2016", 660, 1120, 300}, ¬
  {
"2017", 1030, 540, 350}}

set aJsonArrayStr to array2DToJSONArray(aList) of me

–Pie Chart Template HTML
set myStr to "<!DOCTYPE html>
<html lang=\"UTF-8\">
<head>
<script type=\"text/javascript\" src=\"https://www.gstatic.com/charts/loader.js\"></script>

<script type=\"text/javascript\">
// Load google charts
google.charts.load(’current’, {’packages’:[’bar’]});
google.charts.setOnLoadCallback(drawChart);

// Draw the chart and set the chart values
function drawChart() {
var data =google.visualization.arrayToDataTable(%@);

// Optional; add a title and set the width and height of the chart
var options = {
chart: {
title: ’Company Performance’,
subtitle: ’Sales, Expenses, and Profit: 2014-2017’,
}
};

// Display the chart inside the <div> element with id=\"columnchart_values\"
var chart = new google.charts.Bar(document.getElementById(\"columnchart_material\"));
chart.draw(data, google.charts.Bar.convertOptions(options));
}
</script>
<body>
<div id=\"columnchart_material\" style=\"width: 800px; height: 200;\"></div>
</body>
</html>"

set aString to current application’s NSString’s stringWithFormat_(myStr, aJsonArrayStr) as string

set paramObj to {myMessage:"Column Chart Test", mySubMessage:"This is a simple Column chart using google charts", htmlStr:aString}
–my browseStrWebContents:paramObj–for debug
my performSelectorOnMainThread:"browseStrWebContents:" withObject:(paramObj) waitUntilDone:true

on browseStrWebContents:paramObj
  set aMainMes to myMessage of paramObj
  
set aSubMes to mySubMessage of paramObj
  
set htmlString to (htmlStr of paramObj)
  
  
set aWidth to 820
  
set aHeight to 220
  
  
–WebViewをつくる
  
set aConf to WKWebViewConfiguration’s alloc()’s init()
  
  
–指定HTML内のJavaScriptをFetch
  
set jsSource to pickUpFromToStr(htmlString, "<script type=\"text/javascript\">", "</script>") of me
  
  
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)) configuration:aConf
  
aWebView’s setNavigationDelegate:me
  
aWebView’s setUIDelegate:me
  
aWebView’s setTranslatesAutoresizingMaskIntoConstraints:true
  
using terms from scripting additions
    set bURL to |NSURL|’s fileURLWithPath:(POSIX path of (path to me))
  end using terms from
  
aWebView’s loadHTMLString:htmlString baseURL:(bURL)
  
  
— set up alert  
  
set theAlert to NSAlert’s alloc()’s init()
  
tell theAlert
    its setMessageText:aMainMes
    
its setInformativeText:aSubMes
    
its addButtonWithTitle:"OK"
    
–its addButtonWithTitle:"Cancel"
    
its setAccessoryView:aWebView
    
    
set myWindow to its |window|
  end tell
  
  
— show alert in modal loop
  
NSRunningApplication’s currentApplication()’s activateWithOptions:0
  
my performSelectorOnMainThread:"doModal:" withObject:(theAlert) waitUntilDone:true
  
  
–Stop Web View Action
  
set bURL to |NSURL|’s URLWithString:"about:blank"
  
set bReq to NSURLRequest’s requestWithURL:bURL
  
aWebView’s loadRequest:bReq
  
  
if (my returnCode as number) = 1001 then error number -128
end browseStrWebContents:

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

on viewDidLoad:aNotification
  return true
end viewDidLoad:

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

on pickUpFromToStr(aStr as string, s1Str as string, s2Str as string)
  set a1Offset to offset of s1Str in aStr
  
if a1Offset = 0 then return false
  
set bStr to text (a1Offset + (length of s1Str)) thru -1 of aStr
  
set a2Offset to offset of s2Str in bStr
  
if a2Offset = 0 then return false
  
set cStr to text 1 thru (a2Offset – (length of s2Str)) of bStr
  
return cStr as string
end pickUpFromToStr

–リストを任意のデリミタ付きでテキストに
on retArrowText(aList, aDelim)
  set aText to ""
  
set curDelim to AppleScript’s text item delimiters
  
set AppleScript’s text item delimiters to aDelim
  
set aText to aList as text
  
set AppleScript’s text item delimiters to curDelim
  
return aText
end retArrowText

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

on parseByDelim(aData, aDelim)
  set curDelim to AppleScript’s text item delimiters
  
set AppleScript’s text item delimiters to aDelim
  
set dList to text items of aData
  
set AppleScript’s text item delimiters to curDelim
  
return dList
end parseByDelim

★Click Here to Open This Script 

Posted in dialog JSON | Tagged 10.13savvy 10.14savvy 10.15savvy NSAlert NSButton NSRunningApplication NSString NSURL NSURLRequest NSUTF8StringEncoding WKUserContentController WKUserScript WKUserScriptInjectionTimeAtDocumentEnd WKWebView WKWebViewConfiguration | Leave a comment

アラートダイアログ上にWebViewでGoogle Chartを表示(Bubble Chart)

Posted on 6月 1, 2020 by Takaaki Naganoya

アラートダイアログ上にWkWebViewを配置し、Google Chartsを用いてバブルチャートを表示するAppleScriptです。

バブルチャートというのは、3軸の数値の組みわせデータをX軸とY軸に加え、バブル(円)のサイズでもう1軸表現したもののようです。

サンプルでは、X軸に平均寿命、Y軸に出生率、Z軸に人口をとっています。データ件数がそんなに多くなくて、データが散らばっている場合にはその傾向がよく把握できそうです(本グラフのように)。

自動処理のワークフローにおいて本Scriptがどの程度役立つかについては、いろいろ考えてみたものの「多分、Blogに掲載するぐらいしか使い道がないよね!」というところでしょうか。やはり、オーソドックスな円グラフや棒グラフのほうが使い手がよさそうです。あとは、デモンストレーションぐらいでしょうか。Google Chartsを用いたダイアログ部品自体が、デモ向けのそれほど意味のなさそうな内容であります。

AppleScript名:アラートダイアログ上にWebViewでGoogle Chartを表示(Bubble Chart).scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2020/05/30
—
–  Copyright © 2020 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use framework "AppKit"
use framework "WebKit"
use scripting additions
–https://developers.google.com/chart/interactive/docs/gallery/bubblechart

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

property returnCode : 0

set aList to {{"ID", "平均寿命", "出生率", "地域", "人口"}, ¬
  {"CAN", 80.66, 1.67, "北米", 33739900}, ¬
  {
"DEU", 79.84, 1.36, "欧州", 81902307}, ¬
  {
"DNK", 78.6, 1.84, "欧州", 5523095}, ¬
  {
"EGY", 72.73, 2.78, "中東", 79716203}, ¬
  {
"GBR", 80.05, 2, "欧州", 61801570}, ¬
  {
"IRN", 72.49, 1.7, "中東", 73137148}, ¬
  {
"IRQ", 68.09, 4.77, "中東", 31090763}, ¬
  {
"ISR", 81.55, 2.96, "中東", 7485600}, ¬
  {
"RUS", 68.6, 1.54, "欧州", 141850000}, ¬
  {
"USA", 78.09, 2.05, "北米", 307007000}}

set aJsonArrayStr to array2DToJSONArray(aList) of me

–Pie Chart Template HTML
set myStr to "<!DOCTYPE html>
<html lang=\"UTF-8\">
<head>
<script type=\"text/javascript\" src=\"https://www.gstatic.com/charts/loader.js\"></script>
<script type=\"text/javascript\">
// Load google charts
google.charts.load(’current’, {’packages’:[’corechart’]});
google.charts.setOnLoadCallback(drawSeriesChart);

// Draw the chart and set the chart values
function drawSeriesChart() {
var data =google.visualization.arrayToDataTable(%@);

// Optional; add a title and set the width and height of the chart
var options = {
title: ’Correlation between life expectancy, fertility rate ’ + ’and population of some world countries (2010)’,
hAxis: {title: ’平均寿命’},
vAxis: {title: ’出生率’},
bubble: {textStyle: {fontSize: 11}} };

// Display the chart inside the <div> element with id=\"barchart\"
var chart = new google.visualization.BubbleChart(document.getElementById(’series_chart_div’));
chart.draw(data, options);
}
</script>
<body>
<div id=\"series_chart_div\" style=\"width: 800px; height: 200;\"></div>
</body>
</html>"

set aString to current application’s NSString’s stringWithFormat_(myStr, aJsonArrayStr) as string

set paramObj to {myMessage:"Bubble Chart Test", mySubMessage:"This is a simple Bubble Chart using google charts", htmlStr:aString}
–my browseStrWebContents:paramObj–for debug
my performSelectorOnMainThread:"browseStrWebContents:" withObject:(paramObj) waitUntilDone:true

on browseStrWebContents:paramObj
  set aMainMes to myMessage of paramObj
  
set aSubMes to mySubMessage of paramObj
  
set htmlString to (htmlStr of paramObj)
  
  
set aWidth to 820
  
set aHeight to 220
  
  
–WebViewをつくる
  
set aConf to WKWebViewConfiguration’s alloc()’s init()
  
  
–指定HTML内のJavaScriptをFetch
  
set jsSource to pickUpFromToStr(htmlString, "<script type=\"text/javascript\">", "</script>") of me
  
  
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)) configuration:aConf
  
aWebView’s setNavigationDelegate:me
  
aWebView’s setUIDelegate:me
  
aWebView’s setTranslatesAutoresizingMaskIntoConstraints:true
  
using terms from scripting additions
    set bURL to |NSURL|’s fileURLWithPath:(POSIX path of (path to me))
  end using terms from
  
aWebView’s loadHTMLString:htmlString baseURL:(bURL)
  
  
— set up alert  
  
set theAlert to NSAlert’s alloc()’s init()
  
tell theAlert
    its setMessageText:aMainMes
    
its setInformativeText:aSubMes
    
its addButtonWithTitle:"OK"
    
–its addButtonWithTitle:"Cancel"
    
its setAccessoryView:aWebView
    
    
set myWindow to its |window|
  end tell
  
  
— show alert in modal loop
  
NSRunningApplication’s currentApplication()’s activateWithOptions:0
  
my performSelectorOnMainThread:"doModal:" withObject:(theAlert) waitUntilDone:true
  
  
–Stop Web View Action
  
set bURL to |NSURL|’s URLWithString:"about:blank"
  
set bReq to NSURLRequest’s requestWithURL:bURL
  
aWebView’s loadRequest:bReq
  
  
if (my returnCode as number) = 1001 then error number -128
end browseStrWebContents:

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

on viewDidLoad:aNotification
  return true
end viewDidLoad:

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

on pickUpFromToStr(aStr as string, s1Str as string, s2Str as string)
  set a1Offset to offset of s1Str in aStr
  
if a1Offset = 0 then return false
  
set bStr to text (a1Offset + (length of s1Str)) thru -1 of aStr
  
set a2Offset to offset of s2Str in bStr
  
if a2Offset = 0 then return false
  
set cStr to text 1 thru (a2Offset – (length of s2Str)) of bStr
  
return cStr as string
end pickUpFromToStr

–リストを任意のデリミタ付きでテキストに
on retArrowText(aList, aDelim)
  set aText to ""
  
set curDelim to AppleScript’s text item delimiters
  
set AppleScript’s text item delimiters to aDelim
  
set aText to aList as text
  
set AppleScript’s text item delimiters to curDelim
  
return aText
end retArrowText

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

★Click Here to Open This Script 

Posted in dialog | Tagged 10.13savvy 10.14savvy 10.15savvy NSAlert NSButton NSRunningApplication NSString NSURL NSURLRequest NSUTF8StringEncoding WKUserContentController WKUserScript WKUserScriptInjectionTimeAtDocumentEnd WKWebView WKWebViewConfiguration | Leave a comment

アラートダイアログ上にWebViewでGoogle Chartを表示(Gantt Chart)

Posted on 6月 1, 2020 by Takaaki Naganoya

アラートダイアログ上にWkWebViewを配置し、Google Chartsを用いてガントチャートを表示するAppleScriptです。

ガントチャートの表示が行えるのは、なかなか便利そうです。ガントチャート系でAppleScriptから操作が行えるのは、Omni Planぐらいなので、ガントチャート表示用部品が増えるのはいいことです。

# ただ、ガントチャートのデータをもとに自動処理したことはありません。人間との間で行う対話処理が重要なので、自動処理で「あとはよろしくぅ!」というワークフローがそんなに思いつきません(予定が変わった担当者に自動で連絡しておくぐらい?)

何らかのデータ処理を行なった末にガントチャートで結果を表示する……という流れになるとは思うのですが、結果に納得できない場合にデータ修正できるようになっていないと、「なんですかそれは?」という話になりかねません。

なので、表UIでデータを入力し、その内容を反映させたガントチャートを表示。表UIとガントチャートの間で自由に行き来できる必要があります。Google Chartsではこのように複数のグラフUIを組み合わせる(並べて表示、再描画を連動)こともできるため、そういう組み合わせで利用するための「下調べ」といったところでしょう。

AppleScript名:アラートダイアログ上にWebViewでGoogle Chartを表示(Gantt Chart).scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2020/05/27
—
–  Copyright © 2020 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use framework "AppKit"
use framework "WebKit"
use scripting additions

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

property returnCode : 0
property aBrowserAgentRes : ""

–Sample Data
–set aJsonArrayStr to array2DToJSONArray(aList) of me

–Map Template HTML
set myStr to "<!DOCTYPE html>
<html lang=\"UTF-8\">
<head>
<script type=\"text/javascript\" src=\"https://www.gstatic.com/charts/loader.js\"></script>

<script type=\"text/javascript\">
google.charts.load(’current’, {’packages’:[’gantt’]});
google.charts.setOnLoadCallback(drawChart);

function daysToMilliseconds(days) {
return days * 24 * 60 * 60 * 1000;
}

function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn(’string’, ’Task ID’);
data.addColumn(’string’, ’Task Name’);
data.addColumn(’date’, ’Start Date’);
data.addColumn(’date’, ’End Date’);
data.addColumn(’number’, ’Duration’);
data.addColumn(’number’, ’Percent Complete’);
data.addColumn(’string’, ’Dependencies’);

data.addRows([
[’Research’, ’Find sources’,
new Date(2015, 0, 1), new Date(2015, 0, 5), null, 100, null],
[’Write’, ’Write paper’,
null, new Date(2015, 0, 9), daysToMilliseconds(3), 25, ’Research,Outline’],
[’Cite’, ’Create bibliography’,
null, new Date(2015, 0, 7), daysToMilliseconds(1), 20, ’Research’],
[’Complete’, ’Hand in paper’,
null, new Date(2015, 0, 10), daysToMilliseconds(1), 0, ’Cite,Write’],
[’Outline’, ’Outline paper’,
null, new Date(2015, 0, 6), daysToMilliseconds(1), 100, ’Research’]
]);

var options = {
height: 275
};

var chart = new google.visualization.Gantt(document.getElementById(’chart_div’));

chart.draw(data, options);
}
</script>
</head>
<body>
  <div id=\"chart_div\"></div>
</body>
</html>"

–set aString to NSString’s stringWithFormat_(myStr, aJsonArrayStr) as string

set paramObj to {myMessage:"Google Gantt Chart Test", mySubMessage:"This is a simple Gantt Chart using google charts", htmlStr:myStr}
–my browseStrWebContents:paramObj –for debug
my performSelectorOnMainThread:"browseStrWebContents:" withObject:(paramObj) waitUntilDone:true

on browseStrWebContents:paramObj
  set aMainMes to myMessage of paramObj
  
set aSubMes to mySubMessage of paramObj
  
set htmlString to (htmlStr of paramObj)
  
  
set aWidth to 1000
  
set aHeight to 300
  
  
–WebViewをつくる
  
set aConf to WKWebViewConfiguration’s alloc()’s init()
  
  
–指定HTML内のJavaScriptをFetch
  
set jsSource to pickUpFromToStr(htmlString, "<script type=\"text/javascript\">", "</script>") of me
  
  
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)) configuration:aConf
  
aWebView’s setNavigationDelegate:me
  
aWebView’s setUIDelegate:me
  
aWebView’s setTranslatesAutoresizingMaskIntoConstraints:true
  
  
set bURL to |NSURL|’s fileURLWithPath:(POSIX path of (path to me))
  
aWebView’s loadHTMLString:htmlString baseURL:(bURL)
  
  
— set up alert  
  
set theAlert to NSAlert’s alloc()’s init()
  
tell theAlert
    its setMessageText:aMainMes
    
its setInformativeText:aSubMes
    
its addButtonWithTitle:"OK"
    
–its addButtonWithTitle:"Cancel"
    
its setAccessoryView:aWebView
    
    
set myWindow to its |window|
  end tell
  
  
— show alert in modal loop
  
NSRunningApplication’s currentApplication()’s activateWithOptions:0
  
my performSelectorOnMainThread:"doModal:" withObject:(theAlert) waitUntilDone:true
  
  
–Stop Web View Action
  
set bURL to |NSURL|’s URLWithString:"about:blank"
  
set bReq to NSURLRequest’s requestWithURL:bURL
  
aWebView’s loadRequest:bReq
  
  
if (my returnCode as number) = 1001 then error number -128
end browseStrWebContents:

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

on viewDidLoad:aNotification
  return true
end viewDidLoad:

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

on pickUpFromToStr(aStr as string, s1Str as string, s2Str as string)
  set a1Offset to offset of s1Str in aStr
  
if a1Offset = 0 then return false
  
set bStr to text (a1Offset + (length of s1Str)) thru -1 of aStr
  
set a2Offset to offset of s2Str in bStr
  
if a2Offset = 0 then return false
  
set cStr to text 1 thru (a2Offset – (length of s2Str)) of bStr
  
return cStr as string
end pickUpFromToStr

–リストを任意のデリミタ付きでテキストに
on retArrowText(aList, aDelim)
  set aText to ""
  
set curDelim to AppleScript’s text item delimiters
  
set AppleScript’s text item delimiters to aDelim
  
set aText to aList as text
  
set AppleScript’s text item delimiters to curDelim
  
return aText
end retArrowText

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

★Click Here to Open This Script 

Posted in dialog | Tagged 10.13savvy 10.14savvy 10.15savvy NSAlert NSArray NSBundle NSButton NSRunningApplication NSString NSURL NSURLRequest NSUTF8StringEncoding WKUserContentController WKUserScript WKUserScriptInjectionTimeAtDocumentEnd WKWebView WKWebViewConfiguration | Leave a comment

アラートダイアログ上にWebViewでGoogle Chartを表示(Bar Chart)

Posted on 5月 30, 2020 by Takaaki Naganoya

アラートダイアログ上にWkWebViewを配置し、Google Chartsを用いてbarChartを表示するAppleScriptです。

Googleのオンラインドキュメント品質が一定になっておらず、一番簡単なはずの棒グラフを書かせるのに手間取ってしまいました。

Cocoa Scriptingを始めた当初は、このJavaScriptを含んだHTMLコンテンツをダイアログ上に表示してインタラクティブな表示を行わせるなど、夢のまた夢という感じでしたが、いまでは見慣れた光景になってしまいました。

箱庭ダイアログ系AppleScriptも、YouTubeの動画表示ができるようになった頃から、進化にはずみがついた気がします。

ひととおりGoogle Chartsを表示できるようになったので、チャート表示のScript Libraryにまとめ、sdef(AppleScript用語辞書)をかぶせてカプセル化するといい感じでしょうか。Google Charts Scripting Libとかいって、display google chartコマンドを実行するのでしょうか。そこまで作り込むと、無料公開は勘弁して欲しいところですけれども。

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

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

property returnCode : 0

set aList to {{"City", "2010 Population", "2000 Population"}, ¬
  {"New York City, NY", 8175000, 8008000}, ¬
  {
"Los Angeles, CA", 3792000, 3694000}, ¬
  {
"Chicago, IL", 2695000, 2896000}, ¬
  {
"Houston, TX", 2099000, 1953000}, ¬
  {
"Philadelphia, PA", 1526000, 1517000}}

set aJsonArrayStr to array2DToJSONArray(aList) of me

–Pie Chart Template HTML
set myStr to "<!DOCTYPE html>
<html lang=\"UTF-8\">
<head>
<script type=\"text/javascript\" src=\"https://www.gstatic.com/charts/loader.js\"></script>

<script type=\"text/javascript\">
// Load google charts
google.charts.load(’current’, {’packages’:[’corechart’, ’bar’]});
google.charts.setOnLoadCallback(drawChart);

// Draw the chart and set the chart values
function drawChart() {
var data =google.visualization.arrayToDataTable(%@);

// Optional; add a title and set the width and height of the chart
var options = {
  title: ’Population’,
  chartArea: {width: ’400’},
  isStacked: true,
  hAxis: {
   title: ’Total Population’,
   minValue: 0,
  },
  vAxis: {
   title: ’City’
  }
};

// Display the chart inside the <div> element with id=\"barchart\"
var chart = new google.visualization.BarChart(document.getElementById(\"barchart_values\"));
chart.draw(data, options);
}
</script>
<body>
<div id=\"barchart_values\" style=\"width: 800px; height: 200;\"></div>
</body>
</html>"

set aString to current application’s NSString’s stringWithFormat_(myStr, aJsonArrayStr) as string

set paramObj to {myMessage:"Bar Chart Test", mySubMessage:"This is a simple bar chart using google charts", htmlStr:aString}
–my browseStrWebContents:paramObj–for debug
my performSelectorOnMainThread:"browseStrWebContents:" withObject:(paramObj) waitUntilDone:true

on browseStrWebContents:paramObj
  set aMainMes to myMessage of paramObj
  
set aSubMes to mySubMessage of paramObj
  
set htmlString to (htmlStr of paramObj)
  
  
set aWidth to 820
  
set aHeight to 220
  
  
–WebViewをつくる
  
set aConf to WKWebViewConfiguration’s alloc()’s init()
  
  
–指定HTML内のJavaScriptをFetch
  
set jsSource to pickUpFromToStr(htmlString, "<script type=\"text/javascript\">", "</script>") of me
  
  
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)) configuration:aConf
  
aWebView’s setNavigationDelegate:me
  
aWebView’s setUIDelegate:me
  
aWebView’s setTranslatesAutoresizingMaskIntoConstraints:true
  
using terms from scripting additions
    set bURL to |NSURL|’s fileURLWithPath:(POSIX path of (path to me))
  end using terms from
  
aWebView’s loadHTMLString:htmlString baseURL:(bURL)
  
  
— set up alert  
  
set theAlert to NSAlert’s alloc()’s init()
  
tell theAlert
    its setMessageText:aMainMes
    
its setInformativeText:aSubMes
    
its addButtonWithTitle:"OK"
    
–its addButtonWithTitle:"Cancel"
    
its setAccessoryView:aWebView
    
    
set myWindow to its |window|
  end tell
  
  
— show alert in modal loop
  
NSRunningApplication’s currentApplication()’s activateWithOptions:0
  
my performSelectorOnMainThread:"doModal:" withObject:(theAlert) waitUntilDone:true
  
  
–Stop Web View Action
  
set bURL to |NSURL|’s URLWithString:"about:blank"
  
set bReq to NSURLRequest’s requestWithURL:bURL
  
aWebView’s loadRequest:bReq
  
  
if (my returnCode as number) = 1001 then error number -128
end browseStrWebContents:

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

on viewDidLoad:aNotification
  return true
end viewDidLoad:

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

on pickUpFromToStr(aStr as string, s1Str as string, s2Str as string)
  set a1Offset to offset of s1Str in aStr
  
if a1Offset = 0 then return false
  
set bStr to text (a1Offset + (length of s1Str)) thru -1 of aStr
  
set a2Offset to offset of s2Str in bStr
  
if a2Offset = 0 then return false
  
set cStr to text 1 thru (a2Offset – (length of s2Str)) of bStr
  
return cStr as string
end pickUpFromToStr

–リストを任意のデリミタ付きでテキストに
on retArrowText(aList, aDelim)
  set aText to ""
  
set curDelim to AppleScript’s text item delimiters
  
set AppleScript’s text item delimiters to aDelim
  
set aText to aList as text
  
set AppleScript’s text item delimiters to curDelim
  
return aText
end retArrowText

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

on parseByDelim(aData, aDelim)
  set curDelim to AppleScript’s text item delimiters
  
set AppleScript’s text item delimiters to aDelim
  
set dList to text items of aData
  
set AppleScript’s text item delimiters to curDelim
  
return dList
end parseByDelim

★Click Here to Open This Script 

Posted in dialog URL | Tagged 10.13savvy 10.14savvy 10.15savvy NSAlert NSButton NSRunningApplication NSString NSURL NSURLRequest NSUTF8StringEncoding WKUserContentController WKUserScript WKUserScriptInjectionTimeAtDocumentEnd WKWebView WKWebViewConfiguration | Leave a comment

アラートダイアログ上にWebViewでGoogle Chartを表示(WordTree)

Posted on 5月 29, 2020 by Takaaki Naganoya

アラートダイアログ上にWkWebViewを配置し、Google Chartsを用いてWordTreeを表示するAppleScriptです。

Mindmap風の図を表示するので、純粋にMindmapの表示部品として使えるとよさそうですが、そういうわけでもないようです。図を表示するだけです。

また、Wordtree中の途中のノードを選択するとツリーが閉じたりしますが、どのノードを選択したかといった情報を(現状では)取得できるわけでもないため、超多項目の選択User Interfaceに使いたい場合に「使えそうで使えない」という浮世離れした部品になっています。

一応、JavaScript内ではノードのクリックイベントを拾うことができましたが、selectionで得られる属性値が「word」「color」「weight」といった、個別にノードを特定できる値ではないものばかりなので(idぐらい取れてもいいんやで)、選択UIとして使うのはつらそうです。さらに、WkWebView内のJavaScriptからその「外側の外側」にいるAppleScriptにイベントや値を渡す方法がさっぱり見つかりません。JavaScript側からローカルのファイル……に書けそうな気配はないので、cookie経由で値を受け渡すぐらいでしょうか。


▲Appleのサンプルコード「TreeView」(Written in Objective-C)。これがもっと使いまわしやすい部品として書きこなれていればいいのですが、、、、

# Mindmap風の選択UIは、なかなか手を加えてすぐに使いまわしやすい部品になっていなくて、、

プログラム自体は他のScriptとの共有部品ばかりで、新規に起こしたものはほとんどありません。


▲選択肢をツリーで描画してクリック選択でき、選択した内容をもとに処理できるという意味ではGraphViz+Dot言語が難易度低くていい感じ?(実際に使っています)


▲これもゆくゆくは多項目表示の部品として利用? 制約条件(不自由さ)を設けることで発想につなげようというコンセプトなので、自由なデータ表現の部品にはならないという見方も

AppleScript名:アラートダイアログ上にWebViewでGoogle Chartを表示(WordTree1).scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2020/05/27
—
–  Copyright © 2020 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use framework "AppKit"
use framework "WebKit"
use scripting additions

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

property returnCode : 0
property aBrowserAgentRes : ""

–Sample Data
set aList to {{"Phrases"}, ¬
  {"cats are better than dogs"}, ¬
  {
"cats eat kibble"}, ¬
  {
"cats are better than hamsters"}, ¬
  {
"cats are awesome"}, ¬
  {
"cats are people too"}, ¬
  {
"cats eat mice"}, ¬
  {
"cats meowing"}, ¬
  {
"cats in the cradle"}, ¬
  {
"cats eat mice"}, ¬
  {
"cats in the cradle lyrics"}, ¬
  {
"cats eat kibble"}, ¬
  {
"cats for adoption"}, ¬
  {
"cats are family"}, ¬
  {
"cats eat mice"}, ¬
  {
"cats are better than kittens"}, ¬
  {
"cats are evil"}, ¬
  {
"cats are weir"}, ¬
  {
"cats eat mice"}}

set aJsonArrayStr to array2DToJSONArray(aList) of me

–Map Template HTML
set myStr to "<!DOCTYPE html>
<html lang=\"UTF-8\">
<head>
<script type=\"text/javascript\" src=\"https://www.gstatic.com/charts/loader.js\"></script>

<script type=\"text/javascript\">
google.charts.load(’current’, {’packages’:[’wordtree’]});
google.charts.setOnLoadCallback(drawChart);

function drawChart() {
var data = google.visualization.arrayToDataTable(%@);

var options = {
wordtree: {
format: ’implicit’,
word: ’cats’
}
};

  var chart = new google.visualization.WordTree(document.getElementById(’wordtree’));
chart.draw(data, options);
}
</script>
</head>
<body>
  <div id=\"wordtree\" style=\"width: 900px; height: 500px;\"></div>
</body>
</html>"

set aString to NSString’s stringWithFormat_(myStr, aJsonArrayStr) as string

set paramObj to {myMessage:"Google Word Tree Test", mySubMessage:"This is a simple Word Tree using google charts", htmlStr:aString}
–my browseStrWebContents:paramObj –for debug
my performSelectorOnMainThread:"browseStrWebContents:" withObject:(paramObj) waitUntilDone:true

on browseStrWebContents:paramObj
  set aMainMes to myMessage of paramObj
  
set aSubMes to mySubMessage of paramObj
  
set htmlString to (htmlStr of paramObj)
  
  
set aWidth to 920
  
set aHeight to 540
  
  
–WebViewをつくる
  
set aConf to WKWebViewConfiguration’s alloc()’s init()
  
  
–指定HTML内のJavaScriptをFetch
  
set jsSource to pickUpFromToStr(htmlString, "<script type=\"text/javascript\">", "</script>") of me
  
  
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)) configuration:aConf
  
aWebView’s setNavigationDelegate:me
  
aWebView’s setUIDelegate:me
  
aWebView’s setTranslatesAutoresizingMaskIntoConstraints:true
  
  
set bURL to |NSURL|’s fileURLWithPath:(POSIX path of (path to me))
  
aWebView’s loadHTMLString:htmlString baseURL:(bURL)
  
  
— set up alert  
  
set theAlert to NSAlert’s alloc()’s init()
  
tell theAlert
    its setMessageText:aMainMes
    
its setInformativeText:aSubMes
    
its addButtonWithTitle:"OK"
    
–its addButtonWithTitle:"Cancel"
    
its setAccessoryView:aWebView
    
    
set myWindow to its |window|
  end tell
  
  
— show alert in modal loop
  
NSRunningApplication’s currentApplication()’s activateWithOptions:0
  
my performSelectorOnMainThread:"doModal:" withObject:(theAlert) waitUntilDone:true
  
  
–Stop Web View Action
  
set bURL to |NSURL|’s URLWithString:"about:blank"
  
set bReq to NSURLRequest’s requestWithURL:bURL
  
aWebView’s loadRequest:bReq
  
  
if (my returnCode as number) = 1001 then error number -128
end browseStrWebContents:

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

on viewDidLoad:aNotification
  return true
end viewDidLoad:

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

on pickUpFromToStr(aStr as string, s1Str as string, s2Str as string)
  set a1Offset to offset of s1Str in aStr
  
if a1Offset = 0 then return false
  
set bStr to text (a1Offset + (length of s1Str)) thru -1 of aStr
  
set a2Offset to offset of s2Str in bStr
  
if a2Offset = 0 then return false
  
set cStr to text 1 thru (a2Offset – (length of s2Str)) of bStr
  
return cStr as string
end pickUpFromToStr

–リストを任意のデリミタ付きでテキストに
on retArrowText(aList, aDelim)
  set aText to ""
  
set curDelim to AppleScript’s text item delimiters
  
set AppleScript’s text item delimiters to aDelim
  
set aText to aList as text
  
set AppleScript’s text item delimiters to curDelim
  
return aText
end retArrowText

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

★Click Here to Open This Script 

Posted in dialog | Tagged 10.13savvy 10.14savvy 10.15savvy NSAlert NSArray NSBundle NSButton NSRunningApplication NSString NSURL NSURLRequest NSUTF8StringEncoding WKUserContentController WKUserScript WKUserScriptInjectionTimeAtDocumentEnd WKWebView WKWebViewConfiguration | Leave a comment

クリップボード内のテキストをSayコマンドで読み上げて音声ファイル化

Posted on 5月 27, 2020 by Takaaki Naganoya

読み上げ対象のテキストをコピーした状態で実行するAppleScriptです。クリップボード内のテキストをSayコマンドで読み上げて、音声ファイルにレンダリングします。出力後、読み上げ所要時間を出力ファイルから求めてダイアログ表示します。

音声レンダリング処理は実際の音声読み上げ処理よりも短い時間で完了します。

–> Downlad Script With library within its bundle

掲載のリストを実行しても、スライダー入力ライブラリが含まれていないため、そのままでは実行できません。↑のScriptをまるごとダウンロードして展開すると、ライブラリ入りのScriptになります。実行にはダウンロードしたScriptをご利用ください。プログラムリスト掲載は参考のために行なっているものです。


▲ステップ1:念のために、読み上げ対象テキストをダイアログ表示


▲ステップ2:読み上げ時の速度をスライダーで選択


▲ステップ3:読み上げ音声を選択


▲ステップ4:読み上げ所要時間をダイアログ表示


▲ステップ5:音声レンダリングしたファイルをQuickTime Playerでオープン

AppleScript名:クリップボード内のテキストをSayコマンドで読み上げて音声ファイル化.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2020/05/27
—
–  Copyright © 2020 Piyomaru Software, All Rights Reserved
—

use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use framework "AppKit"
use framework "AVFoundation"
use scripting additions
use slLib : script "sliderLib"

property |NSURL| : a reference to current application’s |NSURL|
property NSDate : a reference to current application’s NSDate
property NSUUID : a reference to current application’s NSUUID
property NSFileManager : a reference to current application’s NSFileManager
property AVAudioPlayer : a reference to current application’s AVAudioPlayer
property NSDateFormatter : a reference to current application’s NSDateFormatter
property NSSpeechSynthesizer : a reference to current application’s NSSpeechSynthesizer

set aInfo to clipboard info
set uCount to (clipboard info for Unicode text)
if uCount = {} then
  display dialog "There is no text information in the clipboard" with title "Terminate information" buttons {"OK"} default button 1 with icon 2
  
return
end if

set totalCount to item 2 of item 1 of uCount

set aStr to the clipboard as text

–読み上げ内容の確認
display dialog aStr with title "Text length:" & (uCount as string) & " chars."

–読み上げ速度をSliderで入力
set rRes to slLib’s chooseBySlider(180, 220, "Select TTS reading pitch (small number:slow)")

–読み上げTTSキャラクタの選択
set aLoc to (current application’s NSLocale’s currentLocale()’s identifier()) as string –>  "ja_JP"
set vList to getTTSVoiceNameWithLanguage(aLoc) of me
set vRes to choose from list vList with prompt ("Select TTS Voice in your language :" & aLoc) without empty selection allowed
if vRes = false then return

set vCharacter to contents of first item of vRes

–音声ファイルの作成先パスを求める
set aUUID to NSUUID’s UUID()’s UUIDString() as string
set aPath to (((path to movies folder) as string) & aUUID & ".aif")
set aPOSIX to POSIX path of aPath

–音声レンダリング
tell current application
  say aStr using vCharacter saving to (aPOSIX) speaking rate rRes without waiting until completion
end tell

–レンダリングした音声の読み上げ所要時間を計算
set aDur to getDuration(aPath as alias) of me

–レンダリングした音声ファイルをオープン
tell application "QuickTime Player"
  open aPath
end tell

–完了報告
display dialog "読み上げ所要時間:" & my formatHMS(aDur)

on getTTSVoiceNameWithLanguage(voiceLang)
  set outArray to current application’s NSMutableArray’s new()
  
  
set aList to NSSpeechSynthesizer’s availableVoices()
  
set bList to aList as list
  
  
repeat with i in bList
    set j to contents of i
    
set aDIc to (NSSpeechSynthesizer’s attributesForVoice:j)
    (
outArray’s addObject:aDIc)
  end repeat
  
  
set aPredicate to current application’s NSPredicate’s predicateWithFormat_("VoiceLocaleIdentifier == %@", voiceLang)
  
set filteredArray to outArray’s filteredArrayUsingPredicate:aPredicate
  
set aResList to (filteredArray’s valueForKey:"VoiceName") as list
  
  
return aResList
end getTTSVoiceNameWithLanguage

on getDuration(aFile)
  set aURL to |NSURL|’s fileURLWithPath:(POSIX path of aFile)
  
  
repeat 1000 times
    set aAudioPlayer to AVAudioPlayer’s alloc()’s initWithContentsOfURL:aURL |error|:(missing value)
    
set aRes to aAudioPlayer’s prepareToPlay()
    
if aRes as boolean = true then exit repeat
    
delay 0.5
  end repeat
  
  
set channelCount to aAudioPlayer’s numberOfChannels()
  
set aDuration to aAudioPlayer’s duration()
  
return aDuration as real
end getDuration

on retAvailableTTSnames()
  set outList to {}
  
  
set aList to NSSpeechSynthesizer’s availableVoices()
  
set bList to aList as list
  
  
repeat with i in bList
    set j to contents of i
    
set aInfo to (NSSpeechSynthesizer’s attributesForVoice:j)
    
set aInfoRec to aInfo as record
    
set aName to VoiceName of aInfoRec
    
set the end of outList to aName
  end repeat
  
  
return outList
end retAvailableTTSnames

on formatHMS(aTime)
  set aDate to NSDate’s dateWithTimeIntervalSince1970:aTime
  
set aFormatter to NSDateFormatter’s alloc()’s init()
  
  
—This formatter text is localized in Japanese.
  
if aTime < hours then
    aFormatter’s setDateFormat:"mm分ss秒"
  else if aTime < days then
    aFormatter’s setDateFormat:"HH時間mm分ss秒"
  else
    aFormatter’s setDateFormat:"DD日HH時間mm分ss秒"
  end if
  
  
set timeStr to (aFormatter’s stringFromDate:aDate) as string
  
return timeStr
end formatHMS

★Click Here to Open This Script 

Posted in dialog file Language Locale Text | Tagged 10.13savvy 10.14savvy 10.15savvy AVAudioPlayer NSDate NSDateFormatter NSFileManager NSMutableArray NSPredicate NSSpeechSynthesizer NSURL NSUUID | Leave a comment

指定のドメインのIPアドレスを指定DNSで引いて返す

Posted on 5月 26, 2020 by Takaaki Naganoya

指定のドメインのIPアドレスを、指定のDNSサーバーで引いて結果を返すAppleScriptです。

DNS系のFramework(Objective-Cで書いてあるもの)はいろいろためしてみたものの、不思議とどれも動作が重くて、このようにshell commandを呼び出したほうが手軽で高速でした。

# うまく動いていなかったために遅かった、というのが正確なところかも。タイムアウトエラーを起こして処理が完了しないものばかりだったので、、、書き換えがうまく行っていなかった可能性が50%以上あります

nslookupの結果を取り出すためにいろいろやっていますが、ありもののルーチンを引っ張り出して加工してしているだけです。

apple.comのように、CDNサービスを利用してアクセス負荷分散を行なっているようなドメインだと、問い合わせごとにIPアドレスが変わるようです。

一方で、piyocast.comのように固定ホスト(バーチャルホストではありますが)で細々とホスティングしているようなドメインでは、IPアドレスが毎回変わるということはありません。

AppleScript名:指定のドメインのIPアドレスを指定DNSで引いて返す v2.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2020/05/25
—
–  Copyright © 2020 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use scripting additions

property NSScanner : a reference to current application’s NSScanner
property NSMutableArray : a reference to current application’s NSMutableArray

set aDomain to "apple.com"
set aDNS to "8.8.4.4"
set dnRes to getIPAddress(aDomain, aDNS) of me
–> {serverName:"apple.com", serverAddr:{"17.172.224.47", "17.178.96.59", "17.142.160.59"}}–CDNの影響でアドレスが頻繁に変わる?

set dnRes to getIPAddress("piyocast.com", aDNS) of me
–> {serverName:"piyocast.com", serverAddr:{"157.112.183.74"}}

on getIPAddress(aDomain, aDNS)
  set searchStr to "answer:"
  
  
using terms from scripting additions
    set aRes to do shell script ("nslookup " & aDomain & " " & aDNS)
    
set bRes to offset of searchStr in aRes
  end using terms from
  
  
if bRes = 0 then return false
  
  
set cRes to text (bRes + (length of searchStr) + 1) thru -1 of aRes
  
  
set adRes1 to extractStrFromTo(cRes, "Name:", return) of me
  
set adRes2 to extractStrFromTo(cRes, "Address:", return) of me
  
  
set outList to {}
  
set erList to {}
  
repeat with i from 1 to (length of adRes2)
    set j1 to contents of (item i of adRes1)
    
set j2 to contents of (item i of adRes2)
    
if j1 is equal to aDomain then
      set the end of outList to j2
    else
      set the end of erList to {j1, j2}
    end if
  end repeat
  
  
return {serverName:j1, serverAddr:outList}
end getIPAddress

–offset命令の実行を横取りして高速実行(x2.5 faster)
on offset of searchStr in str
  set aRes to getOffset(str, searchStr) of me
  
return aRes
end offset

on getOffset(str, searchStr)
  set d to divideBy(str, searchStr)
  
if (count d) is less than 2 then return 0
  
return (length of item 1 of d) + 1
end getOffset

on divideBy(str, separator)
  set delSave to AppleScript’s text item delimiters
  
set the AppleScript’s text item delimiters to separator
  
set strItems to every text item of str
  
set the AppleScript’s text item delimiters to delSave
  
return strItems
end divideBy

–指定文字と終了文字に囲まれた内容を抽出
on extractStrFromTo(aParamStr, fromStr, toStr)
  set theScanner to NSScanner’s scannerWithString:aParamStr
  
set anArray to NSMutableArray’s array()
  
  
repeat until (theScanner’s isAtEnd as boolean)
    set {theResult, theKey} to theScanner’s scanUpToString:fromStr intoString:(reference)
    
theScanner’s scanString:fromStr intoString:(missing value)
    
set {theResult, theValue} to theScanner’s scanUpToString:toStr intoString:(reference)
    
if theValue is missing value then set theValue to "" –>追加
    
theScanner’s scanString:toStr intoString:(missing value)
    
anArray’s addObject:theValue
  end repeat
  
  
return (anArray as list)
end extractStrFromTo

★Click Here to Open This Script 

Posted in Internet | Tagged 10.13savvy 10.14savvy 10.15savvy NSMutableArray NSScanner | Leave a comment

アラートダイアログ上にWebViewでGoogle Chartsを表示(Geo Chart 1)

Posted on 5月 24, 2020 by Takaaki Naganoya

NSAlertのアラートダイアログ上にGoogleChartsを用いたGeoChartを表示するAppleScriptです。

Geo Chartに表示されている地図の上でマウスカーソルを移動させると、Chartが反応してデータ表示を行います。

本Scriptに掲載しているAPI KeyはGoogleに掲載されているサンプル用のものであり、サンプルデータの表示以外には使用できません。Google開発者アカウントを取得し、API Keyを取得して記入しておく必要があります。

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

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

property returnCode : 0
property aBrowserAgentRes : ""

set mapsAPIKey to "AIzaSyD-9tSrke72PouQMnMX-a7eZSW0jkFMBWY" –for demonstration only

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

–Sample Data
set aList to {{"Country", "Popularity"}, ¬
  {"Germany", 200}, ¬
  {
"United States", 300}, ¬
  {
"Brazil", 400}, ¬
  {
"Canada", 500}, ¬
  {
"France", 600}, ¬
  {
"RU", 700}}

set aJsonArrayStr to array2DToJSONArray(aList) of me

–Map Template HTML
set myStr to "<!DOCTYPE html>
<html lang=\"UTF-8\">
<head>
<script type=\"text/javascript\" src=\"https://www.gstatic.com/charts/loader.js\"></script>

<script type=\"text/javascript\">
google.charts.load(’current’, {’packages’:[’geochart’], ’mapsApiKey’: ’%@’});
google.charts.setOnLoadCallback(drawRegionsMap);

function drawRegionsMap() {
var data = google.visualization.arrayToDataTable(%@);

var options = {};

var chart = new google.visualization.GeoChart(document.getElementById(’regions_div’));
chart.draw(data, options);
};
</script>
</head>
<body>
  <div id=\"regions_div\" style=\"width: 900px; height: 500px;\"></div>
</body>
</html>"

set aString to NSString’s stringWithFormat_(myStr, mapsAPIKey, aJsonArrayStr) as string

set paramObj to {myMessage:"Google GeoChart Test", mySubMessage:"This is a simple GeoChart using google charts", htmlStr:aString}
–my browseStrWebContents:paramObj –for debug
my performSelectorOnMainThread:"browseStrWebContents:" withObject:(paramObj) waitUntilDone:true

on browseStrWebContents:paramObj
  set aMainMes to myMessage of paramObj
  
set aSubMes to mySubMessage of paramObj
  
set htmlString to (htmlStr of paramObj)
  
  
set aWidth to 920
  
set aHeight to 520
  
  
–WebViewをつくる
  
set aConf to WKWebViewConfiguration’s alloc()’s init()
  
  
–指定HTML内のJavaScriptをFetch
  
set jsSource to pickUpFromToStr(htmlString, "<script type=\"text/javascript\">", "</script>") of me
  
  
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)) configuration:aConf
  
aWebView’s setNavigationDelegate:me
  
aWebView’s setUIDelegate:me
  
aWebView’s setTranslatesAutoresizingMaskIntoConstraints:true
  
aWebView’s setCustomUserAgent:(my aBrowserAgentRes)
  
  
set bURL to |NSURL|’s fileURLWithPath:(POSIX path of (path to me))
  
aWebView’s loadHTMLString:htmlString baseURL:(bURL)
  
  
— set up alert  
  
set theAlert to NSAlert’s alloc()’s init()
  
tell theAlert
    its setMessageText:aMainMes
    
its setInformativeText:aSubMes
    
its addButtonWithTitle:"OK"
    
–its addButtonWithTitle:"Cancel"
    
its setAccessoryView:aWebView
    
    
set myWindow to its |window|
  end tell
  
  
— show alert in modal loop
  
NSRunningApplication’s currentApplication()’s activateWithOptions:0
  
my performSelectorOnMainThread:"doModal:" withObject:(theAlert) waitUntilDone:true
  
  
–Stop Web View Action
  
set bURL to |NSURL|’s URLWithString:"about:blank"
  
set bReq to NSURLRequest’s requestWithURL:bURL
  
aWebView’s loadRequest:bReq
  
  
if (my returnCode as number) = 1001 then error number -128
end browseStrWebContents:

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

on viewDidLoad:aNotification
  return true
end viewDidLoad:

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

on pickUpFromToStr(aStr as string, s1Str as string, s2Str as string)
  set a1Offset to offset of s1Str in aStr
  
if a1Offset = 0 then return false
  
set bStr to text (a1Offset + (length of s1Str)) thru -1 of aStr
  
set a2Offset to offset of s2Str in bStr
  
if a2Offset = 0 then return false
  
set cStr to text 1 thru (a2Offset – (length of s2Str)) of bStr
  
return cStr as string
end pickUpFromToStr

–リストを任意のデリミタ付きでテキストに
on retArrowText(aList, aDelim)
  set aText to ""
  
set curDelim to AppleScript’s text item delimiters
  
set AppleScript’s text item delimiters to aDelim
  
set aText to aList as text
  
set AppleScript’s text item delimiters to curDelim
  
return aText
end retArrowText

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

–Safariと同じUser Agentの文字列を取得する
on getSafariUserAgentString:anObject
  set aBundle to NSBundle’s bundleWithIdentifier:"com.apple.Safari"
  
set aVer to (aBundle’s infoDictionary()’s objectForKey:"CFBundleShortVersionString") as text
  
–>  "9.0.2"
  
  
set aBuildNo to (aBundle’s infoDictionary()’s objectForKey:"CFBundleVersion") as text
  
–>  "11601.3.6"
  
  
set {v1, v2, v3} to parseVersionNumber(aBuildNo) of me
  
set aV1 to NSString’s stringWithString:v1
  
set bV1 to aV1’s substringFromIndex:2 –3 characters from tail –?????
  
–> "601"
  
  
set bStr to retStrFromArrayWithDelimiter({bV1, v2, v3}, ".") of me
  
  
set aWebView to WebView’s alloc()’s init()
  
set aRes to (aWebView’s stringByEvaluatingJavaScriptFromString:"navigator.userAgent") as text
  
–>  "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/601.3.6 (KHTML, like Gecko)"
  
  
set aBrowserAgentRes to (aRes & " Version/" & aVer & " Safari/" & bStr)
end getSafariUserAgentString:

–バージョン番号文字列からメジャーバージョンを取り出し数値として返す
on parseVersionNumber(a)
  set aStr to current application’s NSString’s stringWithString:a
  
set aRes to (aStr’s componentsSeparatedByString:".")
  
set bRes to aRes’s allObjects()
  
return bRes as list
end parseVersionNumber

–リストを指定デリミタをはさんでテキスト化
on retStrFromArrayWithDelimiter(aList, aDelim)
  set anArray to NSArray’s arrayWithArray:aList
  
set aRes to anArray’s componentsJoinedByString:aDelim
  
return aRes as text
end retStrFromArrayWithDelimiter

★Click Here to Open This Script 

Posted in dialog | Tagged 10.13savvy 10.14savvy 10.15savvy NSAlert NSArray NSBundle NSButton NSRunningApplication NSString NSURL NSURLRequest NSUTF8StringEncoding WKUserContentController WKUserScript WKUserScriptInjectionTimeAtDocumentEnd WKWebView WKWebViewConfiguration | Leave a comment

アラートダイアログのウィンドウタイトル部分にアイコン指定

Posted on 5月 23, 2020 by Takaaki Naganoya

アラートダイアログのウィンドウタイトル部分に任意の画像をアイコンとして表示するAppleScriptです。

本来、NSWindowのタイトル部分にアイコン表示を行うワザのようです。なにか、Cocoaのバグのような仕様を使っているようです。本来、タイトル部分に直接アイコンを表示させることはできないのですが、ドキュメントのURLを指定すると、該当するパス(URL)の書類アイコンを指定する機能はあります。


▲Mac App Store上で販売中のAppleScriptで開発したアプリケーション「Kamenoko」でも、ウィンドウにアイコン表示するコードが使われています。本Scriptではなく、もっとまっとうな方法で

そこに、存在しないURLを指定すると、直後にアイコン指定できるという、、、どこで役立つのかわかりませんが、そういう方法もあるということで。

AppleScript名:アラートダイアログでウィンドウタイトル部分にアイコン指定
— Created 2020-05-08 by Takaaki Naganoya
— 2020 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"

property NSAlert : a reference to current application’s NSAlert
property |NSURL| : a reference to current application’s |NSURL|
property NSImage : a reference to current application’s NSImage
property NSRunningApplication : a reference to current application’s NSRunningApplication
property NSImageNameComputer : a reference to current application’s NSImageNameComputer
property NSWindowDocumentIconButton : a reference to current application’s NSWindowDocumentIconButton

property returnCode : 0

–Get Computer Icon
set anImage to getComputerIcon() of me
set aMainMes to "TEST"
set aSubMes to "Window title icon TEST"
set wTitle to "Window Title"

set paramObj to {myMessage:aMainMes, mySubMessage:aSubMes, myWinTitle:wTitle, myImage:anImage}
–my displayAlertDialog:paramObj

my performSelectorOnMainThread:"displayAlertDialog:" withObject:(paramObj) waitUntilDone:true

on displayAlertDialog:paramObj
  set aMainMes to myMessage of paramObj
  
set aSubMes to mySubMessage of paramObj
  
set anImage to myImage of paramObj
  
set aWinTitle to myWinTitle of paramObj
  
  
— 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 setIcon:anImage
    
set aWin to its |window|()
  end tell
  
  
aWin’s setTitle:aWinTitle
  
  
aWin’s setRepresentedURL:(|NSURL|’s URLWithString:"WindowTitle") –Dummy URL
  (
aWin’s standardWindowButton:(current application’s NSWindowDocumentIconButton))’s setImage:(anImage)
  
  
— 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 displayAlertDialog:

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

on getComputerIcon()
  return NSImage’s imageNamed:(NSImageNameComputer)
end getComputerIcon

★Click Here to Open This Script 

Posted in dialog | Tagged 10.13savvy 10.14savvy 10.15savvy NSAlert NSImage NSImageNameComputer NSRunningApplication NSURL NSWindowDocumentIconButton | Leave a comment

自分のウィンドウのフルスクリーン化 v3

Posted on 5月 22, 2020 by Takaaki Naganoya

Xcode上で作成したAppleScriptアプリケーションのウィンドウをフルスクリーン化するAppleScriptです。

–> download fullScreenTestv3 (Xcode project archive)

前バージョンを実際にアプリケーションに組み込んで実行してみたところ、メニューバーを表示しないうえにツールバー(NSToolbar)も非表示状態でフルスクリーン化したうえに、通常表示状態に戻ってこれませんでした。戻ってくるにはアプリケーションを終了(Command-Q)するしかありませんでした。

ゲームならこれでいいと思うのですが、通常のアプリケーションでフルスクリーンモードから戻ってこられないのは困りますし、メニューやツールバーが使えないのは困ります。

そこで、複数あるうちの別のやりかたを試してみました。本テストアプリケーションのツールバー上の左側のボタンが前バージョンと同じ働きをするもの、右側が新規に試したものです。

ツールバーの右側のボタンをクリックすると、ウィンドウの緑色のボタンをクリックして全画面表示させたのと同じ動きを行います。


▲ビルドして起動したところ


▲ツールバー左側のボタンをクリックして全画面表示させたところ。全画面表示されるが、ツールバーもメニューも表示されない。Command-Qで終了しないと解除されない


▲ツールバー右側のボタンをクリックして全画面表示させたところ。もう一度クリックすると通常表示モードに戻る


▲自分のアプリケーション(Kamenoko)のツールバーに組み込んで実験したところ(制作中のv1.1)

AppleScript名:AppDelegate.applescript
—
— AppDelegate.applescript
— fullScreenTest
—
— Created by Takaaki Naganoya on 2020/05/21.
— Copyright © 2020 Takaaki Naganoya. All rights reserved.
—

script AppDelegate
  property parent : class "NSObject"
  
  
— IBOutlets
  
property theWindow : missing value
  
property theWindowView : missing value
  
  
on applicationWillFinishLaunching:aNotification
  
end applicationWillFinishLaunching:
  
  
on applicationShouldTerminate:sender
    return current application’s NSTerminateNow
  end applicationShouldTerminate:
  
  
on clicked:aSender
    set aTag to (tag of aSender) as integer
    
    
if aTag = 10 then
      set curScreen to theWindow’s screen()
      
set fMode to (theWindowView’s inFullScreenMode) as boolean
      
      
if fMode = true then
        –Can not return from Full Screen Mode. Quit this test app to return from full screen mode
        
theWindowView’s exitFullScreenModeWithOptions:(missing value)
      else
        –Enter Full Screen Mode
        
theWindowView’s enterFullScreenMode:(curScreen) withOptions:(missing value)
      end if
      
    else if aTag = 20 then
      set fMode to (theWindowView’s inFullScreenMode) as boolean
      
      
if fMode = true then
        –Exit Full Screen Mode
        
theWindow’s toggleFullScreen:(missing value)
      else
        –Enter Full Screen Mode with Toolbar
        
theWindow’s toggleFullScreen:theWindow
      end if
    end if
    
  end clicked:
end script

★Click Here to Open This Script 

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

ダブルクリックとコンテクストメニュー表示をサポートするボタン

Posted on 5月 22, 2020 by Takaaki Naganoya

Xcode上で作成するAppleScriptアプリケーションで、ダブルクリックとコンテクストメニュー表示を受け入れるボタンのプロジェクトの試作品です。

–> Download Xcode Projext (doubleClick v2)

ボタンでシングルクリックを受け付けるのは簡単ですが、ダブルクリックを受信するためには、少し手間がかかります。まして、コンテクストメニュー表示は、、、、、

この試作品では、クリックされたボタンを識別できていません。ダブルクリックされたボタンのTagとか、コンテクストメニュー表示させたボタンのTagを取得できるように改変したいところです。

こうした(↑)テーマセレクタで、ダブルクリックでそのままテーマ選択を行えるように対処したいところです。テーマセレクタとか環境設定なんて、アプリケーション開発の最後のほうでやっつけ的に行うので、それほど気合いを入れて作っているものではありません(個人の見解です)。

当初はもっと仕様的に「盛った」ものを作ろうとデザインしたのですが、いざ作ってみたら技術的に難しすぎたので、技術的な難易度を大幅に下げて実装してみました(ここで妥協ができないとモノが仕上がりません)。

自分はRadio Buttonに画像を載せて「選択状態だけとれればいい」と割り切って実装しましたが、たしかにダブルクリックぐらいは受け付けたほうがよいでしょう。Keynoteのテーマセレクタのように。

AppleScript名:AppDelegate.applescript
—
— AppDelegate.applescript
— doubleClick
—
— Created by Takaaki Naganoya on 2020/01/29.
— Copyright © 2020 Takaaki Naganoya. All rights reserved.
—

script AppDelegate
  
  
property parent : class "NSObject"
  
  
— IBOutlets
  
property theWindow : missing value
  
property theView : missing value
  
property DCButton : missing value
  
property aConMenu : missing value
  
  
on applicationWillFinishLaunching:aNotification
    —
  end applicationWillFinishLaunching:
  
  
on applicationShouldTerminate:sender
    return current application’s NSTerminateNow
  end applicationShouldTerminate:
  
  
on clicked:aSender
    display dialog "Clicked"
  end clicked:
  
  
on dispContextual:aEvent
    current application’s NSMenu’s popUpContextMenu:(aConMenu) withEvent:(aEvent) forView:(theView)
  end dispContextual:
  
  
on action:aSender
    display dialog (tag of aSender) as string
  end action:
  
end script

★Click Here to Open This Script 

AppleScript名:DCButton.applescript
—
— DCButton.applescript
— Kamenoko
—
— Created by Takaaki Naganoya on 2020/05/18.
— Copyright © 2020 Takaaki Naganoya. All rights reserved.
—

script DCButton
  property parent : class "NSButton"
  
  
on mouseDown:aEvent
    set buttonNum to aEvent’s buttonNumber()
    
set aEtype to aEvent’s type()
    
set aCount to aEvent’s clickCount()
    
    
if aCount = 3 then –Triple Click
      display dialog "Triple Click"
      
    else if aCount = 2 then –Double Click
      display dialog "Double Click"
      
    end if
  end mouseDown:
  
  
on mouseMoved:theEvent
    log {"mouseMoved", aEvent}
  end mouseMoved:
  
  
on mouseUp:aEvent
    log {"mouseUp", aEvent}
  end mouseUp:
  
  
on mouseDragged:aEvent
    log "mouseDragged"
  end mouseDragged:
  
  
on rightMouseDown:aEvent
    –Display Contextual Menu
    
current application’s NSApp’s delegate()’s performSelector:"dispContextual:" withObject:(aEvent)
  end rightMouseDown:
  
  
on rightMouseUp:aEvent
    log {"rightMouseUp", aEvent}
  end rightMouseUp:
  
  
on clicked:aSender
    continue clicked:(missing value)
  end clicked:
  
  
(*
  on mouseEntered:theEvent
    log {"mouseEntered", theEvent}
  end mouseEntered:

  on mouseExited:theEvent
    log {"mouseExited", theEvent}
  end mouseExited:
*)
end script

★Click Here to Open This Script 

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

自分のウィンドウのフルスクリーン化 v2

Posted on 5月 21, 2020 by Takaaki Naganoya

Xcodeで作成したAppleScriptアプリケーションの、メインウィンドウ上のビューをフルスクリーン表示させるAppleScriptです。

→ Download Xcode Project

AppleScriptのProjectだとoptionにmissing value以外が使えないみたいなのですが、、、、

AppleScript名:AppDelegate.applescript
—
— AppDelegate.applescript
— fullScreenTest
—
— Created by Takaaki Naganoya on 2020/05/21.
— Copyright © 2020 Takaaki Naganoya. All rights reserved.
—

script AppDelegate
  property parent : class "NSObject"
  
  
— IBOutlets
  
property theWindow : missing value
  
property theWindowView : missing value
  
  
on applicationWillFinishLaunching:aNotification
    — Insert code here to initialize your application before any files are opened
  end applicationWillFinishLaunching:
  
  
on applicationShouldTerminate:sender
    — Insert code here to do any housekeeping before your application quits
    
return current application’s NSTerminateNow
  end applicationShouldTerminate:
  
  
on clicked:aSender
    set fMode to (theWindowView’s inFullScreenMode) as boolean
    
if fMode = true then
      theWindowView’s exitFullScreenModeWithOptions:(missing value)
    else
      theWindowView’s enterFullScreenMode:(current application’s NSScreen’s mainScreen()) withOptions:(missing value)
    end if
  end clicked:
end script

★Click Here to Open This Script 

Posted in AppleScript Application on Xcode | Tagged 10.14savvy 10.15savvy NSScreen NSWindow | 1 Comment

slider+buttonを作成 v5

Posted on 5月 21, 2020 by Takaaki Naganoya

スライダーをダイアログ上に表示して、ユーザーの入力を求めるAppleScriptです。


▲Script Editor上で実行


▲Script Debugger上で実行


▲Script Menu上で実行


▲Switch Control上で実行

最近はこうした箱庭ダイアログシリーズも書き方がこなれてきて、ランタイム環境に依存せずに(実際は、特定の環境で動かないということが少なくなりつつ)実行できるようになってきました。

スライダーコントロールはこうした箱庭シリーズの初期にいろいろいじくって試していたものですが、あまりに初期すぎて書き方が古いものが多かったので、最新のこなれた書き方で書き直しておきました。

ただ、スライダーコントロールが単体でダイアログ上に配置されていても、実際にハマる用途が存在せず、単なるデモンストレーションに終始してしまいそうであります。

アラートダイアログの通知メッセージ(一番大きな文字で表示される)をスライダーで変更することができなかったので、ダイアログのタイトルでスライダーの値を表示するようにしています。スライダーが必要な状況というのは、いくつかのパラメータを一緒に設定するケースが多いはずなので、やっぱり単体で設定できても意味がないような気がとてもします。

AppleScript名:slider+buttonを作成 v5
— Created 2020-5-17 by Takaaki Naganoya
— 2020 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"

property NSAlert : a reference to current application’s NSAlert
property NSSlider : a reference to current application’s NSSlider
property NSSplitView : a reference to current application’s NSSplitView
property NSTickMarkBelow : a reference to current application’s NSTickMarkBelow
property NSRunningApplication : a reference to current application’s NSRunningApplication
property NSScreenSaverWindowLevel : a reference to current application’s NSScreenSaverWindowLevel

property windisp : false
property wController : false
property aSliderValMSG : ""

property sliderRes : 0

set aMaxVal to 12
set aButtonMSG to "OK"
set winWidth to 400
set aSliderValMSG to "Slider Value : "

set paramObj to {myMax:aMaxVal, myBMes:aButtonMSG, mySliderMes:aSliderValMSG, myWidth:winWidth}
–my getSliderValue:paramObj
my performSelectorOnMainThread:"getSliderValue:" withObject:(paramObj) waitUntilDone:true
return sliderRes

on getSliderValue:paramObj
  set aMaxVal to (myMax of paramObj) as real
  
set aButtonMSG to (myBMes of paramObj) as string
  
set aSliderValMSG to (mySliderMes of paramObj) as string
  
set winWidth to (myWidth of paramObj) as real
  
  
set (my aSliderValMSG) to aSliderValMSG
  
  
set aView to NSSplitView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, winWidth, 40))
  
aView’s setVertical:false
  
  
–Sliderをつくる
  
set aSlider to makeSider(aMaxVal) of me
  
aView’s setSubviews:{aSlider}
  
  
— set up alert  
  
set theAlert to NSAlert’s alloc()’s init()
  
tell theAlert
    its setMessageText:""
    
–its setInformativeText:aSubMes
    
its addButtonWithTitle:"OK"
    
its addButtonWithTitle:"Cancel"
    
its setAccessoryView:aView
    
set aWin to its |window|()
    
set bList to buttons()
  end tell
  
  
aWin’s setTitle:(my aSliderValMSG & (sliderRes as text))
  
aWin’s setLevel:NSScreenSaverWindowLevel
  
— 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 sliderRes to (aSlider’s intValue()) as number
end getSliderValue:

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

on sliderChanged:aSender
  set sliderRes to aSender’s intValue()
  
set parentWin to aSender’s |window|()
  
parentWin’s setTitle:(my aSliderValMSG & (sliderRes as text))
end sliderChanged:

on makeSider(aMaxNum)
  set aSlider to NSSlider’s alloc()’s init()
  
aSlider’s setMaxValue:aMaxNum
  
aSlider’s setMinValue:1
  
aSlider’s setNumberOfTickMarks:aMaxNum
  
aSlider’s setKnobThickness:50
  
aSlider’s setAllowsTickMarkValuesOnly:true
  
aSlider’s setTickMarkPosition:(NSTickMarkBelow)
  
set sliderRes to (aMaxNum div 2)
  
aSlider’s setIntValue:sliderRes
  
aSlider’s setTarget:me
  
aSlider’s setAction:("sliderChanged:")
  
return aSlider
end makeSider

★Click Here to Open This Script 

Posted in dialog | Tagged 10.13savvy 10.14savvy 10.15savvy NSAlert NSRunningApplication NSSlider NSSplitView | Leave a comment

Post navigation

  • Older posts
  • Newer posts

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

Google Search

Popular posts

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

Tags

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

カテゴリー

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

アーカイブ

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

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

メタ情報

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

Forum Posts

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

メタ情報

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