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

月: 2018年5月

ちょっと古めのAppleScript関連ドキュメントのアーカイブ「AppleScript Reference Library」

Posted on 5月 31, 2018 by Takaaki Naganoya

Philによるちょっと古めのAppleScript関連ドキュメントPDFのアーカイブサイト「AppleScript Reference Library」の更新情報がAppleScript Users ML上で紹介されていました。

Appleが開発者向けに1990年代に刊行していた「Develop」掲載記事や「Inside Machintosh」掲載のAppleScript関連記事などがあらたに追加されたようです。

2000〜2009年ぐらいのドキュメントも割とレガシー入りしており見つけにくくなっているものが多く、そうした意味でもまとめてダウンロードできる同サイトはありがたいところです。

(Visited 29 times, 1 visits today)
Posted in 未分類 | Leave a comment

指定の画像からEXIFの撮影日付(DateTimeOriginal)を取得 v2

Posted on 5月 31, 2018 by Takaaki Naganoya

指定の画像からEXIF情報を取得し、撮影日付(DateTimeOriginal)を取得するAppleScriptです。

Image Eventsで取得するよりも、BridgePlusで取得するほうが高速だったので差し替えてみました。

AppleScript名:指定の画像からEXIFの撮影日付(DateTimeOriginal)を取得 v2
— Created 2014-12-14 by Takaaki Naganoya
— 2014 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use BPlus : script "BridgePlus" –https://www.macosxautomation.com/applescript/apps/BridgePlus.html

property NSString : a reference to current application’s NSString
property NSLocale : a reference to current application’s NSLocale
property SMSForder : a reference to current application’s SMSForder
property NSDateFormatter : a reference to current application’s NSDateFormatter

set aTargFile to choose file of type {"public.image"}
set exifRes to readExifDateTimeOriginal(aTargFile) of me

–指定ファイルからのExifデータを取得し撮影日付を取得する
on readExifDateTimeOriginal(aTargFileAlias)
  set theMetadata to readMetadataFrom(aTargFileAlias) of me
  
set keysList to theMetadata’s allKeys()
  
  
if "{Exif}" is not in (keysList as list) then return false
  
  
set exifDate to theMetadata’s valueForKeyPath:"{Exif}.DateTimeOriginal"
  
if exifDate = missing value then return false
  
  
set fullDate to dateFromStringWithDateFormat(exifDate, "yyyy:MM:dd HH:mm:ss") of me
  
  
return fullDate
end readExifDateTimeOriginal

–指定ファイルからのメタデータ読み込み
on readMetadataFrom(imageFile)
  load framework
  
set {theRecord, theError} to SMSForder’s metadataFromImage:imageFile |error|:(reference)
  
if theRecord = missing value then — there was a problem, so extract the error description
    error (theError’s localizedDescription() as text) — number (theError’s code())
  else
    return theRecord
  end if
end readMetadataFrom

–日付文字列を形式指定しつつdate objectに変換
on dateFromStringWithDateFormat(dateString, dateFormat)
  set dStr to NSString’s stringWithString:dateString
  
set dateFormatStr to NSString’s stringWithString:dateFormat
  
  
set aDateFormatter to NSDateFormatter’s alloc()’s init()
  
aDateFormatter’s setDateFormat:dateFormatStr
  
aDateFormatter’s setLocale:(NSLocale’s alloc()’s initWithLocaleIdentifier:"en_US_POSIX")
  
  
set aDestDate to (aDateFormatter’s dateFromString:dStr)
  
  
return aDestDate as list of string or string
end dateFromStringWithDateFormat

★Click Here to Open This Script 

(Visited 161 times, 1 visits today)
Posted in Calendar exif file Image | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

指定フォルダ内のJPEGファイルのEXIFから撮影日付を取得してファイルの作成日付に反映させる v2

Posted on 5月 31, 2018 by Takaaki Naganoya

指定フォルダ内のすべてのJPEGファイルのEXIF情報から撮影日付を取得し、画像ファイルの作成日付に反映させるAppleScriptです。

写真.app(Photos.app)内で管理している大量の写真ファイルをいったんファイルに書き出して、DVD-Rにコピーして人に渡すときに、写真の作成日付が撮影日になっておらず、Finderなどのファイラー上で整理するのが大変でした。

ファイル書き出しなので仕方のないことですが、この仕様はいただけません。

かようにファイル作成日付が正しくない写真でも、EXIFに正しい撮影日付が保存されているケースが多い(ただし、完全にすべてではない)ため、EXIFの日付をAppleScriptで読み取ってファイル作成日付に反映させてみました。

写真.appなどのアプリケーションにインポートしてしまえばEXIF日付でソートされるので、あまり意味があるとも思えませんが、Finder上での写真整理のために実行してとりあえず走らせてみました。

AppleScript名:EXIFから撮影日付を取得してファイルの作成日付に反映させる v2
— Created 2018-05-30 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
use framework "AppKit"

script spd
  property fList : {}
end script

set renCount to 0

set (fList of spd) to {}

set aFolder to (choose folder)

set aDate to current date

set (fList of spd) to getFilePathList(aFolder, "JPG") of me

repeat with i in (fList of spd)
  set j to contents of i
  
chkCreationDateAsExif(j) of me
  
set renCount to renCount + 1
end repeat

set bDate to current date

return {bDate – aDate, renCount}

on chkCreationDateAsExif(aFile)
  tell application "Image Events"
    launch
    
set this_image to open (aFile as alias)
    
    
try
      tell this_image
        set aVal to (value of metadata tag "creation")
      end tell
    on error
      return
    end try
    
    
close this_image
  end tell
  
  
set a to current application’s NSString’s stringWithString:aVal
  
set {aDateStr, aTimeStr} to (a’s componentsSeparatedByString:" ") as list
  
set bDateStr to repChar(aDateStr, ":", "/") of me
  
set fullDate to date (bDateStr & " " & aTimeStr)
  
  
set aDic to current application’s NSMutableDictionary’s dictionaryWithObject:fullDate forKey:(current application’s NSFileModificationDate)
  
set aFM to current application’s NSFileManager’s defaultManager()’s setAttributes:aDic ofItemAtPath:(POSIX path of aFile) |error|:(missing value)
end chkCreationDateAsExif

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

on getFilePathList(aFol, aExt)
  set aFol to current application’s |NSURL|’s fileURLWithPath:(POSIX path of aFol)
  
  
set aFM to current application’s NSFileManager’s defaultManager()
  
set urlArray to aFM’s contentsOfDirectoryAtURL:aFol includingPropertiesForKeys:{} options:(current application’s NSDirectoryEnumerationSkipsHiddenFiles) |error|:(missing value)
  
set thePred to current application’s NSPredicate’s predicateWithFormat:"pathExtension == [c]%@" argumentArray:{aExt}
  
set anArray to urlArray’s filteredArrayUsingPredicate:thePred
  
return anArray as list — URLs pre-10.11, files under 10.11
end getFilePathList

★Click Here to Open This Script 

(Visited 48 times, 1 visits today)
Posted in exif file Image | Tagged 10.11savvy 10.12savvy 10.13savvy Image Events | Leave a comment

Finderファイルタグの設定や取得

Posted on 5月 29, 2018 by Takaaki Naganoya

指定ファイルのFinderタグを取得/設定/追加を行うAppleScriptです。

もともとはShane Stanleyが数年前に書いたScriptですが、Cocoaっぽいハンドラ記述だと慣れていないScripterには敷居が高いので、OLD Style AppleScript風のハンドラに書き換えたものです。

AppleScript名:Finderファイルタグの設定や取得
–Created By Shane Stanley
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

property |NSURL| : a reference to current application’s |NSURL|
property NSOrderedSet : a reference to current application’s NSOrderedSet
property NSURLTagNamesKey : a reference to current application’s NSURLTagNamesKey

