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

タグ: 10.13savvy

PDFから本文テキストを抽出して配列にストアして文字列検索

Posted on 2月 6, 2018 by Takaaki Naganoya
AppleScript名:PDFから本文テキストを抽出して配列にストアして文字列検索
— Created 2017-06-18 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "Quartz"

property textCache : missing value
property aList : {}

–検索対象の語群
set sList to {"notification", "Cocoa"} –considering case

set thePath to POSIX path of (choose file of type {"com.adobe.pdf"})

–PDFのテキスト内容をあらかじめページごとに読み取って、検索用のテキストキャッシュを作成
set anNSURL to (current application’s |NSURL|’s fileURLWithPath:thePath)
set theDoc to current application’s PDFDocument’s alloc()’s initWithURL:anNSURL
set theCount to theDoc’s pageCount() as integer

set textCache to current application’s NSMutableArray’s new()

repeat with i from 0 to (theCount – 1)
  set aPage to (theDoc’s pageAtIndex:i)
  
set tmpStr to (aPage’s |string|())
  (
textCache’s addObject:{pageIndex:i + 1, pageString:tmpStr})
end repeat

–主にテキストキャッシュを対象にキーワード検索
repeat with s in sList
  
  
–❶部分一致で抽出
  
set bRes to ((my filterRecListByLabel1(textCache, "pageString contains ’" & s & "’"))’s pageIndex) as list
  
  
–❷、❶のページ単位のテキスト検索で見つからなかった場合(ページ間でまたがっている場合など)
  
if bRes = {} then
    set bRes to {}
    
set theSels to (theDoc’s findString:s withOptions:0)
    
repeat with aSel in theSels
      set thePage to (aSel’s pages()’s objectAtIndex:0)’s label()
      
set curPage to (thePage as integer)
      
if curPage is not in bRes then
        set the end of bRes to curPage
      end if
    end repeat
  end if
  
  
set the end of aList to bRes
  
end repeat

return aList

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

★Click Here to Open This Script 

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

PDFの本文テキスト内容からリンクURLを抽出する

Posted on 2月 6, 2018 by Takaaki Naganoya
AppleScript名:本文テキスト内容からリンクURLを抽出する
— Created 2017-08-12 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
use framework "Quartz"
use BPlus : script "BridgePlus" –https://www.macosxautomation.com/applescript/apps/Script_Libs.html#BridgePlus

property NSString : a reference to current application’s NSString
property NSCharacterSet : a reference to current application’s NSCharacterSet
property NSRegularExpression : a reference to current application’s NSRegularExpression
property NSRegularExpressionAnchorsMatchLines : a reference to current application’s NSRegularExpressionAnchorsMatchLines
property NSRegularExpressionDotMatchesLineSeparators : a reference to current application’s NSRegularExpressionDotMatchesLineSeparators

script spdPDF
  property foundURLs : {}
  
property aList : {}
  
property outList : {}
end script

load framework

set (foundURLs of spdPDF) to {}
set theFile to POSIX path of (choose file of type "com.adobe.pdf")
set (aList of spdPDF) to textInPDFinEachPage(theFile) of me

set pCounter to 1

repeat with i in (aList of spdPDF)
  set aURL1 to extractLinksFromNaturalText(i as string) of me
  
set aURL2 to (current application’s SMSForder’s arrayByDeletingBlanksIn:((aURL1) as list))
  
  
set tmpOut to {}
  
repeat with ii in aURL2
    set aURL to (ii’s absoluteString()) as string
    
if aURL begins with "http://piyocast.com/as/" then
      set the end of tmpOut to aURL
    end if
  end repeat
  
  
if tmpOut is not equal to {} then
    set (outList of spdPDF) to (outList of spdPDF) & tmpOut
  end if
end repeat

set outStr to retArrowText(outList of spdPDF, return) of me

on textInPDFinEachPage(thePath)
  script textStorage
    property aList : {}
  end script
  
  
set (aList of textStorage) to {}
  
  
set anNSURL to (current application’s |NSURL|’s fileURLWithPath:thePath)
  
set theDoc to current application’s PDFDocument’s alloc()’s initWithURL:anNSURL
  
  
set theCount to theDoc’s pageCount() as integer
  
  
repeat with i from 1 to theCount
    set thePage to (theDoc’s pageAtIndex:(i – 1))
    
set curStr to (thePage’s |string|())
    
set curStr2 to curStr’s decomposedStringWithCanonicalMapping() –Normalize Text with NFC
    
set targString to string id 13 & string id 10 & string id 32 & string id 65532 –Object Replacement Character
    
set bStr to (curStr2’s stringByTrimmingCharactersInSet:(current application’s NSCharacterSet’s characterSetWithCharactersInString:targString))
    
set the end of (aList of textStorage) to (bStr as string)
  end repeat
  
  
return contents of (aList of textStorage)
end textInPDFinEachPage

on extractLinksFromNaturalText(aString)
  set anNSString to current application’s NSString’s stringWithString:aString
  
  
set {theDetector, theError} to current application’s NSDataDetector’s dataDetectorWithTypes:(current application’s NSTextCheckingTypeLink) |error|:(reference)
  
  
set theMatches to theDetector’s matchesInString:anNSString options:0 range:{0, anNSString’s |length|()}
  
set theResults to theMatches’s valueForKey:"URL"
  
  
return theResults as list
end extractLinksFromNaturalText

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

on retArrowText(aList, aDelim) –自分のASでよく使うハンドラ名称なので、同じものを用意
  return my retStrFromArrayWithDelimiter(aList, aDelim)
end retArrowText

★Click Here to Open This Script 

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

ASOCでPDFをページごとに分解する v3

Posted on 2月 6, 2018 by Takaaki Naganoya
AppleScript名:ASOCでPDFをページごとに分解する v3
— Created 2014-12-26 by Takaaki Naganoya
— Modified 2015-09-26 by Takaaki Naganoya
— Modified 2015-10-01 by Takaaki Naganoya
— 2015 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
–use framework "Quartz"
use framework "QuartzCore"

set aHFSPath to (choose file of type {"com.adobe.pdf"} with prompt "ページごとに分解するPDFを指定してください")
set aPOSIX to POSIX path of aHFSPath
set aURL to (current application’s |NSURL|’s fileURLWithPath:aPOSIX)

set aPOSIXpath to POSIX path of aHFSPath —書き出し先パスをPOSIX pathで用意しておく(あとで加工)

set aPDFdoc to current application’s PDFDocument’s alloc()’s initWithURL:aURL
set pCount to aPDFdoc’s pageCount()

–PDFをページごとに分割してファイル書き出し
repeat with i from 0 to (pCount – 1)
  set thisPage to (aPDFdoc’s pageAtIndex:(i))
  
set thisDoc to (current application’s PDFDocument’s alloc()’s initWithData:(thisPage’s dataRepresentation()))
  
set outPath to addString_beforeExtensionIn_("_" & (i + 1) as string, aPOSIXpath)
  
  (
thisDoc’s writeToFile:outPath) –書き出し
end repeat

–ファイルパス(POSIX path)に対して、文字列(枝番)を追加。拡張子はそのまま
on addString:extraString beforeExtensionIn:aPath
  set pathString to current application’s NSString’s stringWithString:aPath
  
set theExtension to pathString’s pathExtension()
  
set thePathNoExt to pathString’s stringByDeletingPathExtension()
  
  
set newPath to (thePathNoExt’s stringByAppendingString:extraString)’s stringByAppendingPathExtension:theExtension
  
return newPath as string
end addString:beforeExtensionIn:

★Click Here to Open This Script 

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

ASOCでPDFをページごとに分解してJPEGで保存する v3

Posted on 2月 6, 2018 by Takaaki Naganoya
AppleScript名:ASOCでPDFをページごとに分解してJPEGで保存する v3
— Created 2014-12-26 by Takaaki Naganoya
— Modified 2015-09-26 by Takaaki Naganoya
— Modified 2015-10-01 by Takaaki Naganoya
— Modified 2016-07-27 by Takaaki Naganoya–Save each PDF page as jpeg
— Modified 2016-07-27 by Takaaki Naganoya–Zero padding function, Consider Retina Env
— 2016 Piyomaru Software
# http://piyocast.com/as/archives/4176

use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "Quartz"
use framework "QuartzCore"
use framework "AppKit"

set aHFSPath to (choose file of type {"com.adobe.pdf"} with prompt "ページごとに分解するPDFを指定してください")
set aPOSIX to POSIX path of aHFSPath
set aURL to (current application’s |NSURL|’s fileURLWithPath:aPOSIX)

set aPOSIXpath to POSIX path of aHFSPath —書き出し先パスをPOSIX pathで用意しておく(あとで加工)

set aPDFdoc to current application’s PDFDocument’s alloc()’s initWithURL:aURL
set pCount to aPDFdoc’s pageCount()

set compFactor to 1.0 –1.0 — 0.0 = max jpeg compression, 1.0 = none

–Detect Retina Environment
set retinaF to current application’s NSScreen’s mainScreen()’s backingScaleFactor()
if retinaF = 1.0 then
  set aScale to 2.0 –Non Retina Env
else
  set aScale to 1.0 –Retina Env
end if

–PDFをページごとに分割してJPEGでファイル書き出し
repeat with i from 0 to (pCount – 1)
  –Pick Up a PDF page as an image
  
set thisPage to (aPDFdoc’s pageAtIndex:(i))
  
set thisDoc to (current application’s NSImage’s alloc()’s initWithData:(thisPage’s dataRepresentation()))
  
