AppleScript Javascript

[Adobe Illustrator]startupPresets

なんだかうまくいかないので途中で断念した系…

ダウンロード - app.startuppresets.scpt.zip


#!/usr/bin/env osascript -l JavaScript

//----+----1----+----2----+-----3----+----4----+----5----+----6----+----7

//

//

//

//

//                      com.cocolog-nifty.quicktimer.icefloe

//----+----1----+----2----+-----3----+----4----+----5----+----6----+----7


///0-4

///--> ["アートとイラストレーション", "プリント", "フィルムとビデオ", "Web", "モバイル"]

var numPresets=1;


/////////////////////////////////////////////////////////////////////////

var app = Application("Adobe Illustrator");

app = (app.includeStandardAdditions = true, app);


var listStartupPresets = app.startupPresets({});



var strStartupPresets = listStartupPresets[numPresets].toString();


console.log(strStartupPresets);



app.doJavascript("var objActivDoc = app.documents.addDocument(\"" + strStartupPresets + "\");")



|

[JXA] container 指定Pathのひとつ上の階層 その2

[JXA] container 指定Pathのひとつ上の階層 その1
https://quicktimer.cocolog-nifty.com/icefloe/2022/03/post-8219e2.html

別の方法で取得します
こちらの方がシンプルだなぁ

ダウンロード - stringbydeletinglastpathcomponent.scpt.zip



#!/usr/bin/env osascript -l JavaScript

//----+----1----+----2----+-----3----+----4----+----5----+----6----+----7

//

//

//

//

//                      com.cocolog-nifty.quicktimer.icefloe

//----+----1----+----2----+-----3----+----4----+----5----+----6----+----7

//Foundationの宣言

ObjC.import('Foundation')

//currentApplicationの宣言

var capp = Application.currentApplication();

capp.includeStandardAdditions = true;

//Finderの宣言

var finder = Application("Finder");

finder.includeStandardAdditions = true;


var sapp = Application("System Events");


//フォルダの場合

var strDesktopPath = finder.pathTo("desktop",{from:"user domain"}).toString();

console.log(strDesktopPath)



//本処理

strDesktopPath = ObjC.unwrap($(strDesktopPath).stringByDeletingLastPathComponent)

console.log(strDesktopPath)




capp.return;


|

[JXA] displayDialog ダイアログ

比較的よく使うUIのdisplayDialog

ダウンロード - finder.displaydialog.zip




#!/usr/bin/env osascript -l JavaScript

//----+----1----+----2----+-----3----+----4----+----5----+----6----+----7

//

//

//

//

//                      com.cocolog-nifty.quicktimer.icefloe

//----+----1----+----2----+-----3----+----4----+----5----+----6----+----7

var capp = Application.currentApplication();

capp.includeStandardAdditions = true;


var sapp = Application("System Events");

sapp.includeStandardAdditions = true;


var finder = Application("Finder");

finder.includeStandardAdditions = true;


///ユーザーID取得

var strUserName = sapp.currentUser.name().toString();

//ユーザーログイン名取得

var strFullName  = sapp.currentUser.fullName().toString();

///モデルID取得

var strModelName = capp.doShellScript("/usr/sbin/system_profiler SPHardwareDataType | sed -En '/Model Identifier:/ s/^[^:]+: *//p'",{userName: strUserName,administratorPrivileges:false,alteringLineEndings:true,as:'text'})

//分岐用のbool

var boolMacBook = strModelName.includes("MacBook");

var booliMac = strModelName.includes("iMac");

var booliMini = strModelName.includes("Macmin");

///アイコンパス

if (boolMacBook == true){

var strIconPath = Path("/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/com.apple.macbookpro-16-space-gray.icns");

}else if (booliMac == true){

var strIconPath = Path("/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/com.apple.imac-2021-yellow.icns");

}else if(booliMini == true){

var strIconPath = Path("/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/com.apple.macmini-2020.icns");

}else{

var strIconPath = Path("/System/Library/CoreServices/Finder.app/Contents/Resources/Finder.icns");

}


//////////ダイアログ本体

var objDialogResponce = finder.displayDialog(strFullName + "さんが今お使いのモデルID",{withTitle:"ダイアログタイトル",defaultAnswer: strModelName, buttons:["実行","キャンセル"],defaultButton: "実行",cancelButton:"キャンセル",givingUpAfter:10,hiddenAnswer:false, withIcon: strIconPath});

//////////時間切れ判定

var objGaveUp = objDialogResponce["gaveUp"];

if (objGaveUp == false ){

var objButtonReturned = objDialogResponce["buttonReturned"];

}else{

console.log("時間切れで処理が中断しました");

finder.return

}

