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

タグ: Finder

Photosで選択中の写真をKeynoteの現在の書類の現在のスライド以降に配置

Posted on 5月 27, 2019 by Takaaki Naganoya

Photosで選択中の写真をKeynoteで現在オープン中の書類の現在のスライド(ページ)以降に配置していくAppleScriptです。

作業の過程をiPhoneで写真撮影。撮影した写真を写真.app(Photos.app)経由でKeynote書類にまとめる作業を行なっていました。作業工程を時間こみで表示できないとわかりにくかったので、Keynoteの各スライドに時刻を入れるようにAppleScriptを書いておきました(同じ作業が二度あるかは不明ですが、二度目からは明らかに時間の節約。つまり時間の貯金ができることになります)。

写真.app(Photos)上でKeynoteに配置したい写真を選択しておき、本Scriptを実行します。

Keynote書類上に新規スライドを追加し、撮影時刻と写真を配置していきます。

実行直後にPhotosで選択中の写真をファイルに書き出すため、若干待たされます。

# 複数のマシンでiCloudを介して写真を同期した場合に、写真.appのライブラリの写真の並び順は撮影日時どおりにならないようなので、明示的にソートしておく必要があるようです

ちなみに、写真の自作キーボードキットはこの後フットペダルにつなぎなおして、PPSSPP用の足踏みコントローラー化する予定です(「戦場の絆ポータブル」用)。

AppleScript名:Photosで選択中の写真をKeynoteの現在の書類の現在のスライド以降に配置
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/05/26
—
–  Copyright © 2019 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"
use BPlus : script "BridgePlus" –https://www.macosxautomation.com/applescript/apps/BridgePlus.html
use mdLib : script "Metadata Lib" version "2.0.0" –https://www.macosxautomation.com/applescript/apps/Script_Libs.html#Metadata_Lib

property NSUUID : a reference to current application’s NSUUID
property NSString : a reference to current application’s NSString
property NSFileManager : a reference to current application’s NSFileManager

tell application "Keynote"
  if (count every document) = 0 then return
end tell

–Photosで選択中の写真をすべて書き出してalias listを取得する
set aList to exportSelectedPhotoOnPhotos() of me
if aList = {} or aList = false then return

set aLen to length of aList

–書き出した画像の親フォルダを求めておく(あとで削除するため)
tell application "Finder"
  set parentFol to parent of (item 1 of aList)
end tell

tell application "Keynote"
  tell front document
    tell current slide
      set curNum to slide number –現在表示中のスライドの番号(ページ数)を取得する
    end tell
    
    
–Photosから取得した写真のアイテム数でループ
    
repeat with i from 1 to aLen
      set aPhoto to contents of item i of aList
      
set newSlide to make new slide at slide (curNum + i) with properties {base slide:master slide "画像(横長)"} –This item is localized!! Maybe a "Photo"
      
set creTime to getCreationTime(aPhoto) of me
      
tell newSlide
        set object text of default title item to creTime
        
set file name of image 1 to aPhoto –place an image to image placeholder
      end tell
      
      
–配置画像を削除
      
tell application "Finder"
        delete aPhoto –配置した写真を削除
      end tell
    end repeat
  end tell
end tell

–あとしまつ
tell application "Finder"
  delete parentFol –画像のダウンロードフォルダを削除
end tell

–指定のaliasからExif情報の作成日の時刻情報を返す
on getCreationTime(anAlias)
  set exifDate to readExifDateTimeOriginal(anAlias) of me
  
return time string of exifDate
end getCreationTime

–Photosで選択中のファイルをtmporaryフォルダに書き出してalias listで返す
on exportSelectedPhotoOnPhotos()
  set dtPath to (path to temporary items) as text
  
set aUUID to NSUUID’s UUID()’s UUIDString() as text
  
  
set dirPath to ((POSIX path of dtPath) & aUUID)
  
set fileManager to NSFileManager’s defaultManager()
  
set aRes to (fileManager’s createDirectoryAtPath:dirPath withIntermediateDirectories:true attributes:(missing value) |error|:(reference))
  
set dtPath to dtPath & aUUID
  
  
tell application "Photos"
    set a to selection
    
if a = {} then return {}
    
set aRes to (export a to file dtPath)
  end tell
  
  
tell application "Finder"
    tell folder dtPath
      set fList to (every file) as alias list
    end tell
  end tell
  
  
if fList = {} then return false
  
return fList
end exportSelectedPhotoOnPhotos

–指定JPEG画像のExif情報からDateTimeOriginalを取得してAS dateオブジェクトに変換して返す
on readExifDateTimeOriginal(aTargFileAlias)
  set theMetadata to readMetadataFrom(aTargFileAlias) of me
  
if theMetadata = false then return false
  
  
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 a to NSString’s stringWithString:exifDate
  
set {aDateStr, aTimeStr} to (a’s componentsSeparatedByString:" ") as list
  
set bDateStr to repChar(aDateStr, ":", "/") of me
  
set fullDate to date (bDateStr & " " & aTimeStr)
  
  
return fullDate
end readExifDateTimeOriginal

–指定のファイルからメタデータを取得する
on readMetadataFrom(imageFile)
  load framework
  
set {theRecord, theError} to current application’s SMSForder’s metadataFromImage:imageFile |error|:(reference)
  
if theRecord = missing value then — there was a problem, so extract the error description
    error false
  else
    return theRecord
  end if
end readMetadataFrom

–文字置換
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

★Click Here to Open This Script 

Posted in Calendar exif file Image list | Tagged 10.12savvy 10.13savvy 10.14savvy Finder Keynote NSFileManager NSString NSUUID Photos | 1 Comment

指定ファイルサイズのJPEGに変換(圧縮率可変)_1K=1024で計算

Posted on 2月 11, 2019 by Takaaki Naganoya

Finder上で選択中の画像ファイルを指定ファイルサイズを下回るよう圧縮率を調整してJPEGに変換するAppleScriptです。

指定画像を指定のファイルサイズ(1K=1024で計算)以内になるよう、非圧縮の状態から段階的に圧縮率を高くして仕上がりファイルサイズを下回るかどうか演算を行います。ファイルに書き込まずに仕上がりサイズの計算を行うところが新機軸です。

macOS標準搭載のスクリプトメニューから呼び出して使うことを想定しています。実行すると、ダイアログ表示して指定ファイルサイズをKB単位で数値入力する必要があります。

巨大な画像ファイルを処理してしまった場合への対処として、最初に最高圧縮率で圧縮してみて、指定ファイルサイズ以内になるかどうかを計算します。

最初は圧縮率100%から25%まで1%きざみで仕上がり画像ファイルサイズを計算してみたのですが、数十Mバイトの巨大な画像を処理させたら、途中でマウスカーソルが反応しないほどOSが無反応になったので(暴走状態?)、それを避けるために、このような処理を行なってみました。

JPEGにファイル変換した画像はデスクトップに

UUID_JPEG画質.jpg

の形式で出力されます。JPEG画質は1.0から0.01までの数値です。

AppleScript名:指定ファイルサイズのJPEGに変換(圧縮率可変)_1K=1024で計算
— Created 2014-02-21 Shane Stanley
— Modified 2019-02-11 Takaaki Naganoya
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
use framework "AppKit"

property |NSURL| : a reference to current application’s |NSURL|
property NSUUID : a reference to current application’s NSUUID
property NSArray : a reference to current application’s NSArray
property NSString : a reference to current application’s NSString
property NSImage : a reference to current application’s NSImage
property NSPredicate : a reference to current application’s NSPredicate
property NSJPEGFileType : a reference to current application’s NSJPEGFileType
property NSBitmapImageRep : a reference to current application’s NSBitmapImageRep
property NSURLTypeIdentifierKey : a reference to current application’s NSURLTypeIdentifierKey

property compressList : {100, 99, 98, 97, 96, 95, 90, 85, 80, 75, 70, 65, 60, 55, 50, 40, 30, 20, 25} –大→小 へと並んでいる必要がある
property kbBase : 1024

tell application "Finder"
  set inFiles to selection as alias list
end tell

–指定のAlias listのうち画像ファイルのみ抽出
set filRes1 to filterAliasListByUTI(inFiles, "public.image") of me
if filRes1 = {} then return

–ターゲットサイズを指定
set aMessage to "Input Target size in KB ( " & (kbBase as string) & " based )"
set aRes to text returned of (display dialog aMessage default answer "300" buttons {"OK"} default button 1)
if aRes = false or aRes = "" then return
set targLimit to (aRes as number) * kbBase

–選択中のファイルのうちの1つから親フォルダを求め、出力先ファイルパスを組み立てる
set outPathTarg to (contents of first item of filRes1)
set pathString to NSString’s stringWithString:outPathTarg
set newPath to (pathString’s stringByDeletingLastPathComponent()) as string

–Main Loop
repeat with i in filRes1
  set aNSImage to (NSImage’s alloc()’s initWithContentsOfFile:(i))
  
  
–巨大すぎる画像のリサイズ時への保険で、最小サイズで投機的に圧縮して結果を確認する
  
set minSize to calcSavedJPEGSizeFromNSIMage(aNSImage, (last item of compressList) / 100) of me
  
  
if minSize < targLimit then
    –Simulate Suitable JPEG Compression Ratio to target file size
    
repeat with ii in compressList
      set jj to ii / 100
      
set fileSize to calcSavedJPEGSizeFromNSIMage(aNSImage, jj) of me
      
      
if fileSize < targLimit then
        exit repeat
      end if
    end repeat
  else
    set jj to 0.01 –エラー時にはやけくそで1%まで圧縮指定
  end if
  
  
set outPOSIXpath to (newPath & "/" & (NSUUID’s UUID()’s UUIDString()) as string) & "_" & (jj as string)
  
set savePath to outPOSIXpath & ".jpg"
  
  
saveNSImageAtPathAsJPG(aNSImage, savePath, jj) of me
end repeat

–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

–NSImageを指定パスにJPEG形式で保存、qulityNumは0.0〜1.0。1.0は無圧縮
on saveNSImageAtPathAsJPG(anImage, outPath, qulityNum as real)
  set imageRep to anImage’s TIFFRepresentation()
  