if thisDoc = missing value then error "Error in getting imagerep from PDF in page:" & (i as string)
  
  
–Resize Image
  
set pointSize to thisDoc’s |size|()
  
set newSize to current application’s NSMakeSize((pointSize’s width) * aScale, (pointSize’s height) * aScale)
  
set newImage to (current application’s NSImage’s alloc()’s initWithSize:newSize)
  
  
newImage’s lockFocus()
  (
thisDoc’s setSize:newSize)
  (
current application’s NSGraphicsContext’s currentContext()’s setImageInterpolation:(current application’s NSImageInterpolationHigh))
  (
thisDoc’s drawAtPoint:(current application’s NSZeroPoint) fromRect:(current application’s CGRectMake(0, 0, newSize’s width, newSize’s height)) operation:(current application’s NSCompositeCopy) fraction:1.0)
  
newImage’s unlockFocus()
  
  
–Save Image as JPEG
  
set theData to newImage’s TIFFRepresentation()
  
set newRep to (current application’s NSBitmapImageRep’s imageRepWithData:theData)
  
set targData to (newRep’s representationUsingType:(current application’s NSJPEGFileType) |properties|:{NSImageCompressionFactor:compFactor, NSImageProgressive:false})
  
set zText to retZeroPaddingText((i + 1), 4) of me
  
set outPath to addString_beforeExtensionIn_addingExtension_("_" & zText, aPOSIXpath, "jpg")
  
  (
targData’s writeToFile:outPath atomically:true) –書き出し
end repeat

–ファイルパス(POSIX path)に対して、文字列(枝番)を追加。任意の拡張子を追加
on addString:extraString beforeExtensionIn:aPath addingExtension:aExt
  set pathString to current application’s NSString’s stringWithString:aPath
  
set theExtension to pathString’s pathExtension()
  
set thePathNoExt to pathString’s stringByDeletingPathExtension()
  
  
set newPath to (thePathNoExt’s stringByAppendingString:extraString)’s stringByAppendingPathExtension:aExt
  
return newPath as string
end addString:beforeExtensionIn:addingExtension:

on retZeroPaddingText(aNum as integer, aDigitNum as integer)
  if aNum > (((10 ^ aDigitNum) as integer) – 1) then return "" –Range Check
  
set aFormatter to current application’s NSNumberFormatter’s alloc()’s init()
  
aFormatter’s setUsesGroupingSeparator:false
  
aFormatter’s setAllowsFloats:false
  
aFormatter’s setMaximumIntegerDigits:aDigitNum
  
aFormatter’s setMinimumIntegerDigits:aDigitNum
  
aFormatter’s setPaddingCharacter:"0"
  
set aStr to aFormatter’s stringFromNumber:(current application’s NSNumber’s numberWithFloat:aNum)
  
return aStr as string
end retZeroPaddingText

★Click Here to Open This Script 

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

ASOCで指定PDFのページ数をかぞえる v2

Posted on 2月 6, 2018 by Takaaki Naganoya
AppleScript名:ASOCで指定PDFのページ数をかぞえる v2
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"
use framework "QuartzCore"

set aFile to choose file of type {"com.adobe.pdf"}
set pCount to my pdfPageCount:aFile

–指定PDFのページ数をかぞえる(10.9対応。普通にPDFpageから取得)
–返り値:PDFファイルのページ数(整数値)
on pdfPageCount:aFile
  set aFile to POSIX path of aFile
  
set theURL to current application’s |NSURL|’s fileURLWithPath:aFile
  
set aPDFdoc to current application’s PDFDocument’s alloc()’s initWithURL:theURL
  
set aRes to aPDFdoc’s pageCount()
  
return aRes as integer
end pdfPageCount:

★Click Here to Open This Script 

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

迷路をRTFで作成して脱出経路を赤く着色する v3

Posted on 2月 6, 2018 by Takaaki Naganoya

–> MazeFinder.framework

AppleScript名:迷路をRTFで作成して脱出経路を赤く着色する v3
— Created 2017-09-19 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"
use framework "MazeFinder" –https://github.com/tcjennings/MazeFinder

property NSFont : a reference to current application’s NSFont
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 Board2D : a reference to current application’s Board2D
property Pathfinder : a reference to current application’s Pathfinder
property NSDictionary : a reference to current application’s NSDictionary
property NSLiteralSearch : a reference to current application’s NSLiteralSearch
property NSMutableArray : a reference to current application’s NSMutableArray
property NSFontAttributeName : a reference to current application’s NSFontAttributeName
property NSMutableAttributedString : a reference to current application’s NSMutableAttributedString
property NSForegroundColorAttributeName : a reference to current application’s NSForegroundColorAttributeName
property NSDocumentTypeDocumentAttribute : a reference to current application’s NSDocumentTypeDocumentAttribute
–NSNotFoundはプロパティに代入しても認識されなかった

set targFontName to "Courier-Bold" –PostScript Name
set targFontSize to 13 –Point

–迷路テキストデータ作成→Attributed Stringに
set aStr to create2DMazeAndSolveIt(30, 30, 1, 1, 28, 28) of me –Plain Text
set anAttr to changeAttrStrsFontAttribute(aStr, targFontName, targFontSize) of me –Attributed String

–迷路データに着色(参照呼び出し, Call by reference)
markCharOfAttributedString(anAttr, aStr, "!", (NSColor’s redColor())) of me

–結果のRTFをデスクトップ上に書き出す。ファイル名はUUID.rtf
set targFol to current application’s NSHomeDirectory()’s stringByAppendingPathComponent:"Desktop"
set aRes to my saveStyledTextAsRTF(targFol, anAttr)

–指定のAttributed String内で指定文字列が含まれる箇所に指定の色をつける(結果はメイン側に参照渡し)
on markCharOfAttributedString(anAttr, origStr, aTargStr, aColor)
  set rList to searchWordWithRange(origStr, aTargStr) of me
  
repeat with ii in rList
    (anAttr’s addAttribute:(NSForegroundColorAttributeName) value:aColor range:ii)
  end repeat
end markCharOfAttributedString

–指定の文字列をAttributed Stringに変換して任意のフォントを一括指定
on changeAttrStrsFontAttribute(aStr, aFontPSName, aFontSize)
  set tmpAttr to NSMutableAttributedString’s alloc()’s initWithString:aStr
  
set aRange to current application’s NSMakeRange(0, tmpAttr’s |length|())
  
set aVal1 to NSFont’s fontWithName:aFontPSName |size|:aFontSize
  
tmpAttr’s beginEditing()
  
tmpAttr’s addAttribute:(NSFontAttributeName) value:aVal1 range:aRange
  
tmpAttr’s endEditing()
  
return tmpAttr
end changeAttrStrsFontAttribute

–指定テキストデータ(atargText)内に、指定文字列(aSearchStr)が含まれる範囲情報(NSRange)をすべて取得する
on searchWordWithRange(aTargText, aSearchStr)
  set aStr to NSString’s stringWithString:aTargText
  
set bStr to NSString’s stringWithString:aSearchStr
  
set hitArray to NSMutableArray’s alloc()’s init()
  
set cNum to (aStr’s |length|()) as integer
  
  
set aRange to current application’s NSMakeRange(0, cNum)
  
  
repeat
    set detectedRange to aStr’s rangeOfString:bStr options:NSLiteralSearch range:aRange
    
set aLoc to (detectedRange’s location)
    
–CAUTION !!!! Sometimes aLoc returns not NSNotFound (-1) but a Very large number
    
if (aLoc > 9.999999999E+9) or (aLoc = (current application’s NSNotFound)) then exit repeat
    
    
hitArray’s addObject:detectedRange
    
    
set aNum to aLoc as integer
    
set bNum to (detectedRange’s |length|) as integer
    
    
set aRange to current application’s NSMakeRange(aNum + bNum, cNum – (aNum + bNum))
  end repeat
  
  
return hitArray
end searchWordWithRange

–スタイル付きテキストを指定フォルダ(POSIX path)にRTFで書き出し
on saveStyledTextAsRTF(targFol, aStyledString)
  set bstyledLength to aStyledString’s |string|()’s |length|()
  
set bDict to NSDictionary’s dictionaryWithObject:"NSRTFTextDocumentType" forKey:(NSDocumentTypeDocumentAttribute)
  
set bRTF to aStyledString’s RTFFromRange:(current application’s NSMakeRange(0, bstyledLength)) documentAttributes:bDict
  
  
set theName to (NSUUID’s UUID()’s UUIDString())
  
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

–2D迷路を作成して脱出経路を検索して文字列で迷路データを出力する
–迷路サイズ x,y スタート座標 x, y ゴール座標 x,y
on create2DMazeAndSolveIt(xMax, yMax, xStart, yStart, xGoal, yGoal)
  set myBoard to Board2D’s alloc()’s init()
  
myBoard’s setupBoardWithRows:xMax WithColumns:yMax –60×60ぐらいが上限。正方形でないとダメ
  
myBoard’s createMazeFromBoard()
  
  
set myPathfinder to Pathfinder’s alloc()’s init()
  
set myPath to myPathfinder’s findPathThroughMaze:myBoard fromX:xStart fromY:yStart toX:xGoal toY:yGoal
  
  
set aCount to myPath’s |count|()
  
if aCount > 0 then
    set aRes to myBoard’s drawPathThroughMaze:myPath
    
return aRes as string
  else
    return false
  end if
end create2DMazeAndSolveIt

★Click Here to Open This Script 

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