//////////値を取得する

if (objButtonReturned == "実行"){

var strResponce = objDialogResponce["textReturned"];

}else{

console.log("キャンセルしました");

}


console.log("戻り値は" + strResponce);






#!/usr/bin/env osascript -l JavaScript

//----+----1----+----2----+-----3----+----4----+----5----+----6----+----7

//

//

//

//

//                      com.cocolog-nifty.quicktimer.icefloe

//----+----1----+----2----+-----3----+----4----+----5----+----6----+----7



var finder = Application("Finder");

finder.includeStandardAdditions = true;


///アイコンパス

var strIconPath = Path("/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/com.apple.iphone-7-plus-2.icns");

//////////ダイアログ

var objDialogResponce = finder.displayDialog("ダイアログテキスト",{withTitle:"ダイアログタイトル",defaultAnswer:"password", buttons:["実行","キャンセル"],defaultButton: "実行",cancelButton:"キャンセル",givingUpAfter:10,hiddenAnswer:true, withIcon: strIconPath});

//////////時間切れ判定

var objGaveUp = objDialogResponce["gaveUp"];

if (objGaveUp == false ){

var objButtonReturned = objDialogResponce["buttonReturned"];

}else{

console.log("時間切れで処理が中断しました");

finder.return

}

//////////値を取得する

if (objButtonReturned == "実行"){

var strResponce = objDialogResponce["textReturned"];

}else{

console.log("キャンセルしました");

}


console.log("パスワードは" + strResponce);




|

[JXA] 全てのFinderウィンドウを閉じる

全てのFinderウィンドウを閉じる

ダウンロード - closeallwindow.zip



#!/usr/bin/env osascript -l JavaScript

//----+----1----+----2----+-----3----+----4----+----5----+----6----+----7

//

//

//

//

//                      com.cocolog-nifty.quicktimer.icefloe

//----+----1----+----2----+-----3----+----4----+----5----+----6----+----7


//Finderの宣言

var finder = Application("Finder");

finder.includeStandardAdditions = true;


//全てのウィンドウ

var objAllFinderWindow = finder.finderWindows();

//ウインドウの数だけリピートして毎度閉じる

for (var windowID in objAllFinderWindow) {

objAllFinderWindow[windowID].close();

}




finder.return;

|

[JXA] container 指定Pathのひとつ上の階層

指定したパスのひとつ上の階層(フォルダ)を取得します
ファイル名の変更や保存先等でよく使います

ダウンロード - container.scpt.zip


#!/usr/bin/env osascript -l JavaScript

//----+----1----+----2----+-----3----+----4----+----5----+----6----+----7

//

//

//

//

//                      com.cocolog-nifty.quicktimer.icefloe

//----+----1----+----2----+-----3----+----4----+----5----+----6----+----7


//currentApplicationの宣言

var capp = Application.currentApplication();

capp.includeStandardAdditions = true;

//Finderの宣言

var finder = Application("Finder");

finder.includeStandardAdditions = true;


var sapp = Application("System Events");


//フォルダの場合

var strDesktopPath = finder.pathTo("desktop",{from:"user domain"}).toString();

//フォルダか?判定用

var objFileInfo = capp.infoFor(strDesktopPath)['folder'];


//本処理(フォルダの場合)

if( objFileInfo == true){

var containerPath = sapp.folders[strDesktopPath].container().posixPath();

}else{

var containerPath = sapp.files[strDesktopPath].container().posixPath();

}

console.log(containerPath)


//////////////////////////////////


//ファイルの場合

var strFilePath = Path("/System/Library/Desktop Pictures/Monterey Graphic.heic").toString();

//フォルダか?判定用

var objFileInfo = capp.infoFor(strFilePath)['folder'];


//本処理(ファイルの場合)

if( objFileInfo == true){

var containerPath = sapp.folders[strFilePath].container().posixPath();

}else{

var containerPath = sapp.files[strFilePath].container().posixPath();

}

console.log(containerPath)


capp.return;


|

[JXA]新規フォルダを作成する Application("Finder").make

新規フォルダを作成します。
文法的にはAppleScriptと同じですがクセが強いなぁ…

ダウンロード - make.new.folder.zip



#!/usr/bin/env osascript -l JavaScript

//----+----1----+----2----+-----3----+----4----+----5----+----6----+----7

//

//

//

//

//                      com.cocolog-nifty.quicktimer.icefloe

//----+----1----+----2----+-----3----+----4----+----5----+----6----+----7


//currentApplicationの宣言

var capp = Application.currentApplication()

capp.includeStandardAdditions = true;

//Finderの宣言

