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

カテゴリー: Require Control-Command-R to run

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

Posted on 12月 1, 2019 by Takaaki Naganoya

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

–> Watch Demo Movie

–> Download Script Bundle with Sample data

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

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

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

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

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

property NSFont : a reference to current application’s NSFont
property NSView : a reference to current application’s NSView
property NSAlert : a reference to current application’s NSAlert
property NSColor : a reference to current application’s NSColor
property NSMenu : a reference to current application’s NSMenu
property NSArray : a reference to current application’s NSArray
property NSTabView : a reference to current application’s NSTabView
property NSPredicate : a reference to current application’s NSPredicate
property NSTextView : a reference to current application’s NSTextView
property NSMenuItem : a reference to current application’s NSMenuItem
property NSTabViewItem : a reference to current application’s NSTabViewItem
property NSPopUpButton : a reference to current application’s NSPopUpButton
property NSMutableDictionary : a reference to current application’s NSMutableDictionary
property NSRunningApplication : a reference to current application’s NSRunningApplication
property NSFontAttributeName : a reference to current application’s NSFontAttributeName
property NSKernAttributeName : a reference to current application’s NSKernAttributeName
property NSLigatureAttributeName : a reference to current application’s NSLigatureAttributeName
property NSMutableAttributedString : a reference to current application’s NSMutableAttributedString
property NSStrokeWidthAttributeName : a reference to current application’s NSStrokeWidthAttributeName
property NSUnderlineStyleAttributeName : a reference to current application’s NSUnderlineStyleAttributeName
property NSForegroundColorAttributeName : a reference to current application’s NSForegroundColorAttributeName

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

property returnCode : 0

property aTabV : missing value
property selectedNum : {}

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

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

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

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

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

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

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

–書式つきテキストを組み立てる
on makeRTFfromParameters(aStr as string, aFontName as string, aFontSize as real, aColor)
  –フォント
  
set aVal1 to NSFont’s fontWithName:(aFontName) |size|:aFontSize
  
set aKey1 to (NSFontAttributeName)
  
  
–色
  
set aVal2 to aColor
  
set aKey2 to (NSForegroundColorAttributeName)
  
  
–カーニング
  
set aVal3 to 0.0
  
set akey3 to (NSKernAttributeName)
  
  
–アンダーライン
  
set aVal4 to 0
  
set akey4 to (NSUnderlineStyleAttributeName)
  
  
–リガチャ
  
–set aVal5 to 2 –全てのリガチャを有効にする
  
–set akey5 to ( NSLigatureAttributeName)
  
  
–枠線(アウトライン)
  
–set aVal6 to outlineNum
  
–set akey6 to ( NSStrokeWidthAttributeName)
  
  
  
set keyList to {aKey1, aKey2, akey3, akey4}
  
set valList to {aVal1, aVal2, aVal3, aVal4}
  
set attrsDictionary to NSMutableDictionary’s dictionaryWithObjects:valList forKeys:keyList
  
  
set attrStr to NSMutableAttributedString’s alloc()’s initWithString:aStr attributes:attrsDictionary
  
return attrStr
end makeRTFfromParameters

–リストに入れたレコードを、指定の属性ラベルの値で抽出
on filterRecListByLabel1(aRecList as list, aPredicate as string)
  set aArray to NSArray’s arrayWithArray:aRecList
  
set aPredicate to NSPredicate’s predicateWithFormat:aPredicate
  
set filteredArray to aArray’s filteredArrayUsingPredicate:aPredicate
  
set bList to filteredArray
  
return bList
end filterRecListByLabel1

★Click Here to Open This Script 

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

複数入力フィールドつきダイアログを表示

Posted on 2月 24, 2018 by Takaaki Naganoya

AppleScript名:複数入力フィールドつきダイアログを表示
— Created 2017-09-23 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"

property windisp : false
property wController : false

set fieldList to {"field 1", "field 2", "field 3", "field 4", "field 5", "field 6", "field 7", "field 8", "field 9", "field 10"}
–set fieldList to {"field 1", "field 2"}
set aButtonMSG to "OK"
set aWinTitle to "Multiple Text Field Input"
set aVal to getMultiTextFieldValues(fieldList, aWinTitle, aButtonMSG, 180) of me

on getMultiTextFieldValues(fieldList, aWinTitle, aButtonMSG, timeOutSecs)
  set (my windisp) to false
  
set fLen to (length of fieldList) + 1
  
  
set aView to current application’s NSView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, 360, (20 * fLen)))
  
  
set a1y to (30 * fLen)
  
set tList to {}
  
  
repeat with i in fieldList
    set a1TF to (current application’s NSTextField’s alloc()’s initWithFrame:(current application’s NSMakeRect(60, a1y, 80, 20)))
    (
a1TF’s setEditable:false)
    (
a1TF’s setStringValue:(i as string))
    (
a1TF’s setDrawsBackground:false)
    (
a1TF’s setBordered:false)
    
    
set a2TF to (current application’s NSTextField’s alloc()’s initWithFrame:(current application’s NSMakeRect(140, a1y, 200, 20)))
    (
a2TF’s setEditable:true)
    (
a2TF’s setDrawsBackground:true)
    (
a2TF’s setBordered:true)
    
    (
aView’s addSubview:a1TF)
    (
aView’s addSubview:a2TF)
    
    
set the end of tList to a2TF
    
set a1y to a1y – 30
  end repeat
  
  
  
–Buttonをつくる
  
set bButton to (current application’s NSButton’s alloc()’s initWithFrame:(current application’s NSMakeRect(110, 10, 180, 40)))
  
bButton’s setButtonType:(current application’s NSMomentaryLightButton)
  
bButton’s setBezelStyle:(current application’s NSRoundedBezelStyle)
  
bButton’s setTitle:aButtonMSG
  
bButton’s setTarget:me
  
bButton’s setAction:("clicked:")
  
bButton’s setKeyEquivalent:(return)
  
  
aView’s addSubview:bButton
  
aView’s setNeedsDisplay:true
  
  
–NSWindowControllerを作ってみた
  
set aWin to (my makeWinWithView(aView, 400, ((fLen + 1) * 30), aWinTitle))
  
set wController to current application’s NSWindowController’s alloc()
  
wController’s initWithWindow:aWin
  
  
set (my windisp) to true
  
  
wController’s showWindow:me
  
  
set aCount to timeOutSecs * 10
  
  
set hitF to false
  
repeat aCount times
    if (my windisp) = false then
      set hitF to true
      
exit repeat
    end if
    
delay 0.1
    
set aCount to aCount – 1
  end repeat
  
  
my closeWin:aWin
  
  
if hitF = true then
    set aResList to {}
    
repeat with i in tList
      set the end of aResList to (i’s stringValue()) as string
    end repeat
  else
    return false
  end if
  
  
return aResList
  
end getMultiTextFieldValues

on clicked:aSender
  set (my windisp) to false
end clicked:

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

–close win
on closeWin:aWindow
  repeat with n from 10 to 1 by -1
    (aWindow’s setAlphaValue:n / 10)
    
delay 0.02
  end repeat
  
aWindow’s |close|()
end closeWin:

★Click Here to Open This Script 

Posted in GUI Require Control-Command-R to run | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

QuartzComoserでグラフ表示てすと v5(Window Controllerを追加)

Posted on 2月 24, 2018 by Takaaki Naganoya

–> Download script with Quartz composer

AppleScript名:QuartzComoserでグラフ表示てすと v5(Window Controllerを追加)
— Created 2015-11-03 by Takaaki Naganoya
— Modified 2017-10-18 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "Quartz"
use framework "AppKit"
use framework "Carbon" — AEInteractWithUser() is in Carbon

property NSMutableDictionary : a reference to current application’s NSMutableDictionary
property NSWindowCloseButton : a reference to current application’s NSWindowCloseButton
property NSScreen : a reference to current application’s NSScreen
property NSPredicate : a reference to current application’s NSPredicate
property NSDictionary : a reference to current application’s NSDictionary
property NSBackingStoreBuffered : a reference to current application’s NSBackingStoreBuffered
property NSMutableArray : a reference to current application’s NSMutableArray
property NSTitledWindowMask : a reference to current application’s NSTitledWindowMask
property NSString : a reference to current application’s NSString
property NSWindow : a reference to current application’s NSWindow
property NSNumber : a reference to current application’s NSNumber
property NSNormalWindowLevel : a reference to current application’s NSNormalWindowLevel
property QCView : a reference to current application’s QCView
property NSColor : a reference to current application’s NSColor
property NSWindowController : a reference to current application’s NSWindowController

if current application’s AEInteractWithUser(-1, missing value, missing value) is not equal to 0 then return

set chartData to NSMutableArray’s new()

–chartData’s addObject:(NSMutableDictionary’s dictionaryWithObjectsAndKeys_("練馬区", "label", 3, "value", missing value))–older way (Obsolete in 10.13)
chartData’s addObject:(my recWithLabels:{"label", "value"} andValues:{"練馬区", 3})
chartData’s addObject:(my recWithLabels:{"label", "value"} andValues:{"青梅市", 1})
chartData’s addObject:(my recWithLabels:{"label", "value"} andValues:{"中野区", 2})

–上記データの最大値を求める
set aMaxRec to chartData’s filteredArrayUsingPredicate:(NSPredicate’s predicateWithFormat_("SELF.value == %@.@max.value", chartData))
set aMax to value of aMaxRec
set aMaxVal to (first item of aMax) as integer

–Scalingの最大値を求める
if aMaxVal ≥ 10 then
  set aScaleMax to (10 div aMaxVal)
  
set aScaleMin to aScaleMax div 10
else
  set aScaleMax to (10 / aMaxVal)
  
set aScaleMin to 1
end if

try
  set aPath to path to resource "Chart.qtz"
on error
  return
end try

set qtPath to NSString’s stringWithString:(POSIX path of aPath)

set aView to QCView’s alloc()’s init()
set qtRes to (aView’s loadCompositionFromFile:qtPath)

aView’s setValue:chartData forInputKey:"Data"
aView’s setValue:(NSNumber’s numberWithFloat:(0.5)) forInputKey:"Scale"
aView’s setValue:(NSNumber’s numberWithFloat:(0.2)) forInputKey:"Spacing"
aView’s setAutostartsRendering:true

set maXFrameRate to aView’s maxRenderingFrameRate()

(aView’s setValue:(NSNumber’s numberWithFloat:aScaleMax / 10) forInputKey:"Scale")

set aWin to (my makeWinWithView(aView, 800, 600, "AppleScript Composition Test"))

set wController to NSWindowController’s alloc()
wController’s initWithWindow:aWin
aWin’s makeFirstResponder:aView
wController’s showWindow:me

aWin’s makeKeyAndOrderFront:me

delay 5

my closeWin:aWin
aView’s stopRendering() –レンダリング停止

–make Window for Display
on makeWinWithView(aView, aWinWidth, aWinHeight, aTitle)
  set aScreen to NSScreen’s mainScreen()
  
set aFrame to {{0, 0}, {aWinWidth, aWinHeight}}
  
  
set aBacking to NSTitledWindowMask
  
  
set aDefer to NSBackingStoreBuffered
  
  
— Window
  
set aWin to NSWindow’s alloc()
  (
aWin’s initWithContentRect:aFrame styleMask:aBacking backing:aDefer defer:false screen:aScreen)
  
aWin’s setBackgroundColor:(NSColor’s whiteColor())
  
  
aWin’s setTitle:aTitle
  
aWin’s setDelegate:me
  
aWin’s setDisplaysWhenScreenProfileChanges:true
  
aWin’s setHasShadow:true
  
aWin’s setIgnoresMouseEvents:false
  
aWin’s setLevel:(NSNormalWindowLevel)
  
aWin’s setOpaque:false
  
