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

カテゴリー: file

画像+文字作成テスト_v4

Posted on 4月 7, 2018 by Takaaki Naganoya

指定サイズの画像に対して指定の文字を描画して指定ファイル名のPNG画像を書き出すAppleScriptです。

AppleScript名:画像+文字作成テスト_v4
— Created 2015-07-31 by Takaaki Naganoya
— Modified 2015-08-01 by Shane Stanley
— Modified 2017-11-19 by Takaaki Naganoya / macOS 10.13のバグに対応
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"

set aWidth to 400.0 –幅
set aHeight to 200.0 –高さ
set outPath to "~/Desktop/test.png" –書き出し先のファイルパス
set fillColor to current application’s NSColor’s blackColor –塗り色
set drawColor to current application’s NSColor’s whiteColor –文字色
set aText to "ぴよまるソフトウェア"
set {xPos, yPos} to {1, 5}

–新規画像を作成して背景を塗る
set anImage to makeImageWithFilledColor(aWidth, aHeight, outPath, fillColor) of me

–画像に文字を塗る(参照渡し(call by reference)で、結果はaImage1に入る)
drawStringsOnImage(anImage, aText, "HiraKakuStd-W8", 36.0, drawColor, xPos, yPos) of me

–ファイル保存
set aRes to saveImageRepAtPathAsPNG(anImage, outPath) of me

–画像のうえに指定の文字を描画して画像を返す
on drawStringsOnImage(anImage, aText, aFontName, aPoint, drawColor)
  set retinaF to (current application’s NSScreen’s mainScreen()’s backingScaleFactor()) as real
  
–>  2.0 (Retina) / 1.0 (Non Retina)
  
  set aString to current application’s NSString’s stringWithString:aText
  
set aDict to current application’s NSDictionary’s dictionaryWithObjects:{current application’s NSFont’s fontWithName:aFontName |size|:aPoint, drawColor} forKeys:{current application’s NSFontAttributeName, current application’s NSForegroundColorAttributeName}
  
set imageSize to anImage’s |size|()
  
set textSize to aString’s sizeWithAttributes:aDict
  
  set xPos to ((width of imageSize) – (width of textSize)) / 2 / retinaF
  
set yPos to ((height of imageSize) – (height of textSize)) / 2 / retinaF
  
  –文字描画開始
  
anImage’s lockFocus()
  
aString’s drawAtPoint:(current application’s NSMakePoint(xPos, yPos)) withAttributes:aDict
  
anImage’s unlockFocus()
end drawStringsOnImage

–指定サイズの画像を作成し、背景を指定色で塗る
on makeImageWithFilledColor(aWidth, aHeight, outPath, fillColor)
  set anImage to current application’s NSImage’s alloc()’s initWithSize:(current application’s NSMakeSize(aWidth, aHeight))
  
  –描画開始
  
anImage’s lockFocus()
  
  set theRect to {{x:0, y:0}, {width:aWidth, height:aHeight}}
  
set theNSBezierPath to current application’s NSBezierPath’s bezierPath
  
theNSBezierPath’s appendBezierPathWithRect:theRect
  
  fillColor’s |set|() –色設定
  
theNSBezierPath’s fill() –ぬりつぶし
  
  anImage’s unlockFocus()
  
–描画ここまで
  
  return anImage –画像を返す  
end makeImageWithFilledColor

