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

カテゴリー: GUI Scripting

GUI Scripting的なUI Elementへの参照から所属するアプリケーション名を取得する

Posted on 9月 17, 2018 by Takaaki Naganoya

GUI Scripting的なUI Elementへの参照をもとに、そのUI Elementが所属するアプリケーション名を取得するAppleScriptです。

こんな、Safariの「ファイル」メニューの中にあるメニュー項目、

menu item “PDFとして書き出す…” of menu “ファイル” of menu bar item “ファイル” of menu bar 1 of application process “Safari”

があったとして、このオブジェクトが所属しているアプリケーション名を取得したいというケースがありました。上記の例では「Safari」がそれに該当します。

GUI Scripting的なお約束として、オブジェクト階層が上から下に向かって取得する場合には「entire contents」でまとめて取得できるのですが、下から上に向かってparentで取得できるわけでもなく、アプリケーションプロセス名をさかのぼって取得するといった処理ができていませんでした。

AppleScriptの「仕様」的には不可能です。

でも、不可能であることさえわかれば(正攻法では不可能なので)、いつものトリッキーかつ邪道な手口でなんとかなりそうです。

そうです、エラートラップ中で無理やりエラーを起こして、そのエラーメッセージの情報から取得してしまおうという、いつものやつです。

というわけで、GUI Elementの情報から所属アプリケーション名を取得できました。

最近は、さらなる「卑劣な手段」を用意しているので、そちらで華麗かつ卑劣に処理してもよかったのですが、とりあえず手短にまとめたかったのでいつものやつで処理しました。

AppleScript名:GUI Scripting的なUI Elementへの参照から所属するアプリケーション名を取得する.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2018/09/17
—
–  Copyright © 2018 Piyomaru Software, All Rights Reserved
—

use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use scripting additions

tell application "System Events"
  set aRef to menu item "PDFとして書き出す…" of menu "ファイル" of menu bar item "ファイル" of menu bar 1 of application process "Safari"
end tell

set appName to retRootAppProcessNameFromGUIElementRef(aRef) of me
–> "Safari"

–GUI Scripting的なUI Elementへの参照から、rootのアプリケーションプロセス名を取得する
on retRootAppProcessNameFromGUIElementRef(aRef)
  try
    set aStr to aRef as string –force cause error
  on error erM
    set offsetA to offset of " of application \"System Events\"" in erM
    
set offsetB to offset of "«class pcap» " in erM
    
set appName to text (offsetB + (length of "«class pcap» ") + 1) thru (offsetA – 2) of erM
    
return appName as string
  end try
end retRootAppProcessNameFromGUIElementRef

★Click Here to Open This Script 

Posted in GUI GUI Scripting System | Tagged 10.11savvy 10.12savvy 10.13savvy System Events | Leave a comment

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

Posted on 2月 14, 2018 by Takaaki Naganoya

CotEditorでオープン中の書類の「次」のファイルを縦書きでオープンするAppleScriptです。

CotEditorでオープン中の書類のパスを取得して、同一フォルダ内にあるファイル名一覧からオープン中の書類の「次」に該当する書類をオープンします。

ファイルオープン後にCotEditorのメニューをGUI Scriptingで強制的に操作して縦書きに設定します。

CotEditor v3.3.2のメニューにバグがあって、横書きのメニュー項目にも縦書きのメニュー項目にも「縦書き」と書いてあり、メニュー項目を名称で指定するとうまく動きません。そこだけItem No.で指定しています。このメニュー項目の不具合については、近い将来のアップデートで修正される見込みです。


▲CotEditor内蔵のScript Menuから実行するとGUI Scriptingの実行が制限されて縦書きにならない


▲OS側のScript Menuから実行すると問題なく実行できる

AppleScript名:表示中のCotEditor書類の「次」のファイルを縦書きでオープン v2
— Created 2017-12-15 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use bPlus : script "BridgePlus"