set anAlias to (choose file)
set aRes to getTagsForPath(anAlias) of me

— get the tags
on getTagsForPath(anAlias)
  set aURL to |NSURL|’s fileURLWithPath:(POSIX path of anAlias)
  
set {theResult, theTags} to aURL’s getResourceValue:(reference) forKey:(NSURLTagNamesKey) |error|:(missing value)
  
if theTags = missing value then return {} — because when there are none, it returns missing value
  
return theTags as list
end getTagsForPath

— set the tags, replacing any existing
on setTagsForPath(tagList, anAlias)
  set aURL to |NSURL|’s fileURLWithPath:(POSIX path of anAlias)
  
aURL’s setResourceValue:tagList forKey:(NSURLTagNamesKey) |error|:(missing value)
end setTagsForPath

— add to existing tags
on addTagsForPath(tagList, anAlias)
  set aURL to |NSURL|’s fileURLWithPath:(POSIX path of anAlias)
  
— get existing tags
  
set {theResult, theTags} to aURL’s getResourceValue:(reference) forKey:(NSURLTagNamesKey) |error|:(missing value)
  
if theTags ≠ missing value then — add new tags
    set tagList to (theTags as list) & tagList
    
set tagList to (NSOrderedSet’s orderedSetWithArray:tagList)’s allObjects() — delete any duplicates
  end if
  
aURL’s setResourceValue:tagList forKey:(NSURLTagNamesKey) |error|:(missing value)
end addTagsForPath

★Click Here to Open This Script 

(Visited 234 times, 1 visits today)
Posted in file Tag | Tagged 10.11savvy 10.12savvy 10.13savvy Finder | Leave a comment

各TTSの名前とバージョン情報を取得

Posted on 5月 28, 2018 by Takaaki Naganoya

OSにインストールされている各TTS(Text To Speech)の名称一覧とバージョン情報を取得するAppleScriptです。

AppleScriptのsayコマンドには音声を指定する機能が用意されていますが、その一方でOSにインストールされているTTS音声の一覧を取得する機能がないため、このようにしてTTS音声名称を取得したり、対応言語(英語とか日本語とか)でしぼりこみを行なって指定言語のテキスト読み上げに必要なTTS音声が存在しているかといった判定を行います。

各TTS Voiceには、

{​​​​​​​VoiceName:”Vicki”, ​​​​​​​VoiceLocaleIdentifier:”en_US”, ​​​​​​​VoiceIndividuallySpokenCharacters:{{….}}, VoiceDemoText:”Isn’t it nice to have a computer that will talk to you?”, ​​​​​​​VoiceSupportedCharacters:{​​​​​​​​​{…}}, VoiceShowInFullListOnly:1, ​​​​​​​VoiceGender:”VoiceGenderFemale”, ​​​​​​​VoiceVersion:”3.6″, ​​​​​​​VoiceAge:35, ​​​​​​​VoiceIdentifier:”com.apple.speech.synthesis.voice.Vicki”, ​​​​​​​VoiceRelativeDesirability:5100, ​​​​​​​VoiceLanguage:”en-US”​​​​​}

のような属性情報があり、このVoiceNameとVoiceVersionを求めています。

Japanese TTS VoiceのOtoya v6.3.1とKyoko v6.3.1でも、あいかわらず「捥げる」「もげる」を正しく読み上げられない(「げる」、「もげ」になる)バグは治っていません(これを確認するのが本Scriptの目的です)。

AppleScript名:各TTSの名前とバージョン情報を取得
— Created 2015-08-25 by Takaaki Naganoya
— Modified 2015-08-26 by Shane Stanley, Takaaki Naganoya
— 2015 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"

set v1Res to getVoiceNamesAndVers()
–>  {{"Agnes", "3.6"}, {"Albert", "3.6"}, {"Alex", "2.0.36"}, {"Alice", "6.1.1"}, {"Allison", "6.3.1"}, {"Alva", "6.1.1"}, {"Amelie", "6.1.1"}, {"Anna", "6.3.1"}, {"Audrey", "6.3.1"}, {"Ava", "6.3.1"}, {"Bad News", "3.6"}, {"Bahh", "3.6"}, {"Bells", "3.6"}, {"Boing", "3.6"}, {"Bruce", "3.6"}, {"Bubbles", "3.6"}, {"Carmit", "6.1.1"}, {"Cellos", "3.6"}, {"Damayanti", "6.1.1"}, {"Daniel", "6.3.1"}, {"Deranged", "3.6"}, {"Diego", "6.1.1"}, {"Ellen", "6.1.1"}, {"Emily", "2.0.3"}, {"Fiona", "6.1.1"}, {"Fred", "3.6"}, {"Good News", "3.6"}, {"Hysterical", "3.6"}, {"Ioana", "6.1.1"}, {"Jill", "2.0.3"}, {"Joana", "6.1.1"}, {"Jorge", "6.1.1"}, {"Juan", "6.1.1"}, {"Junior", "3.6"}, {"Kanya", "6.1.1"}, {"Karen", "6.3.1"}, {"Kate", "6.3.1"}, {"Kathy", "3.6"}, {"Kyoko", "6.3.1"}, {"Laura", "6.1.1"}, {"Lee", "6.3.1"}, {"Lekha", "6.1.1"}, {"Luca", "6.1.1"}, {"Luciana", "6.1.1"}, {"Maged", "6.1.1"}, {"Mariska", "6.1.1"}, {"Mei-Jia", "6.1.1"}, {"Melina", "6.1.1"}, {"Milena", "6.1.1"}, {"Moira", "6.1.1"}, {"Monica", "6.1.1"}, {"Nora", "6.1.1"}, {"Otoya", "6.3.1"}, {"Paulina", "6.1.1"}, {"Pipe Organ", "3.6"}, {"Princess", "3.6"}, {"Ralph", "3.6"}, {"Samantha", "6.3.1"}, {"Sara", "6.1.1"}, {"Satu", "6.1.1"}, {"Serena", "6.3.1"}, {"Sin-ji", "6.1.1"}, {"Tessa", "6.1.1"}, {"Thomas", "6.1.1"}, {"Ting-Ting", "6.3.1"}, {"Tom", "6.3.1"}, {"Trinoids", "3.6"}, {"Veena", "6.1.1"}, {"Vicki", "3.6"}, {"Victoria", "3.6"}, {"Whisper", "3.6"}, {"Xander", "6.1.1"}, {"Yelda", "6.1.1"}, {"Yuna", "6.3.1"}, {"Yuri", "6.1.1"}, {"Zarvox", "3.6"}, {"Zosia", "6.1.1"}, {"Zuzana", "6.1.1"}}

–Get TTS Voice names and versions
on getVoiceNamesAndVers()
  set aList to {}
  
  
set nameList to (current application’s NSSpeechSynthesizer’s availableVoices()) as list
  
repeat with i in nameList
    set j to contents of i
    
set aDic to ((current application’s NSSpeechSynthesizer’s attributesForVoice:j))
    
set aName to (aDic’s VoiceName) as string
    
set aVer to (aDic’s VoiceVersion) as string
    
set the end of aList to {aName, aVer}
  end repeat
  
  
return aList as list
end getVoiceNamesAndVers

★Click Here to Open This Script 

(Visited 66 times, 2 visits today)
Posted in list System | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

noteのオンラインマガジン「猛者」に新規Noteを寄稿(3)

Posted on 5月 28, 2018 by Takaaki Naganoya

オンラインマガジンApp Engineer Journal “猛者”(モサ)に「Appleに関するウワサ話を実際に検証(上)」「Appleに関するウワサ話を実際に検証(下)」を寄稿しました。

(Visited 35 times, 1 visits today)
Posted in 未分類 | Leave a comment

