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

選択中のメール本文のSHA3チェックサムを計算

Posted on 2月 26, 2018 by Takaaki Naganoya

Mail.appで選択中のメール本文のSHA3チェックサムを計算するAppleScriptです。

macOS VistaことmacOS 10.13。もう、10.13.xのバージョン中に状況が好転するような気配がまったくしないこのOS。2018年6月のWWDCで次の10.14を発表して「アップデート間隔を伸ばす」と言ったところで、同じCEO、同じスタッフ、同じ開発期間でまた2018年10月にリリースするとかいったら「同じことの繰り返し」になるのではないかと戦々恐々としています。

macOS 10.13のMail.appでメールの文字化けなどが報告されているため、実際に同じ文面のメールのチェックサムを10.12と10.13で比較するためにこのAppleScriptを書いてみました。

結果は、とくに文字化けもなく同じチェックサム値が得られたものの、OSごと勝手にクラッシュしてシャットダウンするとか、Mail.appのルールが着信したてのメールに効かない時があるとか、Finderが不安定だとか、日本語入力時に辞書の用例が表示されると選択した候補で変換候補を確定できないとか、日本語入力時に確定後も変換ウィンドウが消えないとか、いまだにけっこうムチャクチャなOSです。

–> SHA3Kit.framework

AppleScript名:選択中のメール本文のSHA3チェックサムを計算
— Created 2017-02-25 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "SHA3Kit" –https://github.com/jaeggerr/NSString-SHA3

set aMailBody to getSelectedMailBody() of me
if aMailBody = false then error "No Selection"

set origData to (current application’s NSString’s stringWithString:aMailBody)
set aHash1 to (origData’s sha3:256) as string
–> "C69C8E08D1E6A8DA53C4E00D02D5DB5C2937722730CF63C1EC44E59B57A3B03F"

on getSelectedMailBody()
  tell application "Mail"
    set aaSel to selection
    
if aaSel = {} or aaSel = "" then return false
    
    
set aSel to first item of aaSel
    
    
set aCon to content of aSel
    
return aCon
  end tell
end getSelectedMailBody

★Click Here to Open This Script 

Posted in Text | Tagged 10.11savvy 10.12savvy 10.13savvy Mail | Leave a comment

選択中のメール本文のHexダンプを取得

Posted on 2月 26, 2018 by Takaaki Naganoya
AppleScript名:選択中のメール本文のHexダンプを取得
— Created 2017-02-25 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set aMailBody to getSelectedMailBody() of me
if aMailBody = false then error "No Selection"

set theNSString to current application’s NSString’s stringWithString:aMailBody
set aList to hexDumpString(theNSString) of me
return aList

on getSelectedMailBody()
  tell application "Mail"
    set aaSel to selection
    
if aaSel = {} or aaSel = "" then return false
    
    
set aSel to first item of aaSel
    
    
set aCon to content of aSel
    
return aCon
  end tell
end getSelectedMailBody

on hexDumpString(theNSString)
  set theNSData to theNSString’s dataUsingEncoding:(current application’s NSUTF8StringEncoding)
  
set theString to (theNSData’s |description|()’s uppercaseString())
  
  
–Remove "<" ">" characters in head and tail
  
set tLength to (theString’s |length|()) – 2
  
set aRange to current application’s NSMakeRange(1, tLength)
  
set theString2 to theString’s substringWithRange:aRange
  
  
–Replace Space Characters
  
set aString to current application’s NSString’s stringWithString:theString2
  
set bString to aString’s stringByReplacingOccurrencesOfString:" " withString:""
  
  
set aResList to splitString(bString, 2)
  
–> {​​​​​"E3", ​​​​​"81", ​​​​​"82", ​​​​​"E3", ​​​​​"81", ​​​​​"84", ​​​​​"E3", ​​​​​"81", ​​​​​"86", ​​​​​"E3", ​​​​​"81", ​​​​​"88", ​​​​​"E3", ​​​​​"81", ​​​​​"8A"​​​}
  
  
return aResList
end hexDumpString

–Split NSString in specified aNum characters
on splitString(aText, aNum)
  set aStr to current application’s NSString’s stringWithString:aText
  
if aStr’s |length|() ≤ aNum then return aText
  
  
set anArray to current application’s NSMutableArray’s new()
  
set mStr to current application’s NSMutableString’s stringWithString:aStr
  
  
set aRange to current application’s NSMakeRange(0, aNum)
  
  
repeat while (mStr’s |length|()) > 0
    if (mStr’s |length|()) < aNum then
      anArray’s addObject:(current application’s NSString’s stringWithString:mStr)
      
