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

カテゴリー: shell script

オープン中のIllustrator書類をartboardごとに分割 v2

Posted on 8月 9, 2018 by Takaaki Naganoya

Adobe Illustrator CC 2018(バージョン22.1)で、オープン中の(複数のアートボードを持つ)書類を、アートボード単位で別書類に分けるAppleScriptです。

書類は(とりあえず)デスクトップに書き込まれます。

こういうコマンドが最初からあってもおかしくないところですが、存在していないようなので書いてみました。まずは、オープン中の書類のパスを取得し、各アートボードの名称を取得して書き出し時のファイル名として使用します。

元ファイルをクローズしては、デスクトップに新規名称でコピーし、コピーした書類をオープン、書き出し対象外のアートボードを順次選択してはアートボード上のオブジェクトを削除してアートボード自体も削除、すべて削除したら保存してクローズという動作を行います。

本来であれば高速化のために複数のアートボードを一括で削除することを考えるところですが、アートボードの削除だけであればできるものの、アートボード上のオブジェクトの削除が行えなくなってしまうので、順次削除に落ち着きました。また、本Scriptが本気でスピードを求められるようなハードな用途ではなく、文字や画像の流し込みテンプレートのメンテナンス用という「平和な用途」のために作成したものであるため、高速化処理については考慮していません。

最初からアートボード外に置かれたオブジェクトについては削除していません。あくまで自分用のツールなので作り込む必要性を感じません。気が向いたら削除するのではないでしょうか。

本Scriptの作成中にも、単にAppleScriptで命令を出しただけで派手にクラッシュしまくるAdobe Illustrator。バージョンが上がって見た目が変わっても、あの出来の悪いIllustratorであることに変わりはないのだと思い知らされました。

AppleScript名:オープン中のIllustrator書類をartboardごとに分割 v2.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2018/08/07
—
–  Copyright © 2018 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.5" — El Capitan (10.11) or later
use framework "Foundation"
use scripting additions

set dPath to (path to desktop) as string
set namesList to {}

tell application "Adobe Illustrator"
  tell front document
    set aCount to count every artboard
    
set aPath to (file path) as string
  end tell
  
  
repeat with i from 1 to aCount
    set aName to getArtboardName(i – 1) of me –index base correction (1 –> 0)
    
set the end of namesList to aName
  end repeat
  
  
close every document saving no
end tell

repeat with i from 1 to aCount
  
  
set aRes to retSerialListWithExclusion(1, aCount, i) of me
  
set aaRes to reverse of aRes –artboardをIndex値で指定するため、先頭から削除するとIndex値が変わる。そのため逆順に処理
  
  
set tmpName to contents of item i of namesList
  
  
set fromFile to POSIX path of aPath
  
set fromFilePOSIX to quoted form of POSIX path of fromFile
  
  
set toFile to (dPath & tmpName & ".ai")
  
set toFilePOSIX to quoted form of POSIX path of toFile
  
  
set shText to "cp " & fromFilePOSIX & " " & toFilePOSIX
  
do shell script shText
  
  
tell application "Adobe Illustrator"
    open file toFile
    
tell front document
      repeat with ii in aaRes
        set jj to ii as integer
        
selectArtboard(jj – 1) of me –index base correction (1 –> 0)
        
selectobjectsonactiveartboard
        
delete selection
        
delete artboard jj
      end repeat
      
      
close with saving
    end tell
  end tell
  
end repeat

–https://lists.apple.com/archives/applescript-users/2015/Jul/msg00104.html
on selectArtboard(theArtboardIndex as string)
  tell application "Adobe Illustrator"
    tell front document
      –Index is 0 based
      
do javascript ("app.activeDocument.artboards.setActiveArtboardIndex(" & theArtboardIndex & ")")
    end tell
  end tell
end selectArtboard

on getArtboardName(theArtboardIndex as string)
  tell application "Adobe Illustrator"
    tell front document
      –Index is 0 based
      
