Archive for the 'NSFontManager' Category

2017/12/08 指定文字の花文字を取得してRTFで書き出す

指定文字の花文字を取得して、収録グリフ数が10,000以上のフォントから30をデスクトップにRTFで書き出すAppleScriptです。

注意:ただし、本ScriptはRetina Display未対応です

hanamoji1.png

前のバージョンからの改良点は、

 〇慊衒源が指定フォント中にグリフを持っているかどうかチェックしてから処理
 ▲ぅ鵐好函璽襪気譴討い襯侫ント数が少ない場合への対処

といったところです。

花文字作成部分の処理内容は、

 ”漸荵慊衒源を収録しているフォントの一覧を取得
 ↓,納萋世靴織侫ントのうち、グリフ数が10,000以上のものをピックアップ
 スタイル付きテキストを作成。仕上がり(描画)サイズを取得
 せ転紊りサイズでRaw画像を作成
 ズ鄒したRaw画像を塗りつぶす(White)
 ε匹蠅弔屬靴Raw画像にスタイル付きテキストを描画
 Raw画像の各座標から色情報をピックアップ、指定スレッショルド値以上であればドットが存在していると判定
 ┘疋奪箸存在している場合には描画文字列を、存在していない場合にはスペースを配列に追加
 作成した2次元配列をテキストに変換。フォント名をテキストに含める指定を行なっている場合にはフォントのPostScript名を文字列に出力

というところです。

これまでは(macOS 10.10より前)AppleScriptで画像処理を行おうとすると、Photoshopあたりで処理するのが定番でしたが、Cocoaの機能を利用することで、カラープロファイル処理が厳密に求められるような内容でなければPhotoshopなしでけっこうな処理が行えるようになってきました。

テキスト処理において(文字コード自動判別が可能になったため)テキストエディタが要らなくなってきたように、データベース処理で(小規模データであれば)FileMaker Proが要らなくなってきて、同様に画像処理でもPhotoshopなしで処理できるものが増えてきた今日このごろです。

AppleScript名:指定文字の花文字を取得してRTFで書き出す
– Created 2017-11-19 by Takaaki Naganoya
– 2017 Piyomaru Software
use AppleScript version “2.4″
use scripting additions
use framework “Foundation”
use framework “AppKit”
–http://piyocast.com/as/archives/5012

property NSArray : a reference to current application’s NSArray
property NSMutableDictionary : a reference to current application’s NSMutableDictionary
property NSBezierPath : a reference to current application’s NSBezierPath
property NSMutableParagraphStyle : a reference to current application’s NSMutableParagraphStyle
property NSPNGFileType : a reference to current application’s NSPNGFileType
property NSFontAttributeName : a reference to current application’s NSFontAttributeName
property NSKernAttributeName : a reference to current application’s NSKernAttributeName
property NSLigatureAttributeName : a reference to current application’s NSLigatureAttributeName
property NSFont : a reference to current application’s NSFont
property NSUUID : a reference to current application’s NSUUID
property NSMutableAttributedString : a reference to current application’s NSMutableAttributedString
property NSUnderlineStyleAttributeName : a reference to current application’s NSUnderlineStyleAttributeName
property NSImage : a reference to current application’s NSImage
property NSParagraphStyleAttributeName : a reference to current application’s NSParagraphStyleAttributeName
property NSString : a reference to current application’s NSString
property NSForegroundColorAttributeName : a reference to current application’s NSForegroundColorAttributeName
property NSBitmapImageRep : a reference to current application’s NSBitmapImageRep
property NSColor : a reference to current application’s NSColor
property NSColorSpace : a reference to current application’s NSColorSpace
property NSFontManager : a reference to current application’s NSFontManager
property NSPredicate : a reference to current application’s NSPredicate
property NSDictionary : a reference to current application’s NSDictionary

set aString to “あ”
set hanaMax to 30
set hanaSize to 36
set targFontName to “Osaka-Mono” –”Courier New”–結果を出力するRTFのフォント名(PostScript名)

set fRes to getEveryFontPSNameANdGlyphsNum() of me
set theArray to NSArray’s arrayWithArray:fRes
set thePred to NSPredicate’s predicateWithFormat:“fontNum > 10000″
set bArray to (theArray’s filteredArrayUsingPredicate:thePred) as list

if hanaMax > (length of bArray) then
  set hanaMax to (length of bArray)
end if

set aCount to 1

repeat hanaMax * 2 times
  set aFontName to contents of item aCount of bArray
  
  
–花文字文字列を作成
  
set fRes to getHanamojiStr(hanaSize, fontName of aFontName, aString, 0.7, true) of me
  
if fResfalse then
    –StyledStringで結果出力(RTFとしてファイル保存)
    
set aStyledStr to makeRTFfromParameters(fRes, targFontName, 11, 0.0, 0.0) of me
    
set aRange to current application’s NSMakeRange(0, aStyledStr’s |length|())
    
set aVal1 to NSFont’s fontWithName:targFontName |size|:11
    
    
aStyledStr’s beginEditing()
    (
aStyledStr’s addAttribute:(NSFontAttributeName) value:aVal1 range:aRange)
    