set aRawimg to NSBitmapImageRep’s imageRepWithData:imageRep
  
set pathString to NSString’s stringWithString:outPath
  
set newPath to pathString’s stringByExpandingTildeInPath()
  
set myNewImageData to (aRawimg’s representationUsingType:(NSJPEGFileType) |properties|:{NSImageCompressionFactor:qulityNum})
  
  
set aLength to (myNewImageData’s |length|()) as number
  
  
set aRes to (myNewImageData’s writeToFile:newPath atomically:true) as boolean
  
return aRes –true/false
end saveNSImageAtPathAsJPG

–NSImageをJPEG形式で保存したときのファイルサイズを計算
on calcSavedJPEGSizeFromNSIMage(anImage, qulityNum as real)
  set imageRep to anImage’s TIFFRepresentation()
  
set aRawimg to NSBitmapImageRep’s imageRepWithData:imageRep
  
set myNewImageData to (aRawimg’s representationUsingType:(NSJPEGFileType) |properties|:{NSImageCompressionFactor:qulityNum})
  
set aLength to (myNewImageData’s |length|()) as number
  
return aLength
end calcSavedJPEGSizeFromNSIMage

★Click Here to Open This Script 

Posted in file Image list UTI | Tagged 10.11savvy 10.12savvy 10.13savvy 10.14savvy Finder NSArray NSBitmapImageRep NSImage NSPredicate NSString NSURL NSURLTypeIdentifierKey NSUUID | Leave a comment

マウント中のドライブをアンマウント

Posted on 10月 7, 2018 by Takaaki Naganoya

マウント中のドライブのうち、起動ドライブを除いたものをアンマウントします。

NSWorkspace経由でアンマウントするものと、OLD Style AppleScriptでFinder経由でアンマウントするものを掲載しておきます。

ただし、Time Machineのバックアップドライブなど、NSWorkspace経由ではアンマウントできないものもあり、「どちらがいい」とも言い切れない様子です。

–> Download Blank Disk Image for test

AppleScript名:NSWorkSpace経由でアンマウント.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2018/10/07
—
–  Copyright © 2018 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use scripting additions

set aPath to retDrivePosixPath() of me
if aPath = false then return

set aWS to current application’s NSWorkspace’s sharedWorkspace()
set aRes to aWS’s unmountAndEjectDeviceAtPath:aPath

on retDrivePosixPath()
  tell application "Finder"
    set dList to properties of every disk whose startup is false and size > 0
    
    
if length of dList > 1 then
      –複数の対象ドライブがある場合にはユーザーに選択させる
      
set dnList to name of every disk whose startup is false and size > 0
      
–set dnList to name of every disk whose startup is false
      
set dRes to choose from list dnList
      
set driveProp to (properties of disk dRes)
      
set driveURL to URL of driveProp
    else if dList = {} then
      return false
    else
      set driveURL to URL of first item of dList
    end if
    
  end tell
  
  
set dPath to ((current application’s |NSURL|’s URLWithString:driveURL)’s |path|()) as string
  
return dPath
end retDrivePosixPath

★Click Here to Open This Script 

AppleScript名:OLD style AppleScriptでアンマウント可能なドライブをアンマウント
—
–  Created by: Takaaki Naganoya
–  Created on: 2018/10/07
—
–  Copyright © 2018 Piyomaru Software, All Rights Reserved
—
set dName to retEjectableDriveName() of me
if dName = false then return

tell application "Finder" to eject disk dName

on retEjectableDriveName()
  tell application "Finder"
    set dList to properties of every disk whose startup is false and size > 0
    
    
if length of dList > 1 then
      –複数の対象ドライブがある場合にはユーザーに選択させる
      
set dnList to name of every disk whose startup is false and size > 0
      
set dRes to choose from list dnList
    else if dList = {} then
      return false
    else
      set dRes to name of first item of dList
    end if
    
    
return dRes
  end tell
end retEjectableDriveName

★Click Here to Open This Script 

Posted in drive | Tagged 10.11savvy 10.12savvy 10.13savvy 10.14savvy Finder NSWorkspace | Leave a comment

iCloud Driveフォルダへのパスを求める

Posted on 9月 16, 2018 by Takaaki Naganoya

iCloud Driveフォルダへのパスを求めるAppleScriptです。

ただ、これほどわかりにくいものも珍しいことでしょう。自分も避けておきたい仕様です。

パスについての仕様はあり、ファイルの読み書きなどはできそうですが、求めたパスをFinder上で指定すると不思議なことになります。

Finderのサイドバーから「iCloud Drive」アイコンをクリックすると、

のような表示になります。このときのFinder Windowのtargetを取得すると、~/Library/Mobile Documentsが返ってきます(形式はFinder Objectですけれども)。ただ、これと同じことをAppleScript側から行なっても、同じ結果が得られないというジレンマがあります。

~/Library/Mobile Documents

AppleScript名:iCloud Drivegフォルダへのパスを求める
set iCloudPath to ((path to library folder from user domain as string)) & "Mobile Documents:"
tell application "Finder"
  make new Finder window
  
set target of Finder window 1 to (iCloudPath as alias)
end tell

★Click Here to Open This Script 

これは、~/Library/Mobile Documentsをオープンするものですが、これを実行すると、

のようになります。

~/Library/Mobile Documents/com~apple~CloudDocs

これみたいですね。

AppleScript名:iCloud Drivegフォルダへのパスを求める(com~apple~CloudDocs フォルダ)
set iCloudPath to ((path to library folder from user domain as string)) & "Mobile Documents:com~apple~CloudDocs"
tell application "Finder"
  make new Finder window
  
set target of Finder window 1 to (iCloudPath as alias)
end tell

★Click Here to Open This Script 

これは、~/Library/iCloud Drive/com~apple~CloudDocsをオープンするものですが、これを実行すると、

となります。

Terminal上で当該フォルダを表示させてフォルダ名を再度確認してみたところ、きっとこれです。

Posted in File path System | Tagged 10.11savvy 10.12savvy Finder | Leave a comment

Finder上で選択中の画像のうち、最小のものに合わせて各画像の左上を原点にサイズ統一

Posted on 7月 27, 2018 by Takaaki Naganoya

Finderで選択中の画像のうち、最小のものに合わせて各画像の左上を原点にサイズを統一するAppleScriptです。

Finderで選択中のファイルから画像のみ抽出し、そのうちサイズが最小のものに合わせて他の画像をトリミングし、変更したものをデスクトップフォルダに出力します。


▲大きさを揃える画像をFinder上で選択


▲処理前の画像。大きさがまちまち


▲処理後の画像。大きさが最小の画像に合わせてそろっている

スクリーンショット画像を複数撮った場合に、厳密に同じサイズに固定することは(各種スクリーンショット作成ユーティリティを使わないと)行いづらいところです。

そこで、最小の画像を計算で求めて、それに合わせて自動トリミングするようにしてみました。Cocoaの機能を用いて画像処理しているため、Photoshopは必要ありません。

最小の画像を求めるのに、幅+高さの値でソートして最小のものを求めています(widthとheightによる2 key sortではなく1 Keyで済ませたかったので)。

Blogや書籍用の掲載画面図の作成用、といったところでしょうか。Retina画面で撮ったスクリーンショットと非Retina画面のスクリーンショットが混在するとうまく動きません(スクリーンショット画像からはRetina環境で撮った画像であるかどうかを取得できません)。

スクリーンショットの画像からRetina/非Retina環境で撮ったかを判定するのは、(Retina対応機であるかをMachine IDから取得したあとで)Syslogにアクセスしてスクリーンが接続されたか、取り外されたかといった状態を追っていくしかないのかも。

本ScriptをmacOS 10.13.6上で動作確認して驚いたのですが、いままでRecordが返ってくるべき箇所でlistが返ってくる盛大なバグが直って、本ScriptがmacOS 10.13用に書き換えずに動きました(動かないことを確認しようとして動いたので驚いた)。

AppleScript名:Finder上で選択中の画像のうち、最小のものに合わせて各画像の左上を原点にサイズ統一 v2
— Created 2018-07-23 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
use framework "AppKit"
use framework "QuartzCore"

property |NSURL| : a reference to current application’s |NSURL|
property NSUUID : a reference to current application’s NSUUID
property NSArray : a reference to current application’s NSArray
property NSString : a reference to current application’s NSString
property NSImage : a reference to current application’s NSImage
property NSScreen : a reference to current application’s NSScreen
property NSZeroRect : a reference to current application’s NSZeroRect
property NSPredicate : a reference to current application’s NSPredicate
property NSPNGFileType : a reference to current application’s NSPNGFileType
property NSMutableArray : a reference to current application’s NSMutableArray
property NSCompositeCopy : a reference to current application’s NSCompositeCopy
property NSGraphicsContext : a reference to current application’s NSGraphicsContext
property NSBitmapImageRep : a reference to current application’s NSBitmapImageRep
property NSURLTypeIdentifierKey : a reference to current application’s NSURLTypeIdentifierKey
property NSCalibratedRGBColorSpace : a reference to current application’s NSCalibratedRGBColorSpace

tell application "Finder"
  set selList to selection as alias list
end tell

–指定のAlias listのうち画像のみ抽出
set filRes1 to filterAliasListByUTI(selList, "public.image") of me
if filRes1 = {} then
  tell current application
    –Error Message (No Selection)
    
display dialog "Finder上で選択されているファイルはありません。" buttons {"OK"} default button 1 with icon 1 with title "画像リサイズ処理できません"
  end tell
  
return
end if

–各種情報を入れたArrayを作成
set anArray to NSMutableArray’s new()
repeat with i in selList
  set imgPath to (POSIX path of i)
  
  
set aImage to makeNSImageFromFile(i) of me
  
set sizeInfo to |size|() of aImage
  
set sizeInfo to sizeInfo & {aImg:aImage, total:(width of sizeInfo) + (height of sizeInfo), myPath:imgPath}
  (
anArray’s addObject:sizeInfo)
end repeat

–最小のサイズの画像の算出
set aRes to anArray’s valueForKeyPath:("@min.total")
set bRes to first item of (filterRecListByLabel(anArray, "total == " & aRes as string) of me) –最小サイズの画像