現在のスライド上のshapeオブジェクトのうち一番上のものに他のものの幅をそろえる

Posted on 5月 27, 2018 by Takaaki Naganoya

Keynoteの現在のスライド上のshapeオブジェクトのうち、一番上のものに他のものの幅をそろえるAppleScriptです。

いっそ、Shapeオブジェクトのboundsをすべて取得して、横長か縦長かを計算し、自動で基準オブジェクトを上にするか左のものにするかを判定してもよいのですが、少しやりすぎな感じもするので、現状のままにしてあります。

AppleScript名:現在のスライド上のshapeオブジェクトのうち一番上のものに他のものの幅をそろえる
— Created 2018-05-25 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use bPlus : script "BridgePlus" –https://www.macosxautomation.com/applescript/apps/BridgePlus.html

tell application "Keynote"
  tell front document
    tell (current slide)
      — すべてのshapeオブジェクトの座標{x,y}を返す
      
set pList to position of every shape
      
      
— shapeオブジェクトの全座標を昇順ソートして最もX座標値が小さいものを返す
      
set mostLeftPos to first item of sort2DList(pList) of me
      
      
— 一番X座標値が小さい(=左にある)オブジェクトを特定
      
set mostLeftObj to first item of (every shape whose position is equal to mostLeftPos)
      
set mostLeftProp to properties of mostLeftObj
      
–> (*class:shape, opacity:100, parent:slide 5 of document id 253165F1-0596-4E72-B9E3-2AB6D6084125, reflection showing:false, background fill type:color fill, position:32, 160, object text:, width:56, rotation:0, reflection value:0, height:467, locked:false*)
      
      
set mostLeftHeight to height of mostLeftProp
      
set mostLeftWidth to width of mostLeftProp
      
      
— 「一番左」以外のshapeオブジェクトへの参照を取得して一気にオブジェクトのwidthをそろえる
      
set otherShape to a reference to (every shape whose position is not equal to mostLeftPos)
      
set width of otherShape to mostLeftWidth
    end tell
  end tell
end tell

on sort2DList(aList)
  load framework
  
set sortIndexes to {1} –Key Item id: begin from 0
  
set sortOrders to {true} –ascending = true
  
set sortTypes to {"compare:"}
  
set resList to (current application’s SMSForder’s subarraysIn:(aList) sortedByIndexes:sortIndexes ascending:sortOrders sortTypes:sortTypes |error|:(missing value)) as list
  
return resList
end sort2DList

★Click Here to Open This Script 

(Visited 35 times, 1 visits today)
Posted in Sort | Tagged 10.11savvy 10.12savvy 10.13savvy Keynote | Leave a comment

Finderで選択中のPDFを古い順に連結する v2

Posted on 5月 27, 2018 by Takaaki Naganoya

Finder上で選択中のファイルのうちPDFだけを作成日付で古い順に連結するAppleScriptです。

間違ってPDF以外のファイルを選択してしまった場合でも、それについては無視します。

こんな風にmacOS標準装備のScript Menuに入れて利用しています。

AppleScript名:Finderで選択中のPDFを古い順に連結する v2
— Created 2018-05-26 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "Quartz"

property |NSURL| : a reference to current application’s |NSURL|
property NSArray : a reference to current application’s NSArray
property NSPredicate : a reference to current application’s NSPredicate
property NSFileManager : a reference to current application’s NSFileManager
property NSURLPathKey : a reference to current application’s NSURLPathKey
property NSMutableArray : a reference to current application’s NSMutableArray
property NSSortDescriptor : a reference to current application’s NSSortDescriptor
property NSURLIsPackageKey : a reference to current application’s NSURLIsPackageKey
property NSURLIsDirectoryKey : a reference to current application’s NSURLIsDirectoryKey
property NSURLTypeIdentifierKey : a reference to current application’s NSURLTypeIdentifierKey
property NSURLContentModificationDateKey : a reference to current application’s NSURLContentModificationDateKey
property NSDirectoryEnumerationSkipsHiddenFiles : a reference to current application’s NSDirectoryEnumerationSkipsHiddenFiles

–set inFiles to (choose file of type {"pdf"} with prompt "Choose your PDF files:" with multiple selections allowed)
tell application "Finder"
  set inFiles to selection as alias list
end tell

if inFiles = {} then return

–指定のAlias listのうちPDFのみ抽出
set filRes1 to filterAliasListByUTI(inFiles, "com.adobe.pdf") of me

–選択中のファイルのうちの1つから親フォルダを求め、出力先ファイルパスを組み立てる
set outPathTarg to POSIX path of (first item of filRes1)
set pathString to current application’s NSString’s stringWithString:outPathTarg
set newPath to (pathString’s stringByDeletingLastPathComponent()) as string
set destPosixPath to newPath & "/" & ((current application’s NSUUID’s UUID()’s UUIDString()) as string) & ".pdf"

combinePDFsAndSaveIt(filRes1, destPosixPath) of me

on combinePDFsAndSaveIt(inFiles, destPosixPath)
  set inFilesSorted to my filesInListSortFromOldToNew(inFiles)
  
  
— make URL of the first PDF
  
set inNSURL to current application’s |NSURL|’s fileURLWithPath:(POSIX path of item 1 of inFilesSorted)
  
set theDoc to current application’s PDFDocument’s alloc()’s initWithURL:inNSURL
  
  
— loop through the rest
  
set oldDocCount to theDoc’s pageCount()
  
set inFilesSorted to rest of inFilesSorted
  
  
repeat with aFile in inFilesSorted
    set inNSURL to (current application’s |NSURL|’s fileURLWithPath:(POSIX path of aFile))
    
set newDoc to (current application’s PDFDocument’s alloc()’s initWithURL:inNSURL)
    
    
set newDocCount to newDoc’s pageCount()
    
repeat with i from 1 to newDocCount
      set thePDFPage to (newDoc’s pageAtIndex:(i – 1)) — zero-based indexes
      (
theDoc’s insertPage:thePDFPage atIndex:oldDocCount)
      
set oldDocCount to oldDocCount + 1
    end repeat
    
  end repeat
  
  
set outNSURL to current application’s |NSURL|’s fileURLWithPath:destPosixPath
  (
theDoc’s writeToURL:outNSURL)
end combinePDFsAndSaveIt

on filesInListSortFromOldToNew(aliasList)
  set keysToRequest to {NSURLPathKey, NSURLIsPackageKey, NSURLIsDirectoryKey, NSURLContentModificationDateKey}
  
  
set valuesNSArray to NSMutableArray’s array()
  
repeat with i in aliasList
    set oneNSURL to (|NSURL|’s fileURLWithPath:(POSIX path of i))
    (
valuesNSArray’s addObject:(oneNSURL’s resourceValuesForKeys:keysToRequest |error|:(missing value)))
  end repeat
  
  
set theNSPredicate to NSPredicate’s predicateWithFormat_("%K == NO OR %K == YES", NSURLIsDirectoryKey, NSURLIsPackageKey)
  
set valuesNSArray to valuesNSArray’s filteredArrayUsingPredicate:theNSPredicate
  
  
set theDescriptor to NSSortDescriptor’s sortDescriptorWithKey:(NSURLContentModificationDateKey) ascending:true
  
set theSortedNSArray to valuesNSArray’s sortedArrayUsingDescriptors:{theDescriptor}
  
  
— extract just the paths and convert to an AppleScript list
  
return (theSortedNSArray’s valueForKey:(NSURLPathKey)) as list
end filesInListSortFromOldToNew

–Alias listから指定UTIに含まれるものをPOSIX pathのリストで返す
on filterAliasListByUTI(aList, targUTI)
  set newList to {}
  
repeat with i in aList
    set j to POSIX path of i
    