aStyledStr’s endEditing()
    
    
set targFol to POSIX path of (path to desktop)
    
set aUUID to NSUUID’s UUID()’s UUIDString() as text
    
set bRes to my saveStyledTextAsRTF(aUUID, targFol, aStyledStr) –RTFで書き出す
    
    
set aCount to aCount + 1
    
if aCount > hanaMax then exit repeat
  end if
end repeat

–花文字文字列を計算して返す
on getHanamojiStr(aFontSize as real, aFontName as string, aString as string, aThread as real, incFontName as boolean)
  if length of aString is not equal to 1 then return false
  
  
–指定文字コードが指定フォント中に存在するかチェック
  
set fRes to retGlyphsInFont(aFontName, id of aString) of me
  
if fRes = false then return false
  
  
set aThreadShould to 768 * aThread
  
if (chkMultiByteChar(aString) of me) = false then
    set spaceChar to string id 12288 –全角スペース(UTF-16)
  else
    set spaceChar to string id 32 –半角スペース
  end if
  
  
set fillColor to NSColor’s whiteColor –塗り色
  
set bString to aString & ” “ –処理内容の帳尻合わせ(そのままだと右端が欠けるのでスペースを入れた)
  
set anAssrStr to makeRTFfromParameters(bString, aFontName, aFontSize, -2, (aFontSize * 1.2)) of me
  
set aSize to anAssrStr’s |size|()
  
  
if class of aSize = record then
    set attrStrWidth to width of aSize
    
set attrStrHeight to height of aSize
  else if class of aSize = list then –macOS 10.13.xのバグ回避
    copy aSize to {attrStrWidth, attrStrHeight}
  end if
  
  
set {xPos, yPos} to {0, 0}
  
  
set tmpImg1 to makeImageWithFilledColor(attrStrWidth, attrStrHeight, fillColor) of me
  
set tmpImg2 to drawAttributedStringsOnImage(tmpImg1, anAssrStr, xPos, yPos) of me
  
set aRawimg to NSBitmapImageRep’s imageRepWithData:(tmpImg2’s TIFFRepresentation())
  
  
–画像から順次指定座標の色データを拾って花文字listに反映
  
set strList to {}
  
repeat with y from 1 to attrStrHeight - 1
    
    
set strListX to {}
    
repeat with x from 0 to attrStrWidth - 1
      set tmpCol to getColorFromRawImage(aRawimg, x, y) of me
      
      
if tmpCol is not equal to false then
        if tmpCol is not equal to {255, 255, 255} then
          copy tmpCol to {tmpR, tmpG, tmpB}
          
if (tmpR + tmpG + tmpB) < aThreadShould then
            set the end of strListX to aString
          else
            set the end of strListX to spaceChar
          end if
        else
          set the end of strListX to spaceChar
        end if
      end if
      
    end repeat
    
set the end of strList to strListX
  end repeat
  
  
–2D List→Text
  
set aRes to list2dToStringByUsingDelimiters(strList, “”, return) of me
  
  
if incFontName = true then
    set fName to getDisplayedNameOfFont(aFontName) of me
    
set aRes to “■” & fName & return & return & aRes
  end if
  
  
return aRes
end getHanamojiStr

–指定Raw画像中の指定座標のピクセルの色をRGBで取り出す
on getColorFromRawImage(aRawimg, x as real, y as real)
  set origColor to (aRawimg’s colorAtX:x y:y)
  
set srgbColSpace to NSColorSpace’s deviceRGBColorSpace
  
if srgbColSpace = missing value then return false
  
  
set aColor to (origColor’s colorUsingColorSpace:srgbColSpace)
  
  
set aRed to (aColor’s redComponent()) * 255
  
set aGreen to (aColor’s greenComponent()) * 255
  
set aBlue to (aColor’s blueComponent()) * 255
  
  
return {aRed as integer, aGreen as integer, aBlue as integer}
end getColorFromRawImage

–画像のうえに指定のスタイル付きテキストを描画して画像を返す
on drawAttributedStringsOnImage(anImage, anAssrStr, xPos as real, yPos as real)
  anImage’s lockFocus()
  
anAssrStr’s drawAtPoint:(current application’s NSMakePoint(xPos, yPos))
  
anImage’s unlockFocus()
  
return anImage
end drawAttributedStringsOnImage

–書式つきテキストを組み立てる
on makeRTFfromParameters(aStr as string, fontName as string, aFontSize as real, aKerning as real, aLineSpacing as real)
  set aVal1 to NSFont’s fontWithName:fontName |size|:aFontSize
  
set aKey1 to (NSFontAttributeName)
  
  
set aVal2 to NSColor’s blackColor()
  
set aKey2 to (NSForegroundColorAttributeName)
  
  
set aVal3 to aKerning
  
set akey3 to (NSKernAttributeName)
  
  
set aVal4 to 0
  
set akey4 to (NSUnderlineStyleAttributeName)
  
  
set aVal5 to 2 –all ligature ON
  
set akey5 to (NSLigatureAttributeName)
  
  
set aParagraphStyle to NSMutableParagraphStyle’s alloc()’s init()
  
aParagraphStyle’s setMinimumLineHeight:(aLineSpacing)
  