–画像を指定パスにPNG形式で保存
on saveImageRepAtPathAsPNG(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 saveImageRepAtPathAsPNG

★Click Here to Open This Script 

Posted in call by reference file Image Text | Tagged 10.11savvy 10.12savvy 10.13savvy | 1 Comment

DSCaptureで画面キャプチャ

Posted on 4月 7, 2018 by Takaaki Naganoya

shellのscreencaptureコマンドを使わずにフレームワーク経由で画面キャプチャを行うAppleScriptです。

オープンソースのDSCaptureを利用しており、キャプチャ内容をファイルではなくNSImageに格納できる(メモリ上に、ファイルI/Oを経由せずに取得できる)ので、割と使い手があります。とくに、ファイルI/Oに対してはセキュリティ機能による制約が多いために、メモリ上で処理できることのメリットははかりしれません。

本サンプルScriptでは、動作確認のためにキャプチャ内容をファイルに保存していますが、本来このFrameworkの性格からいえばファイル保存するのは「特徴」を台無しにしています。キャプチャしたイメージ(NSImage)をメモリ上で加工するのに向いています。
–> Download DSCapture.framework (To ~/Library/Frameworks/)

AppleScript名:DSCaptureで画面キャプチャ
— Created 2017-01-16 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "DSCapture" –https://github.com/kiding/DSCapture.framework
use framework "AppKit"

–Full Screen (Every Display)
set aCapt to current application’s DSCapture’s sharedCapture()’s |full|()’s captureWithTarget:me selector:"displayCaptureData:" useCG:false

–Selected Area (Selected Area Only by user operation)
–set bCapt to current application’s DSCapture’s sharedCapture()’s |selection|()’s captureWithTarget:me selector:"displayCaptureData:" useCG:false

–Delegate Handler
on displayCaptureData:aSender
  set aCount to aSender’s |count|()
  
repeat with i from 0 to (aCount – 1)
    set anImage to (aSender’s imageAtIndex:i)
    
    
–Make Save Image Path
    
set aDesktopPath to ((current application’s NSProcessInfo’s processInfo()’s environment()’s objectForKey:("HOME"))’s stringByAppendingString:"/Desktop/")
    
set savePath to (aDesktopPath’s stringByAppendingString:((current application’s NSUUID’s UUID()’s UUIDString())’s stringByAppendingString:".png"))
    
saveNSImageAtPathAsPNG(anImage, savePath) of me
    
  end repeat
end displayCaptureData:

–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

★Click Here to Open This Script 

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

画像の指定エリアを塗りつぶしで縦棒グラフを作成 v4

Posted on 4月 6, 2018 by Takaaki Naganoya

指定データをもとに縦棒グラフの画像をデスクトップフォルダ上に作成するAppleScriptです。

グラフの画像を作ろうとしたら、Keynote上で作成して画像書き出しするとかExcel上でグラフを作成して画像書き出しすることを考えますが、アプリケーションを利用しないでグラフ画像を作ってみました。

前バージョンがmacOS 10.13上で動作しなかったので、対処してみました。


▲macOS 10.13.5beta & macOS 10.12.6 (same result)

AppleScript名:画像の指定エリアを塗りつぶしで縦棒グラフを作成 v4
— Created 2017-11-19 by Takaaki Naganoya
— Modified 2018-04-01 by Takaaki Naganoya
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
use framework "AppKit"

property NSUUID : a reference to current application’s NSUUID
property NSColor : a reference to current application’s NSColor
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 NSBezierPath : a reference to current application’s NSBezierPath
property NSPNGFileType : a reference to current application’s NSPNGFileType
property NSBitmapImageRep : a reference to current application’s NSBitmapImageRep

set plotData to {20, 30, 100, 80, 150, 90}
set plotArea to {300, 200}

set innerGapL to 30
set innerGapU to 10
set innerGapR to 20
set innerGapD to 20
set barGap to 10

–パラメータから下地になる画像を作成する
set aSize to current application’s NSMakeSize(first item of plotArea, second item of plotArea)
set anImage to NSImage’s alloc()’s initWithSize:aSize

–各種パラメータの計算
copy plotArea to {plotWidth, plotHeight}
set itemNum to count every item of plotData
set barThickness to (plotWidth – (itemNum * barGap * 2)) div itemNum

–プロットデータの最大値
set anArray to current application’s NSArray’s arrayWithArray:plotData
set aYmax to (anArray’s valueForKeyPath:"@max.self")’s intValue()
set aMaxYVal to plotHeight – innerGapU – innerGapD
set aYPlotArea to plotHeight – innerGapU – innerGapD – 20
set aYUnit to aYPlotArea / aYmax

–数値データをもとに描画データを組み立てる
set drawList to {}

set startX to innerGapL
copy startX to origX

repeat with i in plotData
  set the end of drawList to current application’s NSMakeRect(startX, innerGapD, barThickness, innerGapD + (i * aYUnit))
  
set startX to startX + barThickness + barGap
end repeat

–グラフ塗りつぶし処理呼び出し
set fillColor to (NSColor’s colorWithCalibratedRed:0.1 green:0.1 blue:0.1 alpha:0.3)
set resImage to drawImageWithColorFill(anImage, drawList, fillColor) of me

–数値データ(文字)をグラフィックに記入
set fillColor2 to NSColor’s blackColor()
set resImage to drawImageWithString(resImage, drawList, fillColor2, plotData, "HiraginoSans-W1", 16.0) of me

–補助線を引く
set fillColor3 to (NSColor’s colorWithCalibratedRed:0.0 green:0.0 blue:0.0 alpha:0.8)
set aVertical to current application’s NSMakeRect(origX, innerGapD, plotWidth – innerGapL – innerGapR, 1)
set aHorizontal to current application’s NSMakeRect(origX, innerGapD, 1, plotHeight – innerGapU – innerGapD)
set draw2List to {aVertical, aHorizontal}
set resImage to drawImageWithColorFill(resImage, draw2List, fillColor3) of me

–画像のファイル出力
set imgPath to POSIX path of (path to desktop folder)
set aUUIDstr to (NSUUID’s UUID()’s UUIDString()) as string
set aPath to ((NSString’s stringWithString:imgPath)’s stringByAppendingPathComponent:aUUIDstr)’s stringByAppendingPathExtension:"png"
set fRes to saveImageRepAtPathAsPNG(resImage, aPath) of me

–NSImageに対して文字を描画する
on drawImageWithString(anImage, drawList, fillColor, dataList, aPSFontName, aFontSize)
  set retinaF to (NSScreen’s mainScreen()’s backingScaleFactor()) as real
  
–>  2.0 (Retina) / 1.0 (Non Retina)
  
  
set aDict to (current application’s NSDictionary’s dictionaryWithObjects:{current application’s NSFont’s fontWithName:aPSFontName |size|:aFontSize, fillColor} forKeys:{current application’s NSFontAttributeName, current application’s NSForegroundColorAttributeName})
  
  
anImage’s lockFocus() –描画開始
  
  
set aLen to length of drawList
  
repeat with i from 1 to aLen
    set i1 to contents of item i of drawList
    
    
set v2 to system attribute "sys2"
    
if v2 ≤ 12 then
      –To macOS 10.12.x
      
set origX to (x of origin of i1) / retinaF
      
set origY to (y of origin of i1) / retinaF
      
set sizeX to (width of |size| of i1) / retinaF
      
set sizeY to (height of |size| of i1) / retinaF
      
set theRect to {{x:origX, y:origY}, {width:sizeX, height:sizeY}}
    else
      –macOS 10.13 or later
      
set origX to (item 1 of item 1 of i1) / retinaF
      
set origY to (item 2 of item 1 of i1) / retinaF
      
set sizeX to (item 1 of item 2 of i1) / retinaF
      
set sizeY to (item 2 of item 2 of i1) / retinaF
      
set theRect to {{origX, origY}, {sizeX, sizeY}}
    end if
    
    
set aString to (current application’s NSString’s stringWithString:((contents of item i of dataList) as string))
    (
aString’s drawAtPoint:(current application’s NSMakePoint(origX + (sizeX / 2), sizeY)) withAttributes:aDict)
  end repeat
  
  
anImage’s unlockFocus() –描画ここまで
  
  
return anImage –returns NSImage
end drawImageWithString

–NSImageに対して矩形を塗りつぶす
on drawImageWithColorFill(anImage, drawList, fillColor)
  set retinaF to (NSScreen’s mainScreen()’s backingScaleFactor()) as real
  
–>  2.0 (Retina) / 1.0 (Non Retina)
  
  
anImage’s lockFocus() –描画開始
  
  
repeat with i in drawList
    
    
set v2 to system attribute "sys2"
    
if v2 ≤ 12 then
      –To macOS 10.12.x
      
set origX to (x of origin of i) / retinaF
      
set origY to (y of origin of i) / retinaF
      
set sizeX to (width of |size| of i) / retinaF
      
set sizeY to (height of |size| of i) / retinaF
      
set theRect to {{x:origX, y:origY}, {width:sizeX, height:sizeY}}
    else
      –macOS 10.13 or later
      
set origX to (item 1 of item 1 of i) / retinaF
      
set origY to (item 2 of item 1 of i) / retinaF
      
set sizeX to (item 1 of item 2 of i) / retinaF
      
set sizeY to (item 2 of item 2 of i) / retinaF
      
set theRect to {{origX, origY}, {sizeX, sizeY}}
    end if
    
    
set theNSBezierPath to NSBezierPath’s bezierPath
    (
theNSBezierPath’s appendBezierPathWithRect:theRect)
    
    
fillColor’s |set|() –色設定
    
theNSBezierPath’s fill() –ぬりつぶし
    
  end repeat
  
  
anImage’s unlockFocus() –描画ここまで
  
  
return anImage –returns NSImage
end drawImageWithColorFill

–画像を指定パスにPNG形式で保存
on saveImageRepAtPathAsPNG(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))
  
return (myNewImageData’s writeToFile:newPath atomically:true) as boolean
end saveImageRepAtPathAsPNG

★Click Here to Open This Script 

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

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

Posted on 4月 6, 2018 by Takaaki Naganoya

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

指定ファイルからUTIを取得するのに外部フレームワークを使っていたのを、Shane Stanleyから「標準機能でできるよ」とツッコミが入って書き換えたものです。

AppleScript名:Finder上で選択中の画像を横方向に連結 v3.scptd
— 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}
  
set bRect to current application’s NSMakeRect(x1, y1, x2, y2)
  
  
newImage’s lockFocus()
  
  
set newImageRect to current application’s CGRectZero
  
set newImageRect’s |size| to (newImage’s |size|)
  
  
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 Finder | Leave a comment

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

Posted on 4月 5, 2018 by Takaaki Naganoya

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

以前掲載したバージョンでは、2枚以上の画像を横に連結しない(座標値の加算ミスを行なって2枚目の座標に上書き)という問題点が見つかったので、修正しておいたものです。

画像2枚でしか試験していなかったので問題自体が見つかっていませんでした。

–> MagicKit.framework (To ~/Library/Frameworks/)

AppleScript名:Finder上で選択中の画像を横方向に連結
— Created 2017-11-21 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "QuartzCore"
use framework "AppKit"
use framework "MagicKit" –https://github.com/aidansteele/magickit

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 GEMagicKit : a reference to current application’s GEMagicKit
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 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
  
  
–指定ファイルのUTIを取得して、画像(public.image)があれば処理を行う
  
set aRes to (GEMagicKit’s magicForFileAtPath:aPath)
  
set utiList to (aRes’s uniformTypeHierarchy()) as list
  