クリップボードに入ったproperty宣言部分を見た目の描画サイズ(幅)と文字コードでソート

Posted on 2月 6, 2018 by Takaaki Naganoya

クリップボードに入れたproperty宣言文を見た目の描画サイズ(幅)で行単位の並べ替えを行うAppleScriptです。

property文でCocoaのClass名を定義しており、これを整形するために文字数で短いものから長いものへ並べてみたところ、プロポーショナルフォントで表示されるために「美しく」はなりませんでした。実際に仮装画面上でスタイル付きテキストの描画を行って、描画サイズ(幅)を取得して並べ替えを行ってみたものです。

OLD Style AppleScriptの機能の範囲では逆立ちしても実現できない処理内容です。

AppleScript名:クリップボードに入ったproperty宣言部分を見た目の描画サイズ(幅)と文字コードでソート
— Created 2017-12-08 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
use framework "AppKit"

property NSFont : a reference to current application’s NSFont
property NSData : a reference to current application’s NSData
property NSColor : a reference to current application’s NSColor
property NSArray : a reference to current application’s NSArray
property NSString : a reference to current application’s NSString
property NSDictionary : a reference to current application’s NSDictionary
property NSPasteboard : a reference to current application’s NSPasteboard
property NSCountedSet : a reference to current application’s NSCountedSet
property NSMutableArray : a reference to current application’s NSMutableArray
property NSSortDescriptor : a reference to current application’s NSSortDescriptor
property NSAttributedString : a reference to current application’s NSAttributedString
property NSMutableDictionary : a reference to current application’s NSMutableDictionary
property NSFontAttributeName : a reference to current application’s NSFontAttributeName
property NSKernAttributeName : a reference to current application’s NSKernAttributeName
property NSMutableParagraphStyle : a reference to current application’s NSMutableParagraphStyle
property NSLigatureAttributeName : a reference to current application’s NSLigatureAttributeName
property NSMutableAttributedString : a reference to current application’s NSMutableAttributedString
property NSUnderlineStyleAttributeName : a reference to current application’s NSUnderlineStyleAttributeName
property NSParagraphStyleAttributeName : a reference to current application’s NSParagraphStyleAttributeName
property NSForegroundColorAttributeName : a reference to current application’s NSForegroundColorAttributeName

–クリップボードの内容を文字列として取得
set aStr to (the clipboard) as string
if aStr = "" then
  display dialog "No Data in Clipboard" buttons {"OK"} default button 1
  
return
end if

–クリップボードの内容をStyled Stringで取得して最頻出フォントを取得
set clipboardAttrStr to getClipboardASStyledText() of me
if clipboardAttrStr = missing value then
  display dialog "Can not get clipboard as Styled String" buttons {"OK"} default button 1
  
return
end if
set attrList to getAttributeRunsFromAttrString(clipboardAttrStr) of me
set anArray to (NSArray’s arrayWithArray:attrList)’s valueForKeyPath:"fontName"
set aFontList to (countItemsByItsAppearance(anArray) of me)
set aFontName to theName of first item of aFontList

–クリップボードから取得した文字データについて処理
set aList to paragraphs of aStr –行ごとにparseしてlist化
set bList to {}
repeat with i in aList
  set j to contents of i
  
if j ≠ {} then
    set jList to words of j
    
if jList ≠ {} then
      if contents of first item of jList = "property" then
        set curLabel to contents of second item of jList
        
        
–行をAttributed Stringとして組み立てて、画面描画時の仕上がりサイズを取得
        
set anAssrStr to makeRTFfromParameters(j, aFontName, 16, -2, 16) 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 the end of bList to {aLabel:curLabel, aCon:j, aWidth:attrStrWidth}
      end if
    end if
  end if
end repeat

if bList = {} then
  display dialog "Error" buttons {"OK"} default button 1
  
return
end if

–複数キーでソート(書式つきテキストの仕上がりサイズ幅、文字コード順でソート)
set aArray to NSArray’s arrayWithArray:bList
set desc1 to NSSortDescriptor’s sortDescriptorWithKey:"aWidth" ascending:true
set desc2 to NSSortDescriptor’s sortDescriptorWithKey:"aLabel" ascending:true selector:"localizedCaseInsensitiveCompare:"
set bArray to aArray’s sortedArrayUsingDescriptors:{desc1, desc2}

–ソートしたlist of recordからaCon(元のproperty宣言行そのもの)を一括で取り出す
set dArray to (NSMutableArray’s arrayWithArray:bArray)’s valueForKeyPath:"aCon"

–listをデリミタつきのテキストに
set dStr to retStrFromArrayWithDelimiter(dArray, return) of me

set the clipboard to (dStr & return)

–1D Listを文字列長でソート v2
on sort1DListByIndicatedStringLength(aList as list, aSortKey as string, sortOrder as boolean)
  set aArray to NSArray’s arrayWithArray:aList
  
set descLabel1 to NSString’s stringWithString:(aSortKey & ".length")
  
set descLabel2 to NSString’s stringWithString:aSortKey
  
set desc1 to NSSortDescriptor’s sortDescriptorWithKey:descLabel1 ascending:sortOrder
  
set desc2 to NSSortDescriptor’s sortDescriptorWithKey:descLabel2 ascending:true selector:"localizedCaseInsensitiveCompare:"
  
set bArray to aArray’s sortedArrayUsingDescriptors:{desc1, desc2}
  
return bArray as list
end sort1DListByIndicatedStringLength

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

–書式つきテキストを組み立てる
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

— クリップボードの内容をNSAttributedStringとして取り出して返す
on getClipboardASStyledText()
  set theNSPasteboard to NSPasteboard’s generalPasteboard()
  
set theAttributedStringNSArray to theNSPasteboard’s readObjectsForClasses:({NSAttributedString}) options:(missing value)
  
set theNSAttributedString to theAttributedStringNSArray’s objectAtIndex:0
  
return theNSAttributedString
end getClipboardASStyledText

–指定のNSAttributedStringから書式情報をlist of recordで取得
on getAttributeRunsFromAttrString(theStyledText)
  script aSpd
    property styleList : {}
  end script
  
  
set (styleList of aSpd) to {} —for output
  
  
set thePureString to theStyledText’s |string|() –pure string from theStyledText
  
  
set theLength to theStyledText’s |length|()
  
set startIndex to 0
  
  
repeat until (startIndex = theLength)
    set {theAtts, theRange} to theStyledText’s attributesAtIndex:startIndex longestEffectiveRange:(reference) inRange:{startIndex, theLength – startIndex}
    
    
set aText to (thePureString’s substringWithRange:theRange) as string
    
    
set aColor to (theAtts’s valueForKeyPath:"NSColor")
    
if aColor is not equal to missing value then
      set aSpace to aColor’s colorSpace()
      
      
set aRed to (aColor’s redComponent()) * 255
      
set aGreen to (aColor’s greenComponent()) * 255
      
set aBlue to (aColor’s blueComponent()) * 255
      
      
set colList to {aRed as integer, aGreen as integer, aBlue as integer}
      
set colStrForFind to (aRed as integer as string) & " " & (aGreen as integer as string) & " " & (aBlue as integer as string)
    else
      set colList to {0, 0, 0}
      
set colStrForFind to "0 0 0"
    end if
    
    
set aFont to (theAtts’s valueForKeyPath:"NSFont")
    
if aFont is not equal to missing value then
      set aDFontName to aFont’s displayName()
      
set aDFontSize to aFont’s pointSize()
    end if
    
    
set the end of (styleList of aSpd) to {stringVal:aText, colorStr:colStrForFind, colorVal:colList, fontName:aDFontName as string, fontSize:aDFontSize}
    
set startIndex to current application’s NSMaxRange(theRange)
  end repeat
  
  
return (styleList of aSpd)
end getAttributeRunsFromAttrString

–1D Listをアイテムの出現頻度順でソートして返す
on countItemsByItsAppearance(aList as list)
  set aSet to NSCountedSet’s alloc()’s initWithArray:aList
  
set bArray to NSMutableArray’s array()
  
set theEnumerator to aSet’s objectEnumerator()
  
  
repeat
    set aValue to theEnumerator’s nextObject()
    
if aValue is missing value then exit repeat
    
bArray’s addObject:(NSDictionary’s dictionaryWithObjects:{aValue, (aSet’s countForObject:aValue)} forKeys:{"theName", "numberOfTimes"})
  end repeat
  
  
set theDesc to NSSortDescriptor’s sortDescriptorWithKey:"numberOfTimes" ascending:false
  
bArray’s sortUsingDescriptors:{theDesc}
  
  
return bArray as list
end countItemsByItsAppearance

★Click Here to Open This Script 

Posted in Clipboard Image RTF Text | Tagged 10.11savvy 10.12savvy 10.13savvy | 1 Comment

書式つきテキストを組み立ててサイズを取得して画像書き出し v3a

Posted on 2月 6, 2018 by Takaaki Naganoya

AppleScript名:書式つきテキストを組み立ててサイズを取得して画像書き出し v3a
— Created 2017-09-25 by Takaaki Naganoya
— Modified 2017-09-27 by Shane Stanley
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"

property NSFont : a reference to current application’s NSFont
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 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
property NSMutableDictionary : a reference to current application’s NSMutableDictionary
property NSFontAttributeName : a reference to current application’s NSFontAttributeName
property NSKernAttributeName : a reference to current application’s NSKernAttributeName
property NSMutableParagraphStyle : a reference to current application’s NSMutableParagraphStyle
property NSLigatureAttributeName : a reference to current application’s NSLigatureAttributeName
property NSMutableAttributedString : a reference to current application’s NSMutableAttributedString
property NSUnderlineStyleAttributeName : a reference to current application’s NSUnderlineStyleAttributeName
property NSParagraphStyleAttributeName : a reference to current application’s NSParagraphStyleAttributeName
property NSForegroundColorAttributeName : a reference to current application’s NSForegroundColorAttributeName