aParagraphStyle’s setMaximumLineHeight:(aLineSpacing)
  
set akey7 to (NSParagraphStyleAttributeName)
  
  
set keyList to {aKey1, aKey2, akey3, akey4, akey5, akey7}
  
set valList to {aVal1, aVal2, aVal3, aVal4, aVal5, aParagraphStyle}
  
set attrsDictionary to NSMutableDictionary’s dictionaryWithObjects:valList forKeys:keyList
  
  
set attrStr to NSMutableAttributedString’s alloc()’s initWithString:aStr attributes:attrsDictionary
  
return attrStr
end makeRTFfromParameters

–指定サイズの画像を作成し、背景を指定色で塗る
on makeImageWithFilledColor(aWidth as real, aHeight as real, fillColor)
  set anImage to 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 NSBezierPath’s bezierPath
  
theNSBezierPath’s appendBezierPathWithRect:theRect
  
fillColor’s |set|()
  
theNSBezierPath’s fill()
  
anImage’s unlockFocus()
  
  
return anImage
end makeImageWithFilledColor

–2D Listをアイテム間および行間のデリミタを個別に指定してテキスト変換
on list2dToStringByUsingDelimiters(aList as list, itemDelimiter, lineDelimiter)
  set outList to {}
  
repeat with i in aList
    set aStr to listToStringUsingTextItemDelimiter(i, itemDelimiter) of me
    
set the end of outList to aStr
  end repeat
  
  
set bStr to listToStringUsingTextItemDelimiter(outList, lineDelimiter) of me
  
return bStr
end list2dToStringByUsingDelimiters

on listToStringUsingTextItemDelimiter(sourceList as list, textItemDelimiter)
  set CocoaArray to NSArray’s arrayWithArray:sourceList
  
set CocoaString to CocoaArray’s componentsJoinedByString:textItemDelimiter
  
return (CocoaString as string)
end listToStringUsingTextItemDelimiter

–ユーザー環境にインストールされているすべてのフォントのPostScript名とグリフ数を返す
on getEveryFontPSNameANdGlyphsNum()
  set aFontList to NSFontManager’s sharedFontManager()’s availableFonts()
  
set thePred to NSPredicate’s predicateWithFormat:“NOT SELF BEGINSWITH ’.’”
  
set aFontList to (aFontList’s filteredArrayUsingPredicate:thePred) as list
  
  
set aList to {}
  
repeat with i in aFontList
    set aName to contents of i
    
set aNum to countNumberOfGlyphsInFont(aName) of me
    
set the end of aList to {fontName:aName, fontNum:aNum}
  end repeat
  
  
return aList
end getEveryFontPSNameANdGlyphsNum

–指定Postscript名称のフォントに定義されている文字数を数えて返す
on countNumberOfGlyphsInFont(fontName as string)
  set aFont to NSFont’s fontWithName:fontName |size|:9.0
  
if aFont = missing value then return false
  
set aProp to aFont’s numberOfGlyphs()
  
return aProp as number
end countNumberOfGlyphsInFont

–フォントのPostScript NameからDisplayed Nameを取得
on getDisplayedNameOfFont(aName as string)
  set aFont to NSFont’s fontWithName:aName |size|:9.0
  
set aDispName to (aFont’s displayName()) as string
  
return aDispName
end getDisplayedNameOfFont

–全角文字が存在するか
on chkMultiByteChar(checkString as string)
  set aStr to NSString’s stringWithString:checkString
  
set aRes to aStr’s canBeConvertedToEncoding:(current application’s NSASCIIStringEncoding)
  
return (aRes as boolean)
end chkMultiByteChar

–スタイル付きテキストを指定フォルダ(POSIX path)にRTFで書き出し
on saveStyledTextAsRTF(aFileName as string, targFol as string, aStyledString)
  set bstyledLength to aStyledString’s |string|()’s |length|()
  
set bDict to NSDictionary’s dictionaryWithObject:“NSRTFTextDocumentType” forKey:(current application’s NSDocumentTypeDocumentAttribute)
  
set bRTF to aStyledString’s RTFFromRange:(current application’s NSMakeRange(0, bstyledLength)) documentAttributes:bDict
  
  
set theName to NSString’s stringWithString:aFileName
  
set theName to theName’s stringByReplacingOccurrencesOfString:“/” withString:“_”
  
set theName to theName’s stringByReplacingOccurrencesOfString:“:” withString:“_”
  
set thePath to NSString’s stringWithString:targFol
  
set thePath to (thePath’s stringByAppendingPathComponent:theName)’s stringByAppendingPathExtension:“rtf”
  
  
return (bRTF’s writeToFile:thePath atomically:true) as boolean
end saveStyledTextAsRTF

–指定名称のフォントに指定の文字コードが含まれているかチェック
on retGlyphsInFont(fontName as string, strCode as integer)
  set aFont to NSFont’s fontWithName:fontName |size|:24.0
  
if aFont = missing value then return false
  
set aSet to aFont’s coveredCharacterSet()
  
set aRes to (aSet’s characterIsMember:strCode) as boolean
  
return aRes as list of string or string –as anything
end retGlyphsInFont

★Click Here to Open This Script 

