Menu

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

AppleScriptの穴

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

タグ: 10.13savvy

Numbers上のデータにもとづいてセル上で色プレビュー

Posted on 2月 25, 2018 by Takaaki Naganoya

–> Demo Movie

AppleScript名:Numbers上のデータにもとづいてセル上で色プレビュー

tell application "Numbers"
  tell front document
    tell active sheet
      tell table 1
        set hCount to header row count
        
set fCount to footer row count
        
        
set aRange to address of row of cell range
        
set bRange to items (1 + hCount) thru ((length of aRange) – fCount) of aRange
        
–> {2, 3, 4, 5, 6}
        
        
repeat with i in bRange
          tell row i
            set vList to value of cells 1 thru 3
            
if vList does not contain missing value then
              set bList to chengeColor255to65535(vList) of me
              
              
ignoring application responses
                tell cell 4
                  set background color to bList
                end tell
              end ignoring
              
            end if
          end tell
        end repeat
      end tell
    end tell
  end tell
end tell

on chengeColor255to65535(aColList)
  set aTmpList to {}
  
repeat with i in aColList
    set the end of aTmpList to i * 256
  end repeat
  
return aTmpList
end chengeColor255to65535

★Click Here to Open This Script 

Posted in Color | Tagged 10.11savvy 10.12savvy 10.13savvy Numbers | Leave a comment

エンコーダーの情報を取得する

Posted on 2月 25, 2018 by Takaaki Naganoya
AppleScript名:エンコーダーの情報を取得する
tell application "iTunes"
  set anEncoder to current encoder
  
set aProp to properties of anEncoder
  
–> {class:encoder, id:63, index:1, name:"AAC Encoder"}
  
  
set encList to every encoder
  
–> {encoder id 63 of application "iTunes", encoder id 60 of application "iTunes", encoder id 61 of application "iTunes", encoder id 62 of application "iTunes", encoder id 59 of application "iTunes"}
  
  
set encnameList to name of every encoder
  
–> {"AAC Encoder", "AIFF Encoder", "Lossless Encoder", "MP3 Encoder", "WAV Encoder"}
  
  
set encPropList to properties of every encoder
  
–> {{class:encoder, id:63, index:1, name:"AAC Encoder"}, {class:encoder, id:60, index:2, name:"AIFF Encoder"}, {class:encoder, id:61, index:3, name:"Lossless Encoder"}, {class:encoder, id:62, index:5, name:"MP3 Encoder"}, {class:encoder, id:59, index:6, name:"WAV Encoder"}}
  
end tell

★Click Here to Open This Script 

iTunes Control

Posted in System | Tagged 10.11savvy 10.12savvy 10.13savvy iTunes | Leave a comment

iTunesライブラリの場所を取得

Posted on 2月 25, 2018 by Takaaki Naganoya
AppleScript名:iTunesライブラリの場所を取得
— Created 2017-01-07 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "iTunesLibrary"

set library to current application’s ITLibrary’s libraryWithAPIVersion:"1.0" |error|:(missing value)
if library is equal to missing value then return

set iTunesLibraryLocURL to (library’s musicFolderLocation)’s absoluteString() as string
–>  "file:///Users/me/Music/iTunes/iTunes%20Music/"

set iTunesLibraryLocAlias to (library’s musicFolderLocation) as alias
–>  alias "Cherry:Users:me:Music:iTunes:iTunes Music:"

set iTunesLibraryLocPOSIX to (library’s musicFolderLocation)’s |path|() as string
–>  "/Users/me/Music/iTunes/iTunes Music"

★Click Here to Open This Script 

iTunes Control

Posted in file | Tagged 10.11savvy 10.12savvy 10.13savvy ITLibrary iTunes | Leave a comment

iTunesライブラリの曲のアーティスト名を集計

Posted on 2月 25, 2018 by Takaaki Naganoya

iTunesライブラリ中の曲のアーティスト名を集計して、曲数が多い順に集計するAppleScriptです。

アーティスト名のFirst NameとLast Nameの間にスペースが存在している場合としていない場合が(iTunes Music Storeからダウンロード購入した曲でも)混在していたので、こうしたデータのゆらぎに対処しています。