–最小サイズ画像のwidthとheight
set minWidth to bRes’s width
set minHeight to bRes’s height

–環境情報の取得
set aPath to POSIX path of (path to desktop)
set retinaF to (NSScreen’s mainScreen()’s backingScaleFactor()) as real
–>  2.0 (Retina) / 1.0 (Non Retina)

set cRes to filterRecListByLabel(anArray, "total != " & aRes as string) of me –最小サイズ以外の画像

repeat with i in cRes
  set j to contents of i
  
set anImage to aImg of j
  
set fRes to myPath of j
  
  
set cropedImage to (my cropNSImageBy:{0, 0, minWidth, minHeight} fromImage:anImage) –v1で間違っていた
  
  
–Retina環境対策
  
if retinaF > 1.0 then
    set cropedImage to (my resizedImage:cropedImage toScale:(1.0))
  end if
  
  
–ファイル書き込み
  
set fRes to retUUIDfilePathFromDir(aPath, "png") of me
  
set sRes to saveNSImageAtPathAsPNG(cropedImage, fRes) of me
end repeat

–リストに入れたレコードを、指定の属性ラベルの値で抽出
on filterRecListByLabel(aRecList as list, aPredicate as string)
  –ListからNSArrayへの型変換
  
set aArray to NSArray’s arrayWithArray:aRecList
  
  
–抽出
  
set aPredicate to NSPredicate’s predicateWithFormat:aPredicate
  
set filteredArray to aArray’s filteredArrayUsingPredicate:aPredicate
  
  
–NSArrayからListに型変換して返す
  
set bList to filteredArray as list
  
return bList
end filterRecListByLabel

–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

on cropNSImageTo:{x1, y1, x2, y2} fromImage:theImage
  set newWidth to x2 – x1
  
set newHeight to y2 – y1
  
set theSize to (theImage’s |size|()) as record
  
set oldHeight to height of theSize
  
  
— transpose y value for Cocoa coordintates
  
set y1 to oldHeight – newHeight – y1
  
set newRect to {{x:x1, y:y1}, {width:newWidth, height:newHeight}}
  
theImage’s lockFocus()
  
set theRep to NSBitmapImageRep’s alloc()’s initWithFocusedViewRect:newRect
  
theImage’s unlockFocus()
  
  
set outImage to NSImage’s alloc()’s initWithSize:(theRep’s |size|())
  
outImage’s addRepresentation:theRep
  
  
return outImage
end cropNSImageTo:fromImage:

on makeNSImageFromFile(anAlias)
  set imgPath to (POSIX path of anAlias)
  
set aURL to (|NSURL|’s fileURLWithPath:(imgPath))
  
return (NSImage’s alloc()’s initWithContentsOfURL:aURL)
end makeNSImageFromFile

–NSImageを指定の大きさでトリミング
on cropNSImageBy:{x1, y1, newWidth, newHeight} fromImage:theImage
  set theSize to (theImage’s |size|()) as record
  
set oldHeight to height of theSize
  
  
— transpose y value for Cocoa coordintates
  
set y1 to oldHeight – newHeight – y1
  
set newRect to {{x:x1, y:y1}, {width:newWidth, height:newHeight}}
  
theImage’s lockFocus()
  
set theRep to NSBitmapImageRep’s alloc()’s initWithFocusedViewRect:newRect
  
theImage’s unlockFocus()
  
  
set outImage to NSImage’s alloc()’s initWithSize:(theRep’s |size|())
  
outImage’s addRepresentation:theRep
  
  
return outImage
end cropNSImageBy:fromImage:

on retUUIDfilePathFromDir(aPath, aEXT)
  set aUUIDstr to (NSUUID’s UUID()’s UUIDString()) as string
  
set aPath to ((NSString’s stringWithString:aPath)’s stringByAppendingPathComponent:aUUIDstr)’s stringByAppendingPathExtension:aEXT
  
return aPath
end retUUIDfilePathFromDir

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

on resizedImage:aSourceImg toScale:imgScale
  if (aSourceImg’s isValid()) as boolean = false then error "Invalid NSImage"
  
  
set aSize to aSourceImg’s |size|()
  
–>  {​​​​​width:32.0, ​​​​​height:32.0​​​}
  
  
set aWidth to (aSize’s width) * imgScale
  
set aHeight to (aSize’s height) * imgScale
  
  
set aRep to NSBitmapImageRep’s alloc()’s initWithBitmapDataPlanes:(missing value) pixelsWide:aWidth pixelsHigh:aHeight bitsPerSample:8 samplesPerPixel:4 hasAlpha:true isPlanar:false colorSpaceName:(NSCalibratedRGBColorSpace) bytesPerRow:0 bitsPerPixel:0
  
  
set newSize to {width:aWidth, height:aHeight}
  
aRep’s setSize:newSize
  
  
NSGraphicsContext’s saveGraphicsState()
  
NSGraphicsContext’s setCurrentContext:(NSGraphicsContext’s graphicsContextWithBitmapImageRep:aRep)
  
  
aSourceImg’s drawInRect:(current application’s NSMakeRect(0, 0, aWidth, aHeight)) fromRect:(NSZeroRect) operation:(NSCompositeCopy) fraction:(1.0)
  
  
NSGraphicsContext’s restoreGraphicsState()
  
  
set newImg to NSImage’s alloc()’s initWithSize:newSize
  
newImg’s addRepresentation:aRep
  
  
return newImg
end resizedImage:toScale:

★Click Here to Open This Script 

Posted in file Image | Tagged 10.11savvy 10.12savvy 10.13savvy Finder NSArray NSBitmapImageRep NSImage NSMutableArray NSPredicate NSScreen NSString NSURL NSUUID | 1 Comment

Finder上で選択中のMarkdown書類をファイル名で昇順ソート(A→Z)して、各書類のタイトル見出しを取得する

Posted on 7月 8, 2018 by Takaaki Naganoya

Finder上で選択中のMarkdown書類を取得し、ファイル名で昇順ソート(A→Z)して、各Markdown書類中のタイトルのうち最もレベルの高い(重要な)ものを抽出し、まとめてテキストにしてクリップボードに転送するAppleScriptです。

大量にあるMarkdown書類の本文中から一番重要なタイトルを抽出する作業を……さすがに手作業で行うわけには行かなかったので、AppleScriptを書いて処理してみました。ただし、新規に書いた処理はほとんどなく、既存のルーチンの寄せ合わせで構成しています。