property |NSURL| : a reference to current application’s |NSURL|
property NSArray : a reference to current application’s NSArray
property NSString : a reference to current application’s NSString
property SMSForder : a reference to current application’s SMSForder
property NSPredicate : a reference to current application’s NSPredicate
property NSFileManager : a reference to current application’s NSFileManager
property NSMutableArray : a reference to current application’s NSMutableArray
property NSSortDescriptor : a reference to current application’s NSSortDescriptor
property NSURLIsPackageKey : a reference to current application’s NSURLIsPackageKey
property NSURLIsDirectoryKey : a reference to current application’s NSURLIsDirectoryKey
property NSDirectoryEnumerationSkipsHiddenFiles : a reference to current application’s NSDirectoryEnumerationSkipsHiddenFiles
property NSDirectoryEnumerationSkipsPackageDescendants : a reference to current application’s NSDirectoryEnumerationSkipsPackageDescendants
property NSDirectoryEnumerationSkipsSubdirectoryDescendants : a reference to current application’s NSDirectoryEnumerationSkipsSubdirectoryDescendants

load framework

tell application "CotEditor"
  set dCount to count every document
  
if dCount = 0 then return
  
  
tell front document
    set curPath to path
  end tell
  
  
tell window 1
    set aBounds to bounds
  end tell
end tell

set aPath to NSString’s stringWithString:curPath
set fileName to (aPath’s lastPathComponent()) –ファイル名
set pathExtension to aPath’s pathExtension() as string
set parentFol to (aPath’s stringByDeletingLastPathComponent()) as string —親フォルダ

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

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

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

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

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

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

makeWinVertical() of me –縦書き表示

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

–Make CotEditor’s front window to Vertical display mode (Tategaki)
on makeWinVertical()
  activate application "CotEditor"
  
tell application "System Events"
    tell process "CotEditor"
      try
        click menu item 3 of menu 1 of menu item "文章の方向" of menu 1 of menu bar item "フォーマット" of menu bar 1
      end try
    end tell
  end tell
end makeWinVertical

★Click Here to Open This Script 

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

MacDownで編集中のMarkDown書類で見出しが見出し落ちしていないかチェック

Posted on 2月 6, 2018 by Takaaki Naganoya

MacDownで編集中のMarkdown書類をいったんデスクトップにPDF書き出しして、見出しがページ末尾に位置していないか(見出し落ち)をチェックするAppleScriptです。

MacDownのAppleScript対応機能が少ないので、ほとんどAppleScriptだけで処理しています。Cocoaの機能を呼べるようになったので、とくに問題ありません。

MacDownで編集中の最前面のMarkdown書類からパスを取得し、AppleScriptで直接ファイルから内容を読み込み、正規表現で見出し一覧を取得します。

MacDownからGUI Scripting経由でメニューをコントロールしてPDF書き出しを行い、ページ単位でPDFからテキストを抽出。不要な空白文字列などを削除。


▲いわゆる「見出し落ち」の状態。ページ末尾に見出し項目が存在している

各ページのテキストが見出しの内容で終了していれば、結果出力用の変数midashiOchiListに{ページ数, 見出し名称} を追加して出力します。

–> {{2, “対象となるFramework”}}

AppleScript名:MacDownで編集中のMarkDown書類で見出しが見出し落ちしていないかチェック
— Created 2017-08-12 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
use framework "Quartz"

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

set docName to getFrontmostMarkdownDocName() of me
if docName = false then return

set newName to repFileNameExtension(docName, ".pdf") of me
set newPath to (POSIX path of (path to desktop)) & newName
set dRes to deleteItemAt(newPath) of me –前回実行時にデスクトップに残った同名のPDFを削除する

–Markdownのソースを元ファイルから直接読み出す
set docSourcePath to getFrontmostMarkdownFullPath() of me
set aStr to (read (docSourcePath as alias) as «class utf8»)

–getHeader List
set aList to retHeaders(aStr) of me

–Export Markdown to PDF (desktop folder)
macDownForceSave() of me

set tList to textInPDFinEachPage(newPath) of me

set pCount to 1
set midashOchiList to {}
repeat with i in tList
  set j to (contents of i) as string
  
  
repeat with ii in aList
    set jj to (contents of second item of ii) as string
    
–set jj2 to replaceText(jj, "(", "(") of me
    
–set jj3 to replaceText(jj2, ")", ")") of me
    
    
if (j ends with jj) then
      set the end of midashOchiList to {pCount, jj}
    end if
  end repeat
  
set pCount to pCount + 1
end repeat