set tmpUTI to my retUTIfromPath(j)
    
set utiRes to my filterUTIList({tmpUTI}, targUTI)
    
if utiRes is not equal to {} then
      set the end of newList to j
    end if
  end repeat
  
return newList
end filterAliasListByUTI

–指定のPOSIX pathのファイルのUTIを求める
on retUTIfromPath(aPOSIXPath)
  set aURL to |NSURL|’s fileURLWithPath:aPOSIXPath
  
set {theResult, theValue} to aURL’s getResourceValue:(reference) forKey:NSURLTypeIdentifierKey |error|:(missing value)
  
  
if theResult = true then
    return theValue as string
  else
    return theResult
  end if
end retUTIfromPath

–UTIリストが指定UTIに含まれているかどうか演算を行う
on filterUTIList(aUTIList, aUTIstr)
  set anArray to NSArray’s arrayWithArray:aUTIList
  
set aPred to NSPredicate’s predicateWithFormat_("SELF UTI-CONFORMS-TO %@", aUTIstr)
  
set bRes to (anArray’s filteredArrayUsingPredicate:aPred) as list
  
return bRes
end filterUTIList

★Click Here to Open This Script 

(Visited 38 times, 1 visits today)
Posted in file PDF Sort UTI | Tagged 10.11savvy 10.12savvy 10.13savvy Finder | Leave a comment

Finderで選択中のファイルのうち、指定UTIに含まれるものを返す

Posted on 5月 26, 2018 by Takaaki Naganoya

Finder上で選択中のファイルのうち、指定UTIに含まれるもの(下位階層のUTIも含む)を返すAppleScriptです。

Finderでfileのkindを指定してフィルタ参照でしぼりこむ方法もありますが、ファイル数が増えると処理速度が大幅に低下するのと、UTIで指定できたほうが便利なので作っておきました。

AppleScript名:Finderで選択中のファイルのうち、指定UTIに含まれるものを返す
— Created 2018-05-26 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

property NSURLTypeIdentifierKey : a reference to current application’s NSURLTypeIdentifierKey
property |NSURL| : a reference to current application’s |NSURL|
property NSPredicate : a reference to current application’s NSPredicate
property NSArray : a reference to current application’s NSArray

tell application "Finder"
  set aSel to selection as alias list
end tell
if aSel = {} then its return

set filRes1 to filterAliasListByUTI(aSel, "com.adobe.pdf") of me
–>  {​​​​​"/Users/me/Pictures/annotation_origin.pdf"​​​}

set filRes2 to filterAliasListByUTI(aSel, "public.image") of me
–>  {"/Users/me/Pictures/スクリーンショット 2017-11-06 20.05.30.png", "/Users/me/Pictures/スクリーンショット 2017-09-27 19.35.08.png", "/Users/me/Pictures/スクリーンショット 2017-09-27 19.33.53.png", "/Users/me/Pictures/スクリーンショット 2017-09-26 16.46.29.png"}

set filRes3 to filterAliasListByUTI(aSel, "public.item") of me
–>  {"/Users/me/Pictures/スクリーンショット 2017-11-06 20.05.30.png", "/Users/me/Pictures/annotation_origin.pdf", "/Users/me/Pictures/スクリーンショット 2017-09-27 19.35.08.png", "/Users/me/Pictures/スクリーンショット 2017-09-27 19.33.53.png", "/Users/me/Pictures/スクリーンショット 2017-09-26 16.46.29.png"}

–Alias listから指定UTIに含まれるものをPOSIX pathのリストで返す
on filterAliasListByUTI(aList, targUTI)
  set newList to {}
  
repeat with i in aList
    set j to POSIX path of i
    
set tmpUTI to my retUTIfromPath(j)
    
set utiRes to my filterUTIList({tmpUTI}, targUTI)
    
if utiRes is not equal to {} then
      set the end of newList to j
    end if
  end repeat
  
return newList
end filterAliasListByUTI

–指定のPOSIX pathのファイルのUTIを求める
on retUTIfromPath(aPOSIXPath)
  set aURL to |NSURL|’s fileURLWithPath:aPOSIXPath
  
set {theResult, theValue} to aURL’s getResourceValue:(reference) forKey:NSURLTypeIdentifierKey |error|:(missing value)
  
  
if theResult = true then
    return theValue as string
  else
    return theResult
  end if
end retUTIfromPath

–UTIリストが指定UTIに含まれているかどうか演算を行う
on filterUTIList(aUTIList, aUTIstr)
  set anArray to NSArray’s arrayWithArray:aUTIList
  
set aPred to NSPredicate’s predicateWithFormat_("SELF UTI-CONFORMS-TO %@", aUTIstr)
  
set bRes to (anArray’s filteredArrayUsingPredicate:aPred) as list
  
return bRes
end filterUTIList

★Click Here to Open This Script 

(Visited 47 times, 1 visits today)
Posted in file UTI | Tagged 10.11savvy 10.12savvy 10.13savvy Finder | Leave a comment

現在のスライド上のshapeオブジェクトのうち一番左のものに他のものの高さをそろえる

Posted on 5月 25, 2018 by Takaaki Naganoya

Keynoteの現在のスライド上のshapeオブジェクトのうち、一番左のものに他のものの高さをそろえるAppleScriptです。

AppleScript名:現在のスライド上のshapeオブジェクトのうち一番左のものに他のものの高さをそろえる
— Created 2018-05-25 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use bPlus : script "BridgePlus" –https://www.macosxautomation.com/applescript/apps/BridgePlus.html

tell application "Keynote"
  tell front document
    tell (current slide)
      — すべてのshapeオブジェクトの座標{x,y}を返す
      
set pList to position of every shape
      
      
— shapeオブジェクトの全座標を昇順ソートして最もX座標値が小さいものを返す
      
set mostLeftPos to first item of sort2DList(pList) of me
      
      
— 一番X座標値が小さい(=左にある)オブジェクトを特定
      
set mostLeftObj to first item of (every shape whose position is equal to mostLeftPos)
      
set mostLeftProp to properties of mostLeftObj
      
–> (*class:shape, opacity:100, parent:slide 5 of document id 253165F1-0596-4E72-B9E3-2AB6D6084125, reflection showing:false, background fill type:color fill, position:32, 160, object text:, width:56, rotation:0, reflection value:0, height:467, locked:false*)
      
      
set mostLeftHeight to height of mostLeftProp
      
set mostLeftWidth to width of mostLeftProp
      
      
— 「一番左」以外のshapeオブジェクトへの参照を取得して一気にオブジェクトのHeightをそろえる
      
set otherShape to a reference to (every shape whose position is not equal to mostLeftPos)
      
set height of otherShape to mostLeftHeight
    end tell
  end tell
end tell

on sort2DList(aList)
  load framework
  
set sortIndexes to {0} –Key Item id: begin from 0
  
set sortOrders to {true} –ascending = true
  
set sortTypes to {"compare:"}
  
set resList to (current application’s SMSForder’s subarraysIn:(aList) sortedByIndexes:sortIndexes ascending:sortOrders sortTypes:sortTypes |error|:(missing value)) as list
  
return resList
end sort2DList

★Click Here to Open This Script 

(Visited 25 times, 1 visits today)
Posted in Sort | Tagged 10.11savvy 10.12savvy 10.13savvy Keynote | Leave a comment

ディスプレイを回転させる

Posted on 5月 25, 2018 by Takaaki Naganoya

指定のディスプレイを回転(表示方向を変更)させるAppleScriptです。

–> Watch Demo Movie

ディスプレイの表示方向の変更には、fb-rotateというコマンドラインツールを用いています。

fb-rotateをバンドル内に内蔵して呼び出すことが多く、AppleScript Librariesとして呼び出してもよいでしょう。

–> AppleScript Bundle file with fb-rotate