Finder上でMarkdown書類を選択した状態で本Scriptを実行すると(Markdown書類以外は除外して)、AppleScriptでMarkdown書類を読み込んで(Markdown書類がUTF-8固定なのでUTF-8を指定して読み込み)、正規表現で書類中のタイトルを抽出し、重要なタイトル(#の個数が少ない)をピックアップ。これをすべての書類について行います。

処理結果をクリップボードに転送します。

最終的には、(手作業で加工して)このようになります。

若干の手作業は発生してしまいますが、このScriptを組まなかったら、とてもその手作業を行う気も起こらなかったわけで、、、

AppleScript名:Finder上で選択中のMarkdown書類をファイル名で昇順ソート(A→Z)して、各書類のタイトル見出しを取得する
— Created 2018-06-26 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "Quartz"
use mdLib : script "Metadata Lib" version "1.0.0"
use bPlus : script "BridgePlus" –https://www.macosxautomation.com/applescript/apps/BridgePlus.html

property |NSURL| : a reference to current application’s |NSURL|
property NSArray : a reference to current application’s NSArray
property NSString : a reference to current application’s NSString
property SMSForder : a reference to current application’s SMSForder
property NSIndexSet : a reference to current application’s NSIndexSet
property NSPredicate : a reference to current application’s NSPredicate
property NSMutableSet : a reference to current application’s NSMutableSet
property NSFileManager : a reference to current application’s NSFileManager
property NSCountedSet : a reference to current application’s NSCountedSet
property NSURLPathKey : a reference to current application’s NSURLPathKey
property NSMutableArray : a reference to current application’s NSMutableArray
property NSURLNameKey : a reference to current application’s NSURLNameKey
property NSSortDescriptor : a reference to current application’s NSSortDescriptor
property NSURLIsPackageKey : a reference to current application’s NSURLIsPackageKey
property NSRegularExpression : a reference to current application’s NSRegularExpression
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 NSRegularExpressionAnchorsMatchLines : a reference to current application’s NSRegularExpressionAnchorsMatchLines
property NSDirectoryEnumerationSkipsHiddenFiles : a reference to current application’s NSDirectoryEnumerationSkipsHiddenFiles
property NSRegularExpressionDotMatchesLineSeparators : a reference to current application’s NSRegularExpressionDotMatchesLineSeparators

load framework

–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のうちMarkdown書類のみ抽出
set filRes1 to filterAliasListByUTI(inFiles, "net.daringfireball.markdown") of me

–指定のPOSIX path listから、各Markdown書類中の一番重要な見出しを抽出して返す
set tRes to listTitlesFromMarkdownDocPathList(filRes1) of me

–取得したタイトル一覧リストをテキストに変換
set t2Res to retStrFromArrayWithDelimiter(tRes, return) of me

–クリップボードに結果を転送
set the clipboard to t2Res

on listTitlesFromMarkdownDocPathList(inFiles)
  set outList to {}
  
set inFilesSorted to my filesInListSortAscending(inFiles)
  
  
repeat with i in inFilesSorted
    –POSIX pathからaliasにパス変換してテキスト読み込み
    
set j to POSIX file (contents of i)
    
set jj to j as alias
    
set aStr to (read jj as «class utf8»)
    
    
set aList to retHeaders(aStr) of me –Markdown書類中の見出しをリストアップ
    
–>  {​​​​​{​​​​​​​1, ​​​​​​​" 2008/3/9 5桁の乱数を生成"​​​​​}​​​}
    
    
if aList is not equal to {} then
      –2D Listの昇順ソート
      
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
      
      
set aCon to contents of second item of first item of resList
      
set the end of outList to aCon
    end if
  end repeat
  
return outList
end listTitlesFromMarkdownDocPathList

on filesInListSortAscending(aliasList as list)
  set cList to {}
  
repeat with i in aliasList
    set j to contents of i
    
set aFileName to ((current application’s NSString’s stringWithString:j)’s valueForKeyPath:"lastPathComponent")
    
set the end of cList to {fileName:aFileName, pathDat:j}
  end repeat
  
  
set aResList to sortRecListByLabel(cList, "fileName", true) of me –昇順ソート
  
set bResList to (aResList’s valueForKeyPath:"pathDat") as list of string or string
  
return bResList
end filesInListSortAscending

–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

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

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

–見出し抽出用サブルーチン群
on retHeaders(aCon)
  set tList to {}
  
set regStr to "^#{1,6}[^#]*?$"
  
  
set headerList to my findPattern:regStr inString:aCon
  
repeat with i in headerList
    set j to contents of i
    
set regStr2 to "^#{1,6}[^#]*?"
    
set headerLevel to length of first item of (my findPattern:regStr2 inString:j)
    
set the end of tList to {headerLevel, text (headerLevel + 1) thru -1 in j}
  end repeat
  
  
return tList
end retHeaders

on findPattern:thePattern inString:theString
  set theOptions to ((NSRegularExpressionDotMatchesLineSeparators) as integer) + ((NSRegularExpressionAnchorsMatchLines) as integer)
  
set theRegEx to NSRegularExpression’s regularExpressionWithPattern:thePattern options:theOptions |error|:(missing value)
  
set theFinds to theRegEx’s matchesInString:theString options:0 range:{location:0, |length|:length of theString}
  
set theFinds to theFinds as list — so we can loop through
  
set theResult to {} — we will add to this
  
set theNSString to NSString’s stringWithString:theString
  
repeat with i from 1 to count of items of theFinds
    set theRange to (item i of theFinds)’s range()
    
set end of theResult to (theNSString’s substringWithRange:theRange) as string
  end repeat
  
return theResult
end findPattern:inString:

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

★Click Here to Open This Script 

Posted in file list Markdown regexp Sort Text | Tagged 10.11savvy 10.12savvy 10.13savvy Finder NSArray NSCountedSet NSDirectoryEnumerationSkipsHiddenFiles NSFileManager NSIndexSet NSMutableArray NSMutableSet NSPredicate NSRegularExpression NSRegularExpressionAnchorsMatchLines NSRegularExpressionDotMatchesLineSeparators NSSortDescriptor NSString NSURL NSURLContentModificationDateKey NSURLIsDirectoryKey NSURLIsPackageKey NSURLNameKey NSURLPathKey NSURLTypeIdentifierKey | 3 Comments

最前面のFinder Windowをクローン

Posted on 7月 4, 2018 by Takaaki Naganoya

Finderの最前面のウィンドウを、同じ対象フォルダ&同じビュー形式で新規作成するAppleScriptです。

昔どこかで拾ってきたものを使い続けているものです。利用頻度はかなり高く、ファイルの整理をFinder上で行なっているときには、たいてい利用しています。

ファイル作成日が2011年になっていましたが、実際にはさらに古い時期のものだと思います。

開けてみて驚きました(v1)。海外のScripterとの間でなんとなく成立している、

 ・過度に英文っぽく書かない
 ・「the」の乱発はやらない(できてもやらない)
 ・過度に短縮記述は行わない
 ・よほどの必要性がないかぎり、暗黙の実行結果「result」は使わない(何を処理しているかがわかりにくいので)
 ・「get」は省略できる場合が多いので、あえて書かない

というお約束が守られておらず、「the」は入りまくっているわ、「get」が無意味に(この後でresultで受け取っていたのだろうか)使われているわで、読みにくいことこのうえない代物でした。

そこで、v2のように書き換えました。これならかなり読みやすく、わかりやすく、無駄な処理もありません。

はるかかなた昔のAppleScriptの中には、今見るとあまり書きこなれていない記述もあったりして、読み直すとかなり驚くものがたくさんあります。

AppleScript名:最前面のWindowをクローン v1
tell application "Finder"
  set sDisk to (name of startup disk) & ":"
  
  
get the exists of the front Finder window –なにこれ???
  
if the (exists of the front Finder window) is true then
    try
      set newWindow to target of front window
      
set oldView to current view of front window
      
make new Finder window to newWindow
      
set current view of front window to oldView
    end try
  else
    try
      make new Finder window to alias sDisk
      
set the current view of the front Finder window to column view
    end try
  end if
end tell

★Click Here to Open This Script 

AppleScript名:最前面のFinder Windowをクローン v2
tell application "Finder"
  set wEx to (exists of front Finder window)
  
  
if wEx = true then
    try
      set winRef to a reference to front window
      
set curTarget to target of winRef
      
set curView to current view of winRef
      
make new Finder window to curTarget
      
set current view of winRef to curView
    end try
  else
    try
      make new Finder window
      
set current view of front Finder window to list view
    end try
  end if
end tell

★Click Here to Open This Script 

Posted in GUI | Tagged 10.11savvy 10.12savvy 10.13savvy Finder | Leave a comment

指定フォルダ内の指定拡張子のファイルのうち、指定キーワードで始まるものを

Posted on 7月 3, 2018 by Takaaki Naganoya

指定フォルダ(デスクトップ)内の指定拡張子のファイルのうち、ファイル名が指定キーワードではじまるものを抽出するAppleScriptです。

AppleScriptでは定番の処理ですが、Finderが10.7あたりでCocoa化されて書き直しが行われたあたりからフィルタ参照を併用した条件抽出のパフォーマンスが大幅に低下。

アプリケーション間通信でパフォーマンスを低下させないための機能であるフィルタ参照が、かえって処理速度を低下させるというたいへん皮肉な事態に。

AppleScript名:指定フォルダ内の指定拡張子のファイルのうち、指定キーワードで始まるものをaliasリストで返す(Finder Version)
tell application "Finder"
  tell folder (path to desktop)
    set aList to (every file whose name starts with "スナップショット" and kind of it is "PNGイメージ") as alias list
  end tell
end tell

★Click Here to Open This Script 

Finder経由で行うと、処理時間は驚愕の4.6秒(67項目から1項目を抽出するだけの処理です)。これをCocoaの機能を用いて処理すると0.002秒。同じAppleScriptなのに2,000倍以上高速。逆にいえば、現在のFinder経由でのファイル処理の速度は遅すぎです。

macOS 10.10以降では、各種ファイル処理についてはFinderではなくCocoaの機能を用いたほうがよいでしょう。

その他、Finder上で選択中のファイルの一覧を取得するとか、Finder上で選択中のフォルダを取得するといった処理であればパフォーマンスの低下はないので、使っても(処理速度上の)問題はありません。

AppleScript名:指定フォルダ内の指定拡張子のファイルのうち、指定キーワードで始まるものをPOSIX pathリストで返す
— Created 2015-10-01 by Takaaki Naganoya
— Modified 2015-10-01 by Shane Stanley–With Cocoa-Style Filtering
— Modified 2018-07-03 by Takaaki Naganoya–Added filtering feature
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"

property |NSURL| : a reference to current application’s |NSURL|
property NSPredicate : a reference to current application’s NSPredicate
property NSFileManager : a reference to current application’s NSFileManager
property NSDirectoryEnumerationSkipsHiddenFiles : a reference to current application’s NSDirectoryEnumerationSkipsHiddenFiles

set aExtension to "png" — no dot
set aKeyword to "スナップショット" –"Snapshot" in Japanese
set aTargetFolder to POSIX path of (path to desktop folder)

set fList to getFilePathListByExtAndKeyword(aTargetFolder, aExtension, aKeyword) of me
–>  {"/Users/me/Desktop/スナップショット-2018-07-03 at 11_42_12 AM-1696613812.png"}

on getFilePathListByExtAndKeyword(aFol, aExt, aKeyword)
  set aFM to NSFileManager’s defaultManager()
  
set aURL to |NSURL|’s fileURLWithPath:aFol
  
set urlArray to aFM’s contentsOfDirectoryAtURL:aURL includingPropertiesForKeys:{} options:(NSDirectoryEnumerationSkipsHiddenFiles) |error|:(missing value)
  
set thePred to NSPredicate’s predicateWithFormat:"pathExtension == [c]%@ && lastPathComponent BEGINSWITH %@" argumentArray:{aExt, aKeyword}
  
set anArray to (urlArray’s filteredArrayUsingPredicate:thePred)
  
if anArray = missing value then return {}
  
return (anArray’s valueForKeyPath:"path") as list
end getFilePathListByExtAndKeyword

★Click Here to Open This Script 

Posted in file | Tagged 10.11savvy 10.12savvy 10.13savvy Finder NSDirectoryEnumerationSkipsHiddenFiles NSFileManager NSPredicate NSURL | Leave a comment

Finder上で選択中のPDFのファイル名の数字部分で小さいものから大きなものへとソート

Posted on 6月 27, 2018 by Takaaki Naganoya

Finder上で選択中のPDFのうち、ファイル名中の数字が小さいものから大きなものへソートを行うAppleScriptです。

Finder上で選択中のPDFをファイル名順でソートするような用途に使用します。選択中のファイルのうちPDFに該当しないものは無視します。

Finderで選択中の各PDFファイルに数字以外の文字がファイル名に混入していても無視します。

ファイル名はいったん数値として評価してソートするため、ファイル名にゼロパディングしてある場合には無視します。

Finder上で選択中のPDFを連結するさいに、ファイル名順で連結するScriptがあったほうが便利なので、そのために作ったものです。

ソートを行う際に、ファイル名の中の数字以外の部分をすべて無視するようにしています。そのため、Finder上の並び順と関係なく、ファイル名の中の数字部分のみをピックアップしてソートします。Finder自体にもFinderのルールでファイル名をソートして返すAppleScriptの機能がありますが、あれに甘えているとまともな処理はできません。

「test1_0004.pdf」というファイル名があった場合には10004という数値を検出するため、こうしたケースに対応する必要があるかもしれませんが、現時点では無用な数字の除去はしていません(それこそ一括処理で行うものではなくユーザーの目で見て判断してもらうような処理なので)。

AppleScript名:Finder上で選択中のPDFの数字のファイル名で小さいものから大きなものへとソート
— Created 2018-06-26 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use mdLib : script "Metadata Lib" version "1.0.0" –https://www.macosxautomation.com/applescript/apps/
use bPlus : script "BridgePlus" –https://www.macosxautomation.com/applescript/apps/BridgePlus.html

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 NSURLTypeIdentifierKey : a reference to current application’s NSURLTypeIdentifierKey

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

–ファイル名
set cList to {}
repeat with i in (filRes1 as list)
  set j to contents of i
  
set aFileName to ((current application’s NSString’s stringWithString:j)’s valueForKeyPath:"lastPathComponent.stringByDeletingPathExtension")
  
  
set aNumF to returnNumberCharsOnly(aFileName) of me
  
set the end of cList to {numDat:(aNumF as integer), pathDat:j}
end repeat

set aResList to sortRecListByLabel(cList, "numDat", true) of me –昇順ソート
set bResList to (aResList’s valueForKeyPath:"pathDat") as list of string or string
–>  {​​​​​"/Users/me/Pictures/243.pdf", ​​​​​"/Users/me/Pictures/244.pdf", ​​​​​"/Users/me/Pictures/245.pdf", ​​​​​"/Users/me/Pictures/246.pdf", ​​​​​"/Users/me/Pictures/247.pdf", ​​​​​"/Users/me/Pictures/248.pdf", ​​​​​"/Users/me/Pictures/249.pdf", ​​​​​"/Users/me/Pictures/250.pdf", ​​​​​"/Users/me/Pictures/251.pdf", ​​​​​"/Users/me/Pictures/252.pdf", ​​​​​"/Users/me/Pictures/253.pdf", ​​​​​"/Users/me/Pictures/254.pdf", ​​​​​"/Users/me/Pictures/255.pdf", ​​​​​"/Users/me/Pictures/256.pdf", ​​​​​"/Users/me/Pictures/257.pdf"​​​}

–文字列中から
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

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

–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 

Posted in file File path PDF Sort | Tagged 10.11savvy 10.12savvy 10.13savvy Finder | Leave a comment

Finderで選択中のPDFを反時計方向に90°回転させる

Posted on 6月 4, 2018 by Takaaki Naganoya

Finder上で選択中のPDFを反時計方向に90°回転(=時計方向に270°回転)させるAppleScriptです。

Finder上で選択中の項目の中にPDF以外のものがあった場合には処理をスキップし、選択中のアイテムがない場合には処理を行いません。

実際には、macOS標準装備のScript Menuに、それぞれの角度(90°、180°、270°)への回転Scriptを個別に入れて使っています。1本のScriptで角度入力を行って回転させるよりも、あらかじめ固定の角度に回転させるものを複数用意しておいたほうが使い勝手がよいためです。

ドキュメントスキャナで紙の資料をPDFにスキャンするような時に、紙がヨレていて1枚ずつでないとスキャンできないような場合で、さらに穴が空いていたりヨレていて通常方向に紙を入れられなかった場合に、他の方向に入れてスキャンしておき、本Scriptのようなプログラムであとでまとめて回転させるなどの処理をよく行っています。

AppleScript名:Finderで選択中のPDFを反時計方向に90°回転させる
— Created 2018-05-26 by Takaaki Naganoya
— Modified 2018-06-02 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 NSUUID : a reference to current application’s NSUUID
property NSArray : a reference to current application’s NSArray
property NSString : a reference to current application’s NSString
property NSPredicate : a reference to current application’s NSPredicate
property PDFDocument : a reference to current application’s PDFDocument
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 targDegree to 270 — targDegree have to be in {0, 90, 180, 270, 360} in clockwise

–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
if filRes1 = {} then return

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

repeat with i in filRes1
  set destPosixPath to newPath & "/" & ((NSUUID’s UUID()’s UUIDString()) as string) & ".pdf"
  
rotatePDFandSaveAt(i, destPosixPath, targDegree) of me
end repeat

–与えられたPOSIX pathのPDFを指定の角度に回転させて新規指定パスに書き出す
on rotatePDFandSaveAt(oldPath as string, newPath as string, aDegree as integer)
  
  
–Error Check
  
if aDegree is not in {0, 90, 180, 270, 360} then error "Wrong Degree"
  
  
set aURL to current application’s |NSURL|’s fileURLWithPath:oldPath
  
set aPDFdoc to PDFDocument’s alloc()’s initWithURL:aURL
  
  
set pCount to aPDFdoc’s pageCount() –count pages
  
  
–Make Blank PDF
  
set newPDFdoc to PDFDocument’s alloc()’s init()
  
  
–Rotate Each Page
  
repeat with i from 0 to (pCount – 1)
    set aPage to (aPDFdoc’s pageAtIndex:i)
    
    
–Set Degree
    
set curDegree to aPage’s |rotation|() –Get Current Degree
    (
aPage’s setRotation:(aDegree + curDegree)) –Set New Degree
    
    (
newPDFdoc’s insertPage:aPage atIndex:i)
  end repeat
  
  
set aRes to newPDFdoc’s writeToFile:newPath
  
return aRes as boolean
  
end rotatePDFandSaveAt

–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 

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

Finder上で選択中の画像をアンチエイリアスなしで200%にリサイズ

Posted on 6月 3, 2018 by Takaaki Naganoya

Finder上で選択中の画像をアンチエイリアスなしで200%にリサイズするAppleScriptです。

よく使う拡大/縮小倍率のScriptを用意してmacOS標準装備のScript Menuに入れておき、Menuから呼び出して使っています。

AppleScript名:Finder上で選択中の画像をアンチエイリアスなしで200%にリサイズ
— Created 2014-02-21 Shane Stanley
— Modified 2018-06-01 Takaaki Naganoya
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
use framework "AppKit"

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 NSURLTypeIdentifierKey : a reference to current application’s NSURLTypeIdentifierKey

set zoomPercent to 2.0

tell application "Finder"
  set inFiles to selection as alias list
end tell

–指定のAlias listのうち画像のみ抽出
set filRes1 to filterAliasListByUTI(inFiles, "public.image") of me
if filRes1 = {} then return

–選択中のファイルのうちの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

repeat with i in filRes1
  
  
set outPOSIXpath to newPath & "/" & (current application’s NSUUID’s UUID()’s UUIDString()) as string
  
  
set aNSImage to (current application’s NSImage’s alloc()’s initWithContentsOfFile:(i))
  
set theImage to (my resizeNSImageWithoutAntlialias:aNSImage toScale:zoomPercent)
  
  
–ファイルパスの拡張子を取得する
  
set pathString to (current application’s NSString’s stringWithString:i)
  
set fileExt to (pathString’s pathExtension()) as string
  
  
set newPath to outPOSIXpath & "." & fileExt
  
  
–元画像のファイルファイルフォーマットに合わせて同じフォーマットに
  
if fileExt is in {"png", "PNG"} then
    my saveNSImageAtPathAsPNG(theImage, newPath)
  else if fileExt is in {"jpg", "jpeg"} then
    my saveNSImageAtPathAsJPG(theImage, newPath, 1.0 as real)
  else if fileExt is in {"tif", "tiff"} then
    my saveNSImageAtPathAsTIFF(theImage, newPath)
  else if fileExt is in {"bmp"} then
    my saveNSImageAtPathAsBMP(theImage, newPath)
  end if
  
end repeat

–NSImageを指定倍率で拡大(アンチエイリアス解除状態で)
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:

–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

–NSImageを指定パスにJPEG形式で保存、qulityNumは0.0〜1.0。1.0は無圧縮
on saveNSImageAtPathAsJPG(anImage, outPath, qulityNum as real)
  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 NSJPEGFileType) |properties|:{NSImageCompressionFactor:qulityNum})
  