do javascript ("app.activeDocument.artboards[" & theArtboardIndex & "].name")
    end tell
  end tell
end getArtboardName

on retSerialListWithExclusion(aFromNum as integer, aToNum as integer, anEXnum as integer)
  set outList to {}
  
repeat with i from aFromNum to aToNum
    if i = anEXnum then
      —
    else
      set the end of outList to i
    end if
  end repeat
  
  
return outList
end retSerialListWithExclusion

★Click Here to Open This Script 

Posted in file File path shell script | Tagged 10.12savvy Illustrator | Leave a comment

Google Drive File StreamのドライブでSpotlight Indexを生成

Posted on 8月 4, 2018 by Takaaki Naganoya

Google Drive File Stream上でSpotlight Indexを生成するAppleScriptです。

Google Driveには、Gmailのオマケでついてくる個人のデバイス間で情報のシンクロを行う目的のPersonal版(DropboxのGoogle版的なもの)と、企業内やグループ内でファイル共有を行うG SuiteのGoodle Drive File Streamがあり、後者についてはGoogleによる「Google Drive File Stream」ツールが提供され、GoogleDriveをデスクトップにマウントできます。

実際にGoogle Drive File Streamを使ってみたところ、デフォルト状態だとSpotlight検索が効きませんでした。

そこで、Index生成してみたものの…既存のファイルについてはSpotlight検索できませんでした。Index生成後に、新規追加したファイルについてはSpotlight検索が有効でした。

後日談:ただ、Google Drive File Streamに対してSpotlight Indexを常時生成するようにすると、CPUに対する負荷が大きくなるため、実際の運用ではSpotlightを無効にして運用するようにしました。

AppleScript名:Google Drive File Streamでインデックス生成
do shell script "mdutil -E /Volumes/GoogleDrive/" with administrator privileges

★Click Here to Open This Script 

自分が試したのは、Google Drive File Stream内の「マイドライブ」領域のみで、

「グループドライブ」領域についてはまだテストできていません。

既存のファイルについては、mdimportコマンドでインデックス作成すれば大丈夫だと思っていますが、実際に試してみると予想外の挙動を行うのかもしれません。

AppleScript名:GDFS上でSpotlight検索
— Created 2016-06-17 by Takaaki Naganoya
— 2016 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

property NSArray : a reference to current application’s NSArray
property NSPredicate : a reference to current application’s NSPredicate
property NSSortDescriptor : a reference to current application’s NSSortDescriptor
property NSMetadataQuery : a reference to current application’s NSMetadataQuery
property NSNotificationCenter : a reference to current application’s NSNotificationCenter
property NSMetadataQueryDidUpdateNotification : a reference to current application’s NSMetadataQueryDidUpdateNotification
property NSMetadataQueryDidFinishGatheringNotification : a reference to current application’s NSMetadataQueryDidFinishGatheringNotification

property searchRes : {}

set origPath to POSIX path of (choose folder)
set aList to spotlightSearch(origPath, "kMDItemContentType == ’public.png’") of me

on spotlightSearch(origPath, aMDfindParam)
  
  
set my searchRes to {} –initialize
  
initiateSearchForFullPath(aMDfindParam, origPath) –Predicate & Scope Directory
  
  
–Waiting for the result
  
repeat while my searchRes = {}
    delay 0.01
  end repeat
  
  
set anObj to my searchRes’s firstObject() –Pick up the first one for test
  
if anObj = missing value then return {} –No Result
  
  
set resArray to {}
  
repeat with anItem in my searchRes
    set j to contents of anItem
    
set aPath to (j’s valueForAttribute:"kMDItemPath") as string
    
set the end of resArray to aPath
  end repeat
  
  
return resArray
  
end spotlightSearch

on initiateSearchForFullPath(aQueryStrings, origPath)
  
  
set aSearch to NSMetadataQuery’s alloc()’s init()
  
  
NSNotificationCenter’s defaultCenter()’s addObserver:(me) selector:"queryDidUpdate:" |name|:(NSMetadataQueryDidUpdateNotification) object:aSearch
  