mStr’s deleteCharactersInRange:(current application’s NSMakeRange(0, mStr’s |length|()))
    else
      anArray’s addObject:(mStr’s substringWithRange:aRange)
      
mStr’s deleteCharactersInRange:aRange
    end if
  end repeat
  
  
return (current application’s NSArray’s arrayWithArray:anArray) as list
end splitString

★Click Here to Open This Script 

Posted in Text | Tagged 10.11savvy 10.12savvy 10.13savvy Mail | Leave a comment

SeleniumでWebサーバー接続のじっけん

Posted on 2月 26, 2018 by Takaaki Naganoya

–> Selenium.framework

AppleScript名:SeleniumでWebサーバー接続テストのじっけん
— Created 2018-02-26 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "Selenium" –https://github.com/appium/selenium-objective-c

set aCap to current application’s SECapabilities’s new()
aCap’s setPlatform:"Mac"
aCap’s setBrowserName:"Safari"
aCap’s setVersion:"11.0.3"

–set anIP to ((current application’s NSHost’s hostWithName:"www.apple.com")’s address()) as string

set {errorF, aRes} to current application’s SERemoteWebDriver’s alloc()’s initWithServerAddress:"0.0.0.0" |port|:8080 desiredCapabilities:aCap requiredCapabilities:(missing value) |error|:(reference)

if errorF = missing value then
  return aRes’s |description|() as list of string or string
  
–>  "Error Domain=NSURLErrorDomain Code=-1004 \"サーバに接続できませんでした。\" UserInfo={NSUnderlyingError=0x6000022459d0 {Error Domain=kCFErrorDomainCFNetwork Code=-1004 \"サーバに接続できませんでした。\" UserInfo={NSErrorFailingURLStringKey=http://0.0.0.0:8080/wd/hub/status, NSErrorFailingURLKey=http://0.0.0.0:8080/wd/hub/status, _kCFStreamErrorCodeKey=61, _kCFStreamErrorDomainKey=1, NSLocalizedDescription=サーバに接続できませんでした。}}, NSErrorFailingURLStringKey=http://0.0.0.0:8080/wd/hub/status, NSErrorFailingURLKey=http://0.0.0.0:8080/wd/hub/status, _kCFStreamErrorDomainKey=1, _kCFStreamErrorCodeKey=61, NSLocalizedDescription=サーバに接続できませんでした。}"
end if

★Click Here to Open This Script 

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

Pages書類からPDF書き出し v2

Posted on 2月 25, 2018 by Takaaki Naganoya
AppleScript名:Pages書類からPDF書き出し v2
— Created 2017-03-28 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set tmpPath to (path to desktop) as string
set aRes to exportPagesDocToPDF(tmpPath)

–Pages書類からPDF書き出し
on exportPagesDocToPDF(targFolderPath as string)
  tell application "Pages"
    set dCount to count every document
    
if dCount = 0 then
      return false
    end if
    
set aPath to file of document 1
  end tell
  
  
set curPath to (current application’s NSString’s stringWithString:(POSIX path of aPath))’s lastPathComponent()’s stringByDeletingPathExtension()’s stringByAppendingString:".pdf"
  
set outPath to (targFolderPath & curPath)
  
  
  
tell application "Pages"
    set anOpt to {class:export options, image quality:Best}
    
export document 1 to file outPath as PDF with properties anOpt
  end tell
end exportPagesDocToPDF

★Click Here to Open This Script 

Posted in file PDF | Tagged 10.11savvy 10.12savvy 10.13savvy Pages | Leave a comment

Keynote書類からPDF書き出し v2

Posted on 2月 25, 2018 by Takaaki Naganoya
AppleScript名:Keynote書類からPDF書き出し v2
— Created 2017-01-21 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set tmpPath to (path to desktop) as string
set aRes to exportKeynoteDocToPDF(tmpPath)

–Keynote書類からPDF書き出し
on exportKeynoteDocToPDF(targFolderPath as string)
  
  
tell application "Keynote"
    set dCount to count every document
    
if dCount = 0 then
      return false
    end if
    
set aPath to file of document 1
  end tell
  
  
set curPath to (current application’s NSString’s stringWithString:(POSIX path of aPath))’s lastPathComponent()’s stringByDeletingPathExtension()’s stringByAppendingString:".pdf"
  
set outPath to (targFolderPath & curPath)
  
  
tell application "Keynote"
    set anOpt to {class:export options, export style:IndividualSlides, all stages:false, skipped slides:true, PDF image quality:Best}
    
export document 1 to file outPath as PDF with properties anOpt
  end tell
  
  
return (outPath as alias)
  
end exportKeynoteDocToPDF