set aRes to (myNewImageData’s writeToFile:newPath atomically:true) as boolean
  
return aRes –true/false
end saveNSImageAtPathAsJPG

–NSImageを指定パスにTIFF形式で保存
on saveNSImageAtPathAsTIFF(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 NSTIFFFileType) |properties|:(missing value))
  
set aRes to (myNewImageData’s writeToFile:newPath atomically:true) as boolean
  
return aRes –true/false
end saveNSImageAtPathAsTIFF

–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を指定パスにBMP形式で保存
on saveNSImageAtPathAsBMP(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 NSBMPFileType) |properties|:(missing value))
  
set aRes to (myNewImageData’s writeToFile:newPath atomically:true) as boolean
  
return aRes –true/false
end saveNSImageAtPathAsBMP

★Click Here to Open This Script 

Posted in file Image | Tagged 10.11savvy 10.12savvy 10.13savvy Finder | Leave a comment

Finder上で選択中の画像をアンチエイリアスありで50%にリサイズ

Posted on 6月 3, 2018 by Takaaki Naganoya

Finder上で選択中の画像をアンチエイリアスありで50%にリサイズするAppleScriptです。

よく使う拡大/縮小倍率のScriptを用意してmacOS標準装備のScript Menuに入れておき、Menuから呼び出して使っています。

AppleScript名:Finder上で選択中の画像をアンチエイリアスありで50%にリサイズ
— Created 2014-02-21 Shane Stanley
— Modified 2018-06-01 Takaaki Naganoya
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
use framework "AppKit"

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 NSURLTypeIdentifierKey : a reference to current application’s NSURLTypeIdentifierKey

set zoomPercent to 0.5

tell application "Finder"
  set inFiles to selection as alias list
end tell

–指定のAlias listのうち画像のみ抽出
set filRes1 to filterAliasListByUTI(inFiles, "public.image") of me
if filRes1 = {} then return

–選択中のファイルのうちの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

repeat with i in filRes1
  set outPOSIXpath to newPath & "/" & (current application’s NSUUID’s UUID()’s UUIDString()) as string
  
set fRes1 to resizeImage(i, outPOSIXpath, zoomPercent) of me
end repeat

on resizeImage(imagePath, newPath, aZoom as real)
  –ファイルパスの拡張子を取得する
  
set pathString to current application’s NSString’s stringWithString:imagePath
  
set fileExt to (pathString’s pathExtension()) as string
  
  
–画像ファイルをNSImageに読み込み
  