2017/11/18 指定文字の花文字を取得 v1.2

OS内にインストールされているフォントのうち収録グリフ数が8,000以上のフォントから50個をリストアップして、各フォントで花文字を作成してCotEditor上に花文字で新規ドキュメントを作成するAppleScriptです。

注意:ただし、本ScriptはRetina Display未対応です

flowerchar3_resized.png

フォント50個に限定しているのは、大量にCotEditorでドキュメントを作成するとCotEditorのパフォーマンスが大幅に低下するためです(メモリの都合? 常識的な挙動なので問題ではありません。ドキュメントの開きすぎで)。

なお、OS内にインストールされているフォントの数が極端に少ない環境(条件に合致するフォントが50個ないとか)ではエラーになる可能性があります。

flowerchar2_resized.png

CotEditor上に50個の未保存のドキュメントができてしまうので、一括で破棄するAppleScriptを掲載しておきます。

2017-11-18-22_12_04.gif

tell application “CotEditor”
  tell every document
    close without saving
  end tell
end tell

★Click Here to Open This Script 

AppleScript名:指定文字の花文字を取得 v1.2
– Created 2017-11-18 by Takaaki Naganoya
– 2017 Piyomaru Software
use AppleScript version “2.4″
use scripting additions
use framework “Foundation”
use framework “AppKit”
–http://piyocast.com/as/archives/4984

property NSArray : a reference to current application’s NSArray
property NSMutableDictionary : a reference to current application’s NSMutableDictionary
property NSBezierPath : a reference to current application’s NSBezierPath
property NSMutableParagraphStyle : a reference to current application’s NSMutableParagraphStyle
property NSPNGFileType : a reference to current application’s NSPNGFileType
property NSFontAttributeName : a reference to current application’s NSFontAttributeName
property NSKernAttributeName : a reference to current application’s NSKernAttributeName
property NSLigatureAttributeName : a reference to current application’s NSLigatureAttributeName
property NSFont : a reference to current application’s NSFont
property NSMutableAttributedString : a reference to current application’s NSMutableAttributedString
property NSUnderlineStyleAttributeName : a reference to current application’s NSUnderlineStyleAttributeName
property NSImage : a reference to current application’s NSImage
property NSParagraphStyleAttributeName : a reference to current application’s NSParagraphStyleAttributeName
property NSString : a reference to current application’s NSString
property NSForegroundColorAttributeName : a reference to current application’s NSForegroundColorAttributeName
property NSBitmapImageRep : a reference to current application’s NSBitmapImageRep
property NSColor : a reference to current application’s NSColor
property NSColorSpace : a reference to current application’s NSColorSpace
property NSFontManager : a reference to current application’s NSFontManager
property NSPredicate : a reference to current application’s NSPredicate

set aString to “ぴ”

set fRes to getEveryFontPSNameANdGlyphsNum() of me
set theArray to current application’s NSArray’s arrayWithArray:fRes
set thePred to current application’s NSPredicate’s predicateWithFormat:“fontNum > 8000″
set bArray to (theArray’s filteredArrayUsingPredicate:thePred) as list
set cArray to items 1 thru 50 of bArray

repeat with i in cArray
  set aFontName to contents of i
  
set fRes to getHanamojiStr(18, fontName of aFontName, aString, 0.7, true) of me
  
makeNewCotEditorDoc(fRes) of me
end repeat

–花文字文字列を計算して返す
on getHanamojiStr(aFontSize, aFontName, aString, aThread, incFontName)
  if length of aString is not equal to 1 then return false
  
  
set aThreadShould to 768 * aThread
  
  
set fillColor to NSColor’s whiteColor –塗り色
  
set bString to aString & ” “
  
set anAssrStr to makeRTFfromParameters(bString, aFontName, aFontSize, -2, (aFontSize * 1.2)) of me
  
set aSize to anAssrStr’s |size|()
  
  
if class of aSize = record then
    set attrStrWidth to width of aSize
    
set attrStrHeight to height of aSize
  else if class of aSize = list then –macOS 10.13.xのバグ回避
    copy aSize to {attrStrWidth, attrStrHeight}
  end if
  
  
set {xPos, yPos} to {0, 0}
  
  
–下地の画像を作成
  
set tmpImg1 to makeImageWithFilledColor(attrStrWidth, attrStrHeight, fillColor) of me
  
  
–下地の画像の上にAttributed Stringを描画
  
set tmpImg2 to drawAttributedStringsOnImage(tmpImg1, anAssrStr, xPos, yPos) of me
  
  
–NSImageからRaw画像を作成
  
set aRawimg to NSBitmapImageRep’s imageRepWithData:(tmpImg2’s TIFFRepresentation())
  
  
–画像から順次指定座標の色データを拾って花文字listに反映
  
set strList to {}
  
repeat with y from 1 to attrStrHeight - 1
    
    
set strListX to {}
    
repeat with x from 0 to attrStrWidth - 1
      set tmpCol to getColorFromRawImage(aRawimg, x, y) of me
      
      
if tmpCol is not equal to false then
        if tmpCol is not equal to {255, 255, 255} then
          copy tmpCol to {tmpR, tmpG, tmpB}
          
