StandardAdditions

macOS15でのdisplay alertの留意事項

ボタンの位置が逆になるケースがあります
2024102901001080x1080_144
サンプルコード

サンプルソース(参考)
行番号ソース
001set recordResponse to (display alert "ファイルにしますか?" message "tsvタブ区切りテキストに保存しますか?" as informational buttons {"保存する", "終了"} cancel button "終了" default button "終了" giving up after 10) as record
002
003if button returned of recordResponse is "保存する" then
004  #
005else if gave up of recordResponse is true then
006  return "時間切れです"
007else
008  return
009end if
AppleScriptで生成しました

|

[ AppleScript] system attribute (UNIXパスで取得出来るので便利な時が多い)


AppleScript サンプルコード

【スクリプトエディタで開く】 |

AppleScript サンプルソース(参考)
行番号ソース
001#! /usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003#com.cocolog-nifty.quicktimer.icefloe
004#
005----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
006use AppleScript version "2.8"
007use scripting additions
008
009
010set listSystemAttr to (system attribute) as list
011repeat with itemAttr in listSystemAttr
012  log (system attribute itemAttr)
013end repeat
014
015
016log (system attribute "USER")
017log (system attribute "COMMAND_MODE")
018log (system attribute "__CFBundleIdentifier")
019log (system attribute "PATH")
020log (system attribute "LOGNAME")
021log (system attribute "SSH_AUTH_SOCK")
022log (system attribute "HOME")
023log (system attribute "SHELL")
024log (system attribute "TMPDIR")
025log (system attribute "__CF_USER_TEXT_ENCODING")
026log (system attribute "XPC_SERVICE_NAME")
027log (system attribute "XPC_FLAGS")
028log (system attribute "SQLITE_EXEMPT_PATH_FROM_VNODE_GUARDS")
AppleScriptで生成しました

|

[StandardAdditions] system attribute


あくまでも参考にしてください

【スクリプトエディタで開く】 |

サンプルソース(参考)
行番号ソース
001#! /usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003# com.cocolog-nifty.quicktimer.icefloe
004(*
005参考URL
006https://www.macscripter.net/t/system-attributes/41107
007*)
008----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
009use AppleScript version "2.8"
010use scripting additions
011
012system attribute "LOGNAME"
013system attribute "USER"
014system attribute "HOME"
015system attribute "TMPDIR"
016#OSversion
017system attribute "sys1"
018system attribute "sys2"
019system attribute "sys3"
020#RAM in MB
021system attribute "ramm"
AppleScriptで生成しました

processInfoと同じ内容
あくまでも参考にしてください