NSNotificationCenter’s defaultCenter()’s addObserver:(me) selector:"initalGatherComplete:" |name|:(NSMetadataQueryDidFinishGatheringNotification) object:aSearch
  
  
set aPredicate to NSPredicate’s predicateWithFormat:aQueryStrings
  
aSearch’s setPredicate:aPredicate
  
  
set aScope to NSArray’s arrayWithObjects:{origPath}
  
aSearch’s setSearchScopes:aScope
  
  
set sortKeys to NSSortDescriptor’s sortDescriptorWithKey:"kMDItemFSName" ascending:true
  
aSearch’s setSortDescriptors:(NSArray’s arrayWithObject:sortKeys)
  
  
aSearch’s startQuery()
  
end initiateSearchForFullPath

on queryDidUpdate:sender
  log sender
  
–> (NSConcreteNotification) NSConcreteNotification 0x7fa618450820 {name = NSMetadataQueryDidFinishGatheringNotification; object = <NSMetadataQuery: 0x7fa6172c6ca0>}
end queryDidUpdate:

on initalGatherComplete:sender
  set anObject to sender’s object
  
anObject’s stopQuery()
  
NSNotificationCenter’s defaultCenter()’s removeObserver:me |name|:(NSMetadataQueryDidUpdateNotification) object:anObject
  
NSNotificationCenter’s defaultCenter()’s removeObserver:me |name|:(NSMetadataQueryDidFinishGatheringNotification) object:anObject
  
  
set my searchRes to anObject’s results()
end initalGatherComplete:

★Click Here to Open This Script 

Posted in drive file shell script Spotlight | Tagged 10.12savvy NSArray NSMetadataQuery NSNotificationCenter NSPredicate NSSortDescriptor | Leave a comment

Enable Script Menu

Posted on 3月 12, 2018 by Takaaki Naganoya

メニューバー上にあるScript Menuを表示状態に設定変更するAppleScriptです。

Script Menuの表示・非表示はスクリプトエディタ内の環境設定で制御するようになっていますが、Script Menu自体はMenu Extraでスクリプトエディタとは独立して動作しているので、外部からオンにすることが可能です。

–> Demo Movie


▲Default


▲実行後

AppleScript名:Enable System Wide Script Menu
tell application "Finder"
  open (POSIX file "/System/Library/CoreServices/Menu Extras/Script Menu.menu") as alias
end tell

★Click Here to Open This Script 

AppleScript名:Enable System Wide Script Menu (Shell)
do shell script "open " & quoted form of "/System/Library/CoreServices/Menu Extras/Script Menu.menu"

★Click Here to Open This Script 

追記:macOS 10.14でOS標準装備のScript MenuがMenu Extraから単体のアプリケーションに変更になったので、Enableの方法も変更になりました。

AppleScript名:Enable System Wide Script Menu_10.14.scpt
tell application "Finder"
  open (POSIX file "/System/Library/CoreServices/Script Menu.app") as alias
end tell

★Click Here to Open This Script 

Posted in shell script System | Tagged 10.11savvy 10.12savvy 10.13savvy 10.14savvy | 1 Comment

shebangっぽい行から実行プログラムを取得してスクリプト言語の拡張子を取得

Posted on 3月 10, 2018 by Takaaki Naganoya

shebangを含む複数行のテキストからshebang(らしきもの)を検索して、実行プログラム名を取得し、実行するScript言語のファイルの拡張子を判定するAppleScriptです。

RTFで記述したシェルスクリプトやRubyのスクリプトのスケルトンに、色分けしたパラメータ部分のデータを差し替えてRubyやシェルスクリプトの実行ファイルを動的に書き出し、所定のスクリプト言語処理系で実行するAppleScriptを書いたときに用いたものです。