▲0°(MacBook Air 11)


▲90°(MacBook Air 11)


▲180°(MacBook Air 11)


▲270°(MacBook Air 11)

AppleScript名:ディスプレイを回転させる
— Created 2016-03-11 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

–fb-rotate
–http://modbookish.lefora.com/topic/3513246/A-Unix-Utility-to-Change-the-Primary-Display-on-OSX/#.VuIe82OFlro

–ディスプレイの情報を取得(基本情報)
getDisplayList() of me
–> {{dispID:"0x4248387", dispWidth:1920, dispHeight:1200, mainD:true}, {dispID:"0x424b104", dispWidth:1920, dispHeight:1200, mainD:false}, {dispID:"0x1b557a25", dispWidth:1920, dispHeight:1080, mainD:false}}

–メインディスプレイを回転させる
rotateMainDisplayToDegree(0) of me –いったんこれを実行すると、構成によってはメインディスプレイが他のIDのものに変わる可能性がある

–ディスプレイの詳細情報を取得
getDisplayInformation() of me
–>  {​​​​​{​​​​​​​dispID:"0x4248387", ​​​​​​​dispWidth:1920, ​​​​​​​dispHeight:1200, ​​​​​​​dispX1:0, ​​​​​​​dispY1:0, ​​​​​​​dispX2:1920, ​​​​​​​dispY2:1200, ​​​​​​​mainD:true, ​​​​​​​rotationDegree:0, ​​​​​​​cousorExists:false​​​​​}, ​​​​​{​​​​​​​dispID:"0x424b104", ​​​​​​​dispWidth:1920, ​​​​​​​dispHeight:1200, ​​​​​​​dispX1:-1920, ​​​​​​​dispY1:0, ​​​​​​​dispX2:0, ​​​​​​​dispY2:1200, ​​​​​​​mainD:false, ​​​​​​​rotationDegree:0, ​​​​​​​cousorExists:true​​​​​}, ​​​​​{​​​​​​​dispID:"0x1b557a25", ​​​​​​​dispWidth:1080, ​​​​​​​dispHeight:1920, ​​​​​​​dispX1:1920, ​​​​​​​dispY1:-362, ​​​​​​​dispX2:3000, ​​​​​​​dispY2:1558, ​​​​​​​mainD:false, ​​​​​​​rotationDegree:270, ​​​​​​​cousorExists:false​​​​​}​​​}

on getDisplayInformation()
  set aPath to POSIX path of (path to me) & "Contents/Resources/fb-rotate"
  
try
    set aRes to (do shell script (quoted form of aPath) & " -i")
  on error
    return false
  end try
  
  
set aList to paragraphs of aRes
  
set aaList to contents of (items 2 thru -2 of aList)
  
  
set a to contents of last item of aList
  
set {b, c} to separateStrByAChar(a, ":") of me
  
set {b1, c1} to separateStrByAChar(c, ",") of me
  
set mouseX to returnNumberCharsOnly(b1) as number
  
set mouseY to returnNumberCharsOnly(c1) as number
  
  
set recList to {}
  
  
repeat with i in aaList
    set j to contents of i
    
    
–Parse Result by space character
    
set aStr to (current application’s NSString’s stringWithString:j)
    
set aLine to (aStr’s componentsSeparatedByString:" ")
    (
aLine’s removeObject:"")
    
set bList to aLine as list
    
–>  {​​​​​"3", ​​​​​"0x4248387", ​​​​​"1920×1200", ​​​​​"0", ​​​​​"0", ​​​​​"-1920", ​​​​​"-1200", ​​​​​"0", ​​​​​"[main]"​​​}
    
    
–Display ID
    
set anID to contents of item 2 of bList
    
    
–Resolution
    
set aResol to contents of item 3 of bList
    
set dParseRes to separateStrByACharAndReturnNumList(aResol, "x") of me
    
if dParseRes = "" then exit repeat –Error
    
copy dParseRes to {aWidth, aHeight}
    
    
–Display_Bounds
    
set dX1 to (contents of item 4 of bList) as number
    
set dY1 to (contents of item 5 of bList) as number
    
set dX2 to (contents of item 6 of bList) as number
    
set dY2 to (contents of item 7 of bList) as number
    
    
–Rotation
    
set aDeg to (contents of item 8 of bList) as number
    
    
–Mouse Cursor Detection
    
set mouseF to (dX1 ≤ mouseX) and (mouseX ≤ dX2) and (dY1 ≤ mouseY) and (mouseY ≤ dY2)
    
    
–Main Display (Menu)
    
set aMain to contents of last item of bList
    
if (contents of last item of bList) contains "main" then
      set aMainF to true
    else
      set aMainF to false
    end if
    
    
set the end of recList to {dispID:anID, dispWidth:aWidth, dispHeight:aHeight, dispX1:dX1, dispY1:dY1, dispX2:dX2, dispY2:dY2, mainD:aMainF, rotationDegree:aDeg, cousorExists:mouseF}
  end repeat
  
  
return recList
  
end getDisplayInformation

–指定IDのディスプレイを指定角度(0, 90, 180, 270のいずれか)に回転させる
on rotateADisplayToDegree(aDispID as string, aDegree as integer)
  if aDegree is not in {0, 90, 180, 270} then return false
  
set aPath to POSIX path of (path to me) & "Contents/Resources/fb-rotate"
  
try
    set aRes to (do shell script (quoted form of aPath) & " -d " & aDispID & " -r " & (aDegree as string))
  on error
    return false
  end try
end rotateADisplayToDegree

–メインディスプレイを指定角度(0, 90, 180, 270のいずれか)に回転させる
on rotateMainDisplayToDegree(aDegree as integer)
  if aDegree is not in {0, 90, 180, 270} then return false
  
set mainID to getMainDispID() of me
  
set aPath to POSIX path of (path to me) & "Contents/Resources/fb-rotate"
  
try
    set aRes to (do shell script (quoted form of aPath) & " -d " & mainID & " -r " & (aDegree as string))
  on error
    return false
  end try
end rotateMainDisplayToDegree

–メインディスプレイのIDを取得する
on getMainDispID()
  set dList to getDisplayList() of me
  
set dDict to current application’s NSArray’s arrayWithArray:dList
  
set aRes to filterRecListByLabel1(dDict, "mainD == true") of me
  
set aMainD to contents of first item of aRes
  
set mainID to dispID of aMainD
  
return mainID
end getMainDispID

–実行中のMacに接続されているディスプレイの一覧を取得する
on getDisplayList()
  set aPath to POSIX path of (path to me) & "Contents/Resources/fb-rotate"
  
try
    set aRes to (do shell script (quoted form of aPath) & " -l")
  on error
    return false
  end try
  
set aList to paragraphs of aRes
  
set aaList to contents of (items 2 thru -1 of aList)
  
  
set recList to {}
  
  
repeat with i in aaList
    set j to contents of i
    
set bList to words of j
    
set anID to contents of item 1 of bList
    
set aResol to contents of item 2 of bList
    
set dParseRes to separateStrByACharAndReturnNumList(aResol, "x") of me
    
if dParseRes = "" then exit repeat –Error
    
copy dParseRes to {aWidth, aHeight}
    
    
set aMain to contents of last item of bList
    
if j ends with "]" then
      set aMainF to true
    else
      set aMainF to false
    end if
    
set the end of recList to {dispID:anID, dispWidth:aWidth, dispHeight:aHeight, mainD:aMainF}
  end repeat
  
  
recList
end getDisplayList

–"1920×1200" といった文字列を"x"でparseしてパラメータを分ける。結果は文字列のリストで返す
on separateStrByAChar(aStr as string, aChar as string)
  if aStr does not contain aChar then return ""
  
if length of aChar is not equal to 1 then return ""
  