aWin’s setReleasedWhenClosed:true
  
aWin’s |center|()
  
aWin’s makeKeyAndOrderFront:(me)
  
–aWin’s movableByWindowBackground:true
  
  
— Set Custom View
  
aWin’s setContentView:aView
  
  
–Set Close Button  
  
set closeButton to NSWindow’s standardWindowButton:(NSWindowCloseButton) forStyleMask:(NSTitledWindowMask)
  
  
return aWin
end makeWinWithView

–close win
on closeWin:aWindow
  repeat with n from 10 to 1 by -1
    (aWindow’s setAlphaValue:n / 10)
    
delay 0.02
  end repeat
  
aWindow’s |close|()
end closeWin:

on recWithLabels:theKeys andValues:theValues
  return (NSDictionary’s dictionaryWithObjects:theValues forKeys:theKeys) as record
end recWithLabels:andValues:

★Click Here to Open This Script 

Posted in GUI Require Control-Command-R to run | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

popup button×2を作成

Posted on 2月 24, 2018 by Takaaki Naganoya

AppleScript名:popup button×2を作成
— Created 2015-12-30 by Takaaki Naganoya
— 2015 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"
use framework "Carbon" — AEInteractWithUser() is in Carbon

property windisp : false
property wController : false

if current application’s AEInteractWithUser(-1, missing value, missing value) is not equal to 0 then return

set ap1List to {"Alpha", "Bravo", "Charlie", "Delta", "Echo", "Foxtrot", "Golf", "Hotel", "India"}
set ap2List to {"Juliett", "Kilo", "Lima", "Mike", "November", "Oscar", "Papa", "Quebec", "Romeo"}

set aButtonMSG to "OK"
set aSliderValMSG to "Numbers上の値を交換するセルの選択"
set aVal to getPopupValues(ap1List, ap2List, aButtonMSG, aSliderValMSG, 20) of me
–>  {​​​​​"Alpha", ​​​​​"Kilo"​​​}–操作した場合
–>  {false, false}–タイムアウト時

on getPopupValues(ap1List, ap2List, aButtonMSG, aSliderValMSG, timeOutSecs)
  
  
set (my windisp) to true
  
  
set aView to current application’s NSView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, 360, 120))
  
  
–Labelをつくる
  
set a1TF to current application’s NSTextField’s alloc()’s initWithFrame:(current application’s NSMakeRect(60, 110, 80, 20))
  
set a2TF to current application’s NSTextField’s alloc()’s initWithFrame:(current application’s NSMakeRect(60, 70, 80, 20))
  
a1TF’s setEditable:false
  
a2TF’s setEditable:false
  
a1TF’s setStringValue:"移動前:"
  
a2TF’s setStringValue:"移動後:"
  
a1TF’s setDrawsBackground:false
  
a2TF’s setDrawsBackground:false
  
a1TF’s setBordered:false
  
a2TF’s setBordered:false
  
  
–Ppopup Buttonをつくる
  
set a1Button to current application’s NSPopUpButton’s alloc()’s initWithFrame:(current application’s NSMakeRect(140, 110, 180, 20)) pullsDown:false
  
set a2Button to current application’s NSPopUpButton’s alloc()’s initWithFrame:(current application’s NSMakeRect(140, 70, 180, 20)) pullsDown:false
  
  
a1Button’s removeAllItems()
  
a2Button’s removeAllItems()
  
  
a1Button’s addItemsWithTitles:ap1List
  
a2Button’s addItemsWithTitles:ap2List
  
  
  
–Buttonをつくる
  
set bButton to (current application’s NSButton’s alloc()’s initWithFrame:(current application’s NSMakeRect(110, 10, 180, 40)))
  
bButton’s setButtonType:(current application’s NSMomentaryLightButton)
  
bButton’s setBezelStyle:(current application’s NSRoundedBezelStyle)
  
bButton’s setTitle:aButtonMSG
  
bButton’s setTarget:me
  
bButton’s setAction:("clicked:")
  
bButton’s setKeyEquivalent:(return)
  
  
aView’s addSubview:a1TF
  
aView’s addSubview:a2TF
  
  
aView’s addSubview:a1Button
  
aView’s addSubview:a2Button
  
aView’s addSubview:bButton
  
aView’s setNeedsDisplay:true
  
  
–NSWindowControllerを作ってみた
  
set aWin to (my makeWinWithView(aView, 400, 160, aSliderValMSG))
  
set wController to current application’s NSWindowController’s alloc()
  
wController’s initWithWindow:aWin
  
  
wController’s showWindow:me
  
  
set aCount to timeOutSecs * 10
  
  
set hitF to false
  
repeat aCount times
    if (my windisp) = false then
      set hitF to true
      
exit repeat
    end if
    
delay 0.1
    
set aCount to aCount – 1
  end repeat
  
  
my closeWin:aWin
  
  
if hitF = true then
    set s1Val to a1Button’s titleOfSelectedItem() as string
    
set s2Val to a2Button’s titleOfSelectedItem() as string
  else
    set {s1Val, s2Val} to {false, false}
  end if
  
  
return {s1Val, s2Val}
  
end getPopupValues

on clicked:aSender
  set (my windisp) to false
end clicked:

–make Window for Display
on makeWinWithView(aView, aWinWidth, aWinHeight, aTitle)
  set aScreen to current application’s NSScreen’s mainScreen()
  
set aFrame to {{0, 0}, {aWinWidth, aWinHeight}}
  
  
set aBacking to current application’s NSTitledWindowMask
  
  
set aDefer to current application’s NSBackingStoreBuffered
  
  
— Window
  
set aWin to current application’s NSWindow’s alloc()
  (
aWin’s initWithContentRect:aFrame styleMask:aBacking backing:aDefer defer:false screen:aScreen)
  
–aWin’s setBackgroundColor:(current application’s NSColor’s whiteColor())
  
  
aWin’s setTitle:aTitle
  
aWin’s setDelegate:me
  
aWin’s setDisplaysWhenScreenProfileChanges:true
  
aWin’s setHasShadow:true
  
aWin’s setIgnoresMouseEvents:false
  
aWin’s setLevel:(current application’s NSNormalWindowLevel)
  
aWin’s setOpaque:false
  
aWin’s setReleasedWhenClosed:true
  
aWin’s |center|()
  
–aWin’s makeKeyAndOrderFront:(me)
  
  
aWin’s setContentView:aView
  
  
return aWin
  
end makeWinWithView

–close win
on closeWin:aWindow
  repeat with n from 10 to 1 by -1
    (aWindow’s setAlphaValue:n / 10)
    
delay 0.02
  end repeat
  
aWindow’s |close|()
end closeWin:

★Click Here to Open This Script 

Posted in GUI Require Control-Command-R to run | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

color popup buttonを作成 v1(Controllerあり)

Posted on 2月 24, 2018 by Takaaki Naganoya

AppleScript名:color popup buttonを作成 v1(Controllerあり)
— Created 2017-07-15 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"
use framework "Carbon" — AEInteractWithUser() is in Carbon

property windisp : false
property wController : false –いらなかったかも?

if current application’s AEInteractWithUser(-1, missing value, missing value) is not equal to 0 then return

set ap1List to {{65535, 0, 65535}, {0, 32896, 16448}, {0, 32896, 65535}, {19702, 31223, 40505}}

set aButtonMSG to "OK"
set aSliderValMSG to "Select Color"
set aVal to getPopupValues(ap1List, 65535, aButtonMSG, aSliderValMSG, 20) of me

on getPopupValues(ap1List, aColMax, aButtonMSG, aSliderValMSG, timeOutSecs)
  
  
set (my windisp) to true
  
  
set aView to current application’s NSView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, 360, 100))
  
  
–Labelをつくる
  
set a1TF to current application’s NSTextField’s alloc()’s initWithFrame:(current application’s NSMakeRect(30, 60, 80, 20))
  
a1TF’s setEditable:false
  
a1TF’s setStringValue:"Color:"
  
a1TF’s setDrawsBackground:false
  
a1TF’s setBordered:false
  
  
–Ppopup Buttonをつくる
  
set a1Button to current application’s NSPopUpButton’s alloc()’s initWithFrame:(current application’s NSMakeRect(80, 60, 200, 20)) pullsDown:false
  
a1Button’s removeAllItems()
  
  
set a1Menu to current application’s NSMenu’s alloc()’s init()
  
  
set iCount to 0
  
repeat with i in ap1List
    copy i to {r1, g1, b1}
    
    
set nsCol to makeNSColorFromRGBAval(r1, g1, b1, aColMax, aColMax) of me
    
set anImage to makeNSImageWithFilledWithColor(64, 16, nsCol) of me
    
    
set aTitle to "col_test_" & (iCount as string)
    
set aMenuItem to (current application’s NSMenuItem’s alloc()’s initWithTitle:aTitle action:"actionHandler:" keyEquivalent:"")
    (
aMenuItem’s setImage:anImage)
    (
aMenuItem’s setEnabled:true)
    (
a1Menu’s addItem:aMenuItem)
    
    
set iCount to iCount + 1
  end repeat
  
  
a1Button’s setMenu:a1Menu
  
  
  
–Buttonをつくる
  
set bButton to (current application’s NSButton’s alloc()’s initWithFrame:(current application’s NSMakeRect(80, 10, 140, 40)))
  
bButton’s setButtonType:(current application’s NSMomentaryLightButton)
  
bButton’s setBezelStyle:(current application’s NSRoundedBezelStyle)
  
bButton’s setTitle:aButtonMSG
  
bButton’s setTarget:me
  
bButton’s setAction:("clicked:")
  
bButton’s setKeyEquivalent:(return)
  
  
aView’s addSubview:a1TF
  
  
aView’s addSubview:a1Button
  
aView’s addSubview:bButton
  
aView’s setNeedsDisplay:true
  
  
–NSWindowControllerを作ってみた(いらない?)
  
set aWin to (my makeWinWithView(aView, 300, 100, aSliderValMSG))
  
  
set wController to current application’s NSWindowController’s alloc()
  
wController’s initWithWindow:aWin
  
  
wController’s showWindow:me
  
  
set aCount to timeOutSecs * 100
  
  
set hitF to false
  
repeat aCount times
    if (my windisp) = false then
      set hitF to true
      
exit repeat
    end if
    
delay 0.01
    
set aCount to aCount – 1
  end repeat
  
  
my closeWin:aWin
  
  
if hitF = true then
    set s1Val to a1Button’s titleOfSelectedItem() as string
  else
    set s1Val to false
  end if
  
  
return s1Val
  
end getPopupValues

on clicked:aSender
  set (my windisp) to false
end clicked:

–make Window for Display
on makeWinWithView(aView, aWinWidth, aWinHeight, aTitle)
  set aScreen to current application’s NSScreen’s mainScreen()
  
set aFrame to {{0, 0}, {aWinWidth, aWinHeight}}
  
  
set aBacking to current application’s NSTitledWindowMask
  
  
set aDefer to current application’s NSBackingStoreBuffered
  
  
— Window
  
set aWin to current application’s NSWindow’s alloc()
  (
aWin’s initWithContentRect:aFrame styleMask:aBacking backing:aDefer defer:false screen:aScreen)
  
–aWin’s setBackgroundColor:(current application’s NSColor’s whiteColor())
  
  
aWin’s setTitle:aTitle
  
aWin’s setDelegate:me
  
aWin’s setDisplaysWhenScreenProfileChanges:true
  
aWin’s setHasShadow:true
  
aWin’s setIgnoresMouseEvents:false
  
aWin’s setLevel:(current application’s NSNormalWindowLevel)
  
aWin’s setOpaque:false
  
aWin’s setReleasedWhenClosed:true
  
aWin’s |center|()
  