set theImage to current application’s NSImage’s alloc()’s initWithContentsOfFile:imagePath — load the file as an NSImage
  
  
— calculate required sizes
  
set theSize to (theImage’s |size|()) as record
  
  
set oldWidth to width of theSize
  
set oldHeight to height of theSize
  
  
set theWidth to oldWidth * aZoom
  
set theHeight to oldHeight * aZoom
  
  
set newImage to current application’s NSImage’s alloc()’s initWithSize:(current application’s NSMakeSize(theWidth, theHeight))
  
  
newImage’s lockFocus()
  
theImage’s drawInRect:{origin:{x:0, y:0}, |size|:{width:theWidth, height:theHeight}} fromRect:(current application’s NSZeroRect) operation:(current application’s NSCompositeSourceOver) fraction:1.0
  
newImage’s unlockFocus()
  
  
set theData to newImage’s TIFFRepresentation()
  
set newRep to current application’s NSBitmapImageRep’s imageRepWithData:theData
  
  
–元画像のファイルファイルフォーマットに合わせて同じフォーマットに
  
if fileExt is in {"png", "PNG"} then
    set theData to (newRep’s representationUsingType:(current application’s NSPNGFileType) |properties|:{NSImageGamma:1.0})
  else if fileExt is in {"jpg", "jpeg"} then
    set theData to (newRep’s representationUsingType:(current application’s NSJPEGFileType) |properties|:{NSImageCompressionFactor:1.0})
  else if fileExt is in {"tif", "tiff"} then
    set theData to (newRep’s representationUsingType:(current application’s NSTIFFFileType) |properties|:(missing value))
  else if fileExt is in {"bmp"} then
    set theData to (newRep’s representationUsingType:(current application’s NSBMPFileType) |properties|:(missing value))
  end if
  
  
set newPath to newPath & "." & fileExt
  
return (theData’s writeToFile:newPath atomically:true)
  
end resizeImage

–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 

Posted in file Image | Tagged 10.11savvy 10.12savvy 10.13savvy Finder | 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 

Posted in file Tag | Tagged 10.11savvy 10.12savvy 10.13savvy Finder | 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 

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 

Posted in file UTI | Tagged 10.11savvy 10.12savvy 10.13savvy Finder | Leave a comment

Finderの最前面のアイコン表示ウィンドウ上の画像をX座標の情報をキーにして横連結

Posted on 4月 17, 2018 by Takaaki Naganoya

Finderの最前面のWindowがアイコン表示になっている場合に、Window(Folder)内の画像ファイルをFinder上でのアイコン位置情報(X座標のみ)を考慮して横方向に1枚ものの画像に結合するAppleScriptです。

Blog掲載時に利用するために、Finder上で選択中の複数の画像ファイルを1枚ものの画像に(横方向/縦方向に)連結するAppleScriptを便利に使っています(ただし、「動けばいいや」程度で雑に作ったので、普段よりもやっつけ度がかなり高い、、、)。

ただし、画像の並び順については「たぶん、作成日時の古い順」に連結されるといった具合に明示的に並び順を指定できるものではなかったので、本Scriptを作ってみました。 –> Demo Movie

Finder上でicon viewに指定したWindow(Folder)内でLeft–>Rightの順に(X座標のみ評価)座標値をソートして連結します。

AppleScript名:Finderの最前面のアイコン表示ウィンドウ上の画像をX座標の情報をキーにして横連結
— Created 2018-04-10 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
use framework "QuartzCore"
use framework "AppKit"
use bPlus : script "BridgePlus" –https://www.macosxautomation.com/applescript/apps/BridgePlus.html

property |NSURL| : a reference to current application’s |NSURL|
property NSUUID : a reference to current application’s NSUUID
property NSArray : a reference to current application’s NSArray
property NSString : a reference to current application’s NSString
property NSImage : a reference to current application’s NSImage
property NSWorkspace : a reference to current application’s NSWorkspace
property NSPNGFileType : a reference to current application’s NSPNGFileType
property NSMutableArray : a reference to current application’s NSMutableArray
property NSBitmapImageRep : a reference to current application’s NSBitmapImageRep
property NSURLTypeIdentifierKey : a reference to current application’s NSURLTypeIdentifierKey

property xGap : 10 –連結時の画像間のアキ(横方向)

load framework

tell application "Finder"
  tell front window
    set curView to current view
    
if curView is not equal to icon view then
      display dialog "最前面のウィンドウがアイコン表示になっていないので、処理を終了します。"
      
return
    end if
    
    
try
      set posList to position of every file whose kind contains "イメージ" –"イメージ" is "image" or "picture" in Japanese
      
set fileList to (every file whose kind contains "イメージ") as alias list –"イメージ" is "image" or "picture" in Japanese
    on error
      display dialog "最前面のウィンドウに画像ファイルが配置されていないため、処理を中止します。"
      
return
    end try
  end tell
  
  
set aList to {}
  
set aLen to length of posList
  
set bLen to length of fileList
  
if aLen is not equal to bLen then return
  
  
repeat with i from 1 to aLen
    set posItem to contents of item i of posList
    
set aPath to POSIX path of item i of fileList
    
set the end of aList to (posItem & aPath)
  end repeat
end tell

–> {{127, 42, "/Users/me/Desktop/名称未設定フォルダ/000_keynote_print.png"}, {302, 43, "/Users/me/Desktop/名称未設定フォルダ/999_indesign_print.png"}}

set bList to sort2DListAscendingWithFirstItemKey(aList) of me
–> {{127, 42, "/Users/me/Desktop/名称未設定フォルダ/000_keynote_print.png"}, {302, 43, "/Users/me/Desktop/名称未設定フォルダ/999_indesign_print.png"}}

set cList to getEveryIndicatedItemsFrom2DList(bList, 3) of me
–>  {​​​​​"/Users/me/Desktop/名称未設定フォルダ/000_keynote_print.png", ​​​​​"/Users/me/Desktop/名称未設定フォルダ/999_indesign_print.png"​​​}

–Finder最前面の画像ファイルをpathからImageを読み込んでArrayに入れる
set imgList to NSMutableArray’s new()
repeat with i in cList
  set aPath to contents of i
  
  
set imgRes to (my isImageAtPath:aPath)
  
if imgRes as boolean = true then
    set aNSImage to (NSImage’s alloc()’s initWithContentsOfFile:aPath)
    (
imgList’s addObject:aNSImage)
  end if
end repeat

–KVCで画像の各種情報をまとめて取得
set sizeList to (imgList’s valueForKeyPath:"size") as list –NSSize to list of record conversion
set maxHeight to ((NSArray’s arrayWithArray:sizeList)’s valueForKeyPath:"@max.height") as real
set totalWidth to ((NSArray’s arrayWithArray:sizeList)’s valueForKeyPath:"@sum.width") as real
set totalCount to ((NSArray’s arrayWithArray:sizeList)’s valueForKeyPath:"@count") as integer

–出力画像作成
set tSize to current application’s NSMakeSize((totalWidth + (xGap * totalCount)), maxHeight)
set newImage to NSImage’s alloc()’s initWithSize:tSize

–順次画像を新規画像に上書き
set xOrig to 0
repeat with i in (imgList as list)
  set j to contents of i
  
set curSize to j’s |size|()
  
set aRect to {xOrig, (maxHeight – (curSize’s height())), (curSize’s width()), (curSize’s height())}
  
set newImage to composeImage(newImage, j, aRect) of me
  
set xOrig to xOrig + (curSize’s width()) + xGap
end repeat

–デスクトップにPNG形式でNSImageをファイル保存
set aDesktopPath to current application’s NSHomeDirectory()’s stringByAppendingString:"/Desktop/"
set savePath to aDesktopPath’s stringByAppendingString:((NSUUID’s UUID()’s UUIDString())’s stringByAppendingString:".png")
set fRes to saveNSImageAtPathAsPNG(newImage, savePath) of me

–2つのNSImageを重ね合わせ合成してNSImageで返す
on composeImage(backImage, composeImage, aTargerRect)
  set newImage to NSImage’s alloc()’s initWithSize:(backImage’s |size|())
  
  
copy aTargerRect to {x1, y1, x2, y2}
  
  
newImage’s lockFocus()
  
  
set v2 to system attribute "sys2"
  
if v2 ≤ 12 then
    –To macOS 10.12.x
    
set bRect to current application’s NSMakeRect(x1, y1, x2, y2)
    
set newImageRect to current application’s CGRectZero
    
set newImageRect’s |size| to (newImage’s |size|)
  else
    –macOS 10.13 or later
    
set bRect to {{x1, y1}, {x2, y2}}
    
set newImageRect to {{0, 0}, (newImage’s |size|)}
  end if
  
  
backImage’s drawInRect:newImageRect
  
composeImage’s drawInRect:bRect
  
  
newImage’s unlockFocus()
  
return newImage
end composeImage

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

–指定のパスのファイルが画像かどうかをチェック
on isImageAtPath:aPath
  set aURL to |NSURL|’s fileURLWithPath:aPath
  
set {theResult, theValue} to aURL’s getResourceValue:(reference) forKey:NSURLTypeIdentifierKey |error|:(missing value)
  
return (NSImage’s imageTypes()’s containsObject:theValue) as boolean
end isImageAtPath:

on sort2DListAscendingWithFirstItemKey(aList as list)
  set sortIndexList 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:sortIndexList ascending:sortOrders sortTypes:sortTypes |error|:(missing value)) as list
  
return resList
end sort2DListAscendingWithFirstItemKey

–2D Listの各要素から、指定アイテムの要素だけを取り出してリストで返す
on getEveryIndicatedItemsFrom2DList(aList as list, anItem as integer) –this item No. begins from 1
  set outList to {}
  
repeat with i in aList
    set j to contents of item anItem of i
    
set the end of outList to j
  end repeat
  
return outList
end getEveryIndicatedItemsFrom2DList

★Click Here to Open This Script 

Posted in file Image | Tagged 10.11savvy 10.12savvy 10.13savvy Finder | Leave a comment

エイリアス書類からオリジナルファイルの情報を取得する

Posted on 4月 16, 2018 by Takaaki Naganoya

指定のエイリアス書類から、オリジナルファイルの情報を取得するAppleScriptです。