★Click Here to Open This Script 

Keynote Control 1

Keynote Control 2

Posted in file PDF | Tagged 10.11savvy 10.12savvy 10.13savvy Keynote | Leave a comment

Numbers書類からPDF書き出し v2

Posted on 2月 25, 2018 by Takaaki Naganoya
AppleScript名:Numbers書類からPDF書き出し v2
— Created 2017-03-28 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set tmpPath to (path to desktop) as string
set aRes to exportNumbersDocToPDF(tmpPath)

–Pages書類からPDF書き出し
on exportNumbersDocToPDF(targFolderPath as string)
  tell application "Numbers"
    set dCount to count every document
    
if dCount = 0 then
      return false
    end if
    
set aPath to file of document 1
  end tell
  
  
set curPath to (current application’s NSString’s stringWithString:(POSIX path of aPath))’s lastPathComponent()’s stringByDeletingPathExtension()’s stringByAppendingString:".pdf"
  
set outPath to (targFolderPath & curPath)
  
  
  
tell application "Numbers"
    set anOpt to {class:export options, image quality:Best}
    
export document 1 to file outPath as PDF with properties anOpt
  end tell
end exportNumbersDocToPDF

★Click Here to Open This Script 

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

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

デスクトップを隠すv6

Posted on 2月 24, 2018 by Takaaki Naganoya

Edama2さんから投稿していただいた、デスクトップを隠すAppleScriptアプレットです。

資料や本のために画面キャプチャを行うさい、デスクトップを隠しておく(アイコンとかデスクトップピクチャとか)必要があるケースがあります。そのような用途のために作られたものです。

–> download デスクトップを隠すv6

AppleScript名:デスクトップを隠すv6
script HideDesktop
  use AppleScript version "2.4"
  
use scripting additions
  
use framework "Foundation"
  
use framework "Carbon" — AEInteractWithUser() is in Carbon
  
  
#GUI部品のtag
  
property _TAG_OF_COLOR_WELL : 501
  
property _TAG_OF_SLIDER : 502
  
property _TAG_OF_BUTTON : 503
  
  
on run
    if current application’s AEInteractWithUser(-1, missing value, missing value) is not equal to 0 then return
    
    
#色データを復元
    
if my _color_data = missing value then
      set myColor to current application’s NSColor’s colorWithCalibratedRed:0.2 green:0.3 blue:0.5 alpha:1
    else
      set str to current application’s NSString’s stringWithString:(my _color_data)
      
set enc to current application’s NSISOLatin1StringEncoding
      
set strData to str’s dataUsingEncoding:(enc)
      
set myColor to current application’s NSUnarchiver’s unarchiveObjectWithData:strData
    end if
    
    
activate
    
my makeSettingWindow(myColor, my _alpha_value, my _is_show_icon)
  end run
  
  
on quit
    repeat with aWin in (current application’s NSApp’s |windows|())
      set aSound to missing value
      
if aWin’s styleMask() = current application’s NSBorderlessWindowMask then
        try
          tell current application’s NSSound’s alloc()
            tell initWithContentsOfFile_byReference_("/Applications/Messages.app/Contents/Resources/Default.aiff", true)
              set dTime to currentTime()
              
play()
              
set aSound to it
            end tell
          end tell
        end try
      end if
      (
my closeWin:(aWin))
      
if aSound ≠ missing value then delay (dTime + 0.5)
    end repeat
    
–continue quit
  end quit
  
  
on makeSettingWindow(myColor, alphaVal, isShowIcon)
    
    
#NSView
    
tell current application’s NSView’s alloc()
      tell initWithFrame_(current application’s NSMakeRect(0, 0, 360, 210))
        setNeedsDisplay_(true)
        
set aView to it
      end tell
    end tell
    
    
#Labelをつくる
    
tell current application’s NSTextField’s alloc()
      tell initWithFrame_(current application’s NSMakeRect(60, 150, 80, 20))
        setEditable_(false)
        
setStringValue_("背景色:")
        
setDrawsBackground_(false)
        
setBordered_(false)
        
setAlignment_(current application’s NSRightTextAlignment)
        
aView’s addSubview:it
      end tell
    end tell
    
tell current application’s NSTextField’s alloc()
      tell initWithFrame_(current application’s NSMakeRect(60, 110, 80, 20))
        setEditable_(false)
        
setStringValue_("透明度:")
        
setDrawsBackground_(false)
        
setBordered_(false)
        
setAlignment_(current application’s NSRightTextAlignment)
        
aView’s addSubview:it
      end tell
    end tell
    