var finder = Application("Finder");

finder.includeStandardAdditions = true;

//デスクトップフォルダ

var strDesktopPath = finder.pathTo("desktop",{from:"user domain"});

//作成するフォルダ名

var strDirName = "名称未設定 フォルダ"

//新規フォルダを作成

finder.make({new:"folder",at:strDesktopPath,withProperties:{name:strDirName,ownerPrivileges:"read write",groupPrivileges:"read write",everyonesPrivileges:"read write", comment:"このフォルダは削除しても大丈夫です", description:"サンプルスクリプトが生成したフォルダです削除しても大丈夫です",labelIndex:3}});


capp.return;


|

[JXA]infoFor ファイルやフォルダの情報を取得する Application.currentApplication()

ファイルやフォルダの情報を取得するのが
infoFor
ファイル名や拡張子等を取得するのに便利です。

ダウンロード - infofor.zip

ファイル名だけ!とかの場合は
[Javascript]ファイルの値を取得する の方法もあります


#!/usr/bin/env osascript -l JavaScript

//----+----1----+----2----+-----3----+----4----+----5----+----6----+----7

//

//

//

//

//                      com.cocolog-nifty.quicktimer.icefloe

//----+----1----+----2----+-----3----+----4----+----5----+----6----+----7


//currentApplicationの宣言

var capp = Application.currentApplication()

capp.includeStandardAdditions = true;

//Finderの宣言

var finder = Application("Finder");

finder.includeStandardAdditions = true;

//デスクトップフォルダ

var strDesktopPath = finder.pathTo("desktop",{from:"user domain"});

//コピーする元のファイル

var strPath = Path("/Library/User Pictures/Sports/8ball.png");

//InfoForApplication.currentApplicationから取得

var objFileInfo = capp.infoFor(strPath);

//InfoForのそれぞれの項目

var strFileDisplayName = objFileInfo['displayedName'].toString();

var strFileName = objFileInfo['name'].toString();

var strFileExtensionHidden = objFileInfo['extensionHidden'].toString();

var strFileNameExtension = objFileInfo['nameExtension'].toString();

var strFileVisible = objFileInfo['visible'].toString();

var strFileDefaultApplication = objFileInfo['defaultApplication'].toString();

var strFileLocked = objFileInfo['locked'].toString();

var strFileKind = objFileInfo['kind'].toString();

var strFileFolder = objFileInfo['folder'].toString();

var strFileAlias = objFileInfo['alias'].toString();

var strFilePackageFolder = objFileInfo['packageFolder'].toString();

var strFileTypeIdentifier = objFileInfo['typeIdentifier'].toString();

var strFileBusyStatus = objFileInfo['busyStatus'].toString();


var strFileCreationDate = objFileInfo['creationDate'].toString();

var strFileModificationDate = objFileInfo['modificationDate'].toString();


//ファイルの複製は『Path』で指定toString()していない形式で指定

finder.duplicate(Path(strPath),{to:strDesktopPath,replacing:true,routingSuppressed:false, exactCopy:true});



capp.return;


|

[JXA]doShellScript javascript内でシェルスクリプトを実行する

currentApplicationに対して有効です。
Finder等では動作しませんので
例文ではcappに格納したcurrentApplication
→AppleScriptで言うtell applicationに対して
var capp = Application.currentApplication()
cappとして実行
→tell current Application to do shell script相当になります。
capp.doShellScript("ここにコマンド");

ダウンロード - doshellscript.zip



#!/usr/bin/env osascript -l JavaScript

//----+----1----+----2----+-----3----+----4----+----5----+----6----+----7

//

//

//

//

//                      com.cocolog-nifty.quicktimer.icefloe

//----+----1----+----2----+-----3----+----4----+----5----+----6----+----7


var capp = Application.currentApplication()

capp.includeStandardAdditions = true;



var doScript = capp.doShellScript("/bin/date '+%Y%m%d'",{administratorPrivileges:false,alteringLineEndings:true,as:'text'})



console.log(doScript)




|

[JXA]処理をX秒数待つ

一般的なJavascriptでは『処理を待つ』が定義されていないので
色々な方法で次の処理に行くのを待たせるわけですが
AppleScriptには『delay』が用意されていますので
Javascriptの中で普通にX秒間 次の処理に行くのを待たせる事ができます。

ダウンロード - finder.displayalert.scpt.zip


#!/usr/bin/env osascript -l JavaScript

//----+----1----+----2----+-----3----+----4----+----5----+----6----+----7

//

//

//

//

//                      com.cocolog-nifty.quicktimer.icefloe

//----+----1----+----2----+-----3----+----4----+----5----+----6----+----7