サンプルソース(参考)
行番号ソース
001set ocidProcessInfo to refMe's NSProcessInfo's processInfo()
002set realMemoryByte to ocidProcessInfo's physicalMemory() as real
003set realGB to "1073741824" as real
004set intPhysicalMemory to realMemoryByte / realGB as integer
005##ユーザー情報
006set ocidEnvDict to ocidProcessInfo's environment()
007set strHOME to (ocidEnvDict's valueForKey:"HOME") as text
008set strUSER to (ocidEnvDict's valueForKey:"USER") as text
009set strLOGNAME to (ocidEnvDict's valueForKey:"LOGNAME") as text
010set strTMPDIR to (ocidEnvDict's valueForKey:"TMPDIR") as text
AppleScriptで生成しました

|

[NSAlert]アラートをカスタマイズする


【スクリプトエディタで開く】|

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
use AppleScript version "2.8"
use framework "Foundation"
use framework "AppKit"
use framework "Carbon"
use framework "UniformTypeIdentifiers"
use scripting additions
property refMe : a reference to current application
property appAlert : (missing value)


set numResult to 1000 as integer

set strValue to "" as text
my performSelectorOnMainThread:("createAlert") withObject:(missing value) waitUntilDone:(true)
my performSelectorOnMainThread:("displayAlert") withObject:(missing value) waitUntilDone:(true)
log numResult
if numResult = (refMe's NSAlertFirstButtonReturn) then
log "OK"
else if numResult = (refMe's NSAlertSecondButtonReturn) then
  error "ユーザによってキャンセルされました。" number -128
else if numResult = (refMe's NSAlertThirdButtonReturn) then
log "選択肢1"
else if numResult = 1000 then
log "OK"
else if numResult = 1001 then
  error "ユーザによってキャンセルされました。" number -128
else if numResult = 1002 then
log "選択肢1"
else if numResult = 1003 then
log "選択肢2"
else if numResult = 1004 then
log "選択肢3"
end if

set boolSuppression to appAlert's suppressionButton's state as boolean
log boolSuppression



on createAlert()
  ##追加のテキストの設定
  set ocidRect to refMe's NSMakeRect(0, 0, 288, 60)
  set ocidTextView to refMe's NSTextView's alloc()'s initWithFrame:(ocidRect)
  #アトリビュートのDICT
  set ocidAttarDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
  #フォント
  set ocidFontSize to refMe's NSFont's systemFontSize()
  set ocidSetFont to refMe's NSFont's systemFontOfSize:(ocidFontSize)
ocidAttarDict's setObject:(ocidSetFont) forKey:(refMe's NSFontAttributeName)
  #センタリング
  set ocidParagraphStyle to refMe's NSMutableParagraphStyle's alloc()'s init()
ocidParagraphStyle's setAlignment:(refMe's NSTextAlignmentCenter)
ocidAttarDict's setObject:(ocidParagraphStyle) forKey:(refMe's NSParagraphStyleAttributeName)
  #リンク
  set strURL to ("https://quicktimer.cocolog-nifty.com/icefloe/") as text
  set ocidURL to refMe's NSURL's URLWithString:(strURL)
ocidAttarDict's setObject:(ocidURL) forKey:(refMe's NSLinkAttributeName)
  #テキスト
  set ocidSetStr to refMe's NSString's stringWithString:("詳しいヘルプはこちら\n" & strURL)
  set ocidSetStrRange to refMe's NSMakeRange(0, ocidSetStr's |length|)
  set ocidSetText to refMe's NSAttributedString's alloc()'s initWithString:(ocidSetStr) attributes:(ocidAttarDict)
ocidTextView's insertText:(ocidSetText) replacementRange:(ocidSetStrRange)
ocidTextView's setEditable:(false)
ocidTextView's setDrawsBackground:(false)
ocidTextView's setSelectable:(true)
  #
  set ocidSetRect to refMe's NSMakeRect(0, 0, 288, 52)
  set ocidTextField to refMe's NSTextField's alloc()'s initWithFrame:(ocidSetRect)
ocidTextField's setStringValue:(ocidSetStr)
  
  ###アラート初期化
  set my appAlert to refMe's NSAlert's alloc()'s init()
  ###メッセージ
appAlert's setMessageText:"アラートタイトル"
appAlert's setInformativeText:"メッセージテキスト"
  ###追加のテキスト
appAlert's setAccessoryView:(ocidTextField)
  ####
  # appAlert's setAccessoryView:(ocidTextView)
  #ヘルプつける場合
appAlert's setShowsHelp:(true)
appAlert's setDelegate:(me)
  # appAlert's setHelpAnchor:(ocidHelpAnc)
  
  #選択肢
appAlert's addButtonWithTitle:("OK")
appAlert's addButtonWithTitle:("キャンセル")
appAlert's addButtonWithTitle:("選択肢1")
appAlert's addButtonWithTitle:("選択肢2")
appAlert's addButtonWithTitle:("選択肢3")
  
  #アイコン
  set strFilePath to "/System/Library/CoreServices/Finder.app/Contents/Resources/Finder.icns" as text
  set ocidFilePathStr to refMe's NSString's stringWithString:(strFilePath)
  set ocidFilePath to ocidFilePathStr's stringByStandardizingPath()
  set ocidFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidFilePath) isDirectory:false)
  set ocidIconImage to refMe's NSImage's alloc()'s initWithContentsOfURL:(ocidFilePathURL)
appAlert's setIcon:(ocidIconImage)
  #
  # appAlert's setAlertStyle:(refMe's NSAlertStyleCritical)
  # appAlert's setAlertStyle:(refMe's NSAlertStyleWarning)
  # appAlert's setAlertStyle:(refMe's NSAlertStyleInformational)
  #
appAlert's setShowsSuppressionButton:(true)
  
end createAlert

on displayAlert()
  set my numResult to appAlert's runModal()
end displayAlert

on alertShowHelp:aNotification
  set strURL to ("https://quicktimer.cocolog-nifty.com/icefloe/") as text
  set strIconFilePath to ("/System/Library/CoreServices/Help Viewer.app/Contents/Resources/AppIcon.icns") as text
  tell application "Finder"
    set aliasIconPath to (POSIX file strIconFilePath) as alias
display dialog "Help ページを開きます" buttons {"OK"} default button 1 with icon (aliasIconPath)
open location strURL
  end tell
return false
end alertShowHelp:

|

[display dialog] 入力欄にドラッグ&ドロップでパスを取得する