tell current application’s NSTextField’s alloc()
      tell initWithFrame_(current application’s NSMakeRect(60, 70, 80, 20))
        setEditable_(false)
        
setStringValue_("オプション:")
        
setDrawsBackground_(false)
        
setBordered_(false)
        
setAlignment_(current application’s NSRightTextAlignment)
        
aView’s addSubview:it
      end tell
    end tell
    
#Color Well
    
tell current application’s NSColorWell’s alloc()
      tell initWithFrame_(current application’s NSMakeRect(140, 150, 180, 20))
        setColor_(myColor)
        
setTag_(my _TAG_OF_COLOR_WELL)
        
aView’s addSubview:it
      end tell
    end tell
    
#スライダー
    
tell current application’s NSSlider’s alloc()
      tell initWithFrame_(current application’s NSMakeRect(140, 110, 180, 20))
        setMaxValue_(100)
        
setMinValue_(10)
        
–setNumberOfTickMarks_(25)
        
setKnobThickness_(1)
        
setAllowsTickMarkValuesOnly_(true)
        
setTickMarkPosition_(current application’s NSTickMarkBelow)
        
setIntValue_(alphaVal)
        
setTag_(my _TAG_OF_SLIDER)
        
aView’s addSubview:it
      end tell
    end tell
    
#アイコンを隠すか
    
tell current application’s NSButton’s alloc()
      tell initWithFrame_(current application’s NSMakeRect(140, 70, 180, 20)) — pullsDown:false
        setButtonType_(current application’s NSSwitchButton)
        
setTitle_("アイコンも隠す")
        
setState_(isShowIcon)
        
setTag_(my _TAG_OF_BUTTON)
        
aView’s addSubview:it
      end tell
    end tell
    
#OK/Cancel Button
    
tell current application’s NSButton’s alloc()
      tell initWithFrame_(current application’s NSMakeRect(110, 10, 90, 40))
        setButtonType_(current application’s NSMomentaryLightButton)
        
setBezelStyle_(current application’s NSRoundedBezelStyle)
        
setTitle_("Cancel")
        
setTarget_(me)
        
setAction_("clicked:")
        
setKeyEquivalent_(ASCII character (27))
        
aView’s addSubview:it
      end tell
    end tell
    
tell current application’s NSButton’s alloc()
      tell initWithFrame_(current application’s NSMakeRect(210, 10, 90, 40))
        setButtonType_(current application’s NSMomentaryLightButton)
        
setBezelStyle_(current application’s NSRoundedBezelStyle)
        
setTitle_("OK")
        
setTarget_(me)
        
setAction_("clicked:")
        
setKeyEquivalent_(return)
        
aView’s addSubview:it
      end tell
    end tell
    
    
set aTitle to current application’s name as text
    
    
#Window
    
set aScreen to current application’s NSScreen’s mainScreen()
    
set aFrame to aView’s frame()
    
set aBacking to current application’s NSTitledWindowMask
    
set aDefer to current application’s NSBackingStoreBuffered
    
tell current application’s NSWindow’s alloc()
      tell initWithContentRect_styleMask_backing_defer_screen_(aFrame, aBacking, aDefer, false, aScreen)
        –setLevel_(current application’s NSNormalWindowLevel)
        
setTitle_(aTitle)
        
setDelegate_(me)
        
setDisplaysWhenScreenProfileChanges_(true)
        
setHasShadow_(true)
        
setIgnoresMouseEvents_(false)
        
setOpaque_(false)
        
setReleasedWhenClosed_(true)
        
setContentView_(aView)
        
|center|()
        
makeKeyAndOrderFront_((me))
      end tell
    end tell
  end makeSettingWindow
  
  
#ボタンをクリックした時
  
on clicked:aSender
    #カラーパネルを閉じる
    
tell current application’s NSColorPanel
      if (sharedColorPanelExists() as boolean) then sharedColorPanel()’s |close|()
    end tell
    
#設定値の読み込み
    
tell aSender’s superview()
      set myColor to viewWithTag_(my _TAG_OF_COLOR_WELL)’s |color|()
      
set alphaVal to viewWithTag_(my _TAG_OF_SLIDER)’s intValue()
      
set isShowIcon to viewWithTag_(my _TAG_OF_BUTTON)’s state()
    end tell
    
#Windowを閉じる
    
my closeWin:(aSender’s |window|())
    
    
set aTitle to aSender’s title() as text
    
if aTitle = "OK" then
      #デスクトップを隠す
      
set {myColor, my _alpha_value, my _is_show_icon} to my makeCoverWindow(myColor, alphaVal, isShowIcon)
      
      
#NSColor–>NSData–>NSString
      
set aData to current application’s NSArchiver’s archivedDataWithRootObject:(myColor)
      