if (tmpR + tmpG + tmpB) < aThreadShould then
            set the end of strListX to aString
          else
            set the end of strListX to “ ”
          end if
        else
          set the end of strListX to “ ”
        end if
      end if
      
    end repeat
    
set the end of strList to strListX
  end repeat
  
  
–2D List→Text
  
set aRes to list2dToStringByUsingDelimiters(strList, “ ”, return) of me
  
  
if incFontName = true then
    set fName to getDisplayedNameOfFont(aFontName) of me
    
set aRes to “■” & fName & return & return & aRes
  end if
  
  
return aRes
end getHanamojiStr

–指定Raw画像中の指定座標のピクセルの色をRGBで取り出す
on getColorFromRawImage(aRawimg, x, y)
  set origColor to (aRawimg’s colorAtX:x y:y)
  
set srgbColSpace to NSColorSpace’s deviceRGBColorSpace
  
if srgbColSpace = missing value then return false
  
  
set aColor to (origColor’s colorUsingColorSpace:srgbColSpace)
  
  
set aRed to (aColor’s redComponent()) * 255
  
set aGreen to (aColor’s greenComponent()) * 255
  
set aBlue to (aColor’s blueComponent()) * 255
  
  
return {aRed as integer, aGreen as integer, aBlue as integer}
end getColorFromRawImage

–画像のうえに指定のスタイル付きテキストを描画して画像を返す
on drawAttributedStringsOnImage(anImage, anAssrStr, xPos, yPos)
  anImage’s lockFocus()
  
anAssrStr’s drawAtPoint:(current application’s NSMakePoint(xPos, yPos))
  
anImage’s unlockFocus()
  
return anImage
end drawAttributedStringsOnImage

–書式つきテキストを組み立てる
on makeRTFfromParameters(aStr as string, fontName as string, aFontSize as real, aKerning as real, aLineSpacing as real)
  set aVal1 to NSFont’s fontWithName:fontName |size|:aFontSize
  
set aKey1 to (NSFontAttributeName)
  
  
set aVal2 to NSColor’s blackColor()
  
set aKey2 to (NSForegroundColorAttributeName)
  
  
set aVal3 to aKerning
  
set akey3 to (NSKernAttributeName)
  
  
set aVal4 to 0
  
set akey4 to (NSUnderlineStyleAttributeName)
  
  
set aVal5 to 2 –all ligature ON
  
set akey5 to (NSLigatureAttributeName)
  
  
set aParagraphStyle to NSMutableParagraphStyle’s alloc()’s init()
  
aParagraphStyle’s setMinimumLineHeight:(aLineSpacing)
  
aParagraphStyle’s setMaximumLineHeight:(aLineSpacing)
  
set akey7 to (NSParagraphStyleAttributeName)
  
  
set keyList to {aKey1, aKey2, akey3, akey4, akey5, akey7}
  
set valList to {aVal1, aVal2, aVal3, aVal4, aVal5, aParagraphStyle}
  
set attrsDictionary to NSMutableDictionary’s dictionaryWithObjects:valList forKeys:keyList
  
  
set attrStr to NSMutableAttributedString’s alloc()’s initWithString:aStr attributes:attrsDictionary
  
return attrStr
end makeRTFfromParameters

–指定サイズの画像を作成し、背景を指定色で塗る
on makeImageWithFilledColor(aWidth, aHeight, fillColor)
  set anImage to 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 NSBezierPath’s bezierPath
  
theNSBezierPath’s appendBezierPathWithRect:theRect
  
fillColor’s |set|()
  
theNSBezierPath’s fill()
  
anImage’s unlockFocus()
  
  
return anImage
end makeImageWithFilledColor

–2D Listをアイテム間および行間のデリミタを個別に指定してテキスト変換
on list2dToStringByUsingDelimiters(aList, itemDelimiter, lineDelimiter)
  set outList to {}
  
repeat with i in aList
    set aStr to listToStringUsingTextItemDelimiter(i, itemDelimiter) of me
    
set the end of outList to aStr
  end repeat
  
  
set bStr to listToStringUsingTextItemDelimiter(outList, lineDelimiter) of me
  
return bStr
end list2dToStringByUsingDelimiters

on listToStringUsingTextItemDelimiter(sourceList, textItemDelimiter)
  set CocoaArray to NSArray’s arrayWithArray:sourceList
  
set CocoaString to CocoaArray’s componentsJoinedByString:textItemDelimiter
  
return (CocoaString as string)
end listToStringUsingTextItemDelimiter

on getEveryFontPSNameANdGlyphsNum()
  set aFontList to NSFontManager’s sharedFontManager()’s availableFonts()
  
set thePred to NSPredicate’s predicateWithFormat:“NOT SELF BEGINSWITH ’.’”
  
set aFontList to (aFontList’s filteredArrayUsingPredicate:thePred) as list
  
  
set aList to {}
  
repeat with i in aFontList
    set aName to contents of i
    
set aNum to countNumberOfGlyphsInFont(aName) of me
    
set the end of aList to {fontName:aName, fontNum:aNum}
  end repeat
  
  
return aList
end getEveryFontPSNameANdGlyphsNum