【スクリプトエディタで開く】|

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
use AppleScript version "2.8"
use framework "Foundation"
use framework "UniformTypeIdentifiers"
use framework "AppKit"
use scripting additions
property refMe : a reference to current application
set appFileManager to refMe's NSFileManager's defaultManager()


########################
## クリップボードの中身取り出し
########################
###初期化
set ocidPasteboard to refMe's NSPasteboard's generalPasteboard()
set ocidPastBoardTypeArray to ocidPasteboard's types
###テキストがあれば
set boolContain to ocidPastBoardTypeArray's containsObject:"public.utf8-plain-text"
if boolContain = true then
  ###値を格納する
  tell application "Finder"
    set strReadString to (the clipboard as text) as text
  end tell
  ###Finderでエラーしたら
else
  set boolContain to ocidPastBoardTypeArray's containsObject:"NSStringPboardType"
  if boolContain = true then
    set ocidReadString to ocidPasteboard's readObjectsForClasses:({refMe's NSString}) options:(missing value)
    set strReadString to ocidReadString as text
  else
log "テキストなし"
    set strReadString to "" as text
  end if
end if
if strReadString starts with "/" then
  set strReadString to strReadString as text
else
  set strReadString to "" as text
end if
##############################
#####ダイアログ
##############################
###ダイアログを前面に出す
set strName to (name of current application) as text
if strName is "osascript" then
  tell application "Finder" to activate
else
  tell current application to activate
end if
set strMes to "パス入力してください"
set aliasIconPath to POSIX file "/System/Applications/Calculator.app/Contents/Resources/AppIcon.icns" as alias
try
  set recordResult to (display dialog strMes with title strMes default answer strReadString buttons {"OK", "キャンセル"} default button "OK" with icon aliasIconPath giving up after 20 without hidden answer) as record
on error
log "エラーしました"
return
end try
if "OK" is equal to (button returned of recordResult) then
  set strReturnedText to (text returned of recordResult) as text
else if (gave up of recordResult) is true then
return "時間切れです"
else
return "キャンセル"
end if
set ocidResponseText to (refMe's NSString's stringWithString:(strReturnedText))
###タブと改行を除去しておく
set ocidTextM to refMe's NSMutableString's alloc()'s initWithCapacity:(0)
ocidTextM's appendString:(ocidResponseText)
##改行除去
set ocidTextM to ocidTextM's stringByReplacingOccurrencesOfString:("\n") withString:("")
set ocidTextM to ocidTextM's stringByReplacingOccurrencesOfString:("\r") withString:("")
##タブ除去
set ocidTextM to ocidTextM's stringByReplacingOccurrencesOfString:("\t") withString:("")



set ocidFilePathStr to (refMe's NSString's stringWithString:(ocidTextM))
set ocidFilePath to ocidFilePathStr's stringByStandardizingPath
set ocidFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidFilePath) isDirectory:true)
####UTIの取得
set ocidBunndle to refMe's NSBundle's bundleWithURL:(ocidFilePathURL)
set ocidBunndleID to ocidBunndle's bundleIdentifier()
set strBunndleID to (ocidBunndleID) as text
###missing value対策
if strBunndleID is "" then
  tell application "Finder"
    set objInfo to info for aliasFilePath
    set strBunndleID to bundle identifier of objInfo as text
  end tell
end if

####ダイアログに指定アプリのアイコンを表示する
set strIconPath to ""
###アイコン名をPLISTから取得
set ocidPlistPathURL to ocidFilePathURL's URLByAppendingPathComponent:("Contents/Info.plist") isDirectory:false
set ocidPlistDict to refMe's NSMutableDictionary's alloc()'s initWithContentsOfURL:(ocidPlistPathURL)
set strIconFileName to (ocidPlistDict's valueForKey:("CFBundleIconFile")) as text
###ICONのURLにして
set strPath to ("Contents/Resources/" & strIconFileName) as text
set ocidIconFilePathURL to ocidFilePathURL's URLByAppendingPathComponent:(strPath) isDirectory:false
###拡張子の有無チェック
set strExtensionName to (ocidIconFilePathURL's pathExtension()) as text
if strExtensionName is "" then
  set ocidIconFilePathURL to ocidIconFilePathURL's URLByAppendingPathExtension:"icns"
end if
##-->これがアイコンパス
log ocidIconFilePathURL's absoluteString() as text
###ICONファイルが実際にあるか?チェック
set boolExists to appFileManager's fileExistsAtPath:(ocidIconFilePathURL's |path|)
###ICONがみつかない時用にデフォルトを用意する
if boolExists is false then
  set aliasIconPath to POSIX file "/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/AlertNoteIcon.icns"
else
  set aliasIconPath to ocidIconFilePathURL's absoluteURL() as alias
  set strIconPath to ocidIconFilePathURL's |path|() as text
end if
if strIconPath is (missing value) then
  set strIconPath to ""
end if

set strMes to ("bundle identifier 戻り値です\rIconPath\r" & strIconPath) as text

set recordResult to (display dialog strMes with title "bundle identifier" default answer strBunndleID buttons {"クリップボードにコピー", "キャンセル", "OK"} default button "OK" cancel button "キャンセル" giving up after 20 with icon aliasIconPath without hidden answer)

if button returned of recordResult is "クリップボードにコピー" then
  try
    set strText to text returned of recordResult as text
    ####ペーストボード宣言
    set appPasteboard to refMe's NSPasteboard's generalPasteboard()
    set ocidText to (refMe's NSString's stringWithString:(strText))
appPasteboard's clearContents()
appPasteboard's setString:(ocidText) forType:(refMe's NSPasteboardTypeString)
  on error
    tell application "Finder"
      set the clipboard to strTitle as text
    end tell
  end try