if aStr = "" or (length of aStr < 3) then return ""
  
set aPos to offset of aChar in aStr
  
set partA to text 1 thru (aPos – 1) of aStr
  
set partB to text (aPos + 1) thru -1 of aStr
  
return {partA, partB}
end separateStrByAChar

–"1920×1200" といった文字列を"x"でparseしてパラメータを分ける。結果は整数のリストで返す
on separateStrByACharAndReturnNumList(aStr as string, aChar as string)
  if aStr does not contain aChar then return ""
  
if length of aChar is not equal to 1 then return ""
  
if aStr = "" or (length of aStr < 3) then return ""
  
set aPos to offset of aChar in aStr
  
set partA to (text 1 thru (aPos – 1) of aStr) as number
  
set partB to (text (aPos + 1) thru -1 of aStr) as number
  
return {partA, partB}
end separateStrByACharAndReturnNumList

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

–数字とプラスマイナスの符号のみ返す
on returnNumberCharsOnly(aStr)
  set anNSString to current application’s NSString’s stringWithString:aStr
  
set anNSString to anNSString’s stringByReplacingOccurrencesOfString:"[^0-9-+]" withString:"" options:(current application’s NSRegularExpressionSearch) range:{0, anNSString’s |length|()}
  
return anNSString as text
end returnNumberCharsOnly

★Click Here to Open This Script 

(Visited 239 times, 1 visits today)
Posted in System | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

OS X 10.11.5+Safari 9.1.1以降で、新たなAS制限機能が増える

Posted on 5月 24, 2018 by Takaaki Naganoya

macOS 10.11.5+Safari 9.1.1以降で、新たなAppleScriptの制限機能が増えました。Safariに対してdo javascriptコマンドによるコマンド実行が可能でしたが、これがデフォルト設定では禁止状態になったということです。

macOS 10.12.x系では、macOS 10.12.6+Safari 11.1にて、macOS 10.13.x系ではmacOS 10.13.5+Safari 11.1.1上にて確認しています。

■デフォルトでdo javascriptコマンドによる制御がオフに

これ以前のmacOSではデフォルトでオンになっていたので、一回オンにする作業が必要になりました(管理者パスワード必要)。

・STEP1 「開発」メニューをオンに
Safariの「環境設定」>「詳細」で、「メニューバーに”開発”メニューを表示」をオンにします。これで、Safariのメニューバーに「開発」メニューが表示されます。

・STEP2 「開発」メニューから「AppleEventからのJavaScriptを許可」「スマート検索フィールドからのJavaScriptを許可」の2つの項目をオンに(管理者パスワード必要)

AppleScript名:最前面のウィンドウのタイトルを取得する
tell application "Safari"
  set aRes to do JavaScript "document.title;" in front document
  
display dialog aRes
end tell

★Click Here to Open This Script 


▲デフォルト状態


▲「開発」メニューからJavaScriptの実行を許可した状態

(Visited 254 times, 1 visits today)
Posted in JavaScript Security | Tagged 10.11savvy 10.12savvy 10.13savvy Safari | Leave a comment

Contactsに登録してある自分の写真をPNGでデスクトップに保存する

Posted on 5月 24, 2018 by Takaaki Naganoya

住所録(Contacts.app)に登録してある自分の写真をPNG形式でデスクトップに保存するAppleScriptです。

住所録情報については、Contacts.appに直接アクセスして処理することも可能ですが、ここではAddressBook.frameworkを用いた方法をご紹介します。

AppleScript名:Contactsに登録してある自分の写真をPNGでデスクトップに保存する
— Created 2016-04-02 by Takaaki Naganoya
— 2016 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AddressBook"

set imgData to current application’s ABAddressBook’s sharedAddressBook()’s |me|()’s imageData()

set aDesktopPath to (current application’s NSProcessInfo’s processInfo()’s environment()’s objectForKey:("HOME"))’s stringByAppendingString:"/Desktop/"
set savePath to aDesktopPath’s stringByAppendingString:((current application’s NSUUID’s UUID()’s UUIDString())’s stringByAppendingString:".png")

saveTIFFDataAtPathAsPNG(imgData, savePath) of me

–NSImageを指定パスにPNG形式で保存
on saveTIFFDataAtPathAsPNG(anImage, outPath)
  –set imageRep to anImage’s TIFFRepresentation()
  
set aRawimg to current application’s NSBitmapImageRep’s imageRepWithData:anImage
  
set pathString to current application’s NSString’s stringWithString:outPath
  
set newPath to pathString’s stringByExpandingTildeInPath()
  
set myNewImageData to (aRawimg’s representationUsingType:(current application’s NSPNGFileType) |properties|:(missing value))
  
set aRes to (myNewImageData’s writeToFile:newPath atomically:true) as boolean
  
return aRes –成功ならtrue、失敗ならfalseが返る
end saveTIFFDataAtPathAsPNG

★Click Here to Open This Script 

(Visited 219 times, 1 visits today)
Posted in System | Tagged 10.11savvy 10.12savvy 10.13savvy Contacts | Leave a comment

CMD-D: Down-Home Scripting Boot Camp 2018を開催

Posted on 5月 24, 2018 by Takaaki Naganoya

Sal Soghoianが主催するイベント「CMD-D: Down-Home Scripting Boot Camp」の2018年版が10月15〜17日の3日間、ジョージア州のHilton Garden Innで行われることが発表されました。

講師はSal SoghoianとRay Robertson。3日間みっちりAppleScriptのセミナーを初心者から経験者向けの内容の解説を行うようです。

(Visited 28 times, 1 visits today)
Posted in 未分類 | Leave a comment

指定パスの所属するドライブ名を取得する v2

Posted on 5月 22, 2018 by Takaaki Naganoya

指定パスの所属するドライブ名を取得するAppleScriptです。

ドライブ名さえ求めてしまえば、Finderに問い合わせてそれが起動ドライブ(startup = true)かどうか確認できるため、起動ドライブ以外であれば外付けディスクやファイルサーバーであるかの判定も行えます。

AppleScript名:指定パスの所属するドライブ名を取得する v2
— Created 2017-09-03 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

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

set aPath to POSIX path of (choose folder)
set dRes to retDiskNameOfTheFolder(aPath) of me

on retDiskNameOfTheFolder(aPath)
  set aURL to |NSURL|’s fileURLWithPath:aPath
  
set aVlomeName to ""
  
set {aRes, driveName} to aURL’s getResourceValue:(reference) forKey:(NSURLVolumeNameKey) |error|:(missing value)
  
return driveName as string
end retDiskNameOfTheFolder

★Click Here to Open This Script 

(Visited 48 times, 1 visits today)
Posted in drive File path | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

Previewでオープン中のファイルのパスを求める(macOS 10.12限定)

Posted on 5月 21, 2018 by Takaaki Naganoya

Preview.appでオープン中の画像のファイルパスをすべてPOSIX pathで求めるAppleScriptです。


▲大昔にあった「日本語AppleScript」(Japanese Dialect)を擬似的に書いたRTFを画像化したもの。AppleScriptがいまでも日本語で書けるとかいうデモではありません(大事なことなので書いておきました)

Preview.appでオープン中の画像のパスをためしに求めてみたところ(macOS 10.12.6)、実際のファイルが、

  /Users/me/Desktop/image.png

であるものが、

  /Users/me/Library/Containers/com.apple.Preview/Data/Desktop/image.png

と返ってきました。一時的に、ライブラリフォルダの下にコピーしてオープンしているのでしょうか。そういう「舞台裏」をそのまま見せてしまうのはどうかと思います。オリジナルのファイルパスをそのまま返せばいいのに。

そこで、Preview.appから返ってきたパスを加工してオリジナルのパスを求めてみました。