–aWin’s makeKeyAndOrderFront:(me)
  
  
aWin’s setContentView:aView
  
  
return aWin
  
end makeWinWithView

–close win
on closeWin:aWindow
  repeat with n from 10 to 1 by -1
    (aWindow’s setAlphaValue:n / 10)
    
delay 0.02
  end repeat
  
aWindow’s |close|()
end closeWin:

–Popup Action Handler
on actionHandler:sender
  set aTag to tag of sender as integer
  
set aTitle to title of sender as string
end actionHandler:

on makeNSColorFromRGBAval(redValue as integer, greenValue as integer, blueValue as integer, alphaValue as integer, aMaxVal as integer)
  set aRedCocoa to (redValue / aMaxVal) as real
  
set aGreenCocoa to (greenValue / aMaxVal) as real
  
set aBlueCocoa to (blueValue / aMaxVal) as real
  
set aAlphaCocoa to (alphaValue / aMaxVal) as real
  
set aColor to current application’s NSColor’s colorWithCalibratedRed:aRedCocoa green:aGreenCocoa blue:aBlueCocoa alpha:aAlphaCocoa
  
return aColor
end makeNSColorFromRGBAval

–指定サイズの画像を作成し、指定色で塗ってファイル書き出し
on makeNSImageWithFilledWithColor(aWidth, aHeight, fillColor)
  set anImage to current application’s NSImage’s alloc()’s initWithSize:(current application’s NSMakeSize(aWidth, aHeight))
  
anImage’s lockFocus()
  
—
  
set theRect to {{x:0, y:0}, {height:aHeight, width:aWidth}}
  
set theNSBezierPath to current application’s NSBezierPath’s bezierPath
  
theNSBezierPath’s appendBezierPathWithRect:theRect
  
—
  
fillColor’s |set|() –色設定
  
theNSBezierPath’s fill() –ぬりつぶし
  
—
  
anImage’s unlockFocus()
  
—
  
return anImage
end makeNSImageWithFilledWithColor

★Click Here to Open This Script 

Posted in GUI Require Control-Command-R to run | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

slider+buttonを作成 v3

Posted on 2月 24, 2018 by Takaaki Naganoya

AppleScript名:slider+buttonを作成 v3
— Created 2015-12-27 by Takaaki Naganoya
— 2015 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"
use framework "Carbon" — AEInteractWithUser() is in Carbon

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

if current application’s AEInteractWithUser(-1, missing value, missing value) is not equal to 0 then return

set aMaxVal to 10
set aButtonMSG to "OK"
set aSliderValMSG to "スライダーの設定値:"
set aVal to getSliderValue(aMaxVal, aButtonMSG, aSliderValMSG) of me

on getSliderValue(aMaxVal, aButtonMSG, aSliderValMSG)
  set (my windisp) to true
  
set (my aSliderValMSG) to aSliderValMSG
  
  
set aView to current application’s NSSplitView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, 360, 40))
  
aView’s setVertical:false
  
  
–Sliderをつくる
  
set aSlider to makeSider(aMaxVal) of me
  
  
–Buttonをつくる
  
set bButton to (current application’s NSButton’s alloc()’s init())
  
bButton’s setTitle:aButtonMSG
  
bButton’s setTarget:me
  
bButton’s setAction:("clicked:")
  
  
bButton’s setKeyEquivalent:(return) –キーボードショートカット(リターンキー)
  
  
aView’s addSubview:aSlider
  
aView’s addSubview:bButton
  
aView’s setNeedsDisplay:true
  
  
–NSWindowControllerを作ってみた
  
set aWin to (my makeWinWithView(aView, 400, 80, aSliderValMSG & (aMaxVal div 2) as string))
  
set wController to current application’s NSWindowController’s alloc()
  
wController’s initWithWindow:aWin
  
wController’s showWindow:me
  
  
set aCount to 1800
  
repeat aCount times
    if (my windisp) = false then
      exit repeat
    end if
    
delay 0.1
    
set aCount to aCount – 1
  end repeat
  
  
my closeWin:aWin
  
  
set sVal to aSlider’s intValue()
  
return sVal
end getSliderValue

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

on clicked:aSender
  set (my windisp) to false
end clicked:

–make Window for Display
on makeWinWithView(aView, aWinWidth, aWinHeight, aTitle)
  set aScreen to current application’s NSScreen’s mainScreen()
  
set aFrame to {{0, 0}, {aWinWidth, aWinHeight}}
  
  
set aBacking to current application’s NSTitledWindowMask
  
  
set aDefer to current application’s NSBackingStoreBuffered
  
  
— Window
  
set aWin to current application’s NSWindow’s alloc()
  (
aWin’s initWithContentRect:aFrame styleMask:aBacking backing:aDefer defer:false screen:aScreen)
  
–aWin’s setBackgroundColor:(current application’s NSColor’s whiteColor())
  
  
aWin’s setTitle:aTitle
  
aWin’s setDelegate:me
  
aWin’s setDisplaysWhenScreenProfileChanges:true
  
aWin’s setHasShadow:true
  
aWin’s setIgnoresMouseEvents:false
  
aWin’s setLevel:(current application’s NSNormalWindowLevel)
  
aWin’s setOpaque:false
  
aWin’s setReleasedWhenClosed:true
  
aWin’s |center|()
  
–aWin’s makeKeyAndOrderFront:(me)
  
  
aWin’s setContentView:aView
  
  
return aWin
  
end makeWinWithView

–close win
on closeWin:aWindow
  repeat with n from 10 to 1 by -1
    (aWindow’s setAlphaValue:n / 10)
    
delay 0.02
  end repeat
  
aWindow’s |close|()
end closeWin:

on makeSider(aMaxNum)
  set aSlider to current application’s 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:(current application’s NSTickMarkBelow)
  
aSlider’s setIntValue:(aMaxNum div 2)
  
aSlider’s setTarget:me
  
aSlider’s setAction:("sliderChanged:")
  
return aSlider
end makeSider

★Click Here to Open This Script 

Posted in GUI Require Control-Command-R to run | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

テーブルビューを表示 v5

Posted on 2月 24, 2018 by Takaaki Naganoya

AppleScript名:ASOCでテーブルビューを表示 v5a.scpt
— Created 2017-12-20 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
use framework "AppKit"
use framework "Quartz"

property |NSURL| : a reference to current application’s |NSURL|
property NSData : a reference to current application’s NSData
property NSView : a reference to current application’s NSView
property NSString : a reference to current application’s NSString
property NSScreen : a reference to current application’s NSScreen
property NSButton : a reference to current application’s NSButton
property NSWindow : a reference to current application’s NSWindow
property MKMapView : a reference to current application’s MKMapView
property NSURLRequest : a reference to current application’s NSURLRequest
property NSURLConnection : a reference to current application’s NSURLConnection
property NSJSONSerialization : a reference to current application’s NSJSONSerialization
property NSWindowController : a reference to current application’s NSWindowController
property NSUTF8StringEncoding : a reference to current application’s NSUTF8StringEncoding

property windisp : false
property theDataSource : {}

on run
  my performSelectorOnMainThread:"disp:" withObject:(missing value) waitUntilDone:true
end run

on disp:aParam
  set aWidth to 400
  
set aHeight to 200
  
  
set aDic to {{field1:"test 10", field2:"test 20"}, {field1:"test 11", field2:"test 21"}, {field1:"test 12", field2:"test 22"}, {field1:"test 13", field2:"test 23"}, {field1:"test 14", field2:"test 24"}, {field1:"test 15", field2:"test 25"}, {field1:"test 16", field2:"test 26"}, {field1:"test 17", field2:"test 27"}, {field1:"test 18", field2:"test 28"}, {field1:"test 19", field2:"test 29"}, {field1:"test 10", field2:"test 20"}, {field1:"test 11", field2:"test 21"}, {field1:"test 12", field2:"test 22"}, {field1:"test 13", field2:"test 23"}, {field1:"test 14", field2:"test 24"}, {field1:"test 15", field2:"test 25"}, {field1:"test 16", field2:"test 26"}, {field1:"test 17", field2:"test 27"}, {field1:"test 18", field2:"test 28"}, {field1:"test 19", field2:"test 29"}}
  
  
dispTableView(aWidth, aHeight, "Result", "OK", 180, aDic) of me
end disp:

on dispTableView(aWidth as integer, aHeight as integer, aTitle as text, aButtonMSG as text, timeOutSecs as number, aDictList)
  
  
–Check If this script runs in foreground
  
if not (current application’s NSThread’s isMainThread()) as boolean then
    error "This script must be run from the main thread (Command-Control-R in Script Editor)."
  end if
  
set (my windisp) to true
  
  
  
set aTableView to makeTableView(aDictList, aWidth, aHeight – 40) of me
  
  
  
–Buttonをつくる
  
set bButton to (NSButton’s alloc()’s initWithFrame:(current application’s NSMakeRect(aWidth / 4, 0, aWidth / 2, 40)))
  
bButton’s setTitle:aButtonMSG
  
bButton’s setButtonType:(current application’s NSMomentaryLightButton)
  
bButton’s setBezelStyle:(current application’s NSRoundedBezelStyle)
  
bButton’s setKeyEquivalent:(return)
  
bButton’s setTarget:me
  
bButton’s setAction:("clicked:")
  
  
–NSViewをつくる
  
set aNSV to NSView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aHeight, aWidth))
  
aNSV’s addSubview:aTableView
  
aNSV’s addSubview:bButton
  
aNSV’s setNeedsDisplay:true
  
  
set aWin to makeWinWithView(aNSV, aWidth, aHeight, aTitle, 1.0)
  
  
  
set wController to NSWindowController’s alloc()
  
wController’s initWithWindow:aWin
  
aWin’s makeFirstResponder:aTableView
  
wController’s showWindow:me
  
  
aWin’s makeKeyAndOrderFront:me
  
  
set aCount to timeOutSecs * 10 –timeout seconds * 10
  
repeat aCount times
    if (my windisp) = false then
      exit repeat
    end if
    
delay 0.1
  end repeat
  
  
my closeWin:aWin
  
end dispTableView

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

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

–close win
on closeWin:aWindow
  repeat with n from 10 to 1 by -1
    (aWindow’s setAlphaValue:n / 10)
    
delay 0.02
  end repeat
  
aWindow’s |close|()
end closeWin:

–TableView Event Handlers
on numberOfRowsInTableView:aView
  return my theDataSource’s |count|()
end numberOfRowsInTableView:

on tableView:aView objectValueForTableColumn:aColumn row:aRow
  set aRec to (my theDataSource)’s objectAtIndex:(aRow as number)
  
set aTitle to (aColumn’s headerCell()’s title()) as string
  
set aRes to (aRec’s valueForKey:aTitle)
  
return aRes
end tableView:objectValueForTableColumn:row:

on makeTableView(aDicList, aWidth, aHeight)
  set aOffset to 40
  
set theDataSource to current application’s NSMutableArray’s alloc()’s init()
  
theDataSource’s addObjectsFromArray:aDicList
  
  
set aScroll to current application’s NSScrollView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, aOffset, aWidth, aHeight))
  
set aView to current application’s NSTableView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, aOffset, aWidth, aHeight))
  
  
set aFirstRec to current application’s NSDictionary’s dictionaryWithDictionary:(first item of (aDicList as list))
  
set keyList to (aFirstRec’s allKeys()) as list
  
set aLen to length of keyList
  
  
repeat with i in keyList
    set j to contents of i
    
set aColumn to (current application’s NSTableColumn’s alloc()’s initWithIdentifier:j)
    (
aColumn’s setWidth:(aWidth div aLen))
    (
aColumn’s headerCell()’s setStringValue:j)
    (
aView’s addTableColumn:aColumn)
  end repeat
  
  
aView’s setDelegate:me
  
aView’s setDataSource:me
  