–指定Postscript名称のフォントに定義されている文字数を数えて返す
on countNumberOfGlyphsInFont(fontName)
  set aFont to current application’s NSFont’s fontWithName:fontName |size|:9.0
  
if aFont = missing value then return false
  
set aProp to aFont’s numberOfGlyphs()
  
return aProp
end countNumberOfGlyphsInFont

–フォントのPostScript NameからDisplayed Nameを取得
on getDisplayedNameOfFont(aName)
  set aFont to current application’s NSFont’s fontWithName:aName |size|:9.0
  
set aDispName to (aFont’s displayName()) as string
  
return aDispName
end getDisplayedNameOfFont

on makeNewCotEditorDoc(aCon)
  tell application “CotEditor”
    set newDoc to make new document
    
tell newDoc
      set contents to aCon
    end tell
  end tell
end makeNewCotEditorDoc

★Click Here to Open This Script 

2017/11/02 インストールされているフォントをdisplay nameからキーワード検索 v3

macにインストールされているフォントのdisplay nameからキーワード検索するAppleScriptのShane Stanleyによる高速版です。

  「さすがにFontBook検索より遅いのはダメでしょ」

というツッコミがShane Stanleyからあり、このコードがメールで届いたのでありました。

 FontBook.app:0.6 sec.
 AppleScriptObjc:0.2 sec.

と、このぐらいだと納得できる感じでしょう。

私にはこの、

 NSFontManager’s sharedFontManager()’s availableFonts()

というメソッドを見つけ切れなかったので(一番上に書いてあるのに ーー;)ああいう書き方をしましたが、NSFontManagerからavailableFontFamilies()を経由しないでavailableFonts()で一気に個別のフォント名を取得できれば、条件抽出も割と高速にできるわけです。

AppleScript名:インストールされているフォントをdisplay nameからキーワード検索 v3
– Created 2017-11-01 by Takaaki Naganoya
– Modified 2017-11-02 by Shane Stanley
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"
–http://piyocast.com/as/archives/4948

property NSFontManager : a reference to current application’s NSFontManager
property NSFont : a reference to current application’s NSFont
property NSPredicate : a reference to current application’s NSPredicate

set fRes to getEveryFontContainsAQueryStr("Helvetica") of me
–>  {"Helvetica", "Helvetica-Bold", "Helvetica-BoldOblique", "Helvetica-Light", "Helvetica-LightOblique", "Helvetica-Oblique", "HelveticaNeue", "HelveticaNeue-Bold", "HelveticaNeue-BoldItalic", "HelveticaNeue-CondensedBlack", "HelveticaNeue-CondensedBold", "HelveticaNeue-Italic", "HelveticaNeue-Light", "HelveticaNeue-LightItalic", "HelveticaNeue-Medium", "HelveticaNeue-MediumItalic", "HelveticaNeue-Thin", "HelveticaNeue-ThinItalic", "HelveticaNeue-UltraLight", "HelveticaNeue-UltraLightItalic"}

set fRes to getEveryFontContainsAQueryStr("ことり") of me
–>  {"TheLittleBirdFONT", "kotorimojiFONT-TT"}

on getEveryFontContainsAQueryStr(queryName as string)
  set hitFontList to {}
  
set aFontList to NSFontManager’s sharedFontManager()’s availableFonts()
  
– filter out hidden fonts
  
set thePred to NSPredicate’s predicateWithFormat:"NOT SELF BEGINSWITH ’.’"
  
set aFontList to aFontList’s filteredArrayUsingPredicate:thePred
  
  
repeat with fontName in aFontList
    set aFont to (NSFont’s fontWithName:fontName |size|:16)
    
set aDispFontName to (aFont’s displayName()) as string
    
    
if aDispFontName contains queryName then
      set end of hitFontList to (fontName as text)
    end if
  end repeat
  
  
return hitFontList
end getEveryFontContainsAQueryStr

★Click Here to Open This Script 

2017/11/02 インストールされているフォントをdisplay nameからキーワード検索 v2

macにインストールされているフォントのdisplay nameからキーワード検索するAppleScriptの修正版です。

最初に作成したものを(2年後に)FontBook.appを呼び出すAppleScriptと処理結果を比較したところ、ASOC版の方が間違っていたので修正してみました(たまたま実戦で使っていなかったので、それほど真剣に検証していなかったもよう)。

修正した結果、

 FontBook.app:0.6 sec.
 AppleScriptObjc:0.9 sec.

FontBook版よりも処理時間がかかっています。起動時にこうした「処理に時間がかかる計算」を行っておき、結果をキャッシュしておくことで「見た目の処理時間」を減らすことも可能でしょう。

AppleScript名:インストールされているフォントをdisplay nameからキーワード検索 v2
– Created 2015-08-27 by Takaaki Naganoya
– Modified 2017-11-01 by Takaaki Naganoya
– 2017 Piyomaru Software
use AppleScript version “2.4″
use scripting additions
use framework “Foundation”
use framework “AppKit”
–http://piyocast.com/as/archives/4947

property NSFontManager : a reference to current application’s NSFontManager
property NSFont : a reference to current application’s NSFont