if "public.image" is in utiList 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}
  
set bRect to current application’s NSMakeRect(x1, y1, x2, y2)
  
  
newImage’s lockFocus()
  
  
set newImageRect to current application’s CGRectZero
  
set newImageRect’s |size| to (newImage’s |size|)
  
  
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

★Click Here to Open This Script 

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

アニメーションGIFをフレームごとに画像に分解する

Posted on 4月 5, 2018 by Takaaki Naganoya
AppleScript名:アニメーションGIFをフレームごとにTIFF画像に分解する
— Created 2016-11-29 by Takaaki Naganoya
— 2016 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"

set gifFile to POSIX path of (choose file of type "com.compuserve.gif" with prompt "Select Animation-GIF file")
set destFol to POSIX path of (choose folder with prompt "Select the folder to save gif’s frames")

set anImage to current application’s NSImage’s alloc()’s initWithContentsOfFile:gifFile
if anImage is equal to missing value then error "Illegal GIF Image"

set anImgRep to anImage’s representations()’s firstObject()
set framesNum to (anImgRep’s valueForProperty:"NSImageFrameCount") as integer

repeat with i from 0 to (framesNum – 1)
  (anImgRep’s setProperty:"NSImageCurrentFrame" withValue:i)
  
set aRep to (anImgRep’s representationUsingType:(current application’s NSTIFFFileType) |properties|:(missing value))
  (
aRep’s writeToFile:(destFol & (i as string) & ".tif") atomically:true)
end repeat

★Click Here to Open This Script 

AppleScript名:アニメーションGIFをフレームごとにPNG画像に分解する
— Created 2016-11-29 by Takaaki Naganoya
— 2016 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"

set gifFile to POSIX path of (choose file of type "com.compuserve.gif" with prompt "Select Animation-GIF file")
set destFol to POSIX path of (choose folder with prompt "Select the folder to save gif’s frames")

set anImage to current application’s NSImage’s alloc()’s initWithContentsOfFile:gifFile
if anImage is equal to missing value then error "Illegal GIF Image"

set anImgRep to anImage’s representations()’s firstObject()
set framesNum to (anImgRep’s valueForProperty:"NSImageFrameCount") as integer

repeat with i from 0 to (framesNum – 1)
  (anImgRep’s setProperty:"NSImageCurrentFrame" withValue:i)
  
set aRep to (anImgRep’s representationUsingType:(current application’s NSPNGFileType) |properties|:(missing value))
  (
aRep’s writeToFile:(destFol & (i as string) & ".png") atomically:true)
end repeat

★Click Here to Open This Script 

AppleScript名:アニメーションGIFをフレームごとにJPG画像に分解する
— Created 2016-11-29 by Takaaki Naganoya
— 2016 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"

set gifFile to POSIX path of (choose file of type "com.compuserve.gif" with prompt "Select Animation-GIF file")
set destFol to POSIX path of (choose folder with prompt "Select the folder to save gif’s frames")

set anImage to current application’s NSImage’s alloc()’s initWithContentsOfFile:gifFile
if anImage is equal to missing value then error "Illegal GIF Image"

set anImgRep to anImage’s representations()’s firstObject()
set framesNum to (anImgRep’s valueForProperty:"NSImageFrameCount") as integer

repeat with i from 0 to (framesNum – 1)
  (anImgRep’s setProperty:"NSImageCurrentFrame" withValue:i)
  
set aRep to (anImgRep’s representationUsingType:(current application’s NSJPEGFileType) |properties|:(missing value))
  (
aRep’s writeToFile:(destFol & (i as string) & ".jpg") atomically:true)
end repeat

★Click Here to Open This Script 

AppleScript名:アニメーションGIFをフレームごとにGIFF画像に分解する
— Created 2016-11-29 by Takaaki Naganoya
— 2016 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"

set gifFile to POSIX path of (choose file of type "com.compuserve.gif" with prompt "Select Animation-GIF file")
set destFol to POSIX path of (choose folder with prompt "Select the folder to save gif’s frames")

set anImage to current application’s NSImage’s alloc()’s initWithContentsOfFile:gifFile
if anImage is equal to missing value then error "Illegal GIF Image"

set anImgRep to anImage’s representations()’s firstObject()
set framesNum to (anImgRep’s valueForProperty:"NSImageFrameCount") as integer

repeat with i from 0 to (framesNum – 1)
  (anImgRep’s setProperty:"NSImageCurrentFrame" withValue:i)
  
set aRep to (anImgRep’s representationUsingType:(current application’s NSGIFFileType) |properties|:(missing value))
  (
aRep’s writeToFile:(destFol & (i as string) & ".gif") atomically:true)
end repeat

★Click Here to Open This Script 

Posted in file Image | Tagged 10.11savvy 10.12savvy 10.13savvy | 1 Comment

選択中のEvernoteのNoteに添付されているattachmentのファイルをデスクトップに書き出す

Posted on 4月 1, 2018 by Takaaki Naganoya

Evernoteの選択中のNoteに添付されているattachmentファイル(おそらく画像)をデスクトップに書き出すAppleScriptです。

# Evernoteはバージョン10でAppleScriptサポートが削除されてしまったので、本Scriptはバージョン10以降のEvernoteでは動作しません

書き出す添付ファイルのファイル名はAppleScript経由でオリジナルのものを求めていますが、オリジナルのファイル名に「missing value」を返してくるものもあるので、その場合にはUUIDを割り振っています。

また、MIME TYPEを調査しててきとーに割り振っていますが、すべてのパターンに対処するものではありません。

正直なところ、Evernoteはあまりできのよくないアプリケーションです。同様の機能を提供するアプリケーションやサービスに、もっと出来のいいものがたくさんあります。調子に乗ってAppleScriptから大量のNoteを自動作成すると、デバイス間のデータのシンクロが大量に発生してデータ転送量が増え、利用料金が増えていきます。

# 自分は、MacJournalやmacOS標準装備のメモ(Notes.app)をよく使っています

AppleScript対応機能も動くんだか動かないんだかよくわからないものが多く、挙げ句の果てには間違った命令を実行するとアプリケーションまるごとクラッシュしたりします。

AppleScriptからEvernoteをコントロールしようとすると、

(1)AppleScript用語辞書の範囲内で操作
(2)GUI Scirptingを用いてGUI操作
(3)REST API経由で操作

の3つの方法があるでしょう。Evernoteの(1)の出来がよくないので、(3)について少々調べておくぐらいでしょうか。ただ、調査に無限に時間がかかりそうなので、結局(2)に落ち着きそうな、、、、

AppleScript名:選択中のNoteに添付されているattachmentのファイルをデスクトップに書き出す
set dtPath to (path to desktop folder) as string

tell application "Evernote"
  set aSel to selection
  
if aSel = {} then return
  
  
set aaSel to first item of aSel
  
  
tell aaSel
    set aList to every attachment
    
repeat with i in aList
      set aFN to (filename of i)
      
      
if aFN = missing value then
        –ファイル名が添付画像ファイルについていなかった場合の対策
        
set aFN to (do shell script "uuidgen") & retExtFromEvernoteMIME(mime of i) of me
      end if
      
      
set tmpPath to dtPath & aFN
      
      
try
        write i to file tmpPath
      on error erM
        log erM
      end try
    end repeat
  end tell
  
end tell