aView’s reloadData()
  
  
aScroll’s setDocumentView:aView
  
aView’s enclosingScrollView()’s setHasVerticalScroller:true
  
  
–1行目を選択
  
set aIndexSet to current application’s NSIndexSet’s indexSetWithIndex:0
  
aView’s selectRowIndexes:aIndexSet byExtendingSelection:false
  
  
–強制的にトップにスクロール
  
–set maxHeight to aScroll’s documentView()’s |bounds|()’s |size|()’s height
  
set aDBounds to aScroll’s documentView()’s |bounds|()
  
if class of aDBounds = list then
    –macOS 10.13 or later
    
set maxHeight to item 2 of item 1 of aDBounds
  else
    –macOS 10.10….10.12
    
set maxHeight to height of |size| of aDBounds
  end if
  
  
  
set aPT to current application’s NSMakePoint(0.0, -40.0) —— (aScroll’s documentView()’s |bounds|()’s |size|()’s height))
  
aScroll’s documentView()’s scrollPoint:aPT
  
  
return aScroll
end makeTableView

★Click Here to Open This Script 

Posted in GUI Require Control-Command-R to run | Tagged 10.11savvy 10.12savvy 10.13savvy 10.14savvy | Leave a comment

プログレスバー+buttonを作成

Posted on 2月 24, 2018 by Takaaki Naganoya

ウィンドウを作成して、その上でプログレスバーと途中停止用のボタンを描画、プログレスバーのアニメーション表示を行わせるサンプルScriptです。

スクリプトエディタ上でControl-Command-Rの操作を行い、スクリプトをメインスレッドで実行する必要があります。

AppleScript名:プログレスバー+buttonを作成
— Created 2015-12-11 by Takaaki Naganoya
— 2015 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"
use framework "Carbon" — AEInteractWithUser() is in Carbon

property windisp : false
property aPBar : missing value

if current application’s AEInteractWithUser(-1, missing value, missing value) is not equal to 0 then return

set aMaxVal to 100
set aButtonMSG to "Abort"
set aTitle to "現在進行中…"
set aWin to makeProgressWindow(aMaxVal, aButtonMSG, aTitle) of me

repeat with i from 1 to aMaxVal by 1
  if (my windisp) = false then
    exit repeat
  end if
  (
aPBar’s setDoubleValue:(i as real))
  
delay 0.01
end repeat

if i is not equal to aMaxVal then
  tell current application
    display dialog "Aborted" buttons {"OK"} default button 1
  end tell
end if
my closeWin:aWin
set my aPBar to missing value
set aWin to missing value

on makeProgressWindow(aMaxVal, aButtonMSG, aTitle)
  set (my windisp) to true
  
–set (my aSliderValMSG) to aSliderValMSG
  
  
set aView to current application’s NSSplitView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, 360, 40))
  
aView’s setVertical:false
  
  
–ProgressIndicatorをつくる
  
set aSlider to makeProgressIndicator(aMaxVal) of me
  
  
–Buttonをつくる
  
set bButton to (current application’s NSButton’s alloc()’s init())
  
bButton’s setTitle:aButtonMSG
  
bButton’s setTarget:me
  
bButton’s setAction:("clicked:")
  
  
aView’s addSubview:aSlider
  
aView’s addSubview:bButton
  
aView’s setNeedsDisplay:true
  
  
set aWin to (my makeDockLevelWinWithView(aView, 400, 80, aTitle))
  
  
return aWin
  
end makeProgressWindow

on clicked:aSender
  set (my windisp) to false
end clicked:

–make Window for Display
on makeDockLevelWinWithView(aView, aWinWidth, aWinHeight, aTitle)
  set aScreen to current application’s NSScreen’s mainScreen()
  
set aFrame to {{0, 0}, {aWinWidth, aWinHeight}}
  
  
set aBacking to current application’s NSTitledWindowMask
  
  
set aDefer to current application’s NSBackingStoreBuffered
  
  
— Window
  
set aWin to current application’s NSWindow’s alloc()
  (
aWin’s initWithContentRect:aFrame styleMask:aBacking backing:aDefer defer:false screen:aScreen)
  
–aWin’s setBackgroundColor:(current application’s NSColor’s whiteColor())
  
  
aWin’s setTitle:aTitle
  
aWin’s setDelegate:me
  
aWin’s setDisplaysWhenScreenProfileChanges:true
  
aWin’s setHasShadow:true
  
aWin’s setIgnoresMouseEvents:false
  
aWin’s setLevel:(current application’s NSDockWindowLevel) –プログレスバー表示用に変更
  
aWin’s setOpaque:false
  
aWin’s setReleasedWhenClosed:true
  
aWin’s |center|()
  
aWin’s makeKeyAndOrderFront:(me)
  
  
aWin’s setContentView:aView
  
  
return aWin
  
end makeDockLevelWinWithView

–close win
on closeWin:aWindow
  repeat with n from 10 to 1 by -1
    (aWindow’s setAlphaValue:n / 10)
    
delay 0.02
  end repeat
  
aWindow’s |close|()
end closeWin:

–make progress indicator
on makeProgressIndicator(aMaxNum)
  set aPBar to current application’s NSProgressIndicator’s alloc()’s init()
  
aPBar’s setMaxValue:aMaxNum
  
aPBar’s setMinValue:1
  
aPBar’s setIndeterminate:false
  
aPBar’s setControlSize:(current application’s NSProgressIndicatorPreferredLargeThickness)
  
aPBar’s setDoubleValue:(1.0 as real)
  
return aPBar
end makeProgressIndicator

★Click Here to Open This Script 

Posted in GUI Require Control-Command-R to run | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

テキストビュー+ボタンを作成(フォント指定)v2

Posted on 2月 24, 2018 by Takaaki Naganoya

動的にWindow+TextView+ボタンを作成し、指定フォントで指定文字を表示するAppleScriptです。

スクリプトエディタ上でControl+Command+Rによって実行します(メインスレッドで実行)。

AppleScript名:テキストビュー+ボタンを作成(フォント指定)v2
— Created 2016-02-01 by Takaaki Naganoya
— 2016 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"
use framework "Carbon" — AEInteractWithUser() is in Carbon

property windisp : false

property NSFont : a reference to current application’s NSFont
property NSPredicate : a reference to current application’s NSPredicate
property NSFontManager : a reference to current application’s NSFontManager

set fRes to choose from list getEveryFontPSName() of me
if fRes = {} or fRes = missing value then return

set aFontName to contents of first item of fRes
set aWidth to 600
set aHeight to 450

if current application’s AEInteractWithUser(-1, missing value, missing value) is not equal to 0 then return

set aTitle to "テキストビューのじっけん/TextView Test" –Window Title
set aButtonMSG to "OK" –Button Title

–表示用テキストの作成
set aRes to checkExistenceOfFont(aFontName) of me
if aRes = false then
  display dialog "There is no <" & aFontName & "> font. Designate another one." –No font
  
return
end if
set bRes to retDefinedCharactersInFont(aFontName) of me
set dispStr to listToStringUsingTextItemDelimiter(bRes, ", ") of me

dispTextView(aWidth, aHeight, aFontName, dispStr, aButtonMSG, 180, aFontName, 36) of me

on dispTextView(aWidth as integer, aHeight as integer, aTitle as text, dispStr, aButtonMSG as text, timeOutSecs as number, fontID, fontSize)
  
  
set aColor to current application’s NSColor’s colorWithDeviceRed:0.0 green:0.0 blue:0.0 alpha:1.0
  
set (my windisp) to true
  
  
–Text View+Scroll Viewをつくる
  
set aScroll to current application’s NSScrollView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aWidth, aHeight))
  
set aView to current application’s NSTextView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aWidth, aHeight))
  
aView’s setRichText:true
  
aView’s useAllLigatures:true
  
aView’s setTextColor:(current application’s NSColor’s yellowColor()) –cyanColor
  
aView’s setFont:(current application’s NSFont’s fontWithName:fontID |size|:fontSize) –ヒラギノ明朝Pro W3
  
aView’s setBackgroundColor:aColor
  
aScroll’s setDocumentView:aView
  
aView’s enclosingScrollView()’s setHasVerticalScroller:true
  
  
–Buttonをつくる
  
set bButton to (current application’s NSButton’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aWidth, 40)))
  
bButton’s setTitle:aButtonMSG
  
bButton’s setTarget:me
  
bButton’s setAction:("clicked:")
  
  
–SplitViewをつくる
  
set aSplitV to current application’s NSSplitView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aHeight, aWidth))
  
aSplitV’s setVertical:false
  
  
aSplitV’s addSubview:aScroll
  
aSplitV’s addSubview:bButton
  
aSplitV’s setNeedsDisplay:true
  
  
–WindowとWindow Controllerをつくる
  
set aWin to makeWinWithView(aSplitV, aWidth, aHeight, aTitle, 0.9)
  
aWin’s makeKeyAndOrderFront:(missing value)
  
set wController to current application’s NSWindowController’s alloc()
  
wController’s initWithWindow:aWin
  
aWin’s makeFirstResponder:aView
  
aView’s setString:dispStr
  
wController’s showWindow:me
  
  
set aCount to timeOutSecs * 10 –timeout seconds * 10
  
repeat aCount times
    if (my windisp) = false then
      exit repeat
    end if
    
delay 0.1
    
set aCount to aCount – 1
  end repeat
  
  
my closeWin:aWin
  
end dispTextView

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

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

–close win
on closeWin:aWindow
  repeat with n from 10 to 1 by -1
    (aWindow’s setAlphaValue:n / 10)
    
delay 0.02
  end repeat
  
aWindow’s |close|()
end closeWin:

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

–指定Postscript名称のフォントに定義されている文字数を数えて返す
on countDefinedCharactersInFont(fontName as string)
  
  
script spdF
    property aList : {}
  end script
  
  
set aFont to current application’s NSFont’s fontWithName:fontName |size|:9.0
  
if aFont = missing value then return false
  
  
set aSet to aFont’s coveredCharacterSet()
  
  
set aList of spdF to {}
  
  
repeat with i from 1 to 65535
    set aRes to (aSet’s characterIsMember:i) as boolean
    
if aRes = true then
      set the end of aList of spdF to (string id i)
    end if
  end repeat
  
  
return length of (aList of spdF)
  
end countDefinedCharactersInFont

–指定Postscript名称のフォントに定義されている文字を返す
on retDefinedCharactersInFont(fontName as string)
  
  
script spdG
    property aList : {}
  end script
  
  
set aFont to current application’s NSFont’s fontWithName:fontName |size|:24.0
  
set aSet to aFont’s coveredCharacterSet()
  
  
set aList of spdG to {}
  
  
repeat with i from 1 to 65535
    set aRes to (aSet’s characterIsMember:i) as boolean
    
if aRes = true then
      set the end of aList of spdG to (string id i)
    end if
  end repeat
  
  
return (aList of spdG)
  
end retDefinedCharactersInFont

on listToStringUsingTextItemDelimiter(sourceList, textItemDelimiter)
  set the CocoaArray to current application’s NSArray’s arrayWithArray:sourceList
  
set the CocoaString to CocoaArray’s componentsJoinedByString:textItemDelimiter
  
return (CocoaString as string)
end listToStringUsingTextItemDelimiter

–インストールされているフォントのpost script nameを取得する
on getEveryFontPSName()
  set aFontList to NSFontManager’s sharedFontManager()’s availableFonts()
  
set thePred to NSPredicate’s predicateWithFormat:"NOT SELF BEGINSWITH ’.’"
  
set aFontList to (aFontList’s filteredArrayUsingPredicate:thePred) as list
  
  
set aList to {}
  
repeat with i in aFontList
    set aName to contents of i
    
set the end of aList to aName
  end repeat
  
  