set outPath to "~/Desktop/test9999.png"
set fillColor to NSColor’s whiteColor –塗り色
set aFontSize to 48
set aString to "Takaaki Naganoya" & return & "長野谷隆昌"

set anAssrStr to makeRTFfromParameters(aString, "HiraMinProN-W3", aFontSize, -2, (aFontSize * 1.5)) of me
set aSize to anAssrStr’s |size|()
log aSize
–>  {width:387.424, height:144.0}

set attrStrWidth to width of aSize
set attrStrHeight to height of aSize

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

–PNG形式でファイルに保存
set aRes to saveImageRepAtPathAsPNG(tmpImg2, outPath) of me

–画像のうえに指定のスタイル付きテキストを描画して画像を返す
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)
  –Font
  
set aVal1 to NSFont’s fontWithName:fontName |size|:aFontSize
  
set aKey1 to (NSFontAttributeName)
  
  
–Color
  
set aVal2 to NSColor’s blackColor()
  
set aKey2 to (NSForegroundColorAttributeName)
  
  
–Kerning
  
set aVal3 to aKerning
  
set akey3 to (NSKernAttributeName)
  
  
–Underline
  
set aVal4 to 0
  
set akey4 to (NSUnderlineStyleAttributeName)
  
  
–Ligature
  
set aVal5 to 2 –all ligature ON
  
set akey5 to (NSLigatureAttributeName)
  
  
–縦書き指定–Japanese tategaki setting (Up to down, right to left direction drawing)
  
set aVal6 to true
  
set aKey6 to (current application’s NSVerticalGlyphFormAttributeName)
  
  
–Paragraph space
  
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, aKey6, akey7}
  
set valList to {aVal1, aVal2, aVal3, aVal4, aVal5, aVal6, 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}} –AppleがmacOS 10.13に作ったバグのせいで、width→heightの順番にパラメータを書かないと異常動作する
  
set theNSBezierPath to 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 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
end saveImageRepAtPathAsPNG

★Click Here to Open This Script 

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

指定文字の花文字テキストを取得する(Retina対応)

Posted on 2月 6, 2018 by Takaaki Naganoya

指定の文字から花文字を作成するAppleScriptです。

「花文字」とは、任意の文字を組み合わせて指定の文字を作成するもので、「祝」という文字とスペースを組み合わせて、

  祝         
  祝  祝祝祝祝祝祝 
 祝祝祝祝祝    祝 
 祝祝祝祝祝    祝 
   祝祝祝   祝祝 
  祝祝 祝祝祝祝祝祝 
 祝祝祝祝 祝祝祝   
祝祝祝祝祝 祝 祝   
  祝   祝 祝   
  祝  祝祝 祝  祝
  祝 祝祝  祝祝祝祝
  祝 祝    祝  

のように組み合わせた文字列のことです。

大昔の大型コンピュータの計算結果をプリンタに印刷する際に、ユーザーごとの計算結果の紙が混ざることを防ぐために、ヘッダーページを印刷するようになっていました。当時はまだアウトラインフォントから大きな文字を印刷する技術がなかったので、花文字のように文字を組み合わせて大きな文字を印刷するようなことを行なっていたようです(たぶん)。

類似の処理にこのようなものがあります。
→ Love

花文字はその名残りで、パソコンのメールなどで文字だけを使って何かを表現するような、原始的なアスキーアートの一種といえばよいのでしょうか。

かつては、花文字作成の専用アプリケーションが存在していました。AppleScript的には、そうしたアプリケーションに「このデータを作ってくれ」と依頼するのが本来のスタイルですが、アプリケーションがない場合には、原理的に別に難しいものではないので、自前で作ってしまえばいいわけです。

(1)指定サイズ、指定フォントで書式つきテキストを作成
(2)書式つきテキストをメモリー上に用意したブランク画像に描画
(3)メモリー上の画像のドットを順次読み取って、塗りつぶされている箇所といない箇所を順次検出
(4)塗りつぶし情報を文字列に表現。空白ドットは空白文字で、描画ドットは指定文字で
(5)文字列を出力

という処理を行なっています。描画時のフォント種別の指定や、結果をCotEditorに出力するあたりは「オマケ」です。

この程度の処理であれば、JEdit Ωやmi、OS標準装備のテキストエディットなどさまざまな(AppleScript対応の)エディタにオープンさせられます(Mac用のテキストエディタでAppleScript非対応というものがあれば、何の迷いもなくゴミ箱行きです)。

AppleScript名:指定文字の花文字テキストを取得する(Retina対応)
— Created 2017-12-12 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"

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

set aString to "あ"
set hanaSize to 24
set thisFont to selectAFont(aString) of me
if thisFont = false then return –Cancel

–花文字文字列を作成
set fRes to getHanamojiStr(hanaSize, thisFont, aString, 0.7, true) of me
makeNewDocument given parameter:fRes

–花文字文字列を計算して返す
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 aRatio to getImageRatio() of me –Retina Display対応
  
set origColor to (aRawimg’s colorAtX:(x * aRatio) y:(y * aRatio))
  
  
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))
  
set aRatio to getImageRatio() of me –Retina Display対応
  
  
anImage’s lockFocus()
  
set theRect to {{x:0, y:0}, {width:aWidth * aRatio, height:aHeight * aRatio}}
  
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(aStr)
  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 dName to getDisplayedNameOfFont(aName) of me
    
    
set fRes to retGlyphsInFont(aName, id of aStr) of me
    
if fRes = true then
      set the end of aList to {fontName:aName, fontNum:aNum, dispName:dName}
    end if
  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

–指定名称のフォントに指定の文字コードが含まれているかチェック
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

on selectAFont(aString)
  set fRes to getEveryFontPSNameANdGlyphsNum(aString) of me
  
set theArray to NSArray’s arrayWithArray:fRes
  
set thePred to NSPredicate’s predicateWithFormat:"fontNum > 10000"
  
set bArray to ((theArray’s filteredArrayUsingPredicate:thePred)’s valueForKeyPath:"dispName") as list
  
set thisFont to choose from list bArray
  
return thisFont
end selectAFont

–Retina Display対応ルーチン
on getImageRatio()
  set retinaF to detectRetinaDisplay() of me
  
if retinaF = true then
    return 2.0 as real
  else
    return 1.0 as real
  end if
end getImageRatio

on detectRetinaDisplay()
  set dispList to current application’s NSScreen’s screens()
  
set retinaF to false
  
  
repeat with i in dispList
    set j to contents of i
    
set aDepth to j’s backingScaleFactor()
    
if aDepth > 1.0 then
      set retinaF to true
    end if
  end repeat
  
  
return retinaF
end detectRetinaDisplay

on makeNewDocument given parameter:aStr
  tell application id "com.coteditor.CotEditor"
    activate
    
set newDoc to make new document
    
tell newDoc
      set contents to aStr
    end tell
  end tell
end makeNewDocument

★Click Here to Open This Script 

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

Numbersから緯度経度情報を取得して地図にプロット v3(プログレスバー+セグメント)

Posted on 2月 6, 2018 by Takaaki Naganoya

Numbers書類上に記載した緯度経度情報を取得して、動的に作成したウィンドウの地図上にプロット表示するAppleScriptです。

実行には、「場所名」「緯度」「経度」がワンセットとなったNumbers書類をNumbersでオープンした状態で、本AppleScriptをスクリプトエディタ上でオープンし、Control-Command-Rを実行します。

ひととおり地図上の指定位置へのピンの作成が終わると、普通に地図アプリなどと同様に拡大や縮小、3D表示、マップ表示、航空写真表示などを切り替えてブラウズすることが可能です。

–> Demo Movie

AppleScript名:Numbersから緯度経度情報を取得して地図にプロット v3(プログレスバー+セグメント)
— Created 2017-12-20 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
use framework "AppKit"
use framework "MapKit"
use framework "CoreLocation"
use bPlus : script "BridgePlus" –https://www.macosxautomation.com/applescript/apps/Script_Libs.html#BridgePlus

property NSView : a reference to current application’s NSView
property NSScreen : a reference to current application’s NSScreen
property NSButton : a reference to current application’s NSButton
property SMSForder : a reference to current application’s SMSForder
property NSWindow : a reference to current application’s NSWindow
property MKMapView : a reference to current application’s MKMapView
property MKMapTypeHybrid : a reference to current application’s MKMapTypeHybrid
property MKPointAnnotation : a reference to current application’s MKPointAnnotation
property MKMapTypeSatellite : a reference to current application’s MKMapTypeSatellite
property NSWindowController : a reference to current application’s NSWindowController
property NSTitledWindowMask : a reference to current application’s NSTitledWindowMask
property MKMapTypeStandard : a reference to current application’s MKMapTypeStandard
property NSSegmentedControl : a reference to current application’s NSSegmentedControl
property NSNormalWindowLevel : a reference to current application’s NSNormalWindowLevel
property NSBackingStoreBuffered : a reference to current application’s NSBackingStoreBuffered
property NSSegmentStyleTexturedRounded : a reference to current application’s NSSegmentStyleTexturedRounded

property windisp : false
property selSeg : 0
property aMapView : missing value