–EvernoteのNoteに添付した画像のMIME TYPEから拡張子を判定する(とりあえず版)
on retExtFromEvernoteMIME(aMime)
  if aMime = "image/jpeg" then
    return ".jpg"
  else if aMime = "image/png" then
    return ".png"
  else if aMime = "application/pdf" then
    return ".pdf"
  else
    return ".dat"
  end if
end retExtFromEvernoteMIME

★Click Here to Open This Script 

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

指定PDFの全ページからリンクアノテーションのURLを取得してURLを書きかえる

Posted on 3月 28, 2018 by Takaaki Naganoya

指定PDFの全ページのURLリンクアノテーションのURLを書き換えるAppleScriptです。

URL Linkアノテーションを添付したPDFに対して、Linkアノテーションのboundsを取得して削除し、同じboundsの異なるURLへのリンクアノテーションを作成して保存します。

Keynote、Pages、NumbersのiWorkアプリケーションにはオブジェクトに対してリンクを付加し、URLを指定することができるようになっていますが、URLスキームはhttpがデフォルトで指定されています。

Pages上でURLスキームを指定できたら、それはそれで使い道がいろいろありそうですが、リクエストを出してもここはhttp(かmailto)以外は有効になる気配がありません。

そこで、URLだけダミーのものをこれらのiWorkアプリケーション上で割り振っておいていったんPDF書き出しを行い、書き出されたPDFのLinkアノテーションをあとでAppleScriptから書き換えることで、任意のURLリンクを埋め込むのと同じことができるようになるだろう、と考えて実験してみました。

ただ、1つのグラフィックオブジェクトに対してKeynote上でリンクを付与してPDF書き出しすると、Keynoteがオブジェクトの領域を細分化してリンクを作成するようです。文字とグラフィックにリンクを指定しただけなのに、やたらと大量のリンクアノテーションが検出されるので、念のためにチェックしてみたらこんな(↓)感じでした。

AppleScript名:指定PDFの全ページからリンクアノテーションのURLを取得してURLを書きかえる
— Created 2017-06-08 by Takaaki Naganoya
— Modified 2018-03-14 by Takaaki Naganoya
— 2017, 2018 Piyomaru Software
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
use framework "Quartz"

property |NSURL| : a reference to current application’s |NSURL|
property PDFActionURL : a reference to current application’s PDFActionURL
property PDFDocument : a reference to current application’s PDFDocument
property PDFAnnotationLink : a reference to current application’s PDFAnnotationLink

set aPOSIX to POSIX path of (choose file of type {"com.adobe.pdf"} with prompt "Choose a PDF with Annotation")
set linkList to replaceLinkURLFromPDF(aPOSIX, "http://www.apple.com/jp", "applescript://com.apple.scripteditor?action=new&script=display%20dialog%20%22TEST%22") of me

on replaceLinkURLFromPDF(aPOSIX, origURL, toURL)
  set v2 to system attribute "sys2" –> case: macOS 10.12 =12
  
  
set aURL to (|NSURL|’s fileURLWithPath:aPOSIX)
  
set aPDFdoc to PDFDocument’s alloc()’s initWithURL:aURL
  
set pCount to aPDFdoc’s pageCount()
  
  
–PDFのページ(PDFPage)でループ
  
repeat with ii from 0 to (pCount – 1)
    set tmpPage to (aPDFdoc’s pageAtIndex:ii) –PDFPage
    
    
set anoList to (tmpPage’s annotations()) as list
    
if anoList is not equal to {missing value} then –指定PDF中にAnotationが存在した
      
      
–対象PDFPage内で検出されたAnnotationでループ
      
repeat with i in anoList
        if v2 < 13 then
          set aType to (i’s type()) as string –to macOS Sierra (10.10, 10.11 & 10.12)
        else
          set aType to (i’s |Type|()) as string –macOS High Sierra (10.13) or later
        end if
        
        
–Link Annotationの削除と同様のサイズでLink Annotationの新規作成
        
if aType = "Link" then
          set tmpURL to (i’s |URL|()’s absoluteString()) as string
          
          
if tmpURL = origURL then
            set theBounds to i’s |bounds|() –削除する前にLink Annotationの位置情報を取得
            
–> {origin:{x:78.65625, y:454.7188}, size:{width:96.96875, height:4.0937}}
            
            (
tmpPage’s removeAnnotation:i) –PDFPageから指定のLink Annotationを削除  
            
            
set theLink to (PDFAnnotationLink’s alloc()’s initWithBounds:theBounds)
            
set theAction to (PDFActionURL’s alloc()’s initWithURL:(current application’s |NSURL|’s URLWithString:toURL))
            (
theLink’s setMouseUpAction:theAction)
            (
tmpPage’s addAnnotation:theLink)
            
            
log {ii + 1, theBounds, origURL}
          end if
        end if
      end repeat
    end if
  end repeat
  
  
return (aPDFdoc’s writeToFile:aPOSIX) as boolean
end replaceLinkURLFromPDF

★Click Here to Open This Script 

Posted in file PDF URL | Tagged 10.11savvy 10.12savvy 10.13savvy | 1 Comment

POSIX path stringを与えると、ファイル名の重複を検出&名称回避を行って、ファイル名のみを返す

Posted on 3月 23, 2018 by Takaaki Naganoya

POSIX pathのフルパスの文字列(quoteなし)を与えると、そのファイルを実際に作成した場合に指定のパスに同名のファイルが存在するかどうか重複検出を行い、重複するものがあった場合には重複回避してファイル名を返すAppleScriptです。

# 一部ミスがあるものを掲載していたので、書き換えておきました

ファイルの新規保存を行う際に、安全に新しい名称を指定できるよう、重複検出および重複回避を行います。

デスクトップ上に、

  test.jpg
  test_1.jpg

というファイルがあった場合に、本Scriptで「test.jpg」を指定すると、同じ名前のファイルがデスクトップに存在するものと判定されて、名称の衝突回避を行います。

回避するためにファイル名の末尾に「_」+番号を付けて回避を行いますが、すでに「test_1.jpg」が存在するために、本Scriptではさらに名称回避を行なって「test_2.jpg」の文字列を返します。

子番号については、1〜65535の範囲で追加するようにしています。常識的にこれだけ指定しておけば大丈夫だろう、ということであってとくに上限に意味はありません。

AppleScript名:POSIX path stringを与えると、ファイル名の重複を検出&名称回避を行って、ファイル名のみを返す v2
— Created 2020-08-15 by Takaaki Naganoya
— 2015-2020 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

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

set newPath to POSIX path of (choose file name)

set ab to chkExistPOSIXpathAndIncrementChildNumber(newPath) of me

–POSIX path stringを与えると、ファイル名の重複を検出して、ファイル名の名称回避を行って、ファイル名のみを返す
on chkExistPOSIXpathAndIncrementChildNumber(aPOSIX as string)
  set aStr to NSString’s stringWithString:aPOSIX
  
  
–ファイルパス(フルパス)からファイル名部分を取得
  
set bStr to aStr’s lastPathComponent()
  
–> "P0000_000.csv"
  
  
–ファイル名から拡張子を取得
  
set cStr to (bStr’s pathExtension()) as string
  
–> "csv"
  
  
–ファイル名から拡張子を削除
  
set dStr to (bStr’s stringByDeletingPathExtension()) as string
  
–> "P0000_000"
  
  
–ファイルパス(フルパス)から親フォルダを取得(ただし末尾はスラッシュになっていない)
  
set eStr to (aStr’s stringByDeletingLastPathComponent()) as string
  
–>  "/Users/me/Desktop"
  
  
set aManager to NSFileManager’s defaultManager()
  