return aList
end getEveryFontPSName

★Click Here to Open This Script 

Posted in GUI Require Control-Command-R to run | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

Segmented Controlを表示する

Posted on 2月 24, 2018 by Takaaki Naganoya

AppleScript名:Segmented Controlを表示する
— Created 2017-12-20 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
use framework "AppKit"

property NSView : a reference to current application’s NSView
property NSScreen : a reference to current application’s NSScreen
property NSButton : a reference to current application’s NSButton
property NSWindow : a reference to current application’s NSWindow
property NSWindowController : a reference to current application’s NSWindowController
property NSSegmentedControl : a reference to current application’s NSSegmentedControl

property windisp : false
property selSeg : 0

set aWidth to 500
set aHeight to 100

set segTitleList to {"First Segment", "Second Segment", "Third Segment", "Forth Segment"}

set aRes to dispSegControl(aWidth, aHeight, "Segemented Control", "OK", 180, segTitleList) of me

on dispSegControl(aWidth as integer, aHeight as integer, aTitle as text, aButtonMSG as text, timeOutSecs as number, segTitleList)
  
  
–Check If this script runs in foreground
  
if not (current application’s NSThread’s isMainThread()) as boolean then
    error "This script must be run from the main thread (Command-Control-R in Script Editor)."
  end if
  
  
set selSeg to 0
  
set (my windisp) to true
  
  
–Segmented Controlをつくる
  
set aSeg to makeSegmentedControl(segTitleList, aWidth, aHeight) of me
  
  
–Buttonをつくる
  
set bButton to (NSButton’s alloc()’s initWithFrame:(current application’s NSMakeRect(aWidth / 4, 0, aWidth / 2, 40)))
  
bButton’s setTitle:aButtonMSG
  
bButton’s setButtonType:(current application’s NSMomentaryLightButton)
  
bButton’s setBezelStyle:(current application’s NSRoundedBezelStyle)
  
bButton’s setKeyEquivalent:(return)
  
bButton’s setTarget:me
  
bButton’s setAction:("clicked:")
  
  
–NSViewをつくる
  
set aNSV to NSView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aHeight, aWidth))
  
aNSV’s addSubview:aSeg
  
aNSV’s addSubview:bButton
  
aNSV’s setNeedsDisplay:true
  
  
set aWin to makeWinWithView(aNSV, aWidth, aHeight, aTitle, 1.0)
  
  
  
set wController to NSWindowController’s alloc()
  
wController’s initWithWindow:aWin
  
wController’s showWindow:me
  
  
aWin’s makeKeyAndOrderFront:me
  
  
set aCount to timeOutSecs * 10 –timeout seconds * 10
  
repeat aCount times
    if (my windisp) = false then
      exit repeat
    end if
    
delay 0.1
  end repeat
  
  
my closeWin:aWin
  
  
return (selSeg + 1)
end dispSegControl

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

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

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

–close win
on closeWin:aWindow
  repeat with n from 10 to 1 by -1
    (aWindow’s setAlphaValue:n / 10)
    
delay 0.02
  end repeat
  
aWindow’s |close|()
end closeWin:

on makeSegmentedControl(titleList, aWidth, aHeight)
  set aLen to length of titleList
  
  
set aSeg to NSSegmentedControl’s alloc()’s init()
  
aSeg’s setSegmentCount:aLen
  
  
set aCount to 0
  
repeat with i in titleList
    set j to contents of i
    (
aSeg’s setLabel:j forSegment:aCount)
    
set aCount to aCount + 1
  end repeat
  
  
aSeg’s setTranslatesAutoresizingMaskIntoConstraints:false
  
aSeg’s setSegmentStyle:(current application’s NSSegmentStyleTexturedRounded)
  
aSeg’s setFrame:(current application’s NSMakeRect(20, aHeight – 60, aWidth, aHeight – 40))
  
aSeg’s setTrackingMode:0
  
aSeg’s setTarget:me
  
aSeg’s setAction:"clickedSeg:"
  
aSeg’s setSelectedSegment:0
  
  
return aSeg
end makeSegmentedControl

★Click Here to Open This Script 

Posted in GUI Require Control-Command-R to run | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

Colorsで色バリエーション展開を計算して表示 v2

Posted on 2月 24, 2018 by Takaaki Naganoya

Coloursをフレームワーク化したcolorsKit.frameworkを呼び出して、指定のRGB色のカラーバリエーションを計算するAppleScriptです。

–> colorsKit.framework

AppleScript名:Colorsで色バリエーション展開を計算して表示 v2
— Created 2017-12-20 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
use framework "AppKit"
use framework "colorsKit" –https://github.com/bennyguitar/Colours

property NSView : a reference to current application’s NSView
property NSColor : a reference to current application’s NSColor
property NSString : a reference to current application’s NSString
property NSScreen : a reference to current application’s NSScreen
property NSButton : a reference to current application’s NSButton
property NSWindow : a reference to current application’s NSWindow
property NSColorWell : a reference to current application’s NSColorWell
property NSWindowController : a reference to current application’s NSWindowController

property windisp : false

set aWidth to 500
set aHeight to 250

set {rVal, gVal, bVal} to choose color
set aNSCol to makeNSColorFromRGBAval(rVal, gVal, bVal, 65536, 65536) of me

dispCustomView(aWidth, aHeight, "Color Variation Result", "OK", 180, aNSCol) of me

on dispCustomView(aWidth as integer, aHeight as integer, aTitle as text, aButtonMSG as text, timeOutSecs as number, aNSCol)
  
  
–Check If this script runs in foreground
  
if not (current application’s NSThread’s isMainThread()) as boolean then
    error "This script must be run from the main thread (Command-Control-R in Script Editor)."
  end if
  
  
set (my windisp) to true
  
  
  
–Buttonをつくる
  
set bButton to (NSButton’s alloc()’s initWithFrame:(current application’s NSMakeRect(aWidth / 4, 0, aWidth / 2, 40)))
  
bButton’s setTitle:aButtonMSG
  
bButton’s setButtonType:(current application’s NSMomentaryLightButton)
  
bButton’s setBezelStyle:(current application’s NSRoundedBezelStyle)
  
bButton’s setKeyEquivalent:(return)
  
bButton’s setTarget:me
  
bButton’s setAction:("clicked:")
  
  
–NSViewをつくる
  
set aNSV to NSView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aHeight, aWidth))
  
aNSV’s addSubview:bButton
  
aNSV’s setNeedsDisplay:true
  
  
–NSColorWellをつくる
  
repeat with ii from 0 to 3 by 1
    set colorArray1 to (aNSCol’s colorSchemeOfType:ii) as list
    
set the beginning of colorArray1 to aNSCol
    
set tmpLen to (length of colorArray1)
    
set aStep to 0
    
repeat with i in colorArray1
      set aColorWell to (NSColorWell’s alloc()’s initWithFrame:(current application’s NSMakeRect((100 * aStep), (((3 – ii) * 50) + 40), 100, 40)))
      (
aColorWell’s setColor:i)
      (
aColorWell’s setBordered:true)
      (
aNSV’s addSubview:aColorWell)
      
set aStep to aStep + 1
    end repeat
  end repeat
  
  
set aWin to makeWinWithView(aNSV, aWidth, aHeight, aTitle, 1.0)
  
  
set wController to NSWindowController’s alloc()
  
wController’s initWithWindow:aWin
  
wController’s showWindow:me
  
  
aWin’s makeKeyAndOrderFront:me
  
  
set aCount to timeOutSecs * 10 –timeout seconds * 10
  
repeat aCount times
    if (my windisp) = false then
      exit repeat
    end if
    
delay 0.1
  end repeat
  
  
my closeWin:aWin
  
end dispCustomView

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

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

–close win
on closeWin:aWindow
  repeat with n from 10 to 1 by -1
    (aWindow’s setAlphaValue:n / 10)
    
delay 0.02
  end repeat
  
aWindow’s |close|()
end closeWin:

on makeNSColorFromRGBAval(redValue as integer, greenValue as integer, blueValue as integer, alphaValue as integer, aMaxVal as integer)
  set aRedCocoa to (redValue / aMaxVal) as real
  
set aGreenCocoa to (greenValue / aMaxVal) as real
  
set aBlueCocoa to (blueValue / aMaxVal) as real
  
set aAlphaCocoa to (alphaValue / aMaxVal) as real
  
set aColor to NSColor’s colorWithCalibratedRed:aRedCocoa green:aGreenCocoa blue:aBlueCocoa alpha:aAlphaCocoa
  
return aColor
end makeNSColorFromRGBAval

★Click Here to Open This Script 

Posted in Color GUI Require Control-Command-R to run | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

InputManagerでIMを切り換える

Posted on 2月 20, 2018 by Takaaki Naganoya

InputManager.frameworkを呼び出して、日本語入力Input Methodの入力文字の切り替えを行うAppleScriptです。

スクリプトエディタ上でControl-Command-Rにてフロントエンド・プロセスで実行する必要があります。

–> Demo Movie

–> InputManager.framework

AppleScript名:InputManagerでIMを切り換える
— Created 2017-01-22 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"
use framework "InputManager" –https://github.com/jensnockert/input-manager

–Check If this script runs in foreground
if not (current application’s NSThread’s isMainThread()) as boolean then
  display alert "This script must be run from the main thread (Command-Control-R in Script Editor)." buttons {"Cancel"} as critical
  
error number -128
end if

–Caution: This script runs on only Japanese language environment

set cList to current application’s CSInputSource’s all()
set dList to (cList’s valueForKey:"localizedName")
set aRes to ((dList’s indexOfObject:"ひらがな") as integer) –"Hiragana" in Japanese
set bRes to ((dList’s indexOfObject:"英字") as integer) –"English Letters" in Japanese

set hiraKey to cList’s objectAtIndex:aRes
set engKey to cList’s objectAtIndex:bRes

repeat 10 times
  hiraKey’s |select|()
  
delay 1
  
engKey’s |select|()
  
delay 1
end repeat

★Click Here to Open This Script 

Posted in Input Method Require Control-Command-R to run System | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

Safariで表示中のURLをwebarchive保存

Posted on 2月 11, 2018 by Takaaki Naganoya

Safariで表示中の最前面のウィンドウのURLの内容をデスクトップ上にWebarchive書類として保存するAppleScriptです。

webArchiveはDeprecatedになったので、macOS 10.14あたりまでのOSで使うならOK。今後については何か別の機能が実装されるのかどうか。macOS 10.15で別の何かが紹介されるのでしょうか。

AppleScript名:Safariで表示中のURLをwebarchive保存
— Created 2014-11-13 Shane Stanley
— Modified 2018-02-11 Takaaki Naganoya
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "WebKit"

property theSender : missing value
property thePath : missing value
property loadDone : false –original was "webFrame"
property aWebView : missing value

tell application "Safari"
  if (count every document) = 0 then return
  
tell front document
    set aURL to URL
  end tell
end tell

set aPath to (POSIX path of (path to desktop)) & ((current application’s NSUUID’s UUID()’s UUIDString()) as string) & ".webarchive"
set archRes to archivePageToPathWithoutSearching(aURL, aPath, me, 10) of me

on archivePageToPathWithoutSearching(thePageURL, aPath, sender, timeoutSec)
  –Check If this script runs in foreground
  
if not (current application’s NSThread’s isMainThread()) as boolean then
    display alert "This script must be run from the main thread (Command-Control-R in Script Editor)." buttons {"Cancel"} as critical
    
error number -128
  end if
  
  
set my theSender to sender — store main script so we can call back
  
set my thePath to aPath — store path for use later
  
set my aWebView to missing value
  
set my loadDone to false
  
  
— make a WebView
  
set theView to current application’s WebView’s alloc()’s initWithFrame:{origin:{x:0, y:0}, |size|:{width:100, height:100}}
  
  
— tell it call delegate methods on me
  