割と処理内容はヘロヘロでたいした固い処理は行なっていませんが、凶悪な処理を行うためのキーパーツです。

AppleScript名:shebangっぽい行から実行プログラムを取得してスクリプト言語の拡張子を取得
set aText to "#!/usr/bin/env python
import re
"

set aLang to splitLangFromShebangStr(aText) of me
if aLang = false then error "This data seems not a shebang"
set aExt to detectScriptFileExtension(aLang) of me
return {aLang, aExt}
–> {"python", "py"}

–shebangっぽい行から実行プログラム名を抽出
on splitLangFromShebangStr(aText)
  set aTmpList to paragraphs of aText
  
  
repeat with i in aTmpList
    set j to contents of i
    
if j starts with "#!" then
      set aWorkList to words of j
      
set aLang to contents of last item of aWorkList
      
return aLang
    end if
  end repeat
  
  
return false
end splitLangFromShebangStr

on detectScriptFileExtension(aLang)
  ignoring case
    if aLang = "Ruby" then
      return "rb"
    else if aLang = "Python" then
      return "py"
    else if aLang = "perl" then
      return "pl"
    else if aLang = "sh" then
      return "sh"
    else
      return ""
    end if
  end ignoring
end detectScriptFileExtension

★Click Here to Open This Script 

Posted in shell script Text | Tagged 10.11savvy 10.12savvy 10.13savvy | 1 Comment

shell環境変数を取得する

Posted on 2月 24, 2018 by Takaaki Naganoya

do shell scriptコマンドでシェルコマンドが実行される場合の環境変数の確認は、1コマンドで実行できます。Terminal.app上で実行するときと初期条件が異なるので、必要に応じて環境変数の設定が必要です。

do shell script "env"

★Click Here to Open This Script 

これが、Cocoaの機能だとどういう条件で実行されるのか、というのがこのScriptを書いた原因です。動かしてみて、「ああ、do shell scriptコマンドと同じなんだね」ということが理解できました。

AppleScript名:shell環境変数を取得する
— Created 2016-03-16 by Takaaki Naganoya
— 2016 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

current application’s NSProcessInfo’s processInfo()’s environment()
–>  (NSDictionary) {​​​​​PATH:"/usr/bin:/bin:/usr/sbin:/sbin", ​​​​​TMPDIR:"/var/folders/h4/jfhlwst88xl9z0001s7k9vk00000gr/T/", ​​​​​LOGNAME:"maro", ​​​​​XPC_FLAGS:"0x0", ​​​​​HOME:"/Users/me", ​​​​​Apple_PubSub_Socket_Render:"/private/tmp/com.apple.launchd.KvufhRIpUw/Render", ​​​​​USER:"me", ​​​​​SSH_AUTH_SOCK:"/private/tmp/com.apple.launchd.3B8HzKhUz5/Listeners", ​​​​​DISPLAY:"/private/tmp/com.apple.launchd.el9lFx0WpV/org.macosforge.xquartz:0", ​​​​​XPC_SERVICE_NAME:"au.com.myriad-com.ASObjC-Explorer-4.1891872", ​​​​​SHELL:"/bin/bash", ​​​​​__CF_USER_TEXT_ENCODING:"0x1F8:0x1:0xE"​​​}

★Click Here to Open This Script 

Posted in shell script System | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

文字列で与えたシェルコマンドを実行する v2

Posted on 2月 13, 2018 by Takaaki Naganoya

do shell scriptコマンドとほぼ等価な、Cocoaの機能を用いたshell script実行のAppleScriptです。

よく「Terminal.app上のshell scriptをそのままdo shell scriptコマンドで実行して動かない」という声を聞きますが、そもそも環境変数が全然違うのでそのまま動くはずがありません。

AppleScriptのdo shell scriptコマンドは、いまのmacOSのセキュリティ向上の流れで行けば確実に近い将来に「デフォルトで実行禁止」「環境設定でオンにしてはじめて実行可能に」という扱いになることでしょう。