–データを取得する
set locList to getDataFromNumbersDoc() of me

set aWidth to 800
set aHeight to 600

set segTitleList to {"Map", "Satellite", "Satellite + Map"}
set tableTitle to retCurNumbersDocsTableName() of me
dispMapView(aWidth, aHeight, tableTitle, "OK", 180, locList, segTitleList) of me

on dispMapView(aWidth as integer, aHeight as integer, aTitle as text, aButtonMSG as text, timeOutSecs as number, locList, segTitleList)
  –Check If this script runs in foreground
  
if not (current application’s NSThread’s isMainThread()) as boolean then
    error "This script must be run from the main thread (Command-Control-R in Script Editor)."
  end if
  
  
set selSeg to 0
  
set (my windisp) to true
  
  
  
  
–NSViewをつくる
  
set aNSView to NSView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aHeight, aWidth))
  
  
aNSView’s setNeedsDisplay:true
  
  
set aWin to makeWinWithView(aNSView, aWidth, aHeight, aTitle, 1.0)
  
  
set wController to NSWindowController’s alloc()
  
wController’s initWithWindow:aWin
  
wController’s showWindow:me
  
aWin’s makeKeyAndOrderFront:me –Windowを表示状態に
  
  
  
–Progress Barをつくる
  
set aPBar to current application’s NSProgressIndicator’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 40, aWidth, 40))
  
aPBar’s setMaxValue:(length of locList)
  
aPBar’s setMinValue:1
  
aPBar’s setIndeterminate:false
  
aPBar’s setControlSize:(current application’s NSProgressIndicatorPreferredLargeThickness)
  
aPBar’s setDoubleValue:(1.0 as real)
  
aNSView’s addSubview:aPBar
  
  
  
–MKMapViewをつくる
  
set aMapView to MKMapView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 40, aWidth, aHeight – 40))
  
aMapView’s setMapType:(current application’s MKMapTypeStandard)
  
  
aMapView’s setZoomEnabled:true
  
aMapView’s setScrollEnabled:true
  
aMapView’s setPitchEnabled:true
  
aMapView’s setRotateEnabled:false
  
aMapView’s setShowsCompass:true
  
aMapView’s setShowsZoomControls:true
  
aMapView’s setShowsScale:true
  
aMapView’s setShowsUserLocation:true
  
aMapView’s setDelegate:me
  
  
  
–MapにPinを追加
  
set aCount to 1
  
repeat with i in locList
    (aPBar’s setDoubleValue:(aCount as real)) –Update Progress Bar
    
    
copy i to {tmpAdr, tmpLat, tmpLong}
    
    
set aLocation to current application’s CLLocationCoordinate2DMake(tmpLat, tmpLong)
    
set anAnnotation to MKPointAnnotation’s alloc()’s init()
    (
anAnnotation’s setCoordinate:aLocation)
    (
anAnnotation’s setTitle:tmpAdr)
    (
aMapView’s addAnnotation:anAnnotation)
    
    
set aCount to aCount + 1
  end repeat
  
  
aPBar’s removeFromSuperview() –Remove Progress Bar
  
  
–Segmented Controlをつくる
  
set aSeg to makeSegmentedControl(segTitleList, aWidth, aHeight) of me
  
aNSView’s addSubview:aSeg
  
  
–MapViewをWindow上に表示  
  
copy middle item of locList to {tmpAdr, tmpLat, tmpLong}
  
set aLocation to current application’s CLLocationCoordinate2DMake(tmpLat, tmpLong)
  
aMapView’s setCenterCoordinate:aLocation zoomLevel:7 animated:false
  
aNSView’s addSubview:aMapView
  
  
–Buttonをつくる
  
set bButton to (NSButton’s alloc()’s initWithFrame:(current application’s NSMakeRect(aWidth – 100, 0, 100, 40)))
  
bButton’s setTitle:aButtonMSG
  
bButton’s setButtonType:(current application’s NSMomentaryLightButton)
  
bButton’s setBezelStyle:(current application’s NSRoundedBezelStyle)
  
bButton’s setKeyEquivalent:(return)
  
bButton’s setTarget:me
  
bButton’s setAction:("clicked:")
  
aNSView’s addSubview:bButton
  
  
aWin’s makeFirstResponder:aMapView
  
  
set aCount to timeOutSecs * 10 –timeout seconds * 10
  
repeat aCount times
    if (my windisp) = false then
      exit repeat
    end if
    
delay 0.1
  end repeat
  
  
my closeWin:aWin
  
end dispMapView

–Button Clicked Event Handler
on clicked:aSender
  set (my windisp) to false
end clicked:

–make Window for Input
on makeWinWithView(aView, aWinWidth, aWinHeight, aTitle, alphaV)
  set aScreen to NSScreen’s mainScreen()
  
set aFrame to {{0, 0}, {aWinWidth, aWinHeight}}
  
set aBacking to NSTitledWindowMask
  
set aDefer to NSBackingStoreBuffered
  
  
— Window
  
set aWin to NSWindow’s alloc()
  (
aWin’s initWithContentRect:aFrame styleMask:aBacking backing:aDefer defer:false screen:aScreen)
  
  
aWin’s setTitle:aTitle
  
aWin’s setDelegate:me
  
aWin’s setDisplaysWhenScreenProfileChanges:true
  
aWin’s setHasShadow:true
  
aWin’s setIgnoresMouseEvents:false
  
aWin’s setLevel:(NSNormalWindowLevel)
  
aWin’s setOpaque:false
  
aWin’s setAlphaValue:alphaV –append
  
aWin’s setReleasedWhenClosed:true
  
aWin’s |center|()
  
aWin’s makeKeyAndOrderFront:(me)
  
  
— Set Custom View
  
aWin’s setContentView:aView
  
  
return aWin
end makeWinWithView

–close win
on closeWin:aWindow
  repeat with n from 10 to 1 by -1
    (aWindow’s setAlphaValue:n / 10)
    
delay 0.02
  end repeat
  
aWindow’s |close|()
end closeWin:

on makeSegmentedControl(titleList, aWidth, aHeight)
  set aLen to length of titleList
  
  
set aSeg to NSSegmentedControl’s alloc()’s init()
  
aSeg’s setSegmentCount:aLen
  
  
set aCount to 0
  
repeat with i in titleList
    set j to contents of i
    (
aSeg’s setLabel:j forSegment:aCount)
    
set aCount to aCount + 1
  end repeat
  
  
aSeg’s setTranslatesAutoresizingMaskIntoConstraints:false
  
aSeg’s setSegmentStyle:(NSSegmentStyleTexturedRounded)
  
aSeg’s setFrame:(current application’s NSMakeRect(10, 5, 260, 30))
  
aSeg’s setTrackingMode:0
  
aSeg’s setTarget:me
  
aSeg’s setAction:"clickedSeg:"
  
aSeg’s setSelectedSegment:0
  
  
return aSeg
end makeSegmentedControl

–Numbersでオープン中の書類の選択中のシートの表1からデータを取得して2D Listに
on getDataFromNumbersDoc()
  
  
load framework
  
  
tell application "Numbers"
    if (count every document) = 0 then return false
    
    
tell front document
      if (count every sheet) = 0 then return false
      
      
tell active sheet
        tell table 1
          set colCount to column count
          
set rowCount to row count
          
set headerCount to header row count
          
set footerCount to footer row count
          
          
set dList to value of every cell of cell range
        end tell
      end tell
      
    end tell
  end tell
  
  
–Convert 1D List to 2D List
  
set bList to (SMSForder’s subarraysFrom:dList groupedBy:colCount |error|:(missing value)) as list
  
set sItem to 1 + headerCount
  
set eItem to rowCount – footerCount
  
set cList to items sItem thru eItem of bList
  
  
return cList
  
end getDataFromNumbersDoc

on retCurNumbersDocsTableName()
  tell application "Numbers"
    tell front document
      tell active sheet
        tell table 1
          return name
        end tell
      end tell
    end tell
  end tell
end retCurNumbersDocsTableName

on clickedSeg:aSender
  set aSel to aSender’s selectedSegment()
  
set selSeg to (aSel + 1)
  
set mapList to {MKMapTypeStandard, MKMapTypeSatellite, MKMapTypeHybrid}
  
set curMap to contents of item selSeg of mapList
  
aMapView’s setMapType:(curMap)
end clickedSeg:

★Click Here to Open This Script 

Posted in Require Control-Command-R to run | Tagged 10.11savvy 10.12savvy 10.13savvy Numbers | Leave a comment

指定IPアドレスの情報を取得して地図にプロット v3(プログレスバー+セグメント)

Posted on 2月 6, 2018 by Takaaki Naganoya
AppleScript名:指定IPアドレスの情報を取得して地図にプロット v3(プログレスバー+セグメント)
— Created 2017-12-20 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
use framework "AppKit"
use framework "MapKit"
use framework "CoreLocation"
use bPlus : script "BridgePlus" –https://www.macosxautomation.com/applescript/apps/Script_Libs.html#BridgePlus