set fRes to getEveryFontContainsAQueryStr(“Helvetica”) of me
–>  {”Helvetica”, “Helvetica-Oblique”, “Helvetica-Light”, “Helvetica-LightOblique”, “Helvetica-Bold”, “Helvetica-BoldOblique”, “HelveticaNeue”, “HelveticaNeue-Italic”, “HelveticaNeue-UltraLight”, “HelveticaNeue-UltraLightItalic”, “HelveticaNeue-Thin”, “HelveticaNeue-ThinItalic”, “HelveticaNeue-Light”, “HelveticaNeue-LightItalic”, “HelveticaNeue-Medium”, “HelveticaNeue-MediumItalic”, “HelveticaNeue-Bold”, “HelveticaNeue-BoldItalic”, “HelveticaNeue-CondensedBold”, “HelveticaNeue-CondensedBlack”}

set fRes to getEveryFontContainsAQueryStr(“ことり”) of me
–>  {”kotorimojiFONT-TT”, “TheLittleBirdFONT”}

on getEveryFontContainsAQueryStr(queryName as string)
  set aFontFamilyList to (NSFontManager’s sharedFontManager()’s availableFontFamilies()) as list
  
set hitFontList to {}
  
  
repeat with i in aFontFamilyList
    set aFontList to (current application’s NSFontManager’s sharedFontManager()’s availableMembersOfFontFamily:(i as string)) as list
    
set tmpList to {}
    
repeat with ii in aFontList
      copy ii to {tmpFontName, tmpFontStyle, tmpA, tmpB}
      
      
set aFont to (NSFont’s fontWithName:tmpFontName |size|:16)
      
set aDispFontName to (aFont’s displayName()) as string
      
      
if aDispFontName contains queryName then
        set hitFontList to hitFontList & tmpFontName
      end if
    end repeat
  end repeat
  
  
return hitFontList
end getEveryFontContainsAQueryStr

★Click Here to Open This Script 

2017/11/01 インストールされているフォントをdisplay nameからキーワード検索

macにインストールされているフォントのdisplay nameからキーワード検索するAppleScriptです。

FontBook.appで処理するのとくらべて、ほんの少し速いぐらいです(起動時間を考慮しなければ)。

 FontBook.app:0.6 sec.
 AppleScriptObjc:0.4 sec.

10回実行して平均処理時間が20%程度高速でした。

→ ASOC版はFontではなくFont Familyを検索していました。FontBookの処理の方が正しい内容です。修正版はこちら。

AppleScript名:インストールされているフォントをdisplay nameからキーワード検索
– Created 2015-08-27 by Takaaki Naganoya
– 2015 Piyomaru Software
use AppleScript version “2.4″
use scripting additions
use framework “Foundation”
use framework “AppKit”
–http://piyocast.com/as/archives/4946

property NSFontManager : a reference to current application’s NSFontManager
property NSFont : a reference to current application’s NSFont

set fRes to getEveryFontContainsAQueryStr(“Helvetica”) of me
–>  {{”Helvetica”, “Helvetica”, “Helvetica”}, {”Helvetica Neue”, “Helvetica Neue”, “HelveticaNeue”}}

set fRes to getEveryFontContainsAQueryStr(“ことり”) of me
–>  {{”kotorimojiFONT TT”, “ことり文字ふぉんと等幅”, “kotorimojiFONT-TT”}, {”TheLittleBirdFONT”, “ことり文字ふぉんと”, “TheLittleBirdFONT”}}

on getEveryFontContainsAQueryStr(queryName)
  set aFontList to (NSFontManager’s sharedFontManager()’s availableFontFamilies()) as list
  
  
set hitList to {}
  
  
repeat with i in aFontList
    set aFont to (NSFont’s fontWithName:(i as string) |size|:16)
    
set aDispFontName to (aFont’s displayName()) as string
    
set aFontName to (aFont’s fontName()) as string
    
    
if aDispFontName contains queryName then
      set the end of hitList to {i as string, aDispFontName, aFontName}
    end if
  end repeat
  
  
return hitList
end getEveryFontContainsAQueryStr

★Click Here to Open This Script 

AppleScript名:インストールされているフォントをdisplay nameからキーワード検索(FontBook)
tell application “Font Book”
  set ffList1 to (name of every typeface whose displayed name contains “Helvetica”)
  
–> {”Helvetica Light”, “Helvetica”, “Helvetica Oblique”, “Helvetica Light Oblique”, “Helvetica Bold”, “Helvetica Bold Oblique”, “Helvetica Neue UltraLight”, “Helvetica Neue Thin”, “Helvetica Neue Medium”, “Helvetica Neue Light”, “Helvetica Neue”, “Helvetica Neue Italic”, “Helvetica Neue UltraLight Italic”, “Helvetica Neue Thin Italic”, “Helvetica Neue Medium Italic”, “Helvetica Neue Light Italic”, “Helvetica Neue Bold”, “Helvetica Neue Bold Italic”, “Helvetica Neue Condensed Black”, “Helvetica Neue Condensed Bold”}
  
  
set ffList2 to (name of every typeface whose displayed name contains “ことり”)
  
–> {”kotorimojiFONT-TT”, “TheLittleBirdFONT”}
end tell