end if



|

スクリプトの設定にPLISTを使う(考え中)


【スクリプトエディタで開く】|

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#
#com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
use AppleScript version "2.8"
use framework "Foundation"
use framework "UniformTypeIdentifiers"
use framework "AppKit"
use scripting additions
property refMe : a reference to current application
set appFileManager to refMe's NSFileManager's defaultManager()

####設定
property strMes : ("Xid(twitterID)を入力してください ") as text

###任意項目
property strBundleID : ("com.microsoft.edgemac") as text
set strKeyName to ("twitter.com") as text
####設定ファイル
set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSApplicationSupportDirectory) inDomains:(refMe's NSUserDomainMask))
set ocidApplicationSupportDirPathURL to ocidURLsArray's firstObject()
set ocidPreferencesDirPathURL to ocidApplicationSupportDirPathURL's URLByAppendingPathComponent:("com.cocolog-nifty.quicktimer")
#フォルダ作成
set ocidAttrDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
ocidAttrDict's setValue:(493) forKey:(refMe's NSFilePosixPermissions)
set listBoolMakeDir to appFileManager's createDirectoryAtURL:(ocidPreferencesDirPathURL) withIntermediateDirectories:true attributes:(ocidAttrDict) |error|:(reference)
#設定ファイルパス
set ocidPreferencesFileBasePathURL to ocidPreferencesDirPathURL's URLByAppendingPathComponent:(strBundleID)
set ocidPlistFilePathURL to ocidPreferencesFileBasePathURL's URLByAppendingPathExtension:("plist")
##
set listPlistDict to refMe's NSMutableDictionary's alloc()'s initWithContentsOfURL:(ocidPlistFilePathURL) |error|:(reference)
set ocidPlistDict to (item 1 of listPlistDict)
if ocidPlistDict = (missing value) then
log "設定ファイルが見つかりません"
  ###ダイアログを出す
  set ocidValue to doSetTextDialogue(strBundleID)
  ##新規で設定ファイルを作成する
  set ocidPlistDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