property |NSURL| : a reference to current application’s |NSURL|
property NSData : a reference to current application’s NSData
property NSView : a reference to current application’s NSView
property NSScreen : a reference to current application’s NSScreen
property NSButton : a reference to current application’s NSButton
property SMSForder : a reference to current application’s SMSForder
property NSWindow : a reference to current application’s NSWindow
property MKMapView : a reference to current application’s MKMapView
property NSURLRequest : a reference to current application’s NSURLRequest
property NSURLConnection : a reference to current application’s NSURLConnection
property MKMapTypeHybrid : a reference to current application’s MKMapTypeHybrid
property MKPointAnnotation : a reference to current application’s MKPointAnnotation
property NSJSONSerialization : a reference to current application’s NSJSONSerialization
property MKMapTypeSatellite : a reference to current application’s MKMapTypeSatellite
property NSWindowController : a reference to current application’s NSWindowController
property NSTitledWindowMask : a reference to current application’s NSTitledWindowMask
property MKMapTypeStandard : a reference to current application’s MKMapTypeStandard
property NSSegmentedControl : a reference to current application’s NSSegmentedControl
property NSNormalWindowLevel : a reference to current application’s NSNormalWindowLevel
property NSBackingStoreBuffered : a reference to current application’s NSBackingStoreBuffered
property NSSegmentStyleTexturedRounded : a reference to current application’s NSSegmentStyleTexturedRounded

property windisp : false
property selSeg : 0
property aMapView : missing value

set nRes to hasInternetConnection() of me
if nRes = false then
  display dialog "No Internet Connection…." buttons {"OK"} default button 1 with icon 0
  
return
end if

set aClip to the clipboard
set anIP to text returned of (display dialog "Input IP address to find its location" default answer aClip)

set windisp to false
set aInfo to getIPAddressInfoFreeGeoIP(anIP) of me

if aInfo = missing value then
  display dialog "Network Error"
  
return
end if

set aLong to (longitude of (aInfo as record)) as real
set aLat to (latitude of (aInfo as record)) as real
set aZip to zip_code of (aInfo as record)
set locList to {{aZip, aLat, aLong}}

set aWidth to 800
set aHeight to 600

set segTitleList to {"Map", "Satellite", "Satellite + Map"}
dispMapView(aWidth, aHeight, aZip, "OK", 180, locList, segTitleList) of me

on dispMapView(aWidth as integer, aHeight as integer, aTitle as text, aButtonMSG as text, timeOutSecs as number, locList, segTitleList)
  –Check If this script runs in foreground
  
if not (current application’s NSThread’s isMainThread()) as boolean then
    error "This script must be run from the main thread (Command-Control-R in Script Editor)."
  end if
  
  
set selSeg to 0
  
set (my windisp) to true
  
  
  
  
–NSViewをつくる
  
set aNSView to NSView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aHeight, aWidth))
  
  
aNSView’s setNeedsDisplay:true
  
  
set aWin to makeWinWithView(aNSView, aWidth, aHeight, aTitle, 1.0)
  
  
set wController to NSWindowController’s alloc()
  
wController’s initWithWindow:aWin
  
wController’s showWindow:me
  
aWin’s makeKeyAndOrderFront:me –Windowを表示状態に
  
  
  
–Progress Barをつくる
  
set aPBar to current application’s NSProgressIndicator’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 40, aWidth, 40))
  
aPBar’s setMaxValue:(length of locList)
  
aPBar’s setMinValue:1
  
aPBar’s setIndeterminate:false
  
aPBar’s setControlSize:(current application’s NSProgressIndicatorPreferredLargeThickness)
  
aPBar’s setDoubleValue:(1.0 as real)
  
aNSView’s addSubview:aPBar
  
  
  
–MKMapViewをつくる
  
set aMapView to MKMapView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 40, aWidth, aHeight – 40))
  
aMapView’s setMapType:(current application’s MKMapTypeStandard)
  
  
aMapView’s setZoomEnabled:true
  
aMapView’s setScrollEnabled:true
  
aMapView’s setPitchEnabled:true
  
aMapView’s setRotateEnabled:false
  
aMapView’s setShowsCompass:true
  
aMapView’s setShowsZoomControls:true
  
aMapView’s setShowsScale:true
  
aMapView’s setShowsUserLocation:true
  
aMapView’s setDelegate:me
  
  
  
–MapにPinを追加
  
set aCount to 1
  
repeat with i in locList
    (aPBar’s setDoubleValue:(aCount as real)) –Update Progress Bar
    
    
copy i to {tmpAdr, tmpLat, tmpLong}
    
    
set aLocation to current application’s CLLocationCoordinate2DMake(tmpLat, tmpLong)
    
set anAnnotation to MKPointAnnotation’s alloc()’s init()
    (
anAnnotation’s setCoordinate:aLocation)
    (
anAnnotation’s setTitle:tmpAdr)
    (
aMapView’s addAnnotation:anAnnotation)
    
    
set aCount to aCount + 1
  end repeat
  
  
aPBar’s removeFromSuperview() –Remove Progress Bar
  
  
–Segmented Controlをつくる
  
set aSeg to makeSegmentedControl(segTitleList, aWidth, aHeight) of me
  
aNSView’s addSubview:aSeg
  
  
–MapViewをWindow上に表示  
  
copy middle item of locList to {tmpAdr, tmpLat, tmpLong}
  
set aLocation to current application’s CLLocationCoordinate2DMake(tmpLat, tmpLong)
  
aMapView’s setCenterCoordinate:aLocation zoomLevel:7 animated:false
  
aNSView’s addSubview:aMapView
  
  
–Buttonをつくる
  
set bButton to (NSButton’s alloc()’s initWithFrame:(current application’s NSMakeRect(aWidth – 100, 0, 100, 40)))
  
bButton’s setTitle:aButtonMSG
  
bButton’s setButtonType:(current application’s NSMomentaryLightButton)
  
bButton’s setBezelStyle:(current application’s NSRoundedBezelStyle)
  
bButton’s setKeyEquivalent:(return)
  
bButton’s setTarget:me
  
bButton’s setAction:("clicked:")
  
aNSView’s addSubview:bButton
  
  
aWin’s makeFirstResponder:aMapView
  
  
set aCount to timeOutSecs * 10 –timeout seconds * 10
  
repeat aCount times
    if (my windisp) = false then
      exit repeat
    end if
    
delay 0.1
  end repeat
  
  
my closeWin:aWin
  
end dispMapView

–Button Clicked Event Handler
on clicked:aSender
  set (my windisp) to false
end clicked:

–make Window for Input
on makeWinWithView(aView, aWinWidth, aWinHeight, aTitle, alphaV)
  set aScreen to NSScreen’s mainScreen()
  
set aFrame to {{0, 0}, {aWinWidth, aWinHeight}}
  
set aBacking to NSTitledWindowMask
  
set aDefer to NSBackingStoreBuffered
  
  
— Window
  
set aWin to NSWindow’s alloc()
  (
aWin’s initWithContentRect:aFrame styleMask:aBacking backing:aDefer defer:false screen:aScreen)
  
  
aWin’s setTitle:aTitle
  
aWin’s setDelegate:me
  
aWin’s setDisplaysWhenScreenProfileChanges:true
  
aWin’s setHasShadow:true
  
aWin’s setIgnoresMouseEvents:false
  
aWin’s setLevel:(NSNormalWindowLevel)
  
aWin’s setOpaque:false
  
aWin’s setAlphaValue:alphaV –append
  
aWin’s setReleasedWhenClosed:true
  
aWin’s |center|()
  
aWin’s makeKeyAndOrderFront:(me)
  
  
— Set Custom View
  
aWin’s setContentView:aView
  
  
return aWin
end makeWinWithView

–close win
on closeWin:aWindow
  repeat with n from 10 to 1 by -1
    (aWindow’s setAlphaValue:n / 10)
    
delay 0.02
  end repeat
  
aWindow’s |close|()
end closeWin:

on makeSegmentedControl(titleList, aWidth, aHeight)
  set aLen to length of titleList
  
  
set aSeg to NSSegmentedControl’s alloc()’s init()
  
aSeg’s setSegmentCount:aLen
  
  
set aCount to 0
  
repeat with i in titleList
    set j to contents of i
    (
aSeg’s setLabel:j forSegment:aCount)
    
set aCount to aCount + 1
  end repeat
  
  
aSeg’s setTranslatesAutoresizingMaskIntoConstraints:false
  
aSeg’s setSegmentStyle:(NSSegmentStyleTexturedRounded)
  
aSeg’s setFrame:(current application’s NSMakeRect(10, 5, 260, 30))
  
aSeg’s setTrackingMode:0
  
aSeg’s setTarget:me
  
aSeg’s setAction:"clickedSeg:"
  
aSeg’s setSelectedSegment:0
  
  
return aSeg
end makeSegmentedControl

on clickedSeg:aSender
  set aSel to aSender’s selectedSegment()
  
set selSeg to (aSel + 1)
  
set mapList to {MKMapTypeStandard, MKMapTypeSatellite, MKMapTypeHybrid}
  
set curMap to contents of item selSeg of mapList
  
aMapView’s setMapType:(curMap)
end clickedSeg:

–http://freegeoip.net
on getIPAddressInfoFreeGeoIP(IPAddress)
  try
    with timeout of 10 seconds
      set link to "http://freegeoip.net/json/" & IPAddress
      
set theURL to |NSURL|’s URLWithString:link
      
set jsonData to NSData’s dataWithContentsOfURL:theURL
      
set aJsonDict to (NSJSONSerialization’s JSONObjectWithData:jsonData options:0 |error|:(missing value))
      
return aJsonDict
    end timeout
  on error
    return missing value
  end try
end getIPAddressInfoFreeGeoIP

–Internet Connection Check
on hasInternetConnection()
  set aURL to |NSURL|’s alloc()’s initWithString:"http://www.google.com"
  