6,827曲のライブラリの集計が、筆者の開発環境(MacBook Pro Retina 2012 Core i7 2.66GHz)で2.7秒ぐらいです。

AppleScript名:iTunesライブラリの曲のアーティスト名を集計
— Created 2017-01-07 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "iTunesLibrary"

set library to current application’s ITLibrary’s libraryWithAPIVersion:"1.0" |error|:(missing value)
if library is equal to missing value then return

set allTracks to library’s allMediaItems()
set allCount to allTracks’s |count|()

set anEnu to allTracks’s objectEnumerator()
set newArray to current application’s NSMutableArray’s alloc()’s init()

repeat
  set aPL to anEnu’s nextObject()
  
if aPL = missing value then exit repeat
  
try
    set aKind to (aPL’s mediaKind) as integer
    
    
if (aKind as integer) is equal to 2 then –Music, Song
      set plName to aPL’s artist’s |name| as string
      
set pl2Name to (my changeThis:" " toThat:"" inString:plName) –日本語アーティスト名で姓と名の間にスペースが入っているものがある(表記ゆらぎ)ので対策
      
newArray’s addObject:(pl2Name)
    end if
  on error
    set aLoc to (aPL’s location’s |path|()) as string
    
–log aLoc
  end try
end repeat

set aRes to countItemsByItsAppearance(newArray) of me
–>  {​​​​​{​​​​​​​theName:"浜田省吾", ​​​​​​​numberOfTimes:442​​​​​}, ​​​​​{​​​​​​​theName:"B’z", ​​​​​​​numberOfTimes:379​​​​​}, ​​​​​{​​​​​​​theName:"渡辺岳夫・松山祐士", ​​​​​​​numberOfTimes:199​​​​​}, ​​​​​{​​​​​​​theName:"VariousArtists", ​​​​​​​numberOfTimes:192​​​​​}, ​​​​​{​​​​​​​theName:"菅野よう子", ​​​​​​​numberOfTimes:108​​​​​}, ​​​​​{​​​​​​​theName:"布袋寅泰", ​​​​​​​numberOfTimes:100​​​​​}, ​​​​​{​​​​​​​theName:"三枝成彰", ​​​​​​​numberOfTimes:95​​​​​}, ​​​​​{​​​​​​​theName:"宇多田ヒカル", ​​​​​​​numberOfTimes:94​​​​​}, ​​​​​{​​​​​​​theName:"宮川泰", ​​​​​​​numberOfTimes:81​​​​​}, ​​​​​{​​​​​​​theName:"MichaelJackson", ​​​​​​​numberOfTimes:78​​​​​}, ​​​​​{​​​​​​​theName:"稲葉浩志", ​​​​​​​numberOfTimes:73​​​​​}, ​​​​​…

–出現回数で集計
on countItemsByItsAppearance(aList)
  set aSet to current application’s NSCountedSet’s alloc()’s initWithArray:aList
  
set bArray to current application’s NSMutableArray’s array()
  
set theEnumerator to aSet’s objectEnumerator()
  
  
repeat
    set aValue to theEnumerator’s nextObject()
    
if aValue is missing value then exit repeat
    
bArray’s addObject:(current application’s NSDictionary’s dictionaryWithObjects:{aValue, (aSet’s countForObject:aValue)} forKeys:{"theName", "numberOfTimes"})
  end repeat
  
  
–出現回数(numberOfTimes)で降順ソート
  
set theDesc to current application’s NSSortDescriptor’s sortDescriptorWithKey:"numberOfTimes" ascending:false
  
bArray’s sortUsingDescriptors:{theDesc}
  
  
return bArray as list
end countItemsByItsAppearance

on changeThis:findString toThat:repString inString:someText
  set theString to current application’s NSString’s stringWithString:someText
  
set theString to theString’s stringByReplacingOccurrencesOfString:findString withString:repString options:(current application’s NSRegularExpressionSearch) range:{location:0, |length|:length of someText}
  
return theString as text
end changeThis:toThat:inString:

★Click Here to Open This Script 

iTunes Control

Posted in list Record | Tagged 10.11savvy 10.12savvy 10.13savvy ITLibrary iTunes | Leave a comment

なろう小説APIで各カテゴリごとの集計を実行(大カテゴリのみ)

Posted on 2月 24, 2018 by Takaaki Naganoya

–> GZIP.framework

AppleScript名:なろう小説APIで各カテゴリごとの集計を実行(大カテゴリのみ)
— Created 2017-10-10 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "GZIP"
–https://github.com/nicklockwood/GZIP
–http://dev.syosetu.com/man/api/
–1日の利用上限は80,000または転送量上限400MByte???

property |NSURL| : a reference to current application’s |NSURL|
property NSString : a reference to current application’s NSString
property NSArray : a reference to current application’s NSArray
property NSUTF8StringEncoding : a reference to current application’s NSUTF8StringEncoding
property NSMutableDictionary : a reference to current application’s NSMutableDictionary
property NSURLQueryItem : a reference to current application’s NSURLQueryItem
property NSURLComponents : a reference to current application’s NSURLComponents
property NSJSONSerialization : a reference to current application’s NSJSONSerialization
property NSMutableURLRequest : a reference to current application’s NSMutableURLRequest
property NSURLConnection : a reference to current application’s NSURLConnection
property NSSortDescriptor : a reference to current application’s NSSortDescriptor
property NSNumber : a reference to current application’s NSNumber
property NSNumberFormatter : a reference to current application’s NSNumberFormatter
property NSNumberFormatterRoundUp : a reference to current application’s NSNumberFormatterRoundUp
property NSNumberFormatterRoundDown : a reference to current application’s NSNumberFormatterRoundDown

set invList to {}

set bgList to {1, 2, 3, 4, 99, 98}
set bigGnereLabel to {"恋愛", "ファンタジー", "文芸", "SF", "その他", "ノンジャンル"}

–全体の件数取得
set aRec to {gzip:"5", out:"json", lim:"1"}
set aRESTres to callNarouAPI(aRec, "1", "1") of me
set wholeCount to (allCount of first item of aRESTres)

–カテゴリごとの集計
repeat with i in bgList
  –repeat with ii in gList
  
set aRec to {gzip:"5", biggenre:i as string, out:"json", lim:"1"}
  
set aRESTres to callNarouAPI(aRec, "1", "1") of me
  
set aTotal to allCount of first item of aRESTres
  
  
if aTotal is not equal to 0 then
    set big to contents of i
    
set bigLabel to getLabelFromNum(bgList, bigGnereLabel, big) of me
    
set aPerCentatge to roundingDownNumStr(((aTotal / wholeCount) * 100), 1) of me
    
set the end of invList to {biggenre:bigLabel, totalNum:aTotal, percentage:aPerCentatge}
  end if
  
–end repeat
end repeat

set bList to sortRecListByLabel(invList, "totalNum", false) of me –降順ソート
–>  {​​​​​{​​​​​​​totalNum:274075, ​​​​​​​percentage:53.1, ​​​​​​​biggenre:"ノンジャンル"​​​​​}, ​​​​​{​​​​​​​totalNum:68890, ​​​​​​​percentage:13.3, ​​​​​​​biggenre:"文芸"​​​​​}, ​​​​​{​​​​​​​totalNum:68426, ​​​​​​​percentage:13.2, ​​​​​​​biggenre:"ファンタジー"​​​​​}, ​​​​​{​​​​​​​totalNum:46165, ​​​​​​​percentage:8.9, ​​​​​​​biggenre:"その他"​​​​​}, ​​​​​{​​​​​​​totalNum:45965, ​​​​​​​percentage:8.9, ​​​​​​​biggenre:"恋愛"​​​​​}, ​​​​​{​​​​​​​totalNum:11733, ​​​​​​​percentage:2.2, ​​​​​​​biggenre:"SF"​​​​​}​​​}

on callNarouAPI(aRec, callFrom, callNum)
  set reqURLStr to "http://api.syosetu.com/novelapi/api/" –通常API
  
  
–set aRec to {gzip:"5", |st|:callFrom as string, out:"json", lim:callNum as string}
  
set aURL to retURLwithParams(reqURLStr, aRec) of me
  
set aRes to callRestGETAPIAndParseResults(aURL) of me
  
  
set aRESCode to (responseCode of aRes) as integer
  
if aRESCode is not equal to 200 then return false
  
  
set aRESHeader to responseHeader of aRes
  
set aRESTres to (json of aRes) as list
  
end callNarouAPI

–GET methodのREST APIを呼ぶ
on callRestGETAPIAndParseResults(aURL)
  set aRequest to NSMutableURLRequest’s requestWithURL:(|NSURL|’s URLWithString:aURL)
  
aRequest’s setHTTPMethod:"GET"
  
aRequest’s setValue:"gzip" forHTTPHeaderField:"Content-Encoding"
  
  
set aRes to NSURLConnection’s sendSynchronousRequest:aRequest returningResponse:(reference) |error|:(missing value)
  
set resList to aRes as list
  
  
set bRes to contents of (first item of resList)
  
  
set rRes to bRes’s gunzippedData() –From GZIP.framework
  
  
set resStr to NSString’s alloc()’s initWithData:rRes encoding:(NSUTF8StringEncoding)
  
  
set jsonString to NSString’s stringWithString:resStr
  
set jsonData to jsonString’s dataUsingEncoding:(NSUTF8StringEncoding)
  
set aJsonDict to NSJSONSerialization’s JSONObjectWithData:jsonData options:0 |error|:(missing value)
  
  
–Get Response Code & Header
  
set dRes to contents of second item of resList
  
if dRes is not equal to missing value then
    set resCode to (dRes’s statusCode()) as number
    
set resHeaders to (dRes’s allHeaderFields()) as record
  else
    set resCode to 0
    
set resHeaders to {}
  end if
  
  
return {json:aJsonDict, responseCode:resCode, responseHeader:resHeaders}
end callRestGETAPIAndParseResults

on retURLwithParams(aBaseURL, aRec)
  set aDic to NSMutableDictionary’s dictionaryWithDictionary:aRec
  
  
set aKeyList to (aDic’s allKeys()) as list
  
set aValList to (aDic’s allValues()) as list
  
set aLen to length of aKeyList
  
  
set qList to {}
  
repeat with i from 1 to aLen
    set aName to contents of item i of aKeyList
    
set aVal to contents of item i of aValList
    
set the end of qList to (NSURLQueryItem’s queryItemWithName:aName value:aVal)
  end repeat
  
  
set aComp to NSURLComponents’s alloc()’s initWithString:aBaseURL
  
aComp’s setQueryItems:qList
  
set aURL to (aComp’s |URL|()’s absoluteString()) as text
  
  
return aURL
end retURLwithParams

–リストに入れたレコードを、指定の属性ラベルの値でソート
on sortRecListByLabel(aRecList as list, aLabelStr as string, ascendF as boolean)
  set aArray to NSArray’s arrayWithArray:aRecList
  
  
set sortDesc to NSSortDescriptor’s alloc()’s initWithKey:aLabelStr ascending:ascendF
  
set sortDescArray to NSArray’s arrayWithObjects:sortDesc
  
set sortedArray to aArray’s sortedArrayUsingDescriptors:sortDescArray
  
  
set bList to sortedArray as list
  
return bList
end sortRecListByLabel

on getLabelFromNum(aList, labelLIst, aNum)
  set aInd to offsetOf(aList, aNum) of me
  
set anItem to contents of item aInd of labelLIst
  
return anItem
end getLabelFromNum

on offsetOf(aList as list, aTarg)
  set aArray to current application’s NSArray’s arrayWithArray:aList
  
set aIndex to aArray’s indexOfObjectIdenticalTo:aTarg
  
return (aIndex + 1)
end offsetOf

on roundingDownNumStr(aNum as string, aDigit as integer)
  set a to NSString’s stringWithString:aNum
  
set aa to a’s doubleValue()
  
set aFormatter to NSNumberFormatter’s alloc()’s init()
  
aFormatter’s setMaximumFractionDigits:aDigit
  
aFormatter’s setRoundingMode:(NSNumberFormatterRoundDown)
  
set aStr to aFormatter’s stringFromNumber:aa
  
return (aStr as text) as real
end roundingDownNumStr

on roundingUpNumStr(aNum as string, aDigit as integer)
  set a to NSString’s stringWithString:aNum
  
set aa to a’s doubleValue()
  
set aFormatter to NSNumberFormatter’s alloc()’s init()
  
aFormatter’s setMaximumFractionDigits:aDigit
  
aFormatter’s setRoundingMode:(NSNumberFormatterRoundUp)
  
set aStr to aFormatter’s stringFromNumber:aa
  
return (aStr as text) as real
end roundingUpNumStr

★Click Here to Open This Script 

Posted in Network REST API | Tagged 10.11savvy 10.12savvy 10.13savvy | 1 Comment

日の出、日没時刻を計算するv2

Posted on 2月 24, 2018 by Takaaki Naganoya

EDSunriseSetを用いて、指定の位置における日の出、日没時間を計算するAppleScriptです。

–> EDSunriseSet.framework(~/Library/Frameworks)

AppleScript名:日の出、日没時刻を計算するv2
— Created 2017-06-19 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "EDSunriseSet" –https://github.com/erndev/EDSunriseSet

set cityRecList to {{kCityName:"Tokyo", kCityLatitude:(35.6894875), kCityLongitude:(139.6917064), kCityTimeZone:"Asia/Tokyo"}}

set dList to {}

repeat with i in cityRecList
  set the end of dList to getSunriseSunset(i) of me
end repeat
return dList
–>  {​​​​​{​​​​​​​sunrise:date "2017年6月21日水曜日 4:25:37", ​​​​​​​sunset:date "2017年6月21日水曜日 19:00:21", ​​​​​​​civilTwilightStart:date "2017年6月21日水曜日 3:55:35", ​​​​​​​civilTwilightEnd:date "2017年6月21日水曜日 19:30:23", ​​​​​​​nauticalTwilightStart:date "2017年6月21日水曜日 3:18:15", ​​​​​​​nauticalTwilightEnd:date "2017年6月21日水曜日 20:07:44", ​​​​​​​astronomicalTwilightStart:date "2017年6月21日水曜日 2:36:45", ​​​​​​​astronomicalTwilightEnd:date "2017年6月21日水曜日 20:49:13", ​​​​​​​cityname:"Tokyo"​​​​​}​​​}

on getSunriseSunset(cityRec)
  set curLocale to current application’s NSLocale’s currentLocale()
  
set curDate to current application’s NSDate’s |date|()
  
  
set aTZ to current application’s NSTimeZone’s alloc()’s initWithName:(kCityName of cityRec)
  
set aSunrizeSunset to current application’s EDSunriseSet’s alloc()’s initWithDate:curDate timezone:aTZ latitude:(kCityLatitude of cityRec) longitude:(kCityLongitude of cityRec)
  
  
–日の出、日没  
  
set aSunRiseDate to (aSunrizeSunset’s sunrise) as date
  
set aSunSetDate to (aSunrizeSunset’s sunset) as date
  
  
–https://en.wikipedia.org/wiki/Twilight
  
–https://ja.wikipedia.org/wiki/薄明
  
  
–市民薄明(常用薄明、第三薄明)
  
set aCivilTwilightStart to (aSunrizeSunset’s civilTwilightStart) as date
  
set aCivilTwilightEnd to (aSunrizeSunset’s civilTwilightEnd) as date
  
  
–航海薄明(第二薄明)
  
set aNauticalTwilightStart to (aSunrizeSunset’s nauticalTwilightStart) as date
  
set aNauticalTwilightEnd to (aSunrizeSunset’s nauticalTwilightEnd) as date
  
  
–天文薄明(第一薄明)
  
set anAstronomicalTwilightStart to (aSunrizeSunset’s astronomicalTwilightStart) as date
  
set anAstronomicalTwilightEnd to (aSunrizeSunset’s astronomicalTwilightEnd) as date
  
  
return {sunrise:aSunRiseDate, sunset:aSunSetDate, civilTwilightStart:aCivilTwilightStart, civilTwilightEnd:aCivilTwilightEnd, nauticalTwilightStart:aNauticalTwilightStart, nauticalTwilightEnd:aNauticalTwilightEnd, astronomicalTwilightStart:anAstronomicalTwilightStart, astronomicalTwilightEnd:anAstronomicalTwilightEnd, cityname:kCityName of cityRec}
end getSunriseSunset

★Click Here to Open This Script 

Posted in Calendar | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

2つの日付の期間を日本語表記でていねいに返す

Posted on 2月 24, 2018 by Takaaki Naganoya
AppleScript名:2つの日付の期間を日本語表記でていねいに返す
— Created 2016-01-17 by Takaaki Naganoya
— 2016 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

–Date Difference
set sDate to "2016/1/15" –Japanese Date format "YYYY/MM/DD"
set eDate to "2016/1/20" –Japanese Date format "YYYY/MM/DD"
set aDiffStr to retDateDiffStr(sDate, eDate, "/", "/", "", "〜") of me
–> "2016/1/15〜20"

–Month Difference
set sDate to "2016/1/15" –Japanese Date format "YYYY/MM/DD"
set eDate to "2016/2/20" –Japanese Date format "YYYY/MM/DD"
set bDiffStr to retDateDiffStr(sDate, eDate, "年", "月", "日", "〜") of me
–> "2016年1月15日〜2月20日"

–Year Difference
set sDate to "2015/12/15" –Japanese Date format "YYYY/MM/DD"
set eDate to "2016/1/20" –Japanese Date format "YYYY/MM/DD"
set bDiffStr to retDateDiffStr(sDate, eDate, "年", "月", "日", "〜") of me
–> "2015年12月15日〜2016年1月20日"

–2つの日付の期間を日本語表記でていねいに返す
on retDateDiffStr(sDate, eDate, ySeparator, mSeparator, dSeparator, diffSeparator)
  
  
set sDateO to date sDate
  
set eDateO to date eDate
  
  
set diffY to (year of eDateO) – (year of sDateO)
  
set diffM to (month of eDateO) – (month of sDateO)
  
set diffD to (day of eDateO) – (day of sDateO)
  
  
set sYstr to (year of sDateO) as string
  
set sMstr to (month of sDateO as number) as string
  
set sDstr to (day of sDateO) as string
  
  
set eYstr to (year of eDateO) as string
  
set eMstr to (month of eDateO as number) as string
  
set eDstr to (day of eDateO) as string
  
  
if diffY > 0 then
    –Year Difference
    
set outStr to sYstr & ySeparator & sMstr & mSeparator & sDstr & dSeparator & diffSeparator & eYstr & ySeparator & eMstr & mSeparator & eDstr & dSeparator
  else if diffM > 0 then
    –Month Difference
    
set outStr to sYstr & ySeparator & sMstr & mSeparator & sDstr & dSeparator & diffSeparator & eMstr & mSeparator & eDstr & dSeparator
  else if diffD > 0 then
    –Date Difference
    
set outStr to sYstr & ySeparator & sMstr & mSeparator & sDstr & diffSeparator & eDstr & dSeparator
  end if
  
  
return outStr
  
end retDateDiffStr

★Click Here to Open This Script 

Posted in Calendar | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

getMlenInternational_ASOC

Posted on 2月 24, 2018 by Takaaki Naganoya

年と月を数値で指定した対象月の日数を計算するAppleScriptです。国際化対応バージョンです。

AppleScriptで日付(date)関連の処理を行うと、どうしても言語依存してしまいがちです。

つまり、日本語環境で作ったAppleScriptをその他の言語環境に持って行ったときに、あるいは逆に英語圏で作られたAppleScriptでまっさきに書き換える必要が出てくるのが、日付関連処理です(その次ぐらいにApple純正アプリケーションの「過剰ローカライズ」によりAppleScriptのオブジェクト名までローカライズされてしまうので、その点を書き換えるとか)。

日本語環境以外で通じる処理を書くというのは、けっこう練習が必要です。ただ、国際化対応の処理をいったん書いておけば、二度目からはその処理を使い回すだけです。

そんな、言語環境非依存で真っ先に必要になってくる、指定月の日数計算を書いたものです。少なくとも、Mac App Storeに出すアプリケーションを書くのであれば、こうした他の言語環境でも動作するルーチンを整備しておく必要があります。

AppleScript名:getMlenInternational_ASOC
— Created 2015-02-02 by Shane Stanley
— Modified 2015-02-02 by Takaaki Naganoya
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set mList to {}
repeat with m from 1 to 12
  set the end of mList to getMlenInternational(2012, m) of me –2012 is a Leap Year–2012年はうるう年
end repeat
mList
–>  {​​​​​31, ​​​​​29, ​​​​​31, ​​​​​30, ​​​​​31, ​​​​​30, ​​​​​31, ​​​​​31, ​​​​​30, ​​​​​31, ​​​​​30, ​​​​​31​​​}

–現在のカレンダーで指定年月の日数を返す
on getMlenInternational(aYear, aMonth)
  –From Shane’s getMlenInternational(ASOC) v1
  
set theNSCalendar to current application’s NSCalendar’s currentCalendar() — do *not* use initWithCalendarIdentifier:
  
set theDate to theNSCalendar’s dateWithEra:1 |year|:aYear |month|:aMonth |day|:1 hour:0 minute:0 |second|:0 nanosecond:0
  
set theResult to theNSCalendar’s rangeOfUnit:(current application’s NSDayCalendarUnit) inUnit:(current application’s NSMonthCalendarUnit) forDate:theDate
  
–>  {location:1, length:31}
  
return |length| of theResult
end getMlenInternational

★Click Here to Open This Script 

Posted in Calendar | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

数値の秒を文字フォーマットして返す

Posted on 2月 24, 2018 by Takaaki Naganoya
AppleScript名:数値の秒を文字フォーマットして返す
— Created 2016-02-09 by Takaaki Naganoya
— 2016 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set aStr to formatTimeNum(61) of me
–> "01分 01秒"

set bStr to formatTimeNum(3700) of me
–> "01時間 01分 40秒"

set cStr to formatTimeNum(9100) of me
–> "02時間 31分 40秒"

set dStr to formatTimeNum(720001) of me
–>"200時間 00分 01秒"

set eStr to formatTimeNum(7200001) of me
–>"2000時間 00分 01秒"

–数値の秒を文字フォーマットして返す
on formatTimeNum(a)
  set hourStr to "時間 "
  
set minuteStr to "分 "
  
set secStr to "秒"
  
  
set aRec to separateSec(a) of me
  
set aStr to ""
  
set anHour to hourNum of aRec
  
set aMinute to minuteNum of aRec
  
set aSec to secondNum of aRec
  
  
if anHour > 0 then
    set aStr to aStr & retZeroPaddingText(anHour, 2) of me & hourStr
    
set aStr to aStr & retZeroPaddingText(aMinute, 2) of me & minuteStr
  else if aMinute > 0 then
    set aStr to aStr & retZeroPaddingText(aMinute, 2) of me & minuteStr
  end if
  
set aStr to aStr & retZeroPaddingText(aSec, 2) of me & secStr
  
  
return aStr
end formatTimeNum

—数値の秒を時、分、秒に分解する
on separateSec(a)
  set anHour to a div 3600
  
set b to a – (anHour * 3600)
  
set aMinute to b div 60
  
set c to b – (aMinute * 60)
  
return {hourNum:anHour, minuteNum:aMinute, secondNum:c}
end separateSec

–ゼロパディング
on retZeroPaddingText(aNum as integer, aDigitNum as integer)
  if aNum > (((10 ^ aDigitNum) as integer) – 1) then
    return aNum as string –指定桁数を数値データがオーバーしたら数値を文字化してそのまま返す
  end if
  
set aFormatter to current application’s NSNumberFormatter’s alloc()’s init()
  
aFormatter’s setUsesGroupingSeparator:false
  
aFormatter’s setAllowsFloats:false
  
aFormatter’s setMaximumIntegerDigits:aDigitNum
  
aFormatter’s setMinimumIntegerDigits:aDigitNum
  
aFormatter’s setPaddingCharacter:"0"
  
set aStr to aFormatter’s stringFromNumber:(current application’s NSNumber’s numberWithFloat:aNum)
  
return aStr as string
end retZeroPaddingText

★Click Here to Open This Script 

Posted in Calendar | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

午前午後のローカライズ名称を返す

Posted on 2月 24, 2018 by Takaaki Naganoya
AppleScript名:午前午後のローカライズ名称を返す
— Created 2017-12-19 01:14:42 +0900 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set bList to getLocalizedAMSymbol("ja_JP") of me
–>  "午前"

set bList to getLocalizedPMSymbol("ja_JP") of me
–>  "午後"

–ローカライズされた午前の名称を返す
on getLocalizedAMSymbol(aLoc)
  set df to current application’s NSDateFormatter’s alloc()’s init()
  
df’s setLocale:(current application’s NSLocale’s localeWithLocaleIdentifier:aLoc)
  
set dayNames to df’s AMSymbol()
  
return dayNames as string
end getLocalizedAMSymbol

–ローカライズされた午後の名称を返す
on getLocalizedPMSymbol(aLoc)
  set df to current application’s NSDateFormatter’s alloc()’s init()
  
df’s setLocale:(current application’s NSLocale’s localeWithLocaleIdentifier:aLoc)
  
set dayNames to df’s PMSymbol()
  
return dayNames as string
end getLocalizedPMSymbol

★Click Here to Open This Script 

Posted in Calendar | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

元号変換v31

Posted on 2月 24, 2018 by Takaaki Naganoya
AppleScript名:元号変換v31
set a to "2010/7/21"
set a to parseDate(a) of me
set {aGengoStr, aGengoNum} to retJapaneseGengo(a) of me
–> {"平成", 22}

on retJapaneseGengo(aDate)
  
  
set aYear to year of aDate
  
set aMonth to month of aDate as number
  
set aDay to day of aDate
  
  
set aStr to retZeroPaddingText(aYear, 4) of me & retZeroPaddingText(aMonth, 2) of me & retZeroPaddingText(aDay, 2) of me
  
  
set aGengo to ""
  
if aStr ≥ "19890108" then
    set aGengo to "平成"
    
set aGengoNum to aYear – 1989 + 1
  else if aStr ≥ "19261225" then
    set aGengo to "昭和"
    
set aGengoNum to aYear – 1926 + 1
  else if aStr ≥ "19120730" then
    set aGengo to "大正"
    
set aGengoNum to aYear – 1912 + 1
  else if aStr ≥ "18680125" then
    set aGengo to "明治"
    
set aGengoNum to aYear – 1868 + 1
  end if
  
  
return {aGengo, aGengoNum}
  
end retJapaneseGengo

–数値にゼロパディングしたテキストを返す
on retZeroPaddingText(aNum, aLen)
  set tText to ("0000000000" & aNum as text)
  
set tCount to length of tText
  
set resText to text (tCount – aLen + 1) thru tCount of tText
  
return resText
end retZeroPaddingText

on parseDate(inStr)
  set aClass to class of inStr
  
if aClass = string then
    try
      set aDate to date inStr
    on error
      return false
    end try
  else if aClass = date then
    set aDate to inStr
    
  end if
  
  
return aDate
  
end parseDate

★Click Here to Open This Script 

Posted in Calendar | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a 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

Post navigation

  • Older posts
  • Newer posts

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

Google Search

Popular posts

  • 開発機としてM2 Mac miniが来たのでガチレビュー
  • macOS 15, Sequoia
  • Pages本執筆中に、2つの書類モード切り替えに気がついた
  • Numbersで選択範囲のセルの前後の空白を削除
  • メキシカンハットの描画
  • Pixelmator Pro v3.6.4でAppleScriptからの操作時の挙動に違和感が
  • AppleScriptによる並列処理
  • Safariで「プロファイル」機能を使うとAppleScriptの処理に影響
  • macOS 15でも変化したText to Speech環境
  • AppleScript入門③AppleScriptを使った「自動化」とは?
  • デフォルトインストールされたフォント名を取得するAppleScript
  • 【続報】macOS 15.5で特定ファイル名パターンのfileをaliasにcastすると100%クラッシュするバグ
  • Script Debuggerの開発と販売が2025年に終了
  • macOS 15 リモートApple Eventsにバグ?
  • AppleScript入門① AppleScriptってなんだろう?
  • macOS 14で変更になったOSバージョン取得APIの返り値
  • NSObjectのクラス名を取得 v2.1
  • macOS 15:スクリプトエディタのAppleScript用語辞書を確認できない
  • 有害ではなくなっていたSpaces
  • Xcode上のAppleScriptObjCのプログラムから、Xcodeのログ欄へのメッセージ出力を実行

Tags

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

カテゴリー

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

アーカイブ

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

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

メタ情報

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

Forum Posts

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

メタ情報

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