var finder = Application("Finder");

finder.includeStandardAdditions = true;



var strPath = finder.pathTo("downloads folder",{from:"user domain"}).toString();



var objFilePath = finder.chooseFile({withPrompt:"ファイルを選んでください",defaultLocation: strPath, invisibles:false, multipleSelectionsAllowed:false, showingPackageContents:false,ofType:"public.data" }).toString();


////ここでdelay2 2秒待たせます

delay(2);

console.log("2秒待ちました")


var objAlertResponce = finder.displayAlert("アラートのテキスト",{message: objFilePath,as:"informational",buttons: ["OK","NG"], defaultButton:1, cancelButton:2, givingUpAfter:3});


var objGaveUp = objAlertResponce["gaveUp"];


if (objGaveUp == false ){

var objButtonReturned = objAlertResponce["buttonReturned"];

}else{

finder.return

}


if (objButtonReturned == "OK"){

console.log(objButtonReturned)

}else{


console.log(objButtonReturned)

}




console.log("処理を待たせます")


var numTimer = 0;


while (numTimer < 5) {

////ここでdelay1 1秒待たせます

delay(1);

console.log("1秒待ちました");

numTimer++;


}


console.log("処理を待ちました")




|

[JXA]chooseFromListの値を取得する

詳しくはこちら
https://developer.apple.com/library/archive/documentation/LanguagesUtilities/Conceptual/MacAutomationScriptingGuide/

ダウンロード - app.choosefromlist.applescript.zip

デバック時は↓をお忘れなく
20220219-141223


#!/usr/bin/env osascript -l JavaScript

//----+----1----+----2----+-----3----+----4----+----5----+----6----+----7

//

//

//

//

//                      com.cocolog-nifty.quicktimer.icefloe

//----+----1----+----2----+-----3----+----4----+----5----+----6----+----7

var app = Application("Finder")

app.includeStandardAdditions = true



var listDir = [ "application support","applications folder","desktop","desktop pictures folder","documents folder","downloads folder","favorites folder","Folder Action scripts","fonts","help","home folder","internet plugins","keychain folder","library folder","modem scripts","movies folder","music folder","pictures folder","preferences","printer descriptions","public folder","scripting additions folder","scripts folder","services folder","shared documents","shared libraries","sites folder","startup disk","startup items","system folder","system preferences","temporary items","trash","users folder","utilities folder","workflows folder","voices","apple menu","control panels","control strip modules","extensions","launcher items folder","printer drivers","printmonitor","shutdown folder","speakable items","stationery" ]

 

 

 var chooseDir = app.chooseFromList(listDir, {

 withTitle:"ディレクトリ選択",

    withPrompt: "ディレクトリを選んでください",

multipleSelectionsAllowed:false,

emptySelectionAllowed:false,

    defaultItems: ["downloads folder"]

})

 

var theDir = chooseDir.toString()


console.log(theDir)


var appDir= app.pathTo(

 "" + chooseDir + "" ,

{

folderCreation: false,

from:"user domain"

})


var openFile = appDir.toString()


console.log(openFile)

app.displayDialog(openFile)



app.open(appDir)


|

その他のカテゴリー