Cocoaのshell command呼び出し機能についても同様の制限が加わるかどうかは不明ですが、Cocoa経由でのshell command呼び出しAppleScriptについて調べておきました。

AppleScript名:文字列で与えたシェルコマンドを実行する v2
— Created 2016-02-13 by Takaaki Naganoya
— 2016 Piyomaru Software
–以下を参照:
–http://stackoverflow.com/questions/412562/execute-a-terminal-command-from-a-cocoa-app
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set aRes to (runCommandString("pwd") of me) as string
–>  "/"

set bRes to (runCommandString("cd & ls -la") of me) as string

–Lock Screen
–runCommandAtPath("/System/Library/CoreServices/Menu Extras/User.menu/Contents/Resources/CGSession", "-suspend") of me

–文字列で与えたシェルコマンドを実行する
on runCommandString(commandStr as string)
  set aPipe to current application’s NSPipe’s pipe()
  
set aTask to current application’s NSTask’s alloc()’s init()
  
aTask’s setLaunchPath:"/bin/sh"
  
aTask’s setArguments:{"-c", current application’s NSString’s stringWithFormat_("%@", commandStr)} –stringWithFormatはASOCに書き換え時の要注意点
  
aTask’s setStandardOutput:aPipe
  
set aFile to aPipe’s fileHandleForReading()
  
aTask’s |launch|()
  
return current application’s NSString’s alloc()’s initWithData:(aFile’s readDataToEndOfFile()) encoding:(current application’s NSUTF8StringEncoding)
end runCommandString

–指定したパスのシェルコマンドを実行する(結果などは取得しない)
on runCommandAtPath(commandPath as string, anArgument as string)
  set aTask to current application’s NSTask’s alloc()’s init()
  
aTask’s setLaunchPath:commandPath
  
aTask’s setArguments:(current application’s NSArray’s arrayWithObject:anArgument)
  
aTask’s |launch|()
end runCommandAtPath

★Click Here to Open This Script 

Posted in shell script System | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

Post navigation

  • Newer posts

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

Google Search

Popular posts

  • 開発機としてM2 Mac miniが来たのでガチレビュー
  • CotEditorで2つの書類の行単位での差分検出
  • macOS 15, Sequoia
  • 指定のWordファイルをPDFに書き出す
  • Pages本執筆中に、2つの書類モード切り替えに気がついた
  • Numbersで選択範囲のセルの前後の空白を削除
  • メキシカンハットの描画
  • Pixelmator Pro v3.6.4でAppleScriptからの操作時の挙動に違和感が
  • AdobeがInDesign v19.4からPOSIX pathを採用
  • Safariで「プロファイル」機能を使うとAppleScriptの処理に影響
  • AppleScriptによる並列処理
  • Cocoa Scripting Course 続刊計画
  • macOS 14.xでScript Menuの実行速度が大幅に下がるバグ
  • NaturalLanguage.frameworkでNLEmbeddingの処理が可能な言語をチェック
  • AppleScript入門③AppleScriptを使った「自動化」とは?
  • Keynote/Pagesで選択中の表カラムの幅を均等割
  • Keynote、Pages、Numbers Ver.14.0が登場
  • macOS 15 リモートApple Eventsにバグ?
  • デフォルトインストールされたフォント名を取得するAppleScript
  • AppleScript入門① AppleScriptってなんだろう?

Tags

10.11savvy (1101) 10.12savvy (1242) 10.13savvy (1391) 10.14savvy (587) 10.15savvy (438) 11.0savvy (283) 12.0savvy (212) 13.0savvy (190) 14.0savvy (142) 15.0savvy (121) CotEditor (66) Finder (51) iTunes (19) Keynote (116) 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 (54) Safari (44) Script Editor (27) WKUserContentController (21) WKUserScript (20) WKWebView (23) WKWebViewConfiguration (22)

カテゴリー

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

アーカイブ

  • 2025年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