ファイルサーバー上にある画像や外部HDD上にある画像などについては検証していないので、それについては、別途パスを求め直す必要があることでしょう。

macOS 10.13.5beta上でためしてみたら、こちらでは直っていました。そーーですよねーーーーー、10.12上の仕様の方がおかしいですよねーーー(ーー;;

AppleScript名:Previewでオープン中のファイルのパスを求める
— Created 2018-05-21 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

tell application "Preview"
  set dList to path of every document
  
–> {"/Users/me/Library/Containers/com.apple.Preview/Data/Desktop/スクリーンショット 2018-02-28 14.01.09.png", "/Users/me/Library/Containers/com.apple.Preview/Data/Desktop/スクリーンショット 2018-02-28 14.01.11.png"}
end tell

set mePath to POSIX path of (path to home folder)
set origStr to mePath & "Library/Containers/com.apple.Preview/Data"

set outPathList to {}

repeat with i in dList
  set j to contents of i
  
set the end of outPathList to repChar(j, origStr, (text 1 thru -2 of mePath)) of me
end repeat

return outPathList

on repChar(origText as string, targStr as string, repStr as string)
  set {txdl, AppleScript’s text item delimiters} to {AppleScript’s text item delimiters, targStr}
  
set temp to text items of origText
  
set AppleScript’s text item delimiters to repStr
  
set res to temp as text
  
set AppleScript’s text item delimiters to txdl
  
return res
end repChar

★Click Here to Open This Script 

(Visited 59 times, 1 visits today)
Posted in File path Image Text | Tagged 10.12savvy Preview | Leave a comment

noteのオンラインマガジン「猛者」に新規Noteを寄稿

Posted on 5月 20, 2018 by Takaaki Naganoya

App Engineer Journal “猛者”(モサ)というオンラインマガジンに「Appleに関するウワサ話と付き合う方法(下)」を寄稿しました。

(Visited 30 times, 1 visits today)
Posted in 未分類 | Leave a comment

Xcodeで表示中のソースの選択中の範囲のテキストを取得する v3

Posted on 5月 19, 2018 by Takaaki Naganoya

Xcodeで編集中のテキストの選択中の範囲のテキストを取得するAppleScriptです。

Xcode v9.2+macOS 10.12.6およびXcode v9.3.1+macOS 10.13.5betaで動作を確認しています。

Xcode上で編集中のソーステキストの選択範囲(selected character range)を取得し、さらに実際に選択範囲のテキストを取得しています。

Xcode上でソーステキストではなくXibファイルやplistなどの他のファイルを選択中の場合にはfalseを返します。

また、本Scriptでは個別に独立したWindow上に表示中のテキストについては無視します。

常識的なMacのテキスト編集系のGUIアプリケーションであれば、

 ①指定パスのテキストをオープンできる
 ②テキストを指定パスに保存できる
 ③表示中のテキストの選択範囲のテキストを取得できる
 ④表示中のテキストの選択範囲の内容を書き換えることができる

という動作は期待したいところですが、Xcodeについては①②が怪しく(Workspace Documentに新規テキストを追加するとかできそうもない)、③はなんとかなったものの、④ができるかどうか試行錯誤してみないとわからない、といったところです(パスを取得できているので、Xcodeを経由しないで直接ファイルを書き換えれば不可能ではなさそうですが、、、)。

AppleScript対応アプリケーションが標準でそなえているopen/close/quit/count/delete/exists/make/moveなどのコマンドをのぞくと、XcodeのAppleScript用語辞書に掲載されているコマンドは、build、clean、stop、run、testの5つだけ。archiveとかのproduct(ビルド後に生成されるバイナリ)を操作するための命令は用意されていません(わざと?)。

AppleScript名:表示中のソースの選択中の範囲のテキストを取得する v3
— Created 2018-05-19 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

tell application "Xcode"
  tell front file document
    try
      set selRange to selected character range
      
if selRange = {} or selRange = missing value then return false –No Selection or other
      
      
copy selRange to {aSelBegin, aSelEnd}
      
set aText to text of it
      
set aSelText to text aSelBegin thru aSelEnd of aText
    on error
      return "" –No Selection or other
    end try
    
    
return aSelText
  end tell
end tell

–>
(*
"  property parent : class \"NSObject\"
  property NSTimer : class \"NSTimer\""
*)

★Click Here to Open This Script 

(Visited 31 times, 1 visits today)
Posted in Text | Tagged 10.12savvy 10.13savvy Xcode | Leave a comment

Xcodeでオープン中のソースコードのパスを求める

Posted on 5月 19, 2018 by Takaaki Naganoya

Xcodeでオープン中のソースコードのファイルパスを求めるAppleScriptです。

Xcode v9.2+macOS 10.12.6、Xcode v9.3.1+macOS 10.13.5betaで確認しました。

おおまかにいえば、Xcodeは大きくわけて2種類の書類を扱っています。1つは、拡張子「.xcodeproj」のXcodeプロジェクト(Workspace)書類。

そして、個別のソースコード書類(SwiftとかObjective-CとかAppleScriptとか)。

そんなわけで、普通のGUIアプリケーションとはdocumentの概念がやや異なり、少々めんどくさい上にXcodeのAppleScript用語辞書に載っている用例自体も「え、そんな書き方を推奨するの?」という、なんとも不思議な仕上がりになっていますが、まあいいんでしょう。

ちなみに、本ScriptはXcodeのメインウィンドウ上でソースコードを表示する場合と、個別のウィンドウで表示する場合に対応しています。

また、Xcodeのウィンドウ上でXibファイルやInfo.plistやアイコンのAssetsなどソースコード書類以外のものを表示している場合には、エラートラップをかけてfalseを返すようにしています。


▲XcodeのAppleScript用語辞書に書かれている記述例。Workspace Documentのオープン完了待ちをpropertyを確認しつつループで待つという仕様。そんなとこ、非同期実行してドーする、という不思議感満載

AppleScript名:Xcodeでオープン中のソースコードのパスを求める
— Created 2018-05-19 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

tell application "Xcode"
  –最前面のWindowの情報を取得
  
set winProp to properties of front window
  
set aDoc to document of winProp –Xcode のworkspace document(xcodeproj)
  
–> workspace document "WKWebViewDemo.xcodeproj" of application "Xcode"
  
  
set docProp to properties of aDoc
  
set xcodeDocPath to path of docProp
  
–> "/Users/me/Documents/Objective-C/WKWebViewDemo_MAC-master/WKWebViewDemo.xcodeproj"
  
  
set aFileDoc to name of winProp
  
–> "ViewController.m"
  
  
try
    set aDoc to file document aFileDoc
    
–> source document "ViewController.m" of application "Xcode"
  on error
    –Storyboard/Xib file/info.plist/Assetsなどを表示中の場合にはエラーになる
    
return false
  end try
  
  
set aDocPath to path of aDoc
  
–> "/Users/me/Documents/Objective-C/WKWebViewDemo_MAC-master/WKWebViewDemo/ViewController.m"
end tell

★Click Here to Open This Script 

(Visited 195 times, 1 visits today)
Posted in File path | Tagged 10.12savvy 10.13savvy Xcode | Leave a comment

Keynoteスライドの末尾にQRコードのスライドを追加

Posted on 5月 17, 2018 by Takaaki Naganoya

指定の連絡先情報のQRコード画像を作成して、現在オープン中のKeynoteのスライドの末尾に追加するAppleScriptです。

–> Watch Demo Movie

このAppleScriptでは、ただ固定の文字列をQRコード画像化していますが、Contacts(連絡先)から自分の連絡先の情報を取得して、そこからQRコード画像を作成すると、より「AppleScriptらしい」自動処理になると思います。

さらに、このKeynoteのスライドからPDFを書き出して、Slide Shareに自動アップロードし、そのURLもQRコード画像の中に入れると文句のつけようがありません。

AppleScriptによる自動化で「単なる1つのコマンドをScriptから呼び出すだけ」のものを大量に見かけますが、それだとほとんど意味がありません。複数のアプリケーションや複数のサービスを呼び出してそれらを連携させてはじめて「自動化する意味がある」内容になります。

AppleScript名:Keynoteスライドの末尾にQRコードのスライドを追加
— Created 2018-05-16 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"
use framework "QuartzCore"

–QRCodeを作成
set a to "MEMORY:Piyomaru Software
NAME1:長野谷 隆昌
NAME2:ながのや たかあき
TEL1:080-xxxx-xxxxx
MAIL1:maro@piyocast.com
TEL2:080-xxxx-xxxxx
MAIL2:maro@xxxxxxxxx
MECARD:N:長野谷,隆昌;SOUND:ながのや,たかあき;TEL:080-9999-9999;TEL:03-9999-9999;EMAIL:maro@piyocast.com;EMAIL:maro@xxxxx.xxxxx;NOTE:ぴよまる;;"

set savedPath to makeQRCodeImageOnDesktop(a) of me
set savedFile to (POSIX file savedPath)
set savedAlias to savedFile as alias

tell application "Keynote"
  tell front document
    set endSlide to make new slide at end
    
    
set blankMaster to master slide "空白" –"Blank" in Japanese. This string is *localized*
    
    
tell endSlide
      set base slide to blankMaster
      
set thisImage to make new image with properties {file:savedAlias}
    end tell
  end tell
end tell

do shell script "rm -f " & quoted form of savedPath

on makeQRCodeImageOnDesktop(aData)
  set aStr to current application’s NSString’s stringWithString:aData
  
set strData to aStr’s dataUsingEncoding:(current application’s NSShiftJISStringEncoding) –シフトJISにエンコード
  
set qrFilter to current application’s CIFilter’s filterWithName:"CIQRCodeGenerator"
  
qrFilter’s setValue:strData forKey:"inputMessage"
  
qrFilter’s setValue:"H" forKey:"inputCorrectionLevel"
  
set anImage to qrFilter’s outputImage()
  
  
set convImg to convCIimageToNSImage(anImage) of me
  
  
–NSImageを拡大(アンチエイリアス解除で)
  
set resizedImg to my resizeNSImageWithoutAntlialias:convImg toScale:6.0
  
  
–デスクトップに保存
  
set aDesktopPath to (current application’s NSProcessInfo’s processInfo()’s environment()’s objectForKey:("HOME"))’s stringByAppendingString:"/Desktop/"
  
set savePath to aDesktopPath’s stringByAppendingString:((current application’s NSUUID’s UUID()’s UUIDString())’s stringByAppendingString:".png")
  
saveNSImageAtPathAsPNG(resizedImg, savePath) of me
  
  
return savePath as string
end makeQRCodeImageOnDesktop

on convCIimageToNSImage(aCIImage)
  set aRep to current application’s NSBitmapImageRep’s alloc()’s initWithCIImage:aCIImage
  
set tmpSize to aRep’s |size|()
  
set newImg to current application’s NSImage’s alloc()’s initWithSize:tmpSize
  
newImg’s addRepresentation:aRep
  
return newImg
end convCIimageToNSImage

on convNSImageToCIimage(aNSImage)
  set tiffDat to aNSImage’s TIFFRepresentation()
  
set aRep to current application’s NSBitmapImageRep’s imageRepWithData:tiffDat
  
set newImg to current application’s CIImage’s alloc()’s initWithBitmapImageRep:aRep
  
return newImg as string
end convNSImageToCIimage

–NSImageを指定パスにPNG形式で保存
on saveNSImageAtPathAsPNG(anImage, outPath)
  set imageRep to anImage’s TIFFRepresentation()
  
set aRawimg to current application’s NSBitmapImageRep’s imageRepWithData:imageRep
  
set pathString to current application’s NSString’s stringWithString:outPath
  
set newPath to pathString’s stringByExpandingTildeInPath()
  
set myNewImageData to (aRawimg’s representationUsingType:(current application’s NSPNGFileType) |properties|:(missing value))
  
set aRes to (myNewImageData’s writeToFile:newPath atomically:true) as boolean
  
return aRes –成功ならtrue、失敗ならfalseが返る
end saveNSImageAtPathAsPNG

–NSImageを指定倍率で拡大(アンチエイリアス解除状態で)–By Shane Stanley
on resizeNSImageWithoutAntlialias:aSourceImg toScale:imgScale
  set aSize to aSourceImg’s |size|()
  
set aWidth to (aSize’s width) * imgScale
  
set aHeight to (aSize’s height) * imgScale
  
  
set aRep to current application’s NSBitmapImageRep’s alloc()’s initWithBitmapDataPlanes:(missing value) pixelsWide:aWidth pixelsHigh:aHeight bitsPerSample:8 samplesPerPixel:4 hasAlpha:true isPlanar:false colorSpaceName:(current application’s NSCalibratedRGBColorSpace) bytesPerRow:0 bitsPerPixel:0
  
  
set newSize to {width:aWidth, height:aHeight}
  
aRep’s setSize:newSize
  
  
current application’s NSGraphicsContext’s saveGraphicsState()
  
  
set theContext to current application’s NSGraphicsContext’s graphicsContextWithBitmapImageRep:aRep
  
current application’s NSGraphicsContext’s setCurrentContext:theContext
  
theContext’s setShouldAntialias:false
  
theContext’s setImageInterpolation:(current application’s NSImageInterpolationNone)
  
  
aSourceImg’s drawInRect:(current application’s NSMakeRect(0, 0, aWidth, aHeight)) fromRect:(current application’s NSZeroRect) operation:(current application’s NSCompositeCopy) fraction:(1.0)
  
  
current application’s NSGraphicsContext’s restoreGraphicsState()
  
  
set newImg to current application’s NSImage’s alloc()’s initWithSize:newSize
  
newImg’s addRepresentation:aRep
  
  
return newImg
end resizeNSImageWithoutAntlialias:toScale:

★Click Here to Open This Script 

(Visited 559 times, 1 visits today)
Posted in file QR Code | Tagged 10.12savvy 10.13savvy Keynote | Leave a comment

Post navigation

  • Older posts

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

Google Search

Popular posts

  • AppleScriptによるWebブラウザ自動操縦ガイド
  • macOS 13, Ventura(継続更新)
  • ドラッグ&ドロップ機能の未来?
  • macOS 12.x上のAppleScriptのトラブルまとめ
  • PFiddlesoft UI Browserが製品終了に
  • macOS 12.3 beta 5、ASの障害が解消される(?)
  • SF Symbolsを名称で指定してPNG画像化
  • 新刊発売:AppleScriptによるWebブラウザ自動操縦ガイド
  • macOS 12.3上でFinder上で選択中のファイルをそのままオープンできない件
  • Pixelmator Pro v2.4.1で新機能追加+AppleScriptコマンド追加
  • Safariで表示中のYouTubeムービーのサムネイル画像を取得
  • macOS 12のスクリプトエディタで、Context Menu機能にバグ
  • 人類史上初、魔導書の観点から書かれたAppleScript入門書「7つの宝珠」シリーズ開始?!
  • UI Browserがgithub上でソース公開され、オープンソースに
  • macOS 12.5(21G72)がリリースされた!
  • Pages v12に謎のバグ。書類上に11枚しか画像を配置できない→解決
  • 新発売:AppleScriptからSiriを呼び出そう!
  • iWork 12.2がリリースされた
  • macOS 13 TTS Voice環境に変更
  • NSCharacterSetの使い方を間違えた

Tags

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

カテゴリー

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

アーカイブ

  • 2023年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