return midashOchiList

on retHeaders(aCon)
  set tList to {}
  
set regStr to "^#{1,6}[^#]*?$"
  
  
set headerList to my findPattern:regStr inString:aCon
  
repeat with i in headerList
    set j to contents of i
    
set regStr2 to "^#{1,6}[^#]*?"
    
set headerLevel to length of first item of (my findPattern:regStr2 inString:j)
    
set tmpHeader1 to text (headerLevel + 1) thru -1 in j
    
–ヘッダーの前後から空白文字をトリミング
    
set tmpHeader2 to trimWhiteSpaceFromHeadAndTail(tmpHeader1) of me
    
    
–ヘッダー部でPDF書き出ししたときに全角文字が半角文字に置換されてしまうケースに対処
    
set tmpHeader3 to replaceText(tmpHeader2, "(", "(") of me
    
set tmpHeader4 to replaceText(tmpHeader3, ")", ")") of me
    
    
set the end of tList to {headerLevel, tmpHeader4}
  end repeat
  
  
return tList
end retHeaders

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

–指定文字列の前後から空白をトリミング
on trimWhiteSpaceFromHeadAndTail(aStr as string)
  set aString to NSString’s stringWithString:aStr
  
set bString to aString’s stringByTrimmingCharactersInSet:(NSCharacterSet’s whitespaceAndNewlineCharacterSet())
  
return bString as list of string or string –as anything
end trimWhiteSpaceFromHeadAndTail

–ファイル名の拡張子を置換する
on repFileNameExtension(origName, newExt)
  set aName to current application’s NSString’s stringWithString:origName
  
set theExtension to aName’s pathExtension()
  
if (theExtension as string) is not equal to "" then
    set thePathNoExt to aName’s stringByDeletingPathExtension()
    
set newName to (thePathNoExt’s stringByAppendingString:newExt)
  else
    set newName to (aName’s stringByAppendingString:newExt)
  end if
  
  
return newName as string
end repFileNameExtension

on textInPDFinEachPage(thePath)
  set aList 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 to (bStr as string)
  end repeat
  
  
return aList
end textInPDFinEachPage

–注意!! ここでGUI Scriptingを使用。バージョンが変わったときにメニュー階層などの変更があったら書き換え
on macDownForceSave()
  activate application "MacDown"
  
tell application "System Events"
    tell process "MacDown"
      — File > Export > PDF
      
click menu item 2 of menu 1 of menu item 14 of menu 1 of menu bar item 3 of menu bar 1
      
      
–Go to Desktop Folder
      
keystroke "d" using {command down}
      
      
–Save Button on Sheet
      
click button 1 of sheet 1 of window 1
    end tell
  end tell
end macDownForceSave

on getFrontmostMarkdownDocName()
  tell application "MacDown"
    set dList to every document
    
set dCount to count every item of dList
    
if dCount is not equal to 1 then
      display notification "Markdown document is not only one."
      
return false
    end if
    
    
tell document 1
      set docName to name
    end tell
    
return docName
  end tell
end getFrontmostMarkdownDocName

on getFrontmostMarkdownFullPath()
  tell application "MacDown"
    tell document 1
      set aProp to properties
    end tell
  end tell
  
  
set aPath to (file of aProp)
end getFrontmostMarkdownFullPath

–任意のデータから特定の文字列を置換
on replaceText(origData, origText, repText)
  set curDelim to AppleScript’s text item delimiters
  
set AppleScript’s text item delimiters to {origText}
  
set origData to text items of origData
  
set AppleScript’s text item delimiters to {repText}
  
set origData to origData as text
  
set AppleScript’s text item delimiters to curDelim
  
–set b to origData as text
  
return origData
end replaceText

–指定のPOSIX pathのファイルを強制削除(あってもなくてもいい)
on deleteItemAt(aPOSIXpath)
  set theNSFileManager to current application’s NSFileManager’s defaultManager()
  
set theResult to theNSFileManager’s removeItemAtPath:(aPOSIXpath) |error|:(missing value)
  
return (theResult as integer = 1) as boolean
end deleteItemAt

★Click Here to Open This Script 

Posted in GUI Scripting Markdown PDF Text | Tagged 10.11savvy 10.12savvy 10.13savvy MacDown | Leave a comment