theView’s setFrameLoadDelegate:me
  
  
— load the page
  
theView’s setMainFrameURL:thePageURL
  
  
–wait for download & saving
  
repeat timeoutSec * 10 times
    if my loadDone is not equal to false then
      exit repeat
    end if
    
delay 0.1
  end repeat
  
if my loadDone = false then return "timed out"
  
  
  
— the main frame is our interest
  
if (my loadDone) = aWebView’s mainFrame() then
    — get the data and write it to file
    
set theArchiveData to (my loadDone)’s dataSource()’s webArchive()’s |data|()
    
theArchiveData’s writeToFile:thePath atomically:true
    
    
— tell our script it’s all done
    
return "The webarchive was saved"
  end if
end archivePageToPathWithoutSearching

— called when our WebView loads a frame
on WebView:curWebView didFinishLoadForFrame:webFrame
  set my loadDone to webFrame
  
set my aWebView to curWebView
end WebView:didFinishLoadForFrame:

— called when there’s a problem
on WebView:WebView didFailLoadWithError:theError forFrame:webFrame
  — got an error, bail
  
WebView’s stopLoading:me
  
set my loadDone to false
  
error "The webarchive was not saved"
end WebView:didFailLoadWithError:forFrame:

★Click Here to Open This Script 

Posted in file Internet Require Control-Command-R to run | Tagged 10.11savvy 10.12savvy 10.13savvy Safari | 3 Comments

指定URLのページをwebarchive保存 v2

Posted on 2月 11, 2018 by Takaaki Naganoya

指定のURLの内容をデスクトップ上にwebarchive書類として保存するAppleScriptです。

SafariがAppleScript側にwebarchive保存機能を提供していないので、

 (1)GUI Scriptingで無理やりメニューを操作してwebarchive保存
 (2)AppleScriptでCocoaの機能を呼び出してwebarchive保存
 (3)コマンドラインツールを呼び出してwebarchive保存

といった代替策をとる必要があります。本Scriptは(2)を行なったものです。

オリジナルのAppleScriptはShane StanleyがCocoa Scripting普及初期に書いたもので、非同期で処理しておりそのままではAppleScriptのワークフローに組み込むには難がありました(処理結果が正しく実行できたかなど、結果を確実に確認できたほうがよいので)。

そこで、他のワークフローに組み込みやすいように構造を変えてみました。ただ、内部でdelegateによる通知処理を利用しているのでフォアグラウンドでの実行が必須となります(Command-Control-R)。

AppleScript名:指定URLのページをwebarchive保存 v2
— Created 2014-11-13 Shane Stanley
— Modified 2018-02-11 Takaaki Naganoya
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "WebKit"

property theSender : missing value
property thePath : missing value
property theSearchString : missing value
property loadDone : false –original was "webFrame"
property aWebView : missing value

set aPath to (POSIX path of (path to desktop)) & ((current application’s NSUUID’s UUID()’s UUIDString()) as string) & ".webarchive"
set archRes to archivePageToPath("https://www.apple.com/jp/shop/browse/home/specialdeals/mac", aPath, "Mac mini", me, 10) of me

on archivePageToPath(thePageURL, aPath, searchString, sender, timeoutSec)
  –Check If this script runs in foreground
  
if not (current application’s NSThread’s isMainThread()) as boolean then
    display alert "This script must be run from the main thread (Command-Control-R in Script Editor)." buttons {"Cancel"} as critical
    
error number -128
  end if
  
  
set my theSender to sender — store main script so we can call back
  
set my thePath to aPath — store path for use later
  
set my theSearchString to searchString — store for use later
  
set my aWebView to missing value
  
set my loadDone to false
  
  
— make a WebView
  
set theView to current application’s WebView’s alloc()’s initWithFrame:{origin:{x:0, y:0}, |size|:{width:100, height:100}}
  
  
— tell it call delegate methods on me
  
theView’s setFrameLoadDelegate:me
  
  
— load the page
  
theView’s setMainFrameURL:thePageURL
  
  
–wait for download & saving
  
repeat timeoutSec * 10 times
    if my loadDone is not equal to false then
      exit repeat
    end if
    
delay 0.1
  end repeat
  
if my loadDone = false then return "timed out"
  
  
  
— the main frame is our interest
  
if (my loadDone) = aWebView’s mainFrame() then
    
    
— get the text of the page
    
set theText to ((my loadDone)’s DOMDocument()’s documentElement()’s outerText())
    
    
— search it
    
if (theText’s rangeOfString:theSearchString)’s |length|() > 0 then
      
      
— get the data and write it to file
      
set theArchiveData to (my loadDone)’s dataSource()’s webArchive()’s |data|()
      
theArchiveData’s writeToFile:thePath atomically:true
      
      
— tell our script it’s all done
      
return "The webarchive was saved"
    else
      return "Seach string not found"
    end if
  end if
  
end archivePageToPath

— called when our WebView loads a frame
on WebView:curWebView didFinishLoadForFrame:webFrame
  set my loadDone to webFrame
  
set my aWebView to curWebView
end WebView:didFinishLoadForFrame:

— called when there’s a problem
on WebView:WebView didFailLoadWithError:theError forFrame:webFrame
  — got an error, bail
  
WebView’s stopLoading:me
  
set my loadDone to false
  
error "The webarchive was not saved"
end WebView:didFailLoadWithError:forFrame:

★Click Here to Open This Script 

Posted in file Internet Require Control-Command-R to run | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

指定URLをロードしてページ中の画像を取得 v2

Posted on 2月 11, 2018 by Takaaki Naganoya
AppleScript名:指定URLをロードしてページ中の画像を取得 v2
— Created 2015-09-07 by Takaaki Naganoya
— 2015 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "WebKit"

property loadDone : false
property theWebView : missing value

set aURL to "http://piyocast.com/as/archives/1176"
set aRes to getPage(aURL)
set aList to getPageImages() of me
set theWebView to missing value –Purge

aList

–theWebViewにロードしておいたページから画像情報を取得
on getPageImages()
  set aList to {}
  
set imgNum to ((my theWebView)’s stringByEvaluatingJavaScriptFromString:"document.images.length") as integer
  
repeat with i from 0 to (imgNum – 1)
    set jsT to "document.images[" & (i as string) & "].height"
    
set aHeight to ((my theWebView)’s stringByEvaluatingJavaScriptFromString:jsT) as integer
    
    
set jsT to "document.images[" & (i as string) & "].width"
    
set aWidth to ((my theWebView)’s stringByEvaluatingJavaScriptFromString:jsT) as integer
    
    
set jsT to "document.images[" & (i as string) & "].src"
    
set aSRC to ((my theWebView)’s stringByEvaluatingJavaScriptFromString:jsT) as text
    
    
set the end of aList to {aHeight, aWidth, aSRC}
  end repeat
  
return aList
end getPageImages

–theWebViewにロードしておいたページからタイトルを取得
on getPageTitle()
  set x to ((my theWebView)’s stringByEvaluatingJavaScriptFromString:"document.title") as text
  
return x
end getPageTitle

–指定のURLの内容をtheWebViewに取得
on getPage(aURL)
  –Check If this script runs in foreground
  
if not (current application’s NSThread’s isMainThread()) as boolean then
    display alert "This script must be run from the main thread (Command-Control-R in Script Editor)." buttons {"Cancel"} as critical
    
error number -128
  end if
  
  
set my loadDone to false
  
set my theWebView to missing value
  
openURL(aURL)
  
  
set waitLoop to 1000 * 60 –60 seconds
  
  
set hitF to false
  
repeat waitLoop times
    if my loadDone = true then
      set hitF to true
      
exit repeat
    end if
    
current application’s NSThread’s sleepForTimeInterval:("0.001" as real) –delay 0.001
  end repeat
  
if hitF = false then return
  
  
return true
end getPage

–WebViewにURLを読み込む
on openURL(aURL)
  set noter1 to current application’s NSNotificationCenter’s defaultCenter()
  
set my theWebView to current application’s WebView’s alloc()’s init()
  
noter1’s addObserver:me selector:"webLoaded:" |name|:(current application’s WebViewProgressFinishedNotification) object:(my theWebView)
  
my (theWebView’s setMainFrameURL:aURL)
end openURL

–Web Viewのローディング完了時に実行
on webLoaded:aNotification
  set my loadDone to true
end webLoaded:

★Click Here to Open This Script 

Posted in file Internet JavaScript Require Control-Command-R to run | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

ステータスバーのじっけん2

Posted on 2月 8, 2018 by Takaaki Naganoya

AppleScript名:ステータスバーのじっけん2
— Created 2017-03-03 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"

property aStatusItem : missing value

on run
  init() of me
end run

on init()
  set aList to {"Piyomaru", "Software", "", "Takaaki", "Naganoya", "", "Quit"}
  
  
set aStatusItem to current application’s NSStatusBar’s systemStatusBar()’s statusItemWithLength:(current application’s NSVariableStatusItemLength)
  
  
aStatusItem’s setTitle:"🚗"
  
aStatusItem’s setHighlightMode:true
  
aStatusItem’s setMenu:(createMenu(aList) of me)
end init

on createMenu(aList)
  set aMenu to current application’s NSMenu’s alloc()’s init()
  
set aCount to 1
  
  
repeat with i in aList
    set j to contents of i
    
    
if j is not equal to "" then
      
      
if j = "Quit" then
        set aMenuItem to (current application’s NSMenuItem’s alloc()’s initWithTitle:j action:"actionHandler:" keyEquivalent:"")
        
–(aMenuItem’s setKeyEquivalentModifierMask:(current application’s NSControlKeyMask))
      else
        set aMenuItem to (current application’s NSMenuItem’s alloc()’s initWithTitle:j action:"actionHandler:" keyEquivalent:"")
      end if
      
    else
      set aMenuItem to (current application’s NSMenuItem’s separatorItem())
    end if
    (
aMenuItem’s setTarget:me)
    (
aMenuItem’s setTag:aCount)
    (
aMenu’s addItem:aMenuItem)
    
    
if j is not equal to "" then
      set aCount to aCount + 1
    end if
  end repeat
  
  
return aMenu
end createMenu

on actionHandler:sender
  set aTag to tag of sender as integer
  
set aTitle to title of sender as string
  
  
if aTitle is not equal to "Quit" then
    display dialog aTag as string
  else
    current application’s NSStatusBar’s systemStatusBar()’s removeStatusItem:aStatusItem
  end if
end actionHandler:

★Click Here to Open This Script 

Posted in GUI Menu Require Control-Command-R to run | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

指定URLをロードして1枚ものの大きなPNGにレンダリング v2.1

Posted on 2月 8, 2018 by Takaaki Naganoya

指定URLのWebコンテンツをWebViewに読み込んでレンダリングし、1枚ものの大きなPNG画像に保存するAppleScriptです。

資料作成時にWebサイトの内容を利用する場合、こうした1枚ものの大きな画像にレンダリングすることがよくあります(Webサイトのデザインや構成変更の提案時など)。PDFとしてレンダリングする場合が多いですが、サイズ軽減のためにPNGなどの画像でレンダリングすることもあり、その場合のために作成したものです。

ただ、実際に作っておいてナニですが、PDFで保存する場合のほうが多く、PNGでレンダリングするケースはまれです。

# そのままではmacOS 10.13以降の環境で動かなくなっていたので、一部修正しました。ただ、今後のことを考えるとWebViewではなくWkWebViewを使って動作するものがあったほうがよいでしょう

AppleScript名:指定URLをロードして1枚ものの大きなPNGにレンダリング v2a
— Created 2015-09-15 by Takaaki Naganoya
— Modified 2019-11-09 by Takaaki Naganoya
— 2019 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "WebKit"
use framework "Quartz"
use framework "AppKit"