オリジナルファイルを求める処理、というよりはエイリアス書類のリンク切れ(実体ファイルの存在)チェックを行うというのが「隠れた目的」です。

「エイリアス書類」とaliasは別物なので注意が必要です。どちらかといえば説明に注意が必要といったところなのかも???

本Blogでは両者を「エイリアス書類」「alias」と区別して記述しています。

AppleScript名:エイリアス書類からオリジナルファイルの情報を取得する
set aFile to choose file

tell application "Finder"
  try
    set origI to (original item of aFile) as alias
  on error
    –エイリアス書類のオリジナルファイルが削除されていた場合(リンク切れ。オリジナル書類が削除されていた場合)にはエラーになる
    
set origI to false
  end try
end tell

★Click Here to Open This Script 

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

指定フォルダのサブフォルダの中からYYYY_MM_DDで最新のものを抽出してFinderでオープン

Posted on 4月 11, 2018 by Takaaki Naganoya

指定フォルダ以下に存在するYYYY/MM/DDの3階層のフォルダで最新のものを抽出してFinder上で選択状態にするAppleScriptです。

もともと、Safariのダウンロードフォルダに対してFolder Action Scriptを設定して、当日のYYYY/MM/DDの3階層のフォルダを作成してそこにダウンロードしたファイルを移動する処理を行っていました。

その最新フォルダをFinder上で表示する必要があったので、作成したものです。

AppleScriptのPOSIX pathとCocoaのPOSIX path(NSString)では末尾のスラッシュの有無が異なっており、専用ルーチンから切り分けて汎用ルーチンとして使いまわそうとして久しぶりにハマりました。

AppleScript名:指定フォルダのサブフォルダの中からYYYY_MM_DDで最新のものを抽出してFinderでオープン
— Created 2018-04-09 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

set sDL to POSIX path of (choose folder)
–> "/Users/me/Downloads/"–AppleScript HFS to POSIX path (ends with slash)

retLatestYYYYMMDDFolderUnder(sDL, 2017) of me

on retLatestYYYYMMDDFolderUnder(aPOSIXFolderPath as string, minYYYY as integer)
  load framework –load BridgePlus framework
  
  
if aPOSIXFolderPath ends with "/" then
    set aPOSIXFolderPath to text 1 thru -2 of aPOSIXFolderPath
  end if
  
–> "/Users/maro/Downloads"–Cocoa POSIX path (does not end with)
  
  
set sList to (current application’s NSString’s stringWithString:aPOSIXFolderPath)’s pathComponents() as list
  
–>  {​​​​​"/", ​​​​​"Users", ​​​​​"me", ​​​​​"Downloads"​​​}
  
  
set sLen to length of sList
  
–>  4
  
  
set fListRes to getFolderspathComponentsIn(aPOSIXFolderPath) of me
  
–> {​​​​​{​​​​​​​"/", ​​​​​​​"Users", ​​​​​​​"me", ​​​​​​​"Downloads", ​​​​​​​"2016"​​​​​}, ​​​​​ ​​​​​{​​​​​​​"/", ​​​​​​​"Users", ​​​​​​​"me", ​​​​​​​"Downloads", ​​​​​​​"2018", ​​​​​​​"03", ​​​​​​​"20"​​​​​}…}
  
  
set anArray to current application’s NSMutableArray’s arrayWithArray:fListRes
  
  
set predStr to "SELF[SIZE] = " & (sLen + 3) as string
  
set aPredicate to current application’s NSPredicate’s predicateWithFormat:predStr
  
set t1Array to (anArray’s filteredArrayUsingPredicate:aPredicate)
  
–> {​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​{​​​​​​​"/", ​​​​​​​"Users", ​​​​​​​"me", ​​​​​​​"Downloads", ​​​​​​​"2018", ​​​​​​​"03", ​​​​​​​"20"​​​​​}…}
  
  
set predStr1 to ("SELF[" & (sLen) as string) & "].floatValue >= " & (minYYYY as string) & " && SELF[" & ((sLen + 1) as string) & "].floatValue >= 1 && SELF[" & ((sLen + 2) as string) & "].floatValue >= 1"
  
set aPredicate1 to current application’s NSPredicate’s predicateWithFormat:predStr1
  
set t2Array to (t1Array’s filteredArrayUsingPredicate:aPredicate1) as list
  
  
–YYYY, MM, DDでそれぞれ降順ソート。最新のものを取得  
  
set theResult to current application’s SMSForder’s subarraysIn:t2Array sortedByIndexes:{sLen, sLen + 1, sLen + 2} ascending:{false, false, false} sortTypes:{"compare:", "compare:", "compare:"} |error|:(missing value)
  
if (theResult as list = {} or theResult = missing value) then return {}
  
  
–最新のYYYY/MM/DDフォルダを取得してFinder上で選択表示
  
set theNewest to contents of first item of (theResult as list)
  
set theNewestStr to (current application’s NSString’s pathWithComponents:theNewest)
  
set parentPath to theNewestStr’s stringByDeletingLastPathComponent()
  
set aRes to current application’s NSWorkspace’s sharedWorkspace()’s selectFile:theNewestStr inFileViewerRootedAtPath:parentPath
end retLatestYYYYMMDDFolderUnder

on getFolderspathComponentsIn(posixPath)
  script spd
    property allItems : {}
  end script
  
  
set allItems of spd to {}
  
set theNSURL to current application’s |NSURL|’s fileURLWithPath:posixPath
  
set theNSFileManager to current application’s NSFileManager’s new()
  
  
— get URL enumerator
  
set theNSFileEnumerator to theNSFileManager’s enumeratorAtURL:theNSURL includingPropertiesForKeys:{current application’s NSURLIsDirectoryKey, current application’s NSURLIsPackageKey} options:((current application’s NSDirectoryEnumerationSkipsPackageDescendants) + (current application’s NSDirectoryEnumerationSkipsHiddenFiles as integer)) errorHandler:(missing value)
  
  
— get all items from enumerator
  
set (allItems of spd) to theNSFileEnumerator’s allObjects()
  
set theFolders to {} — to store folders
  
  
— loop through
  
repeat with i from 1 to count of (allItems of spd)
    — is it a directory?
    
set {theResult, isDirectory} to ((item i of (allItems of spd))’s getResourceValue:(reference) forKey:(current application’s NSURLIsDirectoryKey) |error|:(missing value))
    
if isDirectory as boolean = true then
      set {theResult, isPackage} to ((item i of (allItems of spd))’s getResourceValue:(reference) forKey:(current application’s NSURLIsPackageKey) |error|:(missing value))
      
      
— is it not a package?
      
if not isPackage as boolean = true then
        set end of theFolders to (item i of (allItems of spd))’s pathComponents() as list –parse each directory into list
      end if
    end if
  end repeat
  
  
return theFolders
end getFolderspathComponentsIn

★Click Here to Open This Script 

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

Finder上で選択中の画像を縦方向に連結 v1

Posted on 4月 8, 2018 by Takaaki Naganoya

Finder上で選択中の画像ファイルを縦方向に連結して結果をデスクトップ上に出力するAppleScriptです。

AppleScript名:Finder上で選択中の画像を縦方向に連結 v1
— Created 2017-11-21 by Takaaki Naganoya
— Modified 2018-04-06 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.5" — El Capitan (10.11) or later
use framework "Foundation"
use framework "QuartzCore"
use framework "AppKit"
use scripting additions

property |NSURL| : a reference to current application’s |NSURL|
property NSUUID : a reference to current application’s NSUUID
property NSArray : a reference to current application’s NSArray
property NSString : a reference to current application’s NSString
property NSImage : a reference to current application’s NSImage
property NSWorkspace : a reference to current application’s NSWorkspace
property NSPNGFileType : a reference to current application’s NSPNGFileType
property NSMutableArray : a reference to current application’s NSMutableArray
property NSBitmapImageRep : a reference to current application’s NSBitmapImageRep
property NSURLTypeIdentifierKey : a reference to current application’s NSURLTypeIdentifierKey

property yGap : 10 –連結時の画像間のアキ(横方向)

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

–選択した画像をArrayに入れる
set imgList to NSMutableArray’s new()
repeat with i in aSel
  set aPath to POSIX path of i
  
  
set imgRes to (my isImageAtPath:aPath)
  
if imgRes as boolean = true then
    set aNSImage to (NSImage’s alloc()’s initWithContentsOfFile:aPath)
    (
imgList’s addObject:aNSImage)
  end if
end repeat

–KVCで画像の各種情報をまとめて取得
set sizeList to (imgList’s valueForKeyPath:"size") as list –NSSize to list of record conversion
set maxWidth to ((NSArray’s arrayWithArray:sizeList)’s valueForKeyPath:"@max.width") as real
set totalHeight to (((NSArray’s arrayWithArray:sizeList)’s valueForKeyPath:"@sum.height") as real) + 50
set totalCount to ((NSArray’s arrayWithArray:sizeList)’s valueForKeyPath:"@count") as integer

–出力画像作成
set tSize to current application’s NSMakeSize(maxWidth, totalHeight + (yGap * totalCount))
set newImage to NSImage’s alloc()’s initWithSize:tSize

–順次画像を新規画像に上書き
set yOrig to 0
repeat with i in (imgList as list)
  set j to contents of i
  
set curSize to j’s |size|()
  
–set aRect to {0, (maxWidth – (curSize’s height())), (curSize’s width()), (curSize’s height())}
  
set aRect to {0, (totalHeight – (curSize’s height())) – yOrig, (curSize’s width()), (curSize’s height())}
  
set newImage to composeImage(newImage, j, aRect) of me
  
set yOrig to yOrig + (curSize’s height()) + yGap
end repeat

–デスクトップにPNG形式でNSImageをファイル保存
set aDesktopPath to current application’s NSHomeDirectory()’s stringByAppendingString:"/Desktop/"
set savePath to aDesktopPath’s stringByAppendingString:((NSUUID’s UUID()’s UUIDString())’s stringByAppendingString:".png")
set fRes to saveNSImageAtPathAsPNG(newImage, savePath) of me