ocidPlistDict's setValue:(ocidValue) forKey:(strKeyName)
  set ocidFormat to (refMe's NSPropertyListXMLFormat_v1_0)
  set listPlistData to refMe's NSPropertyListSerialization's dataWithPropertyList:(ocidPlistDict) format:(ocidFormat) options:0 |error|:(reference)
  set ocidPlistData to (item 1 of listPlistData)
  #保存
  set listDone to ocidPlistData's writeToURL:(ocidPlistFilePathURL) options:0 |error|:(reference)
else
log "設定ファイルから設定を読み込みます"
  set listPlistDict to refMe's NSMutableDictionary's alloc()'s initWithContentsOfURL:(ocidPlistFilePathURL) |error|:(reference)
  set ocidPlistDict to (item 1 of listPlistDict)
  set ocidValue to ocidPlistDict's valueForKey:(strKeyName)
  if ocidValue = (missing value) then
log "設定ファイルに値が見つかりません"
    ###ダイアログを出す
    set ocidValue to doSetTextDialogue(strBundleID)
ocidPlistDict's setValue:(ocidValue) forKey:(strKeyName)
    set ocidFormat to (refMe's NSPropertyListXMLFormat_v1_0)
    set listPlistData to refMe's NSPropertyListSerialization's dataWithPropertyList:(ocidPlistDict) format:(ocidFormat) options:0 |error|:(reference)
    set ocidPlistData to (item 1 of listPlistData)
    #保存
    set listDone to ocidPlistData's writeToURL:(ocidPlistFilePathURL) options:0 |error|:(reference)
  end if
end if
###設定項目の戻り
set strXid to ocidValue as text



####################
## ダイアログ
####################
to doSetTextDialogue(strBundleID)
  ## クリップボードの中身取り出し
  set ocidPasteboard to refMe's NSPasteboard's generalPasteboard()
  set ocidPastBoardTypeArray to ocidPasteboard's types
  ###テキストがあれば
  set boolContain to ocidPastBoardTypeArray's containsObject:"public.utf8-plain-text"
  if boolContain = true then
    ###値を格納する
    tell application "Finder"
      set strReadString to (the clipboard as text) as text
    end tell
    ###Finderでエラーしたら
  else
    set boolContain to ocidPastBoardTypeArray's containsObject:"NSStringPboardType"
    if boolContain = true then
      set ocidReadString to ocidPasteboard's readObjectsForClasses:({refMe's NSString}) options:(missing value)
      set strReadString to ocidReadString as text
    else
      set strReadString to (strMes) as text
    end if
  end if
  ###ダイアログ
  tell current application
    set strName to name as text
  end tell
  ####スクリプトメニューから実行したら
  if strName is "osascript" then
    tell application "Finder" to activate
  else
    tell current application to activate
  end if
  ##
  set ocidIconPathURL to doGetAppIconPathURL(strBundleID)
  set aliasIconPath to (ocidIconPathURL's absoluteURL()) as alias
  set recordResult to (display dialog strMes with title "入力してください" default answer strReadString buttons {"OK", "キャンセル"} default button "OK" with icon aliasIconPath giving up after 20 without hidden answer) as record
  if "OK" is equal to (button returned of recordResult) then
    set strReturnedText to (text returned of recordResult) as text
  else if (gave up of recordResult) is true then
return "時間切れです"
  else
return "キャンセル"
  end if
  ###NSStringに格納
  set ocidResponseText to (refMe's NSString's stringWithString:(strReturnedText))
  ###タブと改行を除去しておく
  set ocidResponseTextM to refMe's NSMutableString's alloc()'s initWithCapacity:(0)
ocidResponseTextM's appendString:(ocidResponseText)
  ##改行除去
  set ocidResponseTextM to ocidResponseTextM's stringByReplacingOccurrencesOfString:("\n") withString:("")
  set ocidResponseTextM to ocidResponseTextM's stringByReplacingOccurrencesOfString:("\r") withString:("")
  ##タブ除去
  set ocidResponseTextM to ocidResponseTextM's stringByReplacingOccurrencesOfString:("\t") withString:("")
  ##
return ocidResponseTextM
end doSetTextDialogue

####################
## アイコンURL取得
####################
to doGetAppIconPathURL(argBundleID)
  set strBundleID to argBundleID as text
  set ocidAppPathURL to doGetAppPathURL(strBundleID)
  if ocidAppPathURL is false then
log "アプリケーションが見つかりませんでした"
    set strIconPath to ("/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/FinderIcon.icns") as text
    set ocidIconPathStr to refMe's NSString's stringWithString:(strIconPath)
    set ocidIconPath to ocidIconPathStr's stringByStandardizingPath()
    set ocidFinderIconPathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidIconPath) isDirectory:false)