★Click Here to Open This Script 

2015/08/28 ASOCでNSFont,NSFontManagerのじっけん

AppleScriptでNSFontやNSFontManagerを操作して情報を取得する実験です。

このあたり、Cocoaを呼べるからものすごい処理ができるぞ(TTSの音声検索なんかはわりとすごい)、とかいうことはなくて・・・普通にPure AppleScriptでFontBook.appを操作する方が有意義な感じがします。

Photoshop書類のテキストレイヤーからフォント情報を取り出してまとめて出力するAppleScriptを組んだときには、FontBookを用いてフォント情報の付け合わせを行いましたが・・・ここであえてNSFontやNSFontManagerを呼び出してみたところで、イレギュラーなフォントについてはまともに名前などの情報を返してこないケースもありますし、Photoshopのテキストレイヤー上に複数のフォントを指定してしまうとScript側からは正しく取得できないので困ります。

AppleScript名:ASOCでNSFontのじっけん
– Created 2015-08-27 by Takaaki Naganoya
– 2015 Piyomaru Software
use AppleScript version “2.4″
use scripting additions
use framework “Foundation”
use framework “AppKit”

set aFont to current application’s NSFont’s fontWithName:“HiraKakuStd-W8″ |size|:16
–>  (NSFont) “HiraKakuStd-W8 16.00 pt. P [] (0×600001457340) fobj=0×6180001f2800, spc=5.33″

aFont’s displayName()
–>  (NSString) “ヒラギノ角ゴ Std W8″

aFont’s familyName()
–>  (NSString) “Hiragino Kaku Gothic Std”

aFont’s fontName()
–>  (NSString) “HiraKakuStd-W8″

aFont’s coveredCharacterSet()
–>  (__NSCFCharacterSet) <__nscfcharacterset : 0x6000004472c0>

aFont’s fontDescriptor()
(*)
–>  (NSCTFontDescriptor) NSCTFontDescriptor <0×61800009cb60> = {
NSFontNameAttribute = “HiraKakuStd-W8″;
NSFontSizeAttribute = 16;
}
*)

aFont’s mostCompatibleStringEncoding()
–>  2.147483649E+9 –???

aFont’s renderingMode()
–>  1
(*
typedef enum NSFontRenderingMode : NSUInteger {
NSFontDefaultRenderingMode = 0,
NSFontAntialiasedRenderingMode = 1,
NSFontIntegerAdvancementsRenderingMode = 2,
NSFontAntialiasedIntegerAdvancementsRenderingMode = 3
} NSFontRenderingMode;
*)

aFont’s printerFont()
–>  (NSFont) “HiraKakuStd-W8 16.00 pt. P [] (0×600001457340) fobj=0×6180001f2800, spc=5.33″

aFont’s screenFont()
–>  (NSFont) “HiraKakuStd-W8 16.00 pt. S [] (0×600001457340) fobj=0×6180001f2800, spc=5.00″

aFont’s numberOfGlyphs()
–>  9354

★Click Here to Open This Script 

AppleScript名:ASOCでNSFontManagerのじっけん
– Created 2015-08-27 by Takaaki Naganoya
– 2015 Piyomaru Software
use AppleScript version “2.4″
use scripting additions
use framework “Foundation”
use framework “AppKit”

set aFontMan to current application’s NSFontManager’s sharedFontManager()’s availableFontFamilies()
–>  (NSArray) {​​​​​”01FLOPDESIGN”, ​​​​​”A-OTF Shin Go Pr6N”, ​​​​​”A-OTF Shin Go Pro”, ​​​​​”Abadi MT Condensed Extra Bold”, ​​​​​”Abadi MT Condensed Light”, ​​​​​”AGENDAJinmeiGyoshotaiL1″, ​​​​​”AGENDAJinmeiSeikaishotaiL1″, ​​​​​”Akubin”,….}

set aFontMan to current application’s NSFontManager’s sharedFontManager()’s availableMembersOfFontFamily:“MS Mincho”
–>  (NSArray) {​​​​​{​​​​​​​”MS-Mincho”, ​​​​​​​”Regular”, ​​​​​​​1, ​​​​​​​0​​​​​}​​​}

set aFontMan to current application’s NSFontManager’s sharedFontManager()’s availableMembersOfFontFamily:“Times”
–>  (NSArray) {​​​​​{​​​​​​​”Times-Roman”, ​​​​​​​”Regular”, ​​​​​​​1, ​​​​​​​0​​​​​}, ​​​​​{​​​​​​​”Times-Italic”, ​​​​​​​”Italic”, ​​​​​​​1, ​​​​​​​1​​​​​}, ​​​​​{​​​​​​​”Times-Bold”, ​​​​​​​”Bold”, ​​​​​​​1, ​​​​​​​2​​​​​}, ​​​​​{​​​​​​​”Times-BoldItalic”, ​​​​​​​”Bold Italic”, ​​​​​​​1, ​​​​​​​3​​​​​}​​​}

set aFontMan to current application’s NSFontManager’s sharedFontManager()’s localizedNameForFamily:“Osaka” face:“Regular-Mono”
–>  (NSString) “レギュラー−等幅”

★Click Here to Open This Script