set enc to current application’s NSISOLatin1StringEncoding
      
set str to current application’s NSString’s alloc()’s initWithData:(aData) encoding:enc
      
set my _color_data to str as text
      
    else if aTitle = "Cancel" then
      tell current application to quit
    end if
  end clicked:
  
  
#ウィンドウを作成
  
on makeCoverWindow(myColor, alphaVal as integer, isShowIcon as boolean)
    
    
set aScreen to current application’s NSScreen’s mainScreen()
    
set screenFrame to aScreen’s frame()
    
set aBacking to current application’s NSBorderlessWindowMask
    
set aDefer to current application’s NSBackingStoreBuffered
    
    
set aHeight to screenFrame’s |size|’s height
    
set aWidth to screenFrame’s |size|’s width
    
set aFrame to current application’s NSMakeRect(0.0, aHeight, aWidth, aHeight)
    
    
#Image
    
tell current application’s NSImage’s alloc()
      tell initWithSize_(screenFrame’s |size|)
        lockFocus()
        
set theColor to myColor’s colorWithAlphaComponent:(alphaVal / 100)
        
tell current application’s NSBezierPath’s bezierPath()
          appendBezierPathWithRect_(screenFrame)
          
theColor’s |set|()
          
fill()
        end tell
        
unlockFocus()
        
set anImage to it
      end tell
    end tell
    
    
#View
    
tell current application’s NSImageView’s alloc()
      tell initWithFrame_(aFrame)
        setNeedsDisplay_(true)
        
setImage_(anImage)
        
set aCustView to it
      end tell
    end tell
    
    
#Window
    
tell current application’s NSWindow’s alloc()
      tell initWithContentRect_styleMask_backing_defer_screen_(aFrame, aBacking, aDefer, false, aScreen)
        
        
#アイコンの表示
        
if not isShowIcon then
          setLevel_(current application’s kCGDesktopWindowLevel)
        else
          setLevel_(((current application’s kCGBackstopMenuLevelKey) – 100)) –>メニューバーの影のため100ひく
        end if
        
setBackgroundColor_(current application’s NSColor’s clearColor())
        
setContentView_(aCustView)
        
setDelegate_(me)
        
setDisplaysWhenScreenProfileChanges_(true)
        
setHasShadow_(false)
        
setIgnoresMouseEvents_(false)
        
setOpaque_(false)
        
setReleasedWhenClosed_(true)
        
makeKeyAndOrderFront_((me))
        
        
#Sound
        
try
          (current application’s NSSound’s alloc()’s initWithContentsOfFile:"/Applications/Messages.app/Contents/Resources/Invitation Accepted.aiff" byReference:true)’s play()
        on error the error_message number the error_number
          (current application’s NSSound’s soundNamed:"Purr")’s play()
        end try
        
        
setFrame_display_animate_(screenFrame, true, true)
      end tell
    end tell
    
    
return {myColor, alphaVal, isShowIcon}
  end makeCoverWindow
  
  
#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|()
    
delay 0.02
  end closeWin:
end script

#設定値
property _color_data : missing value
property _alpha_value : 100
property _is_show_icon : true

on run
  run of HideDesktop
end run

on quit
  quit of HideDesktop
  
continue quit
end quit

★Click Here to Open This Script 

Posted in System | 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

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からの操作時の挙動に違和感が
  • macOS 15でも変化したText to Speech環境
  • AppleScriptによる並列処理
  • Safariで「プロファイル」機能を使うとAppleScriptの処理に影響
  • デフォルトインストールされたフォント名を取得するAppleScript
  • AppleScript入門③AppleScriptを使った「自動化」とは?
  • 【続報】macOS 15.5で特定ファイル名パターンのfileをaliasにcastすると100%クラッシュするバグ
  • macOS 15 リモートApple Eventsにバグ?
  • Script Debuggerの開発と販売が2025年に終了
  • AppleScript入門① AppleScriptってなんだろう?
  • macOS 14で変更になったOSバージョン取得APIの返り値
  • macOS 15:スクリプトエディタのAppleScript用語辞書を確認できない
  • NSObjectのクラス名を取得 v2.1
  • 有害ではなくなっていたSpaces
  • AVSpeechSynthesizerで読み上げテスト

Tags

10.11savvy (1101) 10.12savvy (1242) 10.13savvy (1391) 10.14savvy (587) 10.15savvy (438) 11.0savvy (283) 12.0savvy (212) 13.0savvy (198) 14.0savvy (152) 15.0savvy (141) CotEditor (66) Finder (51) 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) Pixelmator Pro (20) 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年7月
  • 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