property loadDone : false
property theWebView : missing value
property userAgentName : "Version/9.0 Safari/601.1.56"

set aOutPath to "~/Desktop/outIMG_1.png"
set aURL to "http://www.apple.com/jp/shop/browse/home/specialdeals/mac"
–set aURL to "http://piyocast.com/as"

–Check If this script runs in foreground
if not (current application’s NSThread’s isMainThread()) as boolean then
  display alert "This script must be run from the main thread (Command-Control-R in Script Editor)." buttons {"Cancel"} as critical
  
error number -128
end if

set aPath to current application’s NSString’s stringWithString:aOutPath
set bPath to aPath’s stringByExpandingTildeInPath()

–URL Validation check
set aRes to validateURL(aURL)
if aRes = false then return
set aTitle to getURLandRender(aURL)

–Specify Render to image view (HTML world)
set aTargetView to (my theWebView)’s mainFrame()’s frameView()’s documentView()

–Get Web Contents Size
set targRect to aTargetView’s |bounds|()

–Make Window begin–????? Really Needed ???? Very doubtful
if class of targRect = record then
  set aWidth to width of |size| of targRect
  
set aHeight to height of |size| of targRect
else if class of targRect = list then
  set aWidth to item 1 of item 2 of targRect
  
set aHeight to item 2 of item 2 of targRect
end if

set aWin to current application’s NSWindow’s alloc()’s init()
aWin’s setContentSize:{aWidth + 40, aHeight + 20}
aWin’s setContentView:(my theWebView)
aWin’s setOpaque:false
aWin’s |center|()
–Make Window end

set aData to aTargetView’s dataWithPDFInsideRect:targRect
set aImage to current application’s NSImage’s alloc()’s initWithData:aData

set bData to aImage’s TIFFRepresentation()
set aBitmap to current application’s NSBitmapImageRep’s imageRepWithData:bData

–Write To File
set myNewImageData to (aBitmap’s representationUsingType:(current application’s NSPNGFileType) |properties|:(missing value))
set aRes to (myNewImageData’s writeToFile:bPath atomically:true) as boolean

return aRes

–Download the URL page to WebView and get page title
on getURLandRender(aURL)
  
  
set my loadDone to false
  
set my theWebView to missing value
  
openURL(aURL)
  
  
set waitLoop to 1000 * 60 –60 seconds
  
  
set hitF to false
  
repeat waitLoop times
    if my loadDone = true then
      set hitF to true
      
exit repeat
    end if
    
current application’s NSThread’s sleepForTimeInterval:("0.001" as real) –delay 0.001
  end repeat
  
if hitF = false then return
  
  
set jsText to "document.title"
  
set x to ((my theWebView)’s stringByEvaluatingJavaScriptFromString:jsText) as text
  
  
return x
end getURLandRender

–Down Load URL contents to WebView
on openURL(aURL)
  set noter1 to current application’s NSNotificationCenter’s defaultCenter()
  
set (my theWebView) to current application’s WebView’s alloc()’s init()
  (
my theWebView)’s setApplicationNameForUserAgent:userAgentName
  (
my theWebView)’s setMediaStyle:"screen"
  (
my theWebView)’s setDrawsBackground:true –THIS SEEMS NOT TO WORK
  
–(my theWebView)’s backGroundColor:(current application’s NSColor’s whiteColor())–Mistake
  
–(my theWebView)’s setShouldUpdateWhileOffscreen:true
  
noter1’s addObserver:me selector:"webLoaded:" |name|:(current application’s WebViewProgressFinishedNotification) object:(my theWebView)
  (
my theWebView)’s setMainFrameURL:aURL
end openURL

–Web View’s Event Handler:load finished
on webLoaded:aNotification
  set my loadDone to true
end webLoaded:

–URL Validation Check
on validateURL(anURL as text)
  set regEx1 to current application’s NSString’s stringWithString:"((https|http)://)((\\w|-)+)(([.]|[/])((\\w|-)+))+"
  
set predicate1 to current application’s NSPredicate’s predicateWithFormat_("SELF MATCHES %@", regEx1)
  
set aPredRes1 to (predicate1’s evaluateWithObject:anURL) as boolean
  
return aPredRes1
end validateURL

★Click Here to Open This Script 

Posted in Require Control-Command-R to run | Tagged 10.11savvy 10.12savvy 10.13savvy | 1 Comment

Numbersから緯度経度情報を取得して地図にプロット v3(プログレスバー+セグメント)

Posted on 2月 6, 2018 by Takaaki Naganoya

Numbers書類上に記載した緯度経度情報を取得して、動的に作成したウィンドウの地図上にプロット表示するAppleScriptです。

実行には、「場所名」「緯度」「経度」がワンセットとなったNumbers書類をNumbersでオープンした状態で、本AppleScriptをスクリプトエディタ上でオープンし、Control-Command-Rを実行します。

ひととおり地図上の指定位置へのピンの作成が終わると、普通に地図アプリなどと同様に拡大や縮小、3D表示、マップ表示、航空写真表示などを切り替えてブラウズすることが可能です。

–> Demo Movie

AppleScript名:Numbersから緯度経度情報を取得して地図にプロット v3(プログレスバー+セグメント)
— Created 2017-12-20 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
use framework "AppKit"
use framework "MapKit"
use framework "CoreLocation"
use bPlus : script "BridgePlus" –https://www.macosxautomation.com/applescript/apps/Script_Libs.html#BridgePlus

property NSView : a reference to current application’s NSView
property NSScreen : a reference to current application’s NSScreen
property NSButton : a reference to current application’s NSButton
property SMSForder : a reference to current application’s SMSForder
property NSWindow : a reference to current application’s NSWindow
property MKMapView : a reference to current application’s MKMapView
property MKMapTypeHybrid : a reference to current application’s MKMapTypeHybrid
property MKPointAnnotation : a reference to current application’s MKPointAnnotation
property MKMapTypeSatellite : a reference to current application’s MKMapTypeSatellite
property NSWindowController : a reference to current application’s NSWindowController
property NSTitledWindowMask : a reference to current application’s NSTitledWindowMask
property MKMapTypeStandard : a reference to current application’s MKMapTypeStandard
property NSSegmentedControl : a reference to current application’s NSSegmentedControl
property NSNormalWindowLevel : a reference to current application’s NSNormalWindowLevel
property NSBackingStoreBuffered : a reference to current application’s NSBackingStoreBuffered
property NSSegmentStyleTexturedRounded : a reference to current application’s NSSegmentStyleTexturedRounded

property windisp : false
property selSeg : 0
property aMapView : missing value

–データを取得する
set locList to getDataFromNumbersDoc() of me

set aWidth to 800
set aHeight to 600

set segTitleList to {"Map", "Satellite", "Satellite + Map"}
set tableTitle to retCurNumbersDocsTableName() of me
dispMapView(aWidth, aHeight, tableTitle, "OK", 180, locList, segTitleList) of me

on dispMapView(aWidth as integer, aHeight as integer, aTitle as text, aButtonMSG as text, timeOutSecs as number, locList, segTitleList)
  –Check If this script runs in foreground
  
if not (current application’s NSThread’s isMainThread()) as boolean then
    error "This script must be run from the main thread (Command-Control-R in Script Editor)."
  end if
  
  
set selSeg to 0
  
set (my windisp) to true
  
  
  
  
–NSViewをつくる
  
set aNSView to NSView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aHeight, aWidth))
  
  
aNSView’s setNeedsDisplay:true
  
  
set aWin to makeWinWithView(aNSView, aWidth, aHeight, aTitle, 1.0)
  
  
set wController to NSWindowController’s alloc()
  
wController’s initWithWindow:aWin
  
wController’s showWindow:me
  
aWin’s makeKeyAndOrderFront:me –Windowを表示状態に
  
  
  
–Progress Barをつくる
  
set aPBar to current application’s NSProgressIndicator’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 40, aWidth, 40))
  
aPBar’s setMaxValue:(length of locList)
  
aPBar’s setMinValue:1
  
aPBar’s setIndeterminate:false
  
aPBar’s setControlSize:(current application’s NSProgressIndicatorPreferredLargeThickness)
  
aPBar’s setDoubleValue:(1.0 as real)
  
aNSView’s addSubview:aPBar
  
  
  
–MKMapViewをつくる
  
set aMapView to MKMapView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 40, aWidth, aHeight – 40))
  
aMapView’s setMapType:(current application’s MKMapTypeStandard)
  
  
aMapView’s setZoomEnabled:true
  
aMapView’s setScrollEnabled:true
  
aMapView’s setPitchEnabled:true
  
aMapView’s setRotateEnabled:false
  
aMapView’s setShowsCompass:true
  
aMapView’s setShowsZoomControls:true
  
aMapView’s setShowsScale:true
  
aMapView’s setShowsUserLocation:true
  
aMapView’s setDelegate:me
  
  
  
–MapにPinを追加
  
set aCount to 1
  
repeat with i in locList
    (aPBar’s setDoubleValue:(aCount as real)) –Update Progress Bar
    
    
copy i to {tmpAdr, tmpLat, tmpLong}
    
    
set aLocation to current application’s CLLocationCoordinate2DMake(tmpLat, tmpLong)
    
set anAnnotation to MKPointAnnotation’s alloc()’s init()
    (
anAnnotation’s setCoordinate:aLocation)
    (
anAnnotation’s setTitle:tmpAdr)
    (
aMapView’s addAnnotation:anAnnotation)
    
    
set aCount to aCount + 1
  end repeat
  
  
aPBar’s removeFromSuperview() –Remove Progress Bar
  
  
–Segmented Controlをつくる
  
set aSeg to makeSegmentedControl(segTitleList, aWidth, aHeight) of me
  
aNSView’s addSubview:aSeg
  
  
–MapViewをWindow上に表示  
  
copy middle item of locList to {tmpAdr, tmpLat, tmpLong}
  
set aLocation to current application’s CLLocationCoordinate2DMake(tmpLat, tmpLong)
  
aMapView’s setCenterCoordinate:aLocation zoomLevel:7 animated:false
  
aNSView’s addSubview:aMapView
  
  
–Buttonをつくる
  
set bButton to (NSButton’s alloc()’s initWithFrame:(current application’s NSMakeRect(aWidth – 100, 0, 100, 40)))
  
bButton’s setTitle:aButtonMSG
  
bButton’s setButtonType:(current application’s NSMomentaryLightButton)
  
bButton’s setBezelStyle:(current application’s NSRoundedBezelStyle)
  
bButton’s setKeyEquivalent:(return)
  
bButton’s setTarget:me
  
bButton’s setAction:("clicked:")
  
aNSView’s addSubview:bButton
  
  
aWin’s makeFirstResponder:aMapView
  
  
set aCount to timeOutSecs * 10 –timeout seconds * 10
  
repeat aCount times
    if (my windisp) = false then
      exit repeat
    end if
    
delay 0.1
  end repeat
  
  
my closeWin:aWin
  
end dispMapView

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

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

–close win
on closeWin:aWindow
  repeat with n from 10 to 1 by -1
    (aWindow’s setAlphaValue:n / 10)
    
delay 0.02
  end repeat
  
aWindow’s |close|()
end closeWin:

on makeSegmentedControl(titleList, aWidth, aHeight)
  set aLen to length of titleList
  
  
set aSeg to NSSegmentedControl’s alloc()’s init()
  
aSeg’s setSegmentCount:aLen
  
  
set aCount to 0
  
repeat with i in titleList
    set j to contents of i
    (
aSeg’s setLabel:j forSegment:aCount)
    
set aCount to aCount + 1
  end repeat
  
  
aSeg’s setTranslatesAutoresizingMaskIntoConstraints:false
  