set aReq to NSURLRequest’s alloc()’s initWithURL:aURL cachePolicy:(current application’s NSURLRequestReloadIgnoringLocalCacheData) timeoutInterval:5.0
  
set urlRes to (NSURLConnection’s sendSynchronousRequest:aReq returningResponse:(missing value) |error|:(missing value))
  
if urlRes = missing value then
    return false
  else
    return true
  end if
end hasInternetConnection

★Click Here to Open This Script 

Posted in Require Control-Command-R to run | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

JeditΩの最前面のドキュメントのプロパティ取得

Posted on 2月 6, 2018 by Takaaki Naganoya
AppleScript名:JeditΩの最前面のドキュメントのプロパティ取得
tell application id "jp.co.artman21.JeditOmega"
  tell front document
    properties
  end tell
end tell

–> {rich text:true, line endings:LF, path:"/Users/maro/Library/Mobile Documents/iCloud~jp~co~artman21~JeditOmega/Documents/名称未設定5.rtf", selected character range:{loc:21, len:0}, encoding:missing value, class:document, selected attribute range:{loc:2, len:0}, name:"名称未設定5", default attributes:{forecolor:{0, 0, 0}, backcolor:{65535, 65535, 65535}, charfont:"Helvetica", charsize:12.0}, modified:false, selected paragraph range:{loc:1, len:1}, selected text:"", text:"This is Test String.", document type:"リッチテキスト書式(.rtf)"}

–> {rich text:false, line endings:LF, path:"/Users/maro/Library/Mobile Documents/iCloud~jp~co~artman21~JeditOmega/Documents/名称未設定5.txt", selected character range:{loc:21, len:0}, encoding:missing value, class:document, selected attribute range:{loc:2, len:0}, name:"名称未設定5.rtf", default attributes:{forecolor:{0, 0, 0}, backcolor:{65535, 65535, 65535}, charfont:"Helvetica", charsize:12.0}, modified:false, selected paragraph range:{loc:1, len:1}, selected text:"", text:"This is Test String.", document type:"プレーンテキスト書類"}

★Click Here to Open This Script 

Posted in 未分類 | Tagged 10.11savvy 10.12savvy 10.13savvy JeditΩ | Leave a comment

文字種別にカウントする v2.1(JeditΩ版)

Posted on 2月 6, 2018 by Takaaki Naganoya
AppleScript名:文字種別にカウントする v2.1(JeditΩ版)
— Created 2018-1-11 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
–http://piyocast.com/as/archives/5111

property NSString : a reference to current application’s NSString
property NSNumber : a reference to current application’s NSNumber
property NSDictionary : a reference to current application’s NSDictionary
property NSCountedSet : a reference to current application’s NSCountedSet
property NSMutableArray : a reference to current application’s NSMutableArray
property NSNumberFormatter : a reference to current application’s NSNumberFormatter
property NSRegularExpressionSearch : a reference to current application’s NSRegularExpressionSearch
property NSNumberFormatterRoundUp : a reference to current application’s NSNumberFormatterRoundUp

set aRes to getEditorText() of me
if aRes = false then return

set myPath to retFrontDocsPath() of me
if myPath = missing value then return

set aRec to detectCharKindRatio(aRes) of me
set bRes to retFormattedStr(aRec) of me
makeNewDocument of me given parameter:(myPath & return & return & bRes)

on detectCharKindRatio(aStr as string)
  set theCountedSet to NSCountedSet’s alloc()’s initWithArray:(characters of aStr)
  
set theEnumerator to theCountedSet’s objectEnumerator()
  
  
set cCount to 0
  
set hCount to 0
  
set kCount to 0
  
set oCount to 0
  
set lfCount to 0
  
set scCount to 0
  
set anCount to 0
  
  
set totalC to length of aStr
  
set otherList to {}
  
  
repeat
    set aValue to theEnumerator’s nextObject()
    
if aValue is missing value then exit repeat
    
    
set aStr to aValue as string
    
set tmpCount to (theCountedSet’s countForObject:aValue)
    
    
set s1Res to chkKanji(aStr) of me
    
set s2Res to chkKatakana(aStr) of me
    
set s3Res to chkHiragana(aStr) of me
    
set s4Res to chkLineFeed(aStr) of me
    
set s5Res to chkSpecialSign(aStr) of me
    
set s6Res to chkAlphaNumeric(aStr)
    
    
if s1Res = true then
      set cCount to cCount + tmpCount
    else if s2Res = true then
      set kCount to kCount + tmpCount
    else if s3Res = true then
      set hCount to hCount + tmpCount
    else if s4Res = true then
      set lfCount to lfCount + tmpCount
    else if s5Res = true then
      set scCount to scCount + tmpCount
    else if s6Res = true then
      set anCount to anCount + tmpCount
    else
      set oCount to oCount + tmpCount
      
set the end of otherList to aStr
    end if
  end repeat
  
  
set ckRes to roundingUp((cCount / totalC) * 100, 1) of me
  
set kkRes to roundingUp((kCount / totalC) * 100, 1) of me
  
set hgRes to roundingUp((hCount / totalC) * 100, 1) of me
  
set otRes to roundingUp((oCount / totalC) * 100, 1) of me
  
set lfRes to roundingUp((lfCount / totalC) * 100, 1) of me
  
set scRes to roundingUp((scCount / totalC) * 100, 1) of me
  
set anRes to roundingUp((anCount / totalC) * 100, 1) of me
  
  
return {kanjiNum:cCount, kanjiRatio:ckRes, hiraganaNum:hCount, hiraganaRatio:hgRes, katakanaNum:kCount, katakanaRatio:kkRes, otherNum:oCount, otherRatio:otRes, otherContent:otherList, lineFeedCount:lfCount, lineFeedRatio:lfRes, specialSignNum:scCount, specialSignRatio:scRes, alphaNumericNum:anCount, alphaNumericRatio:anRes, totalCount:totalC}
end detectCharKindRatio

on chkKanji(aChar)
  return detectCharKind(aChar, "[一-龠]") of me
end chkKanji

on chkHiragana(aChar)
  return detectCharKind(aChar, "[ぁ-ん]") of me
end chkHiragana

on chkKatakana(aChar)
  return detectCharKind(aChar, "[ァ-ヶ]") of me
end chkKatakana

on chkLineFeed(aChar)
  return aChar is in {string id 10, string id 13, string id 13 & string id 10}
end chkLineFeed

on chkSpecialSign(aChar)
  return aChar is in {"「", "」", "『", "』", "ー", "―", "〜", "~", "!", "?", "&", "/", "《", "》", "#", "…", "・", "♪", "。", "、", ".", "々", "“", "”", "*", "(", ")", "(", ")", " ", " ", "§", "【", "】", "■", "%", "≒"}
end chkSpecialSign

on chkAlphaNumeric(aChar)
  return detectCharKind(aChar, "[a-zA-Z0-9a-zA-Z0-9]") of me –半角全角英数字
end chkAlphaNumeric

on detectCharKind(aChar, aPattern)
  set aChar to NSString’s stringWithString:aChar
  
set searchStr to NSString’s stringWithString:aPattern
  
set matchRes to aChar’s rangeOfString:searchStr options:(NSRegularExpressionSearch)
  
if matchRes’s location() = (current application’s NSNotFound) or (matchRes’s location() as number) > 9.99999999E+8 then
    return false
  else
    return true
  end if
end detectCharKind

on roundingUp(aNum, aDigit as integer)
  set a to aNum as real
  
set aFormatter to NSNumberFormatter’s alloc()’s init()
  
aFormatter’s setMaximumFractionDigits:aDigit
  
aFormatter’s setRoundingMode:(NSNumberFormatterRoundUp)
  
set aStr to aFormatter’s stringFromNumber:(NSNumber’s numberWithFloat:a)
  
return (aStr as text) as real
end roundingUp

on getEditorText()
  tell application id "jp.co.artman21.JeditOmega"
    if (count every document) = 0 then return false
    
tell front document
      return text of it
    end tell
  end tell
end getEditorText

–処理結果から出力データの組み立て
on retFormattedStr(aRec)
  set a to "漢字  :" & (repChar("■", ((kanjiRatio of aRec) div 10)) of me & "  " & (kanjiRatio of aRec) as string) & "%" & return
  
set b to "ひらがな:" & (repChar("■", ((hiraganaRatio of aRec) div 10)) of me & "  " & (hiraganaRatio of aRec) as string) & "%" & return
  
set c to "カタカナ:" & (repChar("■", ((katakanaRatio of aRec) div 10)) of me & "  " & (katakanaRatio of aRec) as string) & "%" & return
  
set d to "改行文字:" & (repChar("■", ((lineFeedRatio of aRec) div 10)) of me & "  " & (lineFeedRatio of aRec) as string) & "%" & return
  
set e to "特殊記号:" & (repChar("■", ((specialSignRatio of aRec) div 10)) of me & "  " & (specialSignRatio of aRec) as string) & "%" & return
  
set f to "英数字 :" & (repChar("■", ((alphaNumericRatio of aRec) div 10)) of me & "  " & (alphaNumericRatio of aRec) as string) & "%" & return & return
  
set g to ("総文字数:" & encodeJapaneseNumText(totalCount of aRec) & " 文字。 400字詰め原稿用紙で約 " & ((totalCount of aRec) div 400) as string) & " 枚分" & return
  
set all to a & b & c & d & e & f & g
  
return all
end retFormattedStr

on repChar(aChar, aTimes)
  set outStr to ""
  
repeat aTimes times
    set outStr to outStr & aChar
  end repeat
  
return outStr
end repChar