return ocidIconPathURL
  end if
  ###アイコン名をPLISTから取得
  set ocidPlistPathURL to ocidAppPathURL's URLByAppendingPathComponent:("Contents/Info.plist") isDirectory:false
  set ocidPlistDict to refMe's NSMutableDictionary's alloc()'s initWithContentsOfURL:(ocidPlistPathURL)
  set strIconFileName to (ocidPlistDict's valueForKey:("CFBundleIconFile")) as text
  ###ICONのURLにして
  set strPath to ("Contents/Resources/" & strIconFileName) as text
  set ocidIconFilePathURL to ocidAppPathURL's URLByAppendingPathComponent:(strPath) isDirectory:false
  ###拡張子の有無チェック
  set strExtensionName to (ocidIconFilePathURL's pathExtension()) as text
  if strExtensionName is "" then
    set ocidIconFilePathURL to ocidIconFilePathURL's URLByAppendingPathExtension:"icns"
  end if
  ###ICONファイルが実際にあるか?チェック
  set appFileManager to refMe's NSFileManager's defaultManager()
  set boolExists to appFileManager's fileExistsAtPath:(ocidIconFilePathURL's |path|)
  ###ICONがみつかない時
  if boolExists is false then
return ocidFinderIconPathURL
  else
return ocidIconFilePathURL
  end if
end doGetAppIconPathURL

####################
## アプリケーションURL取得
####################
to doGetAppPathURL(argBundleID)
  set strBundleID to argBundleID as text
  set appSharedWorkspace to refMe's NSWorkspace's sharedWorkspace()
  ##バンドルIDからアプリケーションのURLを取得
  set ocidAppBundle to (refMe's NSBundle's bundleWithIdentifier:(argBundleID))
  if ocidAppBundle ≠ (missing value) then
    set ocidAppPathURL to ocidAppBundle's bundleURL()
  else if ocidAppBundle = (missing value) then
    set ocidAppPathURL to (appSharedWorkspace's URLForApplicationWithBundleIdentifier:(argBundleID))
  end if
  ##予備(アプリケーションのURL)
  if ocidAppPathURL = (missing value) then
    tell application "Finder"
      try
        set aliasAppApth to (application file id strBundleID) as alias
        set strAppPath to (POSIX path of aliasAppApth) as text
        set strAppPathStr to refMe's NSString's stringWithString:(strAppPath)
        set strAppPath to strAppPathStr's stringByStandardizingPath()
        set ocidAppPathURL to refMe's NSURL's alloc()'s initFileURLWithPath:(strAppPath) isDirectory:true
      on error
log "アプリケーションが見つかりませんでした"
return false
      end try
    end tell
  end if
return ocidAppPathURL
end doGetAppPathURL

|

[Finder]ファイルを1つだけ選択させたい(考え中)


【スクリプトエディタで開く】|

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#
#com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
use AppleScript version "2.8"
use framework "Foundation"
use scripting additions

property refMe : a reference to current application

###対象外リスト
set listRuleOut to {"ディスク作成フォルダ", "スマートフォルダ", "iOSパッケージのアーカイブ", "保存された検索クエリー", "定義済みの検索", "FTPインターネットロケーション", "AFP URL", "インターネットロケーション", "ファイルURL", "ファイルインターネットロケーション", "メールインターネットロケーション", "テキストクリッピング", "Webインターネットロケーション", "FTP URL", "AppleTalkインターネットロケーション", "AFPインターネットロケーション", "Appleデバイスのソフトウェアアップデートファイル", "Finder", "フォルダ", "NSLインターネットロケーション", "ピクチャクリッピング", "ニュースインターネットロケーション", "サウンドクリッピング", "クリッピング", "ボリューム", "ディスク作成フォルダ", "エイリアス"} as list


###選択項目は1つ限定
tell application "Finder"
  set listPath to selection as list
end tell
set numCntSelection to (count of listPath) as integer
if numCntSelection > 1 then
display alert "複数選択されている"
  set aliasFilePath to doChooseFile()
else if numCntSelection = 0 then
display alert "選択されていない"
  set aliasFilePath to doChooseFile()
else if numCntSelection = 1 then
log "1つ選択されている"
  set aliasFilePath to (item 1 of listPath) as alias
end if


###ファイル限定
tell application "Finder"
  set strKind to (kind of item aliasFilePath) as text
end tell

repeat with itemRuleOut in listRuleOut
  set strRuleOut to itemRuleOut as text
  if strRuleOut is strKind then
display alert "対象ファイルではない"
    set aliasFilePath to doChooseFile()
  end if
end repeat


return
set strDirPath to (POSIX path of aliasPath) as text


###ダイアログ
to doChooseFile()
  set strName to (name of current application) as text
  if strName is "osascript" then
    tell application "Finder" to activate
  else
    tell current application to activate
  end if
  ##
  tell application "Finder"
    set aliasDefaultLocation to (path to desktop folder from user domain) as alias
  end tell
  ############
  set listUTI to {"public.data", "public.content"} as list
  set strMes to ("ファイルを選んでください") as text
  set strPrompt to ("ファイルを選んでください") as text
  set aliasResponse to (choose file strMes with prompt strPrompt default location (aliasDefaultLocation) of type listUTI with invisibles and showing package contents without multiple selections allowed) as alias
return aliasResponse
end doChooseFile

|

[choose from list]指定ディレクトリの中のファイル名を選択する(NSMutableDictionaryを使う)


【スクリプトエディタで開く】|

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#
#
#
#com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
use AppleScript version "2.8"
use framework "Foundation"
use scripting additions

property refMe : a reference to current application

####################################
(*
tell application "Finder"
set aliasPathToMe to (path to me) as alias
end tell
###収集するコンテンツのディレクトリURL
set strPathToMe to (POSIX path of aliasPathToMe) as text
*)
set strSearchDirPath to "/System/Library/Desktop Pictures/Solid Colors"
set ocidSearchDirPathStr to refMe's NSString's stringWithString:(strSearchDirPath)
set ocidSearchDirPath to ocidSearchDirPathStr's stringByStandardizingPath()
set ocidSearchDirPathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidSearchDirPath) isDirectory:true)