CotEditorの最前面で表示中のDocumentを縦書き表示に

Posted on 2月 6, 2018 by Takaaki Naganoya

CotEditorで表示中のテキストファイルを、GUI Scripting経由で縦書き表示するAppleScriptです。

CotEditorの途中のバージョンでメニュー構成が変更になったため、本Scriptは動かなくなりました。

とりあえず、メニュー変更に追従して書き換えを行なって使っていましたが、根本的な解決策を1024jpさんに教えてもらえたので(Xattributeの書き換え)、そちらをおすすめします。

AppleScript名:CotEditorの最前面で表示中のDocumentを縦書き表示に
makeWinVertical() of me

on makeWinVertical()
  activate application "CotEditor"
  
tell application "System Events"
    tell process "CotEditor"
      try
        click menu item "縦書きで表示" of menu 1 of menu bar item "フォーマット" of menu bar 1
      end try
    end tell
  end tell
end makeWinVertical

★Click Here to Open This Script 

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

表示中のCotEditor書類と同じフォルダで各書類の1行目で選択して表示

Posted on 2月 6, 2018 by Takaaki Naganoya
AppleScript名:表示中のCotEditor書類と同じフォルダで各書類の1行目で選択して表示
— Created 2017-12-15 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use bPlus : script "BridgePlus"
use mdLib : script "Metadata Lib" version "1.0.0"
use jLib : script "japaneseTextEncodingDetector"

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

load framework

tell application "CotEditor"
  set dCount to count every document
  
if dCount = 0 then return
  
  
tell front document
    set curPath to path
  end tell
  
  
tell window 1
    set aBounds to bounds
  end tell
end tell

set aPath to current application’s NSString’s stringWithString:curPath
set fileName to (aPath’s lastPathComponent()) –ファイル名
set pathExtension to aPath’s pathExtension() as string
set parentFol to (aPath’s stringByDeletingLastPathComponent()) as string —親フォルダ

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

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

–ダイアログ表示用のデータを作成
set ccList to {}
repeat with i in cList
  set j to POSIX path of (i as string)
  
set aStr to readJapanesTextFileWithGuessingEncoding(j) of jLib
  
if aStr = missing value or aStr = false then
    display dialog "Encoding Error"
    
return
  end if
  
  
set aPath to (current application’s NSString’s stringWithString:j)
  
set fileName to (aPath’s lastPathComponent()) as string –ファイル名  
  
set aFirst to first item of paragraphs of aStr
  
set the end of ccList to (fileName & " / " & aFirst)
end repeat

set aMes to "項目を選択してください"
set selRes to retItemFromListByItemNo(ccList, aMes) of me
if selRes = false then return –Cancel

set newPath to contents of item selRes of cList

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

makeWinVertical() of me –縦書き表示

–Make CotEditor’s front window to Vertical display mode (Tategaki)
on makeWinVertical()
  activate application "CotEditor"
  
tell application "System Events"
    tell process "CotEditor"
      try
        click menu item "縦書きで表示" of menu 1 of menu bar item "フォーマット" of menu bar 1
      end try
    end tell
  end tell
end makeWinVertical

on retFileFormatUTI(aExt as string)
  if aExt begins with "." then set aExt to text 2 thru -1 of aExt
  
return (current application’s SMSForder’s UTIForExtension:aExt)
end retFileFormatUTI

on spotlightFindByLabels(aLabelList as list, thePath as string)
  set aList to makeRepeatinglList(length of aLabelList, "kMDItemFSLabel == %@")
  
set aStr to retStrFromArrayWithDelimiter(aList, " OR ") of me
  
set fRes to mdLib’s searchFolders:{thePath} searchString:aStr searchArgs:aLabelList
  
return fRes
end spotlightFindByLabels

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

–指定回数、指定アイテムを連結したリストを作成
on makeRepeatinglList(hitNum as integer, hitItem as string)
  set outList to {}
  
repeat hitNum times
    set the end of outList to hitItem
  end repeat
  
return outList
end makeRepeatinglList

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

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

–リストから選択してアイテム番号を返す
on retItemFromListByItemNo(aList, aMes)
  set aRes to choose from list aList with prompt aMes
  