set aRes to (aManager’s fileExistsAtPath:aStr) as boolean
  
if aRes = false then
    –ファイル名の衝突がなかった場合
    
return bStr as string
  end if
  
  
set hitF to false
  
repeat with i from 1 to 65535
    
    
set tmpPath to (eStr & "/" & dStr & "_" & (i as string) & "." & cStr)
    
set tmpStr to (NSString’s stringWithString:tmpPath)
    
set aRes to (aManager’s fileExistsAtPath:tmpStr) as boolean
    
set bRes to ((tmpStr’s caseInsensitiveCompare:eStr) is not equal to (NSOrderedSame)) as boolean
    
    
if {aRes, bRes} = {false, true} then
      set hitF to true
      
exit repeat
    end if
    
  end repeat
  
  
if hitF = false then return false
  
  
–ファイルパス(フルパス)からファイル名部分を取得
  
set returnFileName to tmpStr’s lastPathComponent()
  
return (returnFileName as string)
  
end chkExistPOSIXpathAndIncrementChildNumber

★Click Here to Open This Script 

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

指定フォルダ内の指定文字列を含むファイル名のファイルをPOSIX pathのlistで抽出する

Posted on 3月 21, 2018 by Takaaki Naganoya
AppleScript名:指定フォルダ内の指定文字列を含むファイル名のファイルをPOSIX pathのlistで抽出する
— Created 2017-09-12 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

property |NSURL| : a reference to current application’s |NSURL|
property NSPredicate : a reference to current application’s NSPredicate
property NSFileManager : a reference to current application’s NSFileManager
property NSMutableArray : a reference to current application’s NSMutableArray
property NSURLIsDirectoryKey : a reference to current application’s NSURLIsDirectoryKey
property NSDirectoryEnumerationSkipsHiddenFiles : a reference to current application’s NSDirectoryEnumerationSkipsHiddenFiles
property NSDirectoryEnumerationSkipsPackageDescendants : a reference to current application’s NSDirectoryEnumerationSkipsPackageDescendants
property NSDirectoryEnumerationSkipsSubdirectoryDescendants : a reference to current application’s NSDirectoryEnumerationSkipsSubdirectoryDescendants

set aFol to POSIX path of (choose folder with prompt "Choose folder" default location (path to desktop folder))
set pRes to my getFilesByIncludedStringInName:"スクリーン" fromDirectory:aFol exceptPackages:true
–> {"/Users/me/Desktop/スクリーンショット 2018-02-28 14.01.09.png", "/Users/me/Desktop/スクリーンショット 2018-02-28 14.01.11.png", …}

–指定フォルダ内の指定文字列を含むファイル名のファイルをPOSIX pathのlistで抽出する
on getFilesByIncludedStringInName:(fileNameStr as string) fromDirectory:(sourceFolder) exceptPackages:(packageF as boolean)
  set fileManager to NSFileManager’s defaultManager()
  
set aURL to |NSURL|’s fileURLWithPath:sourceFolder
  
set theOptions to ((NSDirectoryEnumerationSkipsPackageDescendants) as integer) + ((NSDirectoryEnumerationSkipsHiddenFiles) as integer) + ((NSDirectoryEnumerationSkipsSubdirectoryDescendants) as integer)
  
set directoryContents to fileManager’s contentsOfDirectoryAtURL:aURL includingPropertiesForKeys:{} options:theOptions |error|:(missing value)
  
set findPredicates to NSPredicate’s predicateWithFormat_("lastPathComponent CONTAINS %@", fileNameStr)
  
set foundItemList to directoryContents’s filteredArrayUsingPredicate:findPredicates
  
  
–Remove Folders From found URL Array
  
set anArray to NSMutableArray’s alloc()’s init()
  
repeat with i in foundItemList
    set j to contents of i
    
set {theResult, isDirectory} to (j’s getResourceValue:(reference) forKey:(NSURLIsDirectoryKey) |error|:(missing value))
    
    
–Collect files
    
if (isDirectory as boolean = false) then
      (anArray’s addObject:j)
      
    else if (packageF = false) then
      –Allow Package files?
      
set {theResult, isPackage} to (j’s getResourceValue:(reference) forKey:(current application’s NSURLIsPackageKey) |error|:(missing value))
      
if (isPackage as boolean) = true then
        (anArray’s addObject:j)
      end if
    end if
    
  end repeat
  
  
return (anArray’s valueForKey:"path") as list
end getFilesByIncludedStringInName:fromDirectory:exceptPackages:

★Click Here to Open This Script 

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

ファイルの存在確認

Posted on 3月 20, 2018 by Takaaki Naganoya
AppleScript名:ファイルの存在確認
— Created 2017-10-31 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"

set aPath to POSIX path of (choose file)
set aExt to current application’s NSFileManager’s defaultManager()’s fileExistsAtPath:aPath
–> true

★Click Here to Open This Script 

AppleScript名:ファイルの存在確認(OLD Style AS)
set aFile to choose file

tell application "Finder"
  set aRes to exists of aFile
  
–> true
end tell

★Click Here to Open This Script 

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

2フォルダ間の内容比較

Posted on 3月 20, 2018 by Takaaki Naganoya
AppleScript名:2フォルダ間の内容比較
— Created 2015-12-22 by Takaaki Naganoya
— 2015 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set aFol to (choose folder with prompt "Select Folder A")
set bFol to (choose folder with prompt "Select Folder B")

set aPath to POSIX path of aFol
set bPath to POSIX path of bFol

set aFM to current application’s NSFileManager’s defaultManager()
set aRes to (aFM’s contentsEqualAtPath:aPath andPath:bPath) as boolean

★Click Here to Open This Script 

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

2ファイルの内容比較(Binary)

Posted on 3月 20, 2018 by Takaaki Naganoya
AppleScript名:2ファイルの内容比較(Binary)
— Created 2016-03-22 by Takaaki Naganoya
— 2016 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set aPOSIX to POSIX path of (choose file with prompt "Select File A")
set bPOSIX to POSIX path of (choose file with prompt "Select File B")

set aDat to current application’s NSMutableData’s dataWithContentsOfFile:aPOSIX
set bDat to current application’s NSMutableData’s dataWithContentsOfFile:bPOSIX

set aRes to (aDat’s isEqualToData:bDat) as boolean

★Click Here to Open This Script 

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

2ファイルの内容比較(UTF-8 String)

Posted on 3月 20, 2018 by Takaaki Naganoya
AppleScript名:2ファイルの内容比較(UTF-8 String)
— Created 2016-03-22 by Takaaki Naganoya
— 2016 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set aPOSIX to POSIX path of (choose file with prompt "Select Text File A")
set bPOSIX to POSIX path of (choose file with prompt "Select Text File B")

set aStr to current application’s NSString’s stringWithContentsOfFile:aPOSIX encoding:(current application’s NSUTF8StringEncoding) |error|:(missing value)
set bStr to current application’s NSString’s stringWithContentsOfFile:bPOSIX encoding:(current application’s NSUTF8StringEncoding) |error|:(missing value)

set aRes to (aStr’s isEqualToString:bStr) as boolean

★Click Here to Open This Script 

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

画面キャプチャから指定アプリケーションの表示エリアを切り抜いてファイル書き出し v2

Posted on 3月 2, 2018 by Takaaki Naganoya

指定アプリケーションのメインウィンドウのサイズとポジションを取得し、画面キャプチャから該当エリアを切り抜いてPNG画像に書き出すAppleScriptです。