–2つのNSImageを重ね合わせ合成してNSImageで返す
on composeImage(backImage, composeImage, aTargerRect)
  set newImage to NSImage’s alloc()’s initWithSize:(backImage’s |size|())
  
  
copy aTargerRect to {x1, y1, x2, y2}
  
  
newImage’s lockFocus()
  
  
set v2 to system attribute "sys2"
  
if v2 ≤ 12 then
    –To macOS 10.12.x
    
set bRect to current application’s NSMakeRect(x1, y1, x2, y2)
    
set newImageRect to current application’s CGRectZero
    
set newImageRect’s |size| to (newImage’s |size|)
  else
    –macOS 10.13 or later
    
set bRect to {{x1, y1}, {x2, y2}}
    
set newImageRect to {{0, 0}, (newImage’s |size|)}
  end if
  
  
backImage’s drawInRect:newImageRect
  
composeImage’s drawInRect:bRect
  
  
newImage’s unlockFocus()
  
return newImage
end composeImage

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

–指定のパスのファイルが画像かどうかをチェック
on isImageAtPath:aPath
  set aURL to |NSURL|’s fileURLWithPath:aPath
  
set {theResult, theValue} to aURL’s getResourceValue:(reference) forKey:NSURLTypeIdentifierKey |error|:(missing value)
  
return (NSImage’s imageTypes()’s containsObject:theValue) as boolean
end isImageAtPath:

★Click Here to Open This Script 

Posted in file Image | Tagged 10.11savvy 10.12savvy 10.13savvy Finder | Leave a comment

Finder上で選択中の画像を横方向に連結 v4

Posted on 4月 6, 2018 by Takaaki Naganoya

Finder上で選択中の画像ファイルを横方向に連結して結果をデスクトップ上に出力するAppleScriptです。

Shane Stanleyから「macOS 10.13で動かないよ」とツッコミが入ってmacOS 10.13に対応するよう書き換えたものです。

AppleScript名:Finder上で選択中の画像を横方向に連結 v4
— Created 2017-11-21 by Takaaki Naganoya
— Modified 2018-04-06 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.5" — El Capitan (10.11) or later
use framework "Foundation"
use framework "QuartzCore"
use framework "AppKit"
use scripting additions

property |NSURL| : a reference to current application’s |NSURL|
property NSUUID : a reference to current application’s NSUUID
property NSArray : a reference to current application’s NSArray
property NSString : a reference to current application’s NSString
property NSImage : a reference to current application’s NSImage
property NSWorkspace : a reference to current application’s NSWorkspace
property NSPNGFileType : a reference to current application’s NSPNGFileType
property NSMutableArray : a reference to current application’s NSMutableArray
property NSBitmapImageRep : a reference to current application’s NSBitmapImageRep
property NSURLTypeIdentifierKey : a reference to current application’s NSURLTypeIdentifierKey

property xGap : 10 –連結時の画像間のアキ(横方向)

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

–選択した画像をArrayに入れる
set imgList to NSMutableArray’s new()
repeat with i in aSel
  set aPath to POSIX path of i
  
  
set imgRes to (my isImageAtPath:aPath)
  
if imgRes as boolean = true then
    set aNSImage to (NSImage’s alloc()’s initWithContentsOfFile:aPath)
    (
imgList’s addObject:aNSImage)
  end if
end repeat

–KVCで画像の各種情報をまとめて取得
set sizeList to (imgList’s valueForKeyPath:"size") as list –NSSize to list of record conversion
set maxHeight to ((NSArray’s arrayWithArray:sizeList)’s valueForKeyPath:"@max.height") as real
set totalWidth to ((NSArray’s arrayWithArray:sizeList)’s valueForKeyPath:"@sum.width") as real
set totalCount to ((NSArray’s arrayWithArray:sizeList)’s valueForKeyPath:"@count") as integer

–出力画像作成
set tSize to current application’s NSMakeSize((totalWidth + (xGap * totalCount)), maxHeight)
set newImage to NSImage’s alloc()’s initWithSize:tSize

–順次画像を新規画像に上書き
set xOrig to 0
repeat with i in (imgList as list)
  set j to contents of i
  
set curSize to j’s |size|()
  
set aRect to {xOrig, (maxHeight – (curSize’s height())), (curSize’s width()), (curSize’s height())}
  
set newImage to composeImage(newImage, j, aRect) of me
  
set xOrig to xOrig + (curSize’s width()) + xGap
end repeat

–デスクトップにPNG形式でNSImageをファイル保存
set aDesktopPath to current application’s NSHomeDirectory()’s stringByAppendingString:"/Desktop/"
set savePath to aDesktopPath’s stringByAppendingString:((NSUUID’s UUID()’s UUIDString())’s stringByAppendingString:".png")
set fRes to saveNSImageAtPathAsPNG(newImage, savePath) of me

–2つのNSImageを重ね合わせ合成してNSImageで返す
on composeImage(backImage, composeImage, aTargerRect)
  set newImage to NSImage’s alloc()’s initWithSize:(backImage’s |size|())
  
  
copy aTargerRect to {x1, y1, x2, y2}
  
  
newImage’s lockFocus()
  
  
set v2 to system attribute "sys2"
  
if v2 ≤ 12 then
    –To macOS 10.12.x
    
set bRect to current application’s NSMakeRect(x1, y1, x2, y2)
    
set newImageRect to current application’s CGRectZero
    
set newImageRect’s |size| to (newImage’s |size|)
  else
    –macOS 10.13 or later
    
set bRect to {{x1, y1}, {x2, y2}}
    
set newImageRect to {{0, 0}, (newImage’s |size|)}
  end if
  
  
backImage’s drawInRect:newImageRect
  
composeImage’s drawInRect:bRect
  
  
newImage’s unlockFocus()
  
return newImage
end composeImage

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

–指定のパスのファイルが画像かどうかをチェック
on isImageAtPath:aPath
  set aURL to |NSURL|’s fileURLWithPath:aPath
  
set {theResult, theValue} to aURL’s getResourceValue:(reference) forKey:NSURLTypeIdentifierKey |error|:(missing value)
  
return (NSImage’s imageTypes()’s containsObject:theValue) as boolean
end isImageAtPath:

★Click Here to Open This Script 

Posted in file Image | Tagged 10.11savvy 10.12savvy 10.13savvy Finder | Leave a comment

Post navigation

  • Older posts
  • Newer posts

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

Google Search

Popular posts

  • 開発機としてM2 Mac miniが来たのでガチレビュー
  • macOS 13.6.5 AS系のバグ、一切直らず
  • CotEditorで2つの書類の行単位での差分検出
  • Apple純正マウス、キーボードのバッテリー残量取得
  • macOS 15, Sequoia
  • ディスプレイをスリープ状態にして処理続行
  • 初心者がつまづきやすい「log」コマンド
  • Adobe AcrobatをAppleScriptから操作してPDF圧縮
  • 与えられた文字列の1D Listのすべての順列組み合わせパターン文字列を返す v3(ベンチマーク用)
  • 指定のWordファイルをPDFに書き出す
  • メキシカンハットの描画
  • macOS 13 TTS環境の変化について
  • 2023年に書いた価値あるAppleScript
  • Pixelmator Pro v3.6.4でAppleScriptからの操作時の挙動に違和感が
  • AdobeがInDesign v19.4からPOSIX pathを採用
  • Pages本執筆中に、2つの書類モード切り替えに気がついた
  • 可変次元のベクトルに対応したコサイン類似度計算
  • Safariで「プロファイル」機能を使うとAppleScriptの処理に影響
  • Cocoa Scripting Course 続刊計画
  • macOS 13.6.2アップデート Cocoa-AppleScript Applet修正はなし

Tags

10.11savvy (1101) 10.12savvy (1242) 10.13savvy (1391) 10.14savvy (586) 10.15savvy (437) 11.0savvy (281) 12.0savvy (201) 13.0savvy (136) 14.0savvy (84) 15.0savvy (60) CotEditor (63) Finder (51) iTunes (19) Keynote (112) NSAlert (60) NSArray (51) NSBitmapImageRep (20) NSBundle (20) NSButton (34) NSColor (51) NSDictionary (27) NSFileManager (23) NSFont (19) NSImage (41) NSJSONSerialization (21) NSMutableArray (62) NSMutableDictionary (21) NSPredicate (36) NSRunningApplication (56) NSScreen (30) NSScrollView (22) NSString (117) NSURL (97) NSURLRequest (23) NSUTF8StringEncoding (30) NSView (33) NSWorkspace (20) Numbers (67) Pages (51) Safari (44) Script Editor (26) 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
  • Clipboard
  • Code Sign
  • Color
  • Custom Class
  • dialog
  • diff
  • drive
  • Droplet
  • exif
  • file
  • File path
  • filter
  • folder
  • Font
  • Font
  • GAME
  • geolocation
  • GUI
  • GUI Scripting
  • Hex
  • History
  • How To
  • iCloud
  • Icon
  • Image
  • Input Method
  • Internet
  • iOS App
  • JavaScript
  • JSON
  • JXA
  • Keychain
  • Keychain
  • Language
  • Library
  • list
  • Locale
  • Localize
  • Machine Learning
  • Map
  • Markdown
  • Menu
  • Metadata
  • MIDI
  • MIME
  • Natural Language Processing
  • Network
  • news
  • Noification
  • Notarization
  • Number
  • Object control
  • OCR
  • OSA
  • parallel processing
  • PDF
  • Peripheral
  • PRODUCTS
  • QR Code
  • Raw AppleEvent Code
  • Record
  • rectangle
  • recursive call
  • regexp
  • Release
  • Remote Control
  • Require Control-Command-R to run
  • REST API
  • Review
  • RTF
  • Sandbox
  • Screen Saver
  • Script Libraries
  • sdef
  • search
  • Security
  • selection
  • shell script
  • Shortcuts Workflow
  • Sort
  • Sound
  • Spellchecker
  • Spotlight
  • SVG
  • System
  • Tag
  • Telephony
  • Text
  • Text to Speech
  • timezone
  • Tools
  • Update
  • URL
  • UTI
  • Web Contents Control
  • WiFi
  • XML
  • XML-RPC
  • イベント(Event)
  • 未分類

アーカイブ

  • 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