if aRes = false then return 0
  
  
set aRes to contents of item 1 of aRes
  
set hitNum to 1
  
repeat with i in aList
    set j to contents of i
    
if j is equal to aRes then
      exit repeat
    end if
    
set hitNum to hitNum + 1
  end repeat
  
return hitNum
end retItemFromListByItemNo

★Click Here to Open This Script 

Posted in GUI Scripting Spotlight | Tagged 10.11savvy 10.12savvy 10.13savvy CotEditor | Leave a comment

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

Posted on 2月 6, 2018 by Takaaki Naganoya
AppleScript名:表示中のCotEditor書類の「次」のファイルを縦書きでオープン
— Created 2017-12-15 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use bPlus : script "BridgePlus"
–http://piyocast.com/as/archives/5034

property |NSURL| : a reference to current application’s |NSURL|
property NSArray : a reference to current application’s NSArray
property NSString : a reference to current application’s NSString
property SMSForder : a reference to current application’s SMSForder
property NSPredicate : a reference to current application’s NSPredicate
property NSFileManager : a reference to current application’s NSFileManager
property NSMutableArray : a reference to current application’s NSMutableArray
property NSSortDescriptor : a reference to current application’s NSSortDescriptor
property NSURLIsPackageKey : a reference to current application’s NSURLIsPackageKey
property NSURLIsDirectoryKey : a reference to current application’s NSURLIsDirectoryKey
property NSDirectoryEnumerationSkipsHiddenFiles : a reference to current application’s NSDirectoryEnumerationSkipsHiddenFiles
property NSDirectoryEnumerationSkipsPackageDescendants : a reference to current application’s NSDirectoryEnumerationSkipsPackageDescendants
property NSDirectoryEnumerationSkipsSubdirectoryDescendants : a reference to current application’s NSDirectoryEnumerationSkipsSubdirectoryDescendants

load framework

tell application "CotEditor"
  set dCount to count every document
  
if dCount = 0 then return
  
  
tell front document
    set curPath to path
  end tell
  
  
tell window 1
    set aBounds to bounds
  end tell
end tell

set aPath to NSString’s stringWithString:curPath
set fileName to (aPath’s lastPathComponent()) –ファイル名
set pathExtension to aPath’s pathExtension() as string
set parentFol to (aPath’s stringByDeletingLastPathComponent()) as string —親フォルダ

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

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

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

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

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

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

makeWinVertical() of me –縦書き表示

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

–Make CotEditor’s front window to Vertical display mode (Tategaki)
on makeWinVertical()
  activate application "CotEditor"
  
tell application "System Events"
    tell process "CotEditor"
      try
        click menu item "縦書きで表示" of menu 1 of menu bar item "フォーマット" of menu bar 1
      end try
    end tell
  end tell
end makeWinVertical

★Click Here to Open This Script 

Posted in GUI Scripting 未分類 | Tagged 10.11savvy 10.12savvy 10.13savvy CotEditor | Leave a comment

Post navigation

  • Newer posts

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

Google Search

Popular posts

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

Tags

10.11savvy (1101) 10.12savvy (1242) 10.13savvy (1391) 10.14savvy (586) 10.15savvy (437) 11.0savvy (281) 12.0savvy (201) 13.0savvy (129) 14.0savvy (77) 15.0savvy (51) CotEditor (62) Finder (50) iTunes (19) Keynote (110) NSAlert (60) NSArray (51) NSBitmapImageRep (20) NSBundle (20) NSButton (34) NSColor (51) NSDictionary (27) NSFileManager (23) NSFont (19) NSImage (41) NSJSONSerialization (21) NSMutableArray (62) NSMutableDictionary (21) NSPredicate (36) NSRunningApplication (56) NSScreen (30) NSScrollView (22) NSString (117) NSURL (97) NSURLRequest (23) NSUTF8StringEncoding (30) NSView (33) NSWorkspace (20) Numbers (65) Pages (51) Safari (44) Script Editor (26) WKUserContentController (21) WKUserScript (20) WKWebView (23) WKWebViewConfiguration (22)

カテゴリー

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

アーカイブ

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

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

メタ情報

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

Forum Posts

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

メタ情報

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