Mac Blue-ray Playerの再生中のポジションを取得しようとして、AppleScript用語辞書の中身を確認したところ、そのような属性値は存在していません。

そこで、GUI Scripting経由でウィンドウ上のUser Interfaceを確認してみたところ、

といったように、現在の再生ポジションを取得できるような部品にアクセスすることはできませんでした。

ここまで試してダメということは、さすがにAppleScriptでも画面上からまっとうな方法で文字情報を拾うことはできません。

そこで試してみたのがコレです。GUI Scripting経由でメインウィンドウの大きさと位置は取得できます。画面のスクリーンキャプチャから当該エリアのみ切り抜くことも可能です。

そして、現在再生位置を示す文字情報(おそらく画像としてレンダリングして表示)のエリアはウィンドウ位置とサイズから計算で求められます。

これらの文字を、たとえばMicrosoftのCognitive APIなどを呼び出してOCR処理を行うか、あるいは画素数がきわめて少ない情報であるためAppleScript単独で画像解析して0〜9の数字との類似度を計算して擬似的に文字認識を行うといったことは可能でしょう。

いまひとつ、そうした試行錯誤を行う時間がないため、「とりあえず」の場所で止めておきますが、、、、できそうといえばできそうな感じが、、、するようなしないような。

AppleScript名:画面キャプチャから指定アプリケーションの表示エリアを切り抜いてファイル書き出し v2
— Created 2015-12-22 by Takaaki Naganoya
— Modified 2018-03-02 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "Quartz"
use framework "AppKit"
use framework "ApplicationServices"

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

tell application "Blu-ray Player" to activate
tell application "System Events"
  tell application process "Mac Blu-ray Player"
    tell window 1
      set {xSize, ySize} to size
      
set {xPos, yPos} to position
    end tell
  end tell
end tell

do shell script "/usr/sbin/screencapture -c -x"
set aImage to current application’s NSImage’s alloc()’s initWithPasteboard:(current application’s NSPasteboard’s generalPasteboard())

set cropedImage to my cropNSImageBy:{xPos, yPos, xSize, ySize} fromImage:aImage

set aPath to POSIX path of (path to desktop)
set fRes to retUUIDfilePathFromDir(aPath, "png") of me
set sRes to saveNSImageAtPathAsPNG(cropedImage, fRes) of me

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:

–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

★Click Here to Open This Script 

Posted in file Image | Tagged 10.11savvy 10.12savvy 10.13savvy Mac Blu-ray Player | Leave a comment

表示中のCotEditor書類の「前」のファイルを縦書きでオープン v3

Posted on 3月 1, 2018 by Takaaki Naganoya

CotEditor内のScript Menuに入れて、現在オープン中の(連番つき)テキストファイルと同一フォルダに入っているテキストファイルのうち、番号が「前」に該当するファイルのXattr(拡張属性)を操作して、CotEditorの縦書き属性を追加し、CotEditorのファイルオープン時にデフォルトで縦書き表示を行うAppleScriptです。

前バージョンではGUI Scriptingを使っていたため、CotEditor内蔵Script MenuではなくOS側のScript Menuから呼び出すことしかできませんでした。本バージョンでは、CotEditor内蔵メニューから呼び出せます。

CotEditor内蔵Script Menuから呼べると、ファイル名に指定の特殊文字を入れておくことで、キーボードショートカットから呼び出せるようになります。

–> XAttribute.framework (To ~/Library/Frameworks/)

AppleScript名:表示中のCotEditor書類の「前」のファイルを縦書きでオープン v3
— Created 2017-12-15 by Takaaki Naganoya
— Modified 2018-02-28 by Takaaki Naganoya
— 2018 Piyomaru Software
–v3:Xattrに追記してCotEditorでデフォルト縦書き表示を行わせた。CotEditorのアプリケーション内のScript Menuから実行可能に
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "XAttribute" –https://github.com/rylio/OTMXAttribute
use bPlus : script "BridgePlus"

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 NSPredicate : a reference to current application’s NSPredicate
property NSFileManager : a reference to current application’s NSFileManager
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 NSDirectoryEnumerationSkipsHiddenFiles : a reference to current application’s NSDirectoryEnumerationSkipsHiddenFiles
property NSDirectoryEnumerationSkipsPackageDescendants : a reference to current application’s NSDirectoryEnumerationSkipsPackageDescendants
property NSDirectoryEnumerationSkipsSubdirectoryDescendants : a reference to current application’s NSDirectoryEnumerationSkipsSubdirectoryDescendants

load framework

tell application "CotEditor"
  set dCount to count every document
  
if dCount = 0 then return
  
  
tell front document
    set curPath to path –returns POSIX path, not alias or file
  end tell
  
  
tell window 1
    set aBounds to bounds
  end tell
end tell

–オープン中のテキストファイルの親フォルダを求める
set aPath to NSString’s stringWithString:curPath
set fileName to (aPath’s lastPathComponent()) –ファイル名
set pathExtension to aPath’s pathExtension() as string –拡張子
set parentFol to (aPath’s stringByDeletingLastPathComponent()) as string —親フォルダ

–同じフォルダから同じ拡張子のファイルのファイル名を取得
set fList to my getFilesByIncludedStringInName:(pathExtension) fromDirectory:(parentFol) exceptPackages:(true)

–昇順ソート
set aArray to NSArray’s arrayWithArray:fList
set desc1 to NSSortDescriptor’s sortDescriptorWithKey:"self" ascending:true selector:"localizedCaseInsensitiveCompare:"
set bArray to aArray’s sortedArrayUsingDescriptors:{desc1}

–ファイル名検索
set aIndex to (SMSForder’s indexesOfItem:fileName inArray:bArray inverting:false) as list
if aIndex = {} then
  display notification "Error: File Not Found"
  
return
end if

set bIndex to (contents of first item of aIndex) + 1 – 1 –0 based to 1 based conversion & previous one
set aLen to length of (bArray as list)
if bIndex > aLen then
  display notification "Error: Out of bounds"
  
return
end if

set newFile to contents of item bIndex of (bArray as list)
set newPath to parentFol & "/" & newFile

–Add Vertical Xattribute (for CotEditor only)
set xRes to addXAttrToFile(newPath, "com.coteditor.VerticalText", "1") of me

–Open Previous Document
tell application "CotEditor"
  set oldDoc to front document
  
  
open (POSIX file newPath) as alias
  
tell window 1
    set bounds to aBounds
  end tell
  
  
close oldDoc without saving
end tell

–指定フォルダ内の指定文字列を含むファイル名のファイルをPOSIX pathのlistで抽出する
on getFilesByIncludedStringInName:(fileNameStr as string) fromDirectory:(sourceFolder) exceptPackages:(packageF as boolean)
  set fileManager to NSFileManager’s defaultManager()
  
set aURL to |NSURL|’s fileURLWithPath:sourceFolder
  
set theOptions to ((NSDirectoryEnumerationSkipsPackageDescendants) as integer) + ((NSDirectoryEnumerationSkipsHiddenFiles) as integer) + ((NSDirectoryEnumerationSkipsSubdirectoryDescendants) as integer)
  
set directoryContents to fileManager’s contentsOfDirectoryAtURL:aURL includingPropertiesForKeys:{} options:theOptions |error|:(missing value)
  
set findPredicates to NSPredicate’s predicateWithFormat_("lastPathComponent CONTAINS %@", fileNameStr)
  