–数字文字列を日本語数値表現文字列に変換
on encodeJapaneseNumText(aText as string)
  set dotText to "." as string
  
set upperDigit to ""
  
set lowerDigit to ""
  
  
–小数点の処理
  
if dotText is in aText then
    set b to offset of dotText in aText
    
set upperDigit to characters 1 thru (b – 1) of aText
    
set upperDigit to upperDigit as string
    
set lowerDigit to characters b thru -1 of aText
    
set lowerDigit to lowerDigit as string
  else
    set upperDigit to aText
  end if
  
  
set scaleList3 to {"", "万", "億", "兆", "京", "垓", "丈", "壌", "溝", "砂", "正", "載", "極", "恒河沙", "阿僧梢", "那由他", "不可思議", "無量大数"}
  
set splitDigit to 4
  
set nList to splitByDigit(upperDigit, splitDigit) of me
  
set nList to reverse of nList
  
  
set resText to ""
  
set digCount to 1
  
repeat with i in nList
    set b to (contents of i) as number
    
if b is not equal to 0 then
      set resText to (b as text) & item digCount of scaleList3 & resText
    end if
    
set digCount to digCount + 1
  end repeat
  
  
return resText & lowerDigit
  
end encodeJapaneseNumText

–指定桁数で区切る
on splitByDigit(a, splitDigit)
  set aList to characters of a
  
set aList to reverse of aList
  
  
set resList to {}
  
set tempT to ""
  
set tempC to 1
  
repeat with i in aList
    set tempT to contents of i & tempT
    
if tempC mod splitDigit = 0 then
      set resList to {tempT} & resList
      
set tempT to ""
    end if
    
set tempC to tempC + 1
  end repeat
  
  
if tempT is not equal to "" then
    set resList to {tempT} & resList
  end if
  
  
resList
  
end splitByDigit

on makeNewDocument given parameter:aStr
  tell application id "jp.co.artman21.JeditOmega"
    set aDoc to make new document with properties {text:aStr}
  end tell
end makeNewDocument

on retFrontDocsPath()
  tell application id "jp.co.artman21.JeditOmega"
    tell front document
      return path
    end tell
  end tell
end retFrontDocsPath

★Click Here to Open This Script 

Posted in 未分類 | Tagged 10.11savvy 10.12savvy 10.13savvy JeditΩ | Leave a comment

JeditΩで新規ドキュメント作成

Posted on 2月 6, 2018 by Takaaki Naganoya
AppleScript名:JeditΩで新規ドキュメント作成
set aCon to "This is Test String."
set newDoc to makeNewDocumentWithJeditOmega(aCon, false) of me –make new plain text
–makeADocToPlan(newDoc) of me

on makeNewDocumentWithJeditOmega(aCon)
  tell application id "jp.co.artman21.JeditOmega"
    set aDoc to make new document with properties {text:aCon}
    
activate
    
return aDoc
  end tell
end makeNewDocumentWithJeditOmega

on makeADocToPlan(aDocRef)
  tell application id "jp.co.artman21.JeditOmega"
    tell aDocRef
      set rich text to false
    end tell
  end tell
end makeADocToPlan

★Click Here to Open This Script 

Posted in 未分類 | Tagged 10.11savvy 10.12savvy 10.13savvy JeditΩ | Leave a comment

各画面でムービーを全画面再生

Posted on 2月 6, 2018 by Takaaki Naganoya
AppleScript名:各画面でムービーを全画面再生
tell application "QuickTime Player"
  activate
  
set current time of every document to 0
  
present every document
  
play every document
end tell

★Click Here to Open This Script 

Posted in 未分類 | Tagged 10.11savvy 10.12savvy 10.13savvy QuickTime Player | Leave a comment

QuickTime Player X経由でムービー情報を取得

Posted on 2月 6, 2018 by Takaaki Naganoya
AppleScript名:QuickTime Player X経由でムービー情報を取得

–QuickTime Player Xでムービーの情報を取得
tell application id "com.apple.QuickTimePlayerX"
  tell document 1
    properties
    
–> {size:59828718, volume:1.0, modified:false, current audio compression:missing value, name:"戦場の絆 17_07_31 17_09 リボー・コロニー(R) 4VS4 Aクラス.mp4", current microphone:missing value, output muted:false, duration:305.203077777778, current movie compression:missing value, current screen compression:missing value, data rate:196029, current camera:missing value, preview resolution:false, playing:true, class:document, file:file "Cherry:Users:me:Movies:戦場の絆 17_07_31 17_09 リボー・コロニー(R) 4VS4 Aクラス.mp4", natural dimensions:{1280, 720}, looping:false, time:1.6761711, rate:1.0}
  end tell
end tell

★Click Here to Open This Script 

Posted in 未分類 | Tagged 10.11savvy 10.12savvy 10.13savvy QuickTime Player | Leave a comment

QuickTime Player Xで録音を開始する

Posted on 2月 6, 2018 by Takaaki Naganoya
AppleScript名:QuickTime Player Xで録音を開始する
tell application id "com.apple.QuickTimePlayerX"
  set recSound to (new audio recording)
  
  
tell recSound
    start
  end tell
end tell

★Click Here to Open This Script 

Posted in 未分類 | Tagged 10.11savvy 10.12savvy 10.13savvy QuickTime Player | Leave a comment

QuickTimeムービーの縦横ドット数を取得する

Posted on 2月 6, 2018 by Takaaki Naganoya
AppleScript名:QuickTimeムービーの縦横ドット数を取得する
tell application "QuickTime Player"
  tell document 1
    set {aWidth, aHeight} to natural dimensions
  end tell
end tell
–>{640, 480}

★Click Here to Open This Script 

Posted in 未分類 | Tagged 10.11savvy 10.12savvy 10.13savvy QuickTime Player | Leave a comment

QT Playerでムービー再生位置を先頭に(巻き戻し)

Posted on 2月 6, 2018 by Takaaki Naganoya
AppleScript名:QT Playerでムービー再生位置を先頭に(巻き戻し)
tell application "QuickTime Player"
  tell document 1
    set current time to 0
  end tell
end tell

★Click Here to Open This Script 

Posted in 未分類 | Tagged 10.11savvy 10.12savvy 10.13savvy QuickTime Player | Leave a comment

オープン中のムービーのファイルにラベルを付ける

Posted on 2月 6, 2018 by Takaaki Naganoya
AppleScript名:オープン中のムービーのファイルにラベルを付ける
— Created 2017-10-26 by Takaaki Naganoya
— 2017 Piyomaru Software
–http://piyocast.com/as/archives/4925
tell application "QuickTime Player"
  set aDocList to every document
end tell

repeat with i in aDocList
  
  
tell application "QuickTime Player"
    tell i
      set aProp to properties
      
set aFile to (file of aProp) as alias
    end tell
  end tell
  
  
tell application "Finder"
    set label index of aFile to 5
  end tell
  
end repeat

★Click Here to Open This Script 

Posted in 未分類 | Tagged 10.11savvy 10.12savvy 10.13savvy QuickTime Player | Leave a comment

Post navigation

  • Older posts
  • Newer posts

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

Google Search

Popular posts

  • 開発機としてM2 Mac miniが来たのでガチレビュー
  • macOS 15, Sequoia
  • Pages本執筆中に、2つの書類モード切り替えに気がついた
  • Numbersで選択範囲のセルの前後の空白を削除
  • メキシカンハットの描画
  • Pixelmator Pro v3.6.4でAppleScriptからの操作時の挙動に違和感が
  • AppleScriptによる並列処理
  • macOS 15でも変化したText to Speech環境
  • Safariで「プロファイル」機能を使うとAppleScriptの処理に影響
  • AppleScript入門③AppleScriptを使った「自動化」とは?
  • デフォルトインストールされたフォント名を取得するAppleScript
  • 【続報】macOS 15.5で特定ファイル名パターンのfileをaliasにcastすると100%クラッシュするバグ
  • Script Debuggerの開発と販売が2025年に終了
  • macOS 15 リモートApple Eventsにバグ?
  • AppleScript入門① AppleScriptってなんだろう?
  • macOS 14で変更になったOSバージョン取得APIの返り値
  • NSObjectのクラス名を取得 v2.1
  • macOS 15:スクリプトエディタのAppleScript用語辞書を確認できない
  • 有害ではなくなっていたSpaces
  • AVSpeechSynthesizerで読み上げテスト

Tags

10.11savvy (1101) 10.12savvy (1242) 10.13savvy (1391) 10.14savvy (587) 10.15savvy (438) 11.0savvy (283) 12.0savvy (212) 13.0savvy (195) 14.0savvy (148) 15.0savvy (137) CotEditor (66) Finder (51) Keynote (119) NSAlert (61) NSArray (51) NSBitmapImageRep (20) NSBundle (20) NSButton (34) NSColor (53) NSDictionary (28) NSFileManager (23) NSFont (21) NSImage (41) NSJSONSerialization (21) NSMutableArray (63) NSMutableDictionary (22) NSPredicate (36) NSRunningApplication (56) NSScreen (30) NSScrollView (22) NSString (119) NSURL (98) NSURLRequest (23) NSUTF8StringEncoding (30) NSView (33) NSWorkspace (20) Numbers (76) Pages (55) Pixelmator Pro (20) Safari (44) Script Editor (27) WKUserContentController (21) WKUserScript (20) WKWebView (23) WKWebViewConfiguration (22)

カテゴリー

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

アーカイブ

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

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

メタ情報

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

Forum Posts

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

メタ情報

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