aSeg’s setSegmentStyle:(NSSegmentStyleTexturedRounded)
  
aSeg’s setFrame:(current application’s NSMakeRect(10, 5, 260, 30))
  
aSeg’s setTrackingMode:0
  
aSeg’s setTarget:me
  
aSeg’s setAction:"clickedSeg:"
  
aSeg’s setSelectedSegment:0
  
  
return aSeg
end makeSegmentedControl

–Numbersでオープン中の書類の選択中のシートの表1からデータを取得して2D Listに
on getDataFromNumbersDoc()
  
  
load framework
  
  
tell application "Numbers"
    if (count every document) = 0 then return false
    
    
tell front document
      if (count every sheet) = 0 then return false
      
      
tell active sheet
        tell table 1
          set colCount to column count
          
set rowCount to row count
          
set headerCount to header row count
          
set footerCount to footer row count
          
          
set dList to value of every cell of cell range
        end tell
      end tell
      
    end tell
  end tell
  
  
–Convert 1D List to 2D List
  
set bList to (SMSForder’s subarraysFrom:dList groupedBy:colCount |error|:(missing value)) as list
  
set sItem to 1 + headerCount
  
set eItem to rowCount – footerCount
  
set cList to items sItem thru eItem of bList
  
  
return cList
  
end getDataFromNumbersDoc

on retCurNumbersDocsTableName()
  tell application "Numbers"
    tell front document
      tell active sheet
        tell table 1
          return name
        end tell
      end tell
    end tell
  end tell
end retCurNumbersDocsTableName

on clickedSeg:aSender
  set aSel to aSender’s selectedSegment()
  
set selSeg to (aSel + 1)
  
set mapList to {MKMapTypeStandard, MKMapTypeSatellite, MKMapTypeHybrid}
  
set curMap to contents of item selSeg of mapList
  
aMapView’s setMapType:(curMap)
end clickedSeg:

★Click Here to Open This Script 

Posted in Require Control-Command-R to run | Tagged 10.11savvy 10.12savvy 10.13savvy Numbers | Leave a comment

指定IPアドレスの情報を取得して地図にプロット v3(プログレスバー+セグメント)

Posted on 2月 6, 2018 by Takaaki Naganoya
AppleScript名:指定IPアドレスの情報を取得して地図にプロット v3(プログレスバー+セグメント)
— Created 2017-12-20 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
use framework "AppKit"
use framework "MapKit"
use framework "CoreLocation"
use bPlus : script "BridgePlus" –https://www.macosxautomation.com/applescript/apps/Script_Libs.html#BridgePlus

property |NSURL| : a reference to current application’s |NSURL|
property NSData : a reference to current application’s NSData
property NSView : a reference to current application’s NSView
property NSScreen : a reference to current application’s NSScreen
property NSButton : a reference to current application’s NSButton
property SMSForder : a reference to current application’s SMSForder
property NSWindow : a reference to current application’s NSWindow
property MKMapView : a reference to current application’s MKMapView
property NSURLRequest : a reference to current application’s NSURLRequest
property NSURLConnection : a reference to current application’s NSURLConnection
property MKMapTypeHybrid : a reference to current application’s MKMapTypeHybrid
property MKPointAnnotation : a reference to current application’s MKPointAnnotation
property NSJSONSerialization : a reference to current application’s NSJSONSerialization
property MKMapTypeSatellite : a reference to current application’s MKMapTypeSatellite
property NSWindowController : a reference to current application’s NSWindowController
property NSTitledWindowMask : a reference to current application’s NSTitledWindowMask
property MKMapTypeStandard : a reference to current application’s MKMapTypeStandard
property NSSegmentedControl : a reference to current application’s NSSegmentedControl
property NSNormalWindowLevel : a reference to current application’s NSNormalWindowLevel
property NSBackingStoreBuffered : a reference to current application’s NSBackingStoreBuffered
property NSSegmentStyleTexturedRounded : a reference to current application’s NSSegmentStyleTexturedRounded

property windisp : false
property selSeg : 0
property aMapView : missing value

set nRes to hasInternetConnection() of me
if nRes = false then
  display dialog "No Internet Connection…." buttons {"OK"} default button 1 with icon 0
  
return
end if

set aClip to the clipboard
set anIP to text returned of (display dialog "Input IP address to find its location" default answer aClip)

set windisp to false
set aInfo to getIPAddressInfoFreeGeoIP(anIP) of me

if aInfo = missing value then
  display dialog "Network Error"
  
return
end if

set aLong to (longitude of (aInfo as record)) as real
set aLat to (latitude of (aInfo as record)) as real
set aZip to zip_code of (aInfo as record)
set locList to {{aZip, aLat, aLong}}

set aWidth to 800
set aHeight to 600

set segTitleList to {"Map", "Satellite", "Satellite + Map"}
dispMapView(aWidth, aHeight, aZip, "OK", 180, locList, segTitleList) of me

on dispMapView(aWidth as integer, aHeight as integer, aTitle as text, aButtonMSG as text, timeOutSecs as number, locList, segTitleList)
  –Check If this script runs in foreground
  
if not (current application’s NSThread’s isMainThread()) as boolean then
    error "This script must be run from the main thread (Command-Control-R in Script Editor)."
  end if
  
  
set selSeg to 0
  
set (my windisp) to true
  
  
  
  
–NSViewをつくる
  
set aNSView to NSView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aHeight, aWidth))
  
  
aNSView’s setNeedsDisplay:true
  
  
set aWin to makeWinWithView(aNSView, aWidth, aHeight, aTitle, 1.0)
  
  
set wController to NSWindowController’s alloc()
  
wController’s initWithWindow:aWin
  
wController’s showWindow:me
  
aWin’s makeKeyAndOrderFront:me –Windowを表示状態に
  
  
  
–Progress Barをつくる
  
set aPBar to current application’s NSProgressIndicator’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 40, aWidth, 40))
  
aPBar’s setMaxValue:(length of locList)
  
aPBar’s setMinValue:1
  
aPBar’s setIndeterminate:false
  
aPBar’s setControlSize:(current application’s NSProgressIndicatorPreferredLargeThickness)
  
aPBar’s setDoubleValue:(1.0 as real)
  
aNSView’s addSubview:aPBar
  
  
  
–MKMapViewをつくる
  
set aMapView to MKMapView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 40, aWidth, aHeight – 40))
  
aMapView’s setMapType:(current application’s MKMapTypeStandard)
  
  
aMapView’s setZoomEnabled:true
  
aMapView’s setScrollEnabled:true
  
aMapView’s setPitchEnabled:true
  
aMapView’s setRotateEnabled:false
  
aMapView’s setShowsCompass:true
  
aMapView’s setShowsZoomControls:true
  
aMapView’s setShowsScale:true
  
aMapView’s setShowsUserLocation:true
  
aMapView’s setDelegate:me
  
  
  
–MapにPinを追加
  
set aCount to 1
  
repeat with i in locList
    (aPBar’s setDoubleValue:(aCount as real)) –Update Progress Bar
    
    
copy i to {tmpAdr, tmpLat, tmpLong}
    
    
set aLocation to current application’s CLLocationCoordinate2DMake(tmpLat, tmpLong)
    
set anAnnotation to MKPointAnnotation’s alloc()’s init()
    (
anAnnotation’s setCoordinate:aLocation)
    (
anAnnotation’s setTitle:tmpAdr)
    (
aMapView’s addAnnotation:anAnnotation)
    
    
set aCount to aCount + 1
  end repeat
  
  
aPBar’s removeFromSuperview() –Remove Progress Bar
  
  
–Segmented Controlをつくる
  
set aSeg to makeSegmentedControl(segTitleList, aWidth, aHeight) of me
  
aNSView’s addSubview:aSeg
  
  
–MapViewをWindow上に表示  
  
copy middle item of locList to {tmpAdr, tmpLat, tmpLong}
  
set aLocation to current application’s CLLocationCoordinate2DMake(tmpLat, tmpLong)
  
aMapView’s setCenterCoordinate:aLocation zoomLevel:7 animated:false
  
aNSView’s addSubview:aMapView
  
  
–Buttonをつくる
  
set bButton to (NSButton’s alloc()’s initWithFrame:(current application’s NSMakeRect(aWidth – 100, 0, 100, 40)))
  
bButton’s setTitle:aButtonMSG
  
bButton’s setButtonType:(current application’s NSMomentaryLightButton)
  
bButton’s setBezelStyle:(current application’s NSRoundedBezelStyle)
  
bButton’s setKeyEquivalent:(return)
  
bButton’s setTarget:me
  
bButton’s setAction:("clicked:")
  
aNSView’s addSubview:bButton
  
  
aWin’s makeFirstResponder:aMapView
  
  
set aCount to timeOutSecs * 10 –timeout seconds * 10
  
repeat aCount times
    if (my windisp) = false then
      exit repeat
    end if
    
delay 0.1
  end repeat
  
  
my closeWin:aWin
  
end dispMapView

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

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

–close win
on closeWin:aWindow
  repeat with n from 10 to 1 by -1
    (aWindow’s setAlphaValue:n / 10)
    
delay 0.02
  end repeat
  
aWindow’s |close|()
end closeWin:

on makeSegmentedControl(titleList, aWidth, aHeight)
  set aLen to length of titleList
  
  
set aSeg to NSSegmentedControl’s alloc()’s init()
  
aSeg’s setSegmentCount:aLen
  
  
set aCount to 0
  
repeat with i in titleList
    set j to contents of i
    (
aSeg’s setLabel:j forSegment:aCount)
    
set aCount to aCount + 1
  end repeat
  
  
aSeg’s setTranslatesAutoresizingMaskIntoConstraints:false
  
aSeg’s setSegmentStyle:(NSSegmentStyleTexturedRounded)
  
aSeg’s setFrame:(current application’s NSMakeRect(10, 5, 260, 30))
  
aSeg’s setTrackingMode:0
  
aSeg’s setTarget:me
  
aSeg’s setAction:"clickedSeg:"
  
aSeg’s setSelectedSegment:0
  
  
return aSeg
end makeSegmentedControl

on clickedSeg:aSender
  set aSel to aSender’s selectedSegment()
  
set selSeg to (aSel + 1)
  
set mapList to {MKMapTypeStandard, MKMapTypeSatellite, MKMapTypeHybrid}
  
set curMap to contents of item selSeg of mapList
  
aMapView’s setMapType:(curMap)
end clickedSeg:

–http://freegeoip.net
on getIPAddressInfoFreeGeoIP(IPAddress)
  try
    with timeout of 10 seconds
      set link to "http://freegeoip.net/json/" & IPAddress
      
set theURL to |NSURL|’s URLWithString:link
      
set jsonData to NSData’s dataWithContentsOfURL:theURL
      
set aJsonDict to (NSJSONSerialization’s JSONObjectWithData:jsonData options:0 |error|:(missing value))
      
return aJsonDict
    end timeout
  on error
    return missing value
  end try
end getIPAddressInfoFreeGeoIP

–Internet Connection Check
on hasInternetConnection()
  set aURL to |NSURL|’s alloc()’s initWithString:"http://www.google.com"
  
set aReq to NSURLRequest’s alloc()’s initWithURL:aURL cachePolicy:(current application’s NSURLRequestReloadIgnoringLocalCacheData) timeoutInterval:5.0
  
set urlRes to (NSURLConnection’s sendSynchronousRequest:aReq returningResponse:(missing value) |error|:(missing value))
  
if urlRes = missing value then
    return false
  else
    return true
  end if
end hasInternetConnection

★Click Here to Open This Script 

Posted in Require Control-Command-R to run | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

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

Google Search

Popular posts

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

Tags

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

カテゴリー

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

アーカイブ

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

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

メタ情報

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

Forum Posts

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

メタ情報

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