set foundItemList to directoryContents’s filteredArrayUsingPredicate:findPredicates
  
  
–Remove Folders From found URL Array
  
set anArray to NSMutableArray’s alloc()’s init()
  
repeat with i in foundItemList
    set j to contents of i
    
set {theResult, isDirectory} to (j’s getResourceValue:(reference) forKey:(NSURLIsDirectoryKey) |error|:(missing value))
    
    
–Collect files
    
if (isDirectory as boolean = false) then
      (anArray’s addObject:j)
      
    else if (packageF = false) then
      –Allow Package files?
      
set {theResult, isPackage} to (j’s getResourceValue:(reference) forKey:(NSURLIsPackageKey) |error|:(missing value))
      
if (isPackage as boolean) = true then
        (anArray’s addObject:j)
      end if
    end if
    
  end repeat
  
  
return (anArray’s valueForKey:"lastPathComponent") as list
end getFilesByIncludedStringInName:fromDirectory:exceptPackages:

on addXAttrToFile(aFile, anXattr, aValue)
  –Get Xattr String
  
set anAttribute to (current application’s OTMXAttribute’s stringAttributeAtPath:aFile |name|:anXattr |error|:(missing value))
  
if anAttribute is not equal to missing value then –Already Exists
    set tmpRes to removeXAttrFromFile(aFile, anXattr) of me
    
if tmpRes = false then return false
  end if
  
  
–Set Xattr
  
set xRes to (current application’s OTMXAttribute’s setAttributeAtPath:aFile |name|:anXattr value:aValue |error|:(missing value))
  
if xRes = missing value then return false
  
return (xRes as boolean)
end addXAttrToFile

on removeXAttrFromFile(aFile, anXattr)
  –Get Xattr String
  
set anAttribute to (current application’s OTMXAttribute’s stringAttributeAtPath:aFile |name|:anXattr |error|:(missing value))
  
if anAttribute = missing value then return true –There is no use to remove xattr
  
  
–Remove Xattr
  
set xRes to (current application’s OTMXAttribute’s removeAttributeAtPath:aFile |name|:anXattr |error|:(missing value))
  
if xRes = missing value then return false
  
return (xRes as boolean)
end removeXAttrFromFile

★Click Here to Open This Script 

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

表示中のCotEditor書類の「次」のファイルを縦書きでオープン v3

Posted on 3月 1, 2018 by Takaaki Naganoya

CotEditor内のScript Menuに入れて、現在オープン中の(連番つき)テキストファイルと同一フォルダに入っているテキストファイルのうち、番号が「次」に該当するファイルのXattr(拡張属性)を操作して、CotEditorの縦書き属性を追加し、CotEditorのファイルオープン時にデフォルトで縦書き表示を行うAppleScriptです。

前バージョンではGUI Scriptingを使っていたため、CotEditor内蔵Script MenuではなくOS側のScript Menuから呼び出すことしかできませんでした。本バージョンでは、CotEditor内蔵メニューから呼び出せます。

–> XAttribute.framework (To ~/Library/Frameworks/)

–> Demo Movie

AppleScript名:表示中のCotEditor書類の「次」のファイルを縦書きでオープン v3
— Created 2017-12-15 by Takaaki Naganoya
— Modified 2018-02-28 by Takaaki Naganoya
— 2018 Piyomaru Software
–v3:Xattrに追記してCotEditorでデフォルト縦書き表示を行わせた。CotEditorのアプリケーション内のScript Menuから実行可能に
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "XAttribute" –https://github.com/rylio/OTMXAttribute
use bPlus : script "BridgePlus"

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 NSPredicate : a reference to current application’s NSPredicate
property NSFileManager : a reference to current application’s NSFileManager
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 NSDirectoryEnumerationSkipsHiddenFiles : a reference to current application’s NSDirectoryEnumerationSkipsHiddenFiles
property NSDirectoryEnumerationSkipsPackageDescendants : a reference to current application’s NSDirectoryEnumerationSkipsPackageDescendants
property NSDirectoryEnumerationSkipsSubdirectoryDescendants : a reference to current application’s NSDirectoryEnumerationSkipsSubdirectoryDescendants

load framework

tell application "CotEditor"
  set dCount to count every document
  
if dCount = 0 then return
  
  
tell front document
    set curPath to path –returns POSIX path, not alias or file
  end tell
  
  
tell window 1
    set aBounds to bounds
  end tell
end tell

–オープン中のテキストファイルの親フォルダを求める
set aPath to NSString’s stringWithString:curPath
set fileName to (aPath’s lastPathComponent()) –ファイル名
set pathExtension to aPath’s pathExtension() as string –拡張子
set parentFol to (aPath’s stringByDeletingLastPathComponent()) as string —親フォルダ

–同じフォルダから同じ拡張子のファイルのファイル名を取得
set fList to my getFilesByIncludedStringInName:(pathExtension) fromDirectory:(parentFol) exceptPackages:(true)

–昇順ソート
set aArray to NSArray’s arrayWithArray:fList
set desc1 to NSSortDescriptor’s sortDescriptorWithKey:"self" ascending:true selector:"localizedCaseInsensitiveCompare:"
set bArray to aArray’s sortedArrayUsingDescriptors:{desc1}

–ファイル名検索
set aIndex to (SMSForder’s indexesOfItem:fileName inArray:bArray inverting:false) as list
if aIndex = {} then
  display notification "Error: File Not Found"
  
return
end if

set bIndex to (contents of first item of aIndex) + 1 + 1 –0 based to 1 based conversion & next one
set aLen to length of (bArray as list)
if bIndex > aLen then
  display notification "Error: Out of bounds"
  
return
end if

set newFile to contents of item bIndex of (bArray as list)
set newPath to parentFol & "/" & newFile

–Add Vertical Xattribute (for CotEditor only)
set xRes to addXAttrToFile(newPath, "com.coteditor.VerticalText", "1") of me

–Open Next Document
tell application "CotEditor"
  set oldDoc to front document
  
  
open (POSIX file newPath) as alias
  
tell window 1
    set bounds to aBounds
  end tell
  
  
close oldDoc without saving
end tell

–指定フォルダ内の指定文字列を含むファイル名のlistを抽出する
on getFilesByIncludedStringInName:(fileNameStr as string) fromDirectory:(sourceFolder) exceptPackages:(packageF as boolean)
  set fileManager to NSFileManager’s defaultManager()
  
set aURL to |NSURL|’s fileURLWithPath:sourceFolder
  
set theOptions to (NSDirectoryEnumerationSkipsPackageDescendants as integer) + (NSDirectoryEnumerationSkipsHiddenFiles as integer) + (NSDirectoryEnumerationSkipsSubdirectoryDescendants as integer)
  
set directoryContents to fileManager’s contentsOfDirectoryAtURL:aURL includingPropertiesForKeys:{} options:theOptions |error|:(missing value)
  
set findPredicates to NSPredicate’s predicateWithFormat_("lastPathComponent CONTAINS %@", fileNameStr)
  
set foundItemList to directoryContents’s filteredArrayUsingPredicate:findPredicates
  
  
–Remove Folders From found URL Array
  
set anArray to NSMutableArray’s alloc()’s init()
  
repeat with i in foundItemList
    set j to contents of i
    
set {theResult, isDirectory} to (j’s getResourceValue:(reference) forKey:(NSURLIsDirectoryKey) |error|:(missing value))
    
    
–Collect files
    
if (isDirectory as boolean = false) then
      (anArray’s addObject:j)
    else if (packageF = false) then
      –Allow Package files?
      