Acrobat Acrobat Annotation Acrobat BookMark Acrobat Dialog Acrobat Distiller Acrobat Form Acrobat JS Acrobat Open Acrobat Plugin Acrobat Preflight Acrobat python Acrobat Reader Acrobat SCA Acrobat Sequ Acrobat Sign Acrobat Stamps Admin Admin Account Admin Apachectl Admin configCode Admin Device Management Admin LaunchServices Admin Locationd Admin loginitem Admin Maintenance Admin Permission Admin Pkg Admin Power Management Admin Printer Admin SetUp Admin SMB Admin System Information Admin Tools Admin Users Admin Volumes Adobe Adobe RemoteUpdateManager Apple AppleScript AppleScript Accessibility AppleScript AppKit AppleScript Applications AppleScript AppStore AppleScript Archive AppleScript Attributes AppleScript Audio AppleScript Automator AppleScript AVAsset AppleScript AVconvert AppleScript AVFoundation AppleScript AVURLAsset AppleScript BackUp AppleScript Barcode AppleScript Bash AppleScript Basic AppleScript Basic Path AppleScript Bluetooth AppleScript BOX AppleScript Browser AppleScript Calendar AppleScript CD/DVD AppleScript Choose AppleScript Chrome AppleScript CIImage AppleScript CloudStorage AppleScript Color AppleScript com.apple.LaunchServices.OpenWith AppleScript Console AppleScript Contacts AppleScript CotEditor AppleScript CURL AppleScript current application AppleScript Date&Time AppleScript delimiters AppleScript Desktop AppleScript Device AppleScript Disk AppleScript do shell script AppleScript Dock AppleScript DropBox AppleScript eMail AppleScript Encode Decode AppleScript Error AppleScript EXIFData AppleScript ffmpeg AppleScript File AppleScript Finder AppleScript Firefox AppleScript Folder AppleScript Fonts AppleScript GIF AppleScript Guide AppleScript HTML AppleScript Icon AppleScript Illustrator AppleScript Image Events AppleScript Image2PDF AppleScript ImageOptim Applescript iWork AppleScript Javascript AppleScript Jedit AppleScript Json AppleScript Label AppleScript List AppleScript locationd AppleScript LRC AppleScript LSSharedFileList AppleScript m3u8 AppleScript Mail AppleScript MakePDF AppleScript Map AppleScript Math AppleScript Microsoft AppleScript Microsoft Edge AppleScript Microsoft Excel AppleScript Mobileconfig AppleScript Mouse AppleScript Movie AppleScript Music AppleScript NetWork AppleScript Notes AppleScript NSArray AppleScript NSBitmapImageRep AppleScript NSBundle AppleScript NSCFBoolean AppleScript NSCharacterSet AppleScript NSColor AppleScript NSColorList AppleScript NSData AppleScript NSDictionary AppleScript NSError AppleScript NSEvent AppleScript NSFileAttributes AppleScript NSFileManager AppleScript NSFileManager enumeratorAtURL AppleScript NSFont AppleScript NSFontManager AppleScript NSImage AppleScript NSIndex AppleScript NSKeyedArchiver AppleScript NSKeyedUnarchiver AppleScript NSLocale AppleScript NSMutableArray AppleScript NSMutableDictionary AppleScript NSMutableString AppleScript NSNotFound AppleScript NSNumber AppleScript NSOpenPanel AppleScript NSPasteboard AppleScript NSPDFImageRep AppleScript NSpoint AppleScript NSPredicate AppleScript NSRange AppleScript NSRegularExpression AppleScript NSRunningApplication AppleScript NSScreen AppleScript NSSize AppleScript NSString AppleScript NSStringCompareOptions AppleScript NSTask AppleScript NSTimeZone AppleScript NSURL AppleScript NSURL File AppleScript NSURLBookmark AppleScript NSURLComponents AppleScript NSURLResourceKey AppleScript NSUserDefaults AppleScript NSUUID AppleScript NSView AppleScript NSWorkspace AppleScript Numbers AppleScript OAuth AppleScript ObjC AppleScript OneDrive AppleScript Osax AppleScript PDF AppleScript PDFAnnotationWidget AppleScript PDFContext AppleScript PDFDisplayBox AppleScript PDFDocumentPermissions AppleScript PDFKit AppleScript PDFnUP AppleScript PDFOutline AppleScript Photos AppleScript Photoshop AppleScript PostScript AppleScript prefPane AppleScript Preview AppleScript Python AppleScript QR AppleScript QR Decode AppleScript QuickLook AppleScript QuickTime AppleScript record AppleScript Regular Expression AppleScript Reminders AppleScript ReName AppleScript Repeat AppleScript RTF AppleScript Safari AppleScript SaveFile AppleScript ScreenCapture AppleScript ScreenSaver AppleScript Script Editor AppleScript Script Menu AppleScript Shortcuts AppleScript Shortcuts Events AppleScript Sort AppleScript Sound AppleScript Spotlight AppleScript SRT AppleScript StandardAdditions AppleScript stringByApplyingTransform AppleScript System Events AppleScript System Events Plist AppleScript System Settings AppleScript TemporaryItems AppleScript Terminal AppleScript Text AppleScript Text CSV AppleScript Text TSV AppleScript TextEdit AppleScript Translate AppleScript Trash AppleScript Twitter AppleScript UI AppleScript Unit Conversion AppleScript UTType AppleScript valueForKeyPath AppleScript Video AppleScript VisionKit AppleScript Visual Studio Code AppleScript webarchive AppleScript webp AppleScript Wifi AppleScript XML AppleScript XML EPUB AppleScript XML OPML AppleScript XML Plist AppleScript XML RSS AppleScript XML savedSearch AppleScript XML SVG AppleScript XML TTML AppleScript XML webloc AppleScript XMP AppleScript YouTube AppleScript Zero Suppress Applications CityCode Design github iPhone List Logs lsappinfo Memo Music perl PlistBuddy pluginkit postalcode ReadMe SF Symbols character id SF Symbols Entity sips Skype Slack sqlite TCC Tools Typography Video Wacom zoom