###コンテンツを収集する 第一階層のみ
set appFileManager to refMe's NSFileManager's defaultManager()
##不可視ファイルを除く
set ocidOption to (refMe's NSDirectoryEnumerationSkipsHiddenFiles)
##パスURLとファイル名を収集
set ocidForKey to refMe's NSArray's alloc()'s initWithArray:({(refMe's NSURLPathKey), (refMe's NSURLNameKey)})
set listFilePathURL to appFileManager's contentsOfDirectoryAtURL:(ocidSearchDirPathURL) includingPropertiesForKeys:{ocidForKey} options:(ocidOption) |error|:(reference)
set ocidFilePathURLArray to (item 1 of listFilePathURL)
##
set ocidFileNameDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
repeat with itemFilePathURL in ocidFilePathURLArray
  set ocidFileName to itemFilePathURL's lastPathComponent()
(ocidFileNameDict's setValue:(itemFilePathURL) forKey:(ocidFileName))
end repeat
set listFileName to (ocidFileNameDict's allKeys()) as list

###ダイアログを前面に出す
tell current application
  set strName to name as text
end tell
####スクリプトメニューから実行したら
if strName is "osascript" then
  tell application "Finder" to activate
else
  tell current application to activate
end if
try
  set listResponse to (choose from list listFileName with title "選んでください" with prompt "選んでください" default items (item 1 of listFileName) OK button name "OK" cancel button name "キャンセル" without multiple selections allowed and empty selection allowed) as list
on error
  log "エラーしました"
return "エラーしました"
end try
if (item 1 of listResponse) is false then
return "キャンセルしました"
end if
###ダイアログの戻り値
set strFileName to (item 1 of listResponse) as text
###レコードから取り出す
set ocidFilePathURL to ocidFileNameDict's valueForKey:(strFileName)

set strFilePath to ocidFilePathURL's |path| as text
set strFilePath to ocidFilePathURL's absoluteString() as text
set aliasFilePath to (ocidFilePathURL's absoluteURL()) as alias



|

[choose from list]指定ディレクトリの中のファイル名を選択する


【スクリプトエディタで開く】|

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
# 指定ディレクトリの中のファイル名を選択する
#
#
#com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
use AppleScript version "2.8"
use framework "Foundation"
use scripting additions

####################################

set strSearchDirPath to "/System/Library/Desktop Pictures/Solid Colors" as text
tell application "Finder"
  # set aliasPathToMe to (path to me) as alias
  # set aliasContainerDir to (container of aliasPathToMe) as alias
  # set aliasSearchDirPath to (folder "bin" of folder aliasContainerDir) as alias
  set aliasSearchDirPath to POSIX file strSearchDirPath as alias
  set listFilePath to every file of aliasSearchDirPath
  ###ファイル名リストとパスと入ったレコードを作成
  set listFileName to {} as list
  ###コンテンツの数だけ繰り返し
  repeat with itemFilePath in listFilePath
    set aliasFilePath to itemFilePath as alias
    set strFileName to (name of aliasFilePath) as text
    set end of listFileName to strFileName
  end repeat
end tell


###ダイアログを前面に出す
tell current application
  set strName to name as text
end tell
####スクリプトメニューから実行したら
if strName is "osascript" then
  tell application "Finder" to activate
else
  tell current application to activate
end if
try
  set listResponse to (choose from list listFileName with title "選んでください" with prompt "選んでください" default items (item 1 of listFileName) OK button name "OK" cancel button name "キャンセル" without multiple selections allowed and empty selection allowed) as list
on error
  log "エラーしました"
return "エラーしました"
end try
if (item 1 of listResponse) is false then
return "キャンセルしました"
end if
set strFileName to (item 1 of listResponse) as text
tell application "Finder"
  set aliasFilePath to (file strFileName of folder aliasSearchDirPath) as alias
end tell

set strFilePath to POSIX path of aliasFilePath as text
log strFilePath

|

mm→pix換算 解像度指定(途中)


【スクリプトエディタで開く】|

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
use AppleScript version "2.8"
use framework "Foundation"
use framework "AppKit"
use scripting additions
property refMe : a reference to current application

###解像度指定
property numPPI : 144 as integer
###ダイアログのアイコンパス
property aliasIconPath : POSIX file "/System/Applications/Calculator.app/Contents/Resources/AppIcon.icns" as alias


####デフォルトの値にクリップボードの中身を使う
set appPasteboard to refMe's NSPasteboard's generalPasteboard()
set ocidPastBoardTypeArray to appPasteboard's types
###ペーストボードのタイプにテキスト形式があればその値を使う
set boolContain to ocidPastBoardTypeArray's containsObject:"public.utf8-plain-text"
if boolContain = true then
  ###プレインテキストで受け取る
  set strReadString to (the clipboard as text)
else
  set boolContain to ocidPastBoardTypeArray's containsObject:"NSStringPboardType"
  if boolContain = true then
    ###プレインテキストにして受け取る
    set ocidReadString to appPasteboard's readObjectsForClasses:({refMe's NSString}) options:(missing value)
    set strReadString to ocidReadString as text
  else
    ####テキスト形式がなかった場合のデフォルト値
    set strReadString to "72" as text
  end if
end if


###入力ダイアログの呼び出し strReadStringはデフォルト値
doCalculation(strReadString)

####ダイアログから値を受け取る場合
##set {numPX, numResponse} to doCalculation(strReadString)

##########################################
##入力ダイアログ サブ
##########################################
to doCalculation(numArgNo)
  ###受け取ったデフォルト値をテキストに確定させて
  set strReadString to numArgNo as text
  ##############################
  #####ダイアログを前面に出す
  ##############################
  tell current application
    set strName to name as text
  end tell
  ####スクリプトメニューから実行したら
  if strName is "osascript" then
    tell application "Finder"
      activate
    end tell
  else
    tell current application
      activate
    end tell
  end if
  ###ダイアログ
  try
    set recordResult to (display dialog "mm数を半角数字で入力" with title "mm(" & numPPI & "ppi)→px" default answer strReadString buttons {"OK", "キャンセル"} default button "OK" cancel button "キャンセル" with icon aliasIconPath giving up after 10 without hidden answer) as record
  on error
    ###エラーの場合falseを戻す
return false
  end try
  ###OKクリックしたら
  if "OK" is equal to (button returned of recordResult) then
    set strReturnedText to (text returned of recordResult) as text
  else if (gave up of recordResult) is true then
    ###エラーの場合falseを戻す
return false
  else
    ###エラーの場合falseを戻す
return false
  end if
  
  ###テキストに
  set ocidResponseText to (refMe's NSString's stringWithString:(strReturnedText))
  ####戻り値を半角にする
  set ocidNSStringTransform to (refMe's NSStringTransformFullwidthToHalfwidth)
  set ocidResponseHalfwidth to (ocidResponseText's stringByApplyingTransform:ocidNSStringTransform |reverse|:false)
  set strResponse to ocidResponseHalfwidth as text
  set numResponse to strResponse as number
  set numInch to (numResponse / 25.4) as text
  set numChr to (count of numInch) as integer
  set numOffSet to (offset of "." in numInch) as integer
  if numOffSet is 0 then
    set numPX to (numInch * numPPI) as integer
  else if (numChr - numOffSet) = 1 then
    set numPX to (numInch * numPPI) as integer
  else
    set numPX to round (numInch * numPPI) as integer
  end if
  ##表示用のダイアログ呼び出し
doDialog({numPX, numResponse})
  ## return {numPX, numResponse}
end doCalculation

##########################################
##表示ダイアログ サブ
##########################################
to doDialog({numPX, numResponse})
  set strAns to ("" & numPX & " px") as text
  set strTitle to "計算結果です:" & numResponse & " mm →" & numPX & " px(" & numPPI & "ppi) " as text
  set strMes to ("" & strTitle & "\rpxピクセルには小数点以下は発生しないので四捨五入値です") as text
  try
    set recordResult to (display dialog strMes with title strTitle default answer strAns buttons {"クリップボードにコピー", "もう一度", "終了"} default button "終了" cancel button "終了" giving up after 20 with icon aliasIconPath without hidden answer) as record
  on error
return "エラーしました"
  end try
  if button returned of recordResult is "終了" then
return "終了します"
  end if
  if (gave up of recordResult) is true then
return "時間切れです"
  end if
  if button returned of recordResult is "もう一度" then
    ###入力ダイアログに戻る 現在の計算結果を渡す
doCalculation(numResponse)
  end if
  if button returned of recordResult is "クリップボードにコピー" then
    set strText to text returned of recordResult as text
    ####ペーストボード宣言
    set appPasteboard to refMe's NSPasteboard's generalPasteboard()
    ##結果をペーストボードにテキストで入れる
    set ocidText to (refMe's NSString's stringWithString:(strText))
appPasteboard's clearContents()
appPasteboard's setString:(ocidText) forType:(refMe's NSPasteboardTypeString)
return
  end if
return
end doDialog


return

|

その他のカテゴリー

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