set {theResult, isPackage} to (j’s getResourceValue:(reference) forKey:(NSURLIsPackageKey) |error|:(missing value))
      
if (isPackage as boolean) = true then
        (anArray’s addObject:j)
      end if
    end if
    
  end repeat
  
  
return (anArray’s valueForKey:"lastPathComponent") as list
end getFilesByIncludedStringInName:fromDirectory:exceptPackages:

on addXAttrToFile(aFile, anXattr, aValue)
  –Get Xattr String
  
set anAttribute to (current application’s OTMXAttribute’s stringAttributeAtPath:aFile |name|:anXattr |error|:(missing value))
  
if anAttribute is not equal to missing value then –Already Exists
    set tmpRes to removeXAttrFromFile(aFile, anXattr) of me
    
if tmpRes = false then return false
  end if
  
  
–Set Xattr
  
set xRes to (current application’s OTMXAttribute’s setAttributeAtPath:aFile |name|:anXattr value:aValue |error|:(missing value))
  
if xRes = missing value then return false
  
return (xRes as boolean)
end addXAttrToFile

on removeXAttrFromFile(aFile, anXattr)
  –Get Xattr String
  
set anAttribute to (current application’s OTMXAttribute’s stringAttributeAtPath:aFile |name|:anXattr |error|:(missing value))
  
if anAttribute = missing value then return true –There is no use to remove xattr
  
  
–Remove Xattr
  
set xRes to (current application’s OTMXAttribute’s removeAttributeAtPath:aFile |name|:anXattr |error|:(missing value))
  
if xRes = missing value then return false
  
return (xRes as boolean)
end removeXAttrFromFile

★Click Here to Open This Script 

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

OTMXAttributeで指定ファイルにxattrを追加してテキストファイルにCotEditor縦書き表示属性を付加する

Posted on 2月 28, 2018 by Takaaki Naganoya

指定テキストファイルのXattr(拡張属性)を操作して、CotEditorの縦書き属性を追加し、CotEditorのファイルオープン時にデフォルトで縦書き表示を行うAppleScriptです。

–> XAttribute.framework (To ~/Library/Frameworks/)

try! macOS meet-upの席上でCotEditorメンテナーの1024jpさんに

「(CotEditorに)デフォルトでプレーンテキストの縦書き表示を行わせる機能ってないんでしょうか?」

と聞いてみたら、本Xattrの存在を教えてもらえました。

これで、GUI Scriptingを併用せずに縦書き表示ができるようになったので、CotEditor内蔵Script Menuからでも縦書きで表示させるファイルを切り替えるようなScriptを呼び出せました。


▲デフォルト時


▲本ScriptによりXattrを追加してFinderからオープン、あるいはCotEditorからオープンを行なった状態

AppleScript名:OTMXAttributeで指定ファイルにxattrを追加する
— Created 2018-02-28 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
use framework "XAttribute" –https://github.com/rylio/OTMXAttribute

set aFile to POSIX path of (choose file)
set xRes to addXAttrToFile(aFile, "com.coteditor.VerticalText", "1")

on addXAttrToFile(aFile, anXattr, aValue)
  –Get Xattr String
  
set anAttribute to (current application’s OTMXAttribute’s stringAttributeAtPath:aFile |name|:anXattr |error|:(missing value))
  
if anAttribute is not equal to missing value then –Already Exists
    set tmpRes to removeXAttrFromFile(aFile, anXattr) of me
    
if tmpRes = false then return false
  end if
  
  
–Set Xattr
  
set xRes to (current application’s OTMXAttribute’s setAttributeAtPath:aFile |name|:anXattr value:aValue |error|:(missing value))
  
if xRes = missing value then return false
  
return (xRes as boolean)
end addXAttrToFile

on removeXAttrFromFile(aFile, anXattr)
  –Get Xattr String
  
set anAttribute to (current application’s OTMXAttribute’s stringAttributeAtPath:aFile |name|:anXattr |error|:(missing value))
  
if anAttribute = missing value then return true –There is no use to remove xattr
  
  
–Remove Xattr
  
set xRes to (current application’s OTMXAttribute’s removeAttributeAtPath:aFile |name|:anXattr |error|:(missing value))
  
if xRes = missing value then return false
  
return (xRes as boolean)
end removeXAttrFromFile

★Click Here to Open This Script 

Posted in file Text | Tagged 10.11savvy 10.12savvy 10.13savvy CotEditor | 1 Comment

Pages書類からPDF書き出し v2

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

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

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

★Click Here to Open This Script 

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

Post navigation

  • Older posts
  • Newer posts

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

Google Search

Popular posts

  • 開発機としてM2 Mac miniが来たのでガチレビュー
  • CotEditorで2つの書類の行単位での差分検出
  • macOS 13.6.5 AS系のバグ、一切直らず
  • macOS 15, Sequoia
  • 初心者がつまづきやすい「log」コマンド
  • 指定のWordファイルをPDFに書き出す
  • Pages本執筆中に、2つの書類モード切り替えに気がついた
  • Adobe AcrobatをAppleScriptから操作してPDF圧縮
  • メキシカンハットの描画
  • 与えられた文字列の1D Listのすべての順列組み合わせパターン文字列を返す v3(ベンチマーク用)
  • 2023年に書いた価値あるAppleScript
  • Pixelmator Pro v3.6.4でAppleScriptからの操作時の挙動に違和感が
  • Numbersで選択範囲のセルの前後の空白を削除
  • AdobeがInDesign v19.4からPOSIX pathを採用
  • Safariで「プロファイル」機能を使うとAppleScriptの処理に影響
  • Cocoa Scripting Course 続刊計画
  • AppleScriptによる並列処理
  • macOS 14.xでScript Menuの実行速度が大幅に下がるバグ
  • NaturalLanguage.frameworkでNLEmbeddingの処理が可能な言語をチェック
  • AppleScript入門③AppleScriptを使った「自動化」とは?

Tags

10.11savvy (1102) 10.12savvy (1243) 10.13savvy (1392) 10.14savvy (587) 10.15savvy (438) 11.0savvy (283) 12.0savvy (212) 13.0savvy (188) 14.0savvy (138) 15.0savvy (116) CotEditor (64) Finder (51) iTunes (19) Keynote (115) NSAlert (61) NSArray (51) NSBitmapImageRep (20) NSBundle (20) NSButton (34) NSColor (53) NSDictionary (28) NSFileManager (23) NSFont (21) NSImage (41) NSJSONSerialization (21) NSMutableArray (63) NSMutableDictionary (22) NSPredicate (36) NSRunningApplication (56) NSScreen (30) NSScrollView (22) NSString (119) NSURL (98) NSURLRequest (23) NSUTF8StringEncoding (30) NSView (33) NSWorkspace (20) Numbers (75) Pages (54) Safari (44) Script Editor (27) WKUserContentController (21) WKUserScript (20) WKWebView (23) WKWebViewConfiguration (22)

カテゴリー

  • 2D Bin Packing
  • 3D
  • AirDrop
  • AirPlay
  • Animation
  • AppleScript Application on Xcode
  • Beginner
  • Benchmark
  • beta
  • Bluetooth
  • Books
  • boolean
  • bounds
  • Bug
  • Calendar
  • call by reference
  • check sum
  • Clipboard
  • Cocoa-AppleScript Applet
  • Code Sign
  • Color
  • Custom Class
  • 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)
  • 未分類

アーカイブ

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

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

メタ情報

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

Forum Posts

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

メタ情報

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