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

カテゴリー: Sandbox

ディスプレイのミラーリング表示(sandbox対応)

Posted on 4月 23, 2020 by Takaaki Naganoya

Mac用のオープンソースのディスプレイミラーリング・ツール「mirror-displays」を改変して、Xcode上でコードサインしやすく、かつAppleScriptアプリケーション(Xcode上で記述)から呼び出しやすくしたものです。

ディスプレイのミラーリング表示のOn/Offを行うmirror-displaysを、そのままMac App Storeに申請するアプリケーションの中にバイナリで入れようとしたら、Xcode上のValidate(Mac App Storeにアップロードする前段階の各種妥当性チェック)でひっかかってしまいました。

アプリケーションバンドル中のResourcesフォルダに入れてdo shell scriptで呼ぶという「お気楽」な呼び方が(Code Signの問題で)できなかったわけです。

# コマンドライン・ツールとしてビルドするときにCode Signすればよかったんじゃないか、という話もありますが、いずれ最終的にこの形式にする必要があったので、これでいいんじゃないかと

そこで、コマンドラインから呼び出す形式ではなく、Objective-Cのプログラム「らしい」形式に変更して(ヘッダファイルをゼロから書き起こしました)、AppleScriptから呼び出しやすく変更してみました。配布条件がGPLだったので、ここにmirror-displayまわりのソースと最低限の呼び出し側のAppleScriptアプリケーションのプロジェクトを掲載した次第です。

–> Download Xcode Project’s zip-archive

AppleScript名:AppDelegate.applescript
—
— AppDelegate.applescript
— mirrorTest
—
— Created by Takaaki Naganoya on 2020/04/15.
— Copyright © 2020 Takaaki Naganoya. All rights reserved.
—

script AppDelegate
  property parent : class "NSObject"
  
  
— IBOutlets
  
property theWindow : missing value
  
  
on applicationWillFinishLaunching:aNotification
    — Insert code here to initialize your application before any files are opened
  end applicationWillFinishLaunching:
  
  
on applicationShouldTerminate:sender
    — Insert code here to do any housekeeping before your application quits
    
return current application’s NSTerminateNow
  end applicationShouldTerminate:
  
  
on clicked:sender
    current application’s mirrorObjC’s alloc()’s init()’s mirror()
  end clicked:
end script

★Click Here to Open This Script 

Posted in Sandbox System | Tagged 10.13savvy 10.14savvy 10.15savvy | Leave a comment

ファイル保存ダイアログ(SavePanel)表示

Posted on 4月 22, 2020 by Takaaki Naganoya

Mac App StoreアプリケーションをAppleScriptで作ったときに、ファイル保存ダイアログを実装するのにchoose file nameコマンドでは拡張子の処理に問題があります(ユーザーが拡張子まで入力しなかった場合への対処を行うと逆効果に)。

choose file nameコマンド
ユーザーが選択、入力したパス:Macintosh HD:Users:me:Desktop:aaaaa
Script側で拡張子を補足:Macintosh HD:Users:me:Desktop:aaaaa.kame
--> エラー(Sandbox制限による)

その回避策としてありものを引っ張り出してきて手直ししたNSSavePanelベースのファイル保存ダイアログ表示サブルーチンです。


▲choose file nameコマンドで表示したファイル名入力ダイアログ。ダイアログ上でタグの選択はできるがchoose file nameにはタグ受信のための機能がない。また、拡張子が入力されていなかったらそのまま


▲本Scriptで表示したNSSavePanelによる保存ファイル名入力ダイアログ。タグの選択、指定した拡張子の指定などが行える。ユーザーが拡張子を入力していなくても自動で補える

choose file nameによるダイアログも、NSSavePanelによるダイアログも、見た目は同じで見分けはつきません。

普通にAppleScriptを書いて自分で実行している分にはchoose file nameコマンドでも問題はありません。

AppleScript名:ファイル保存ダイアログ(SavePanel)表示
— Original by Shane Stanley
— Modified 2020-04-22 by Takaaki Naganoya
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"

property savePath : ""
property saveTag : {}

set savePath to ""
set saveTag to {}

set aParam to {extList:{"kame"}, saveMsg:"新規ファイルの名前と場所を指定", saveName:"Some name", initialDir:(POSIX path of (path to documents folder))}
my performSelectorOnMainThread:"showModalSave:" withObject:(aParam) waitUntilDone:true
return {savePath:savePath as string, saveTags:saveTag as list}
–> {savePath:"/Users/me/Desktop/Some name.kame", saveTags:{"ブルー", "ヤンキー"}}

on showModalSave:sender
  set tmpExt to extList of sender as list
  
set tmpMsg to saveMsg of sender as string
  
set defName to saveName of sender as string
  
set tmpInit to initialDir of sender as string
  
  
using terms from scripting additions
    set startURL to current application’s NSURL’s fileURLWithPath:(tmpInit)
  end using terms from
  
  
set thePanel to current application’s NSSavePanel’s savePanel()
  
tell thePanel
    its setMessage:(tmpMsg)
    
its setAllowedFileTypes:(tmpExt)
    
its setNameFieldStringValue:(defName)
    
its setShowsHiddenFiles:false
    
its setTreatsFilePackagesAsDirectories:false
    
–its setDirectoryURL:startURL–指定しないほうが前回呼び出し時と同じフォルダが表示されて便利
    
set returnCode to its runModal() as integer
  end tell
  
  
if returnCode = (current application’s NSFileHandlingPanelOKButton) as integer then
    set my savePath to thePanel’s |URL|()’s |path|()
    
    
if (thePanel’s respondsToSelector:"tagNames") as boolean then
      set my saveTag to thePanel’s tagNames()
    end if
    
  else
    — cancel button
    
error -1
  end if
end showModalSave:

★Click Here to Open This Script 

Posted in dialog File path Sandbox | Tagged 10.13savvy 10.14savvy 10.15savvy NSSavePanel NSURL | Leave a comment

Sandbox環境で封じられる処理

Posted on 4月 22, 2020 by Takaaki Naganoya

ふだん、AppleScriptの処理はOSによる制約の少ない環境で処理を行っています。サンドボックスによる制約がない、あるいはきわめて少ない環境であるといえます。

そうした自由な環境に慣れていると、Sandbox環境下で(Xcode上で)アプリケーションを作成したときに、あっと驚く制約が存在していて驚かされることが多々あります。

他のアプリケーションを操作するScriptは書き込み禁止に

Sandbox環境下では、他のアプリケーションを操作するAppleScriptについては、実行専用形式で保存したうえでファイル書き込み不可の状態にしておく必要があります。Scriptのプロパティ(resultもプロパティ)を書き換えられてはいけないので、この措置が必要になります。Sandbox環境ではこのプロパティの書き換えが、自己書き換えと判定され、禁則事項に該当してしまうためです。

ファイルの新規保存時のchoose file nameコマンド(+拡張子追加)が抵触

ファイルの新規保存時にchoose file nameコマンドで保存先のパス+ファイル名をユーザーに指定させるような処理を行っています。このときに、ファイルの拡張子が指定されていない場合には、choose file nameから返ってきたパスを文字列に変換して、拡張子を文字列で追加するような処理もよく行っています。

これが、Sandbox環境下では禁じ手になります。

最初に遭遇したときには「意味がわからない!」と、イラつきまくりましたが、落ち着いて考えつつ追試を行ってみたところ理解できました。

Sandbox化したアプリケーションでファイル保存を行うためには、Xcode上でentitlementsファイルを編集し、「com.apple.security.files.user-selected.read-write」といったエントリに「YES」を設定しておくことになります。ユーザーが選択したファイルの読み書きを許可するという設定です。

このとき、choose file nameコマンドで入力されなかった拡張子の部分をAppleScript側で勝手に補ってしまうと、「ユーザーが指定したファイル」以外のファイルを処理することになるわけで、(拡張子を文字列操作で補ったようなパスは)ファイル保存することができませんでした。

そこで、NSSavePanelを用いてファイル保存ダイアログを作成する必要に迫られます。事前に補うべき拡張子の情報を渡してダイアログ表示を行うので、ユーザーが拡張子まで入力しなくても、拡張子がついたファイルパスが返ってきます。

ほかにもいろいろありますが、作成するAppleScriptのプログラム全体の数から見ると、Sandbox環境下で動かすAppleScriptはごく一部であるため、あまりノウハウが蓄積されていません。たまーにSandboxの制約に抵触して驚かされるといったところでしょうか。

Posted in How To Sandbox | Tagged 10.13savvy 10.14savvy 10.15savvy | Leave a comment

tccKitで指定Bundle IDのアプリケーションの「オートメーション」認証状況を取得

Posted on 11月 19, 2018 by Takaaki Naganoya

システム環境設定の「セキュリティとプライバシー」>「セキュリテイ」>「オートメーション」項目に指定Bundle IDのアプリケーションが登録されているかどうかをチェックするAppleScriptです。

macOS 10.14, Mojaveの機能を利用しているため、macOS 10.14以降を必要とします。また、実行にはScript Debugger上で動かすか、本ScriptをAppleScriptアプレットに保存して結果を別の方法で出力する必要があります(ファイルに書き出すとか、他のテキストエディタなどの新規ドキュメント上に書き込むとか、display notificationコマンドでノーティフィケーション表示するとか)。

プログラムの本体は「Hal Mueller’s Blog」の2018年9月4日掲載記事「Privacy Consent in Mojave (part 2: AppleScript)」内のObjective-CのプログラムをCocoa Framework化した「tccKit」です。

#2023/2/8 Update Universal Binaryでビルド
–> Download tccKit.framework (To ~/Library/Frameworks)

–> Download tccKit source (Xcode 10.1 Project)

掲載Sample Scriptのように、結果は文字列(NSString)で返ってきます。

上記のような「セキュリティ」の状況で実行したところ、

 Keynote:”PrivacyConsentStateGranted”(認証ずみ)
 CotEditor:”PrivacyConsentStateUnknown”(不明、実際には未認証)
 Mail:”PrivacyConsentStateUnknown”(不明、実際には未認証)

のような結果が得られました。

Objective-Cのプログラム側では、PrivacyConsentStateUnknown / PrivacyConsentStateGranted / PrivacyConsentStateDenied の3つの状態を返すようになっています。”PrivacyConsentStateGranted”のみユーザーの認証が得られている、と見てよいのでしょう。

もしも、PrivacyConsentStateDenied(ユーザーがダイアログで「許可しない」ボタンを押した)という状況であれば、シェルの/usr/bin/tccutilコマンドで状態をクリアし(do shell script ”tccutil reset com.apple.Terminal” とか)、再度、ユーザーの認証を取得する(activateなど簡単なコマンドを実行)とよいでしょう。
→ 実際には、activateやpropertyを取得する程度だとOSのオートメーション認証が反応せず、ドキュメントを新規作成するぐらいのことをやる必要があります。じゃあドキュメントを作らないタイプのアプリケーションだとどうなんだという話がありますが、それはひととおり試してみるしかなさそうです

ただ、本Frameworkは本当に単純にHal Mueller’s Blogの記述サンプルをコピペで(ちょっと改変して)呼び出して動かしているだけなので、起動中のアプリケーションのBundle Identifierをすべて取得してループでチェック、といった処理を行うと、なぜか結果が返ってきません(Script Debuggerがハングアップ)。連続で呼び出すのがよくないのか、チェック用のAPIに癖があるのかわかりませんが、現状でわかっている問題点として記載しておきます。

–> いろいろ調査してみたら、Code Signされていないアプリケーション(例:Skim)のチェックを行うとハングアップするようです。スクリプタブルではないアプリケーションのBundle IDを渡しても、ハングアップは起こりません

CAUTION: AEDeterminePermissionToAutomateTarget hangs up with unsigned application such as Skim PDF reader

macOS 10.14上で開発を行う場合には心の底から必要な処理だと思うので、本Frameworkはもうちょっとブラッシュアップしたい気持ちでいっぱいです。macOS 10.13が前代未聞・空前絶後のダメダメさだったので(Tim Cookもう勘弁して)、10.14には期待しているんですよ本当に(文句もいっぱい言ってるけど)。

AppleScript名:tccKitでBundle IDで指定したアプリケーションのtcc状況を取得.scpt
—
–  Created by: Takaaki Naganoya
–  Created on: 2018/11/19
—
–  Copyright © 2018 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.7" — Mojave (10.14) or later
use framework "Foundation"
use framework "tccKit" –https://halmueller.wordpress.com/2018/09/04/privacy-consent-in-mojave-part-2-applescript/
use scripting additions

set tccCheker to current application’s tccCheck’s alloc()’s init()

set aBundle to "com.apple.iWork.Keynote"
set aRes to (tccCheker’s automationConsentForBundleIdentifier:aBundle promptIfNeeded:false) as string
log aRes
–> "PrivacyConsentStateGranted"

set bBundle to "com.coteditor.CotEditor"
set bRes to (tccCheker’s automationConsentForBundleIdentifier:bBundle promptIfNeeded:false) as string
log bRes
–> "PrivacyConsentStateUnknown"

set cBundle to "com.apple.mail"
set cRes to (tccCheker’s automationConsentForBundleIdentifier:cBundle promptIfNeeded:false) as string
log cRes
–> "PrivacyConsentStateUnknown"

★Click Here to Open This Script 

Posted in Sandbox Security | Tagged 10.14savvy | 3 Comments

システム環境設定>プライバシーの「オートメーション」項目の表示

Posted on 11月 19, 2018 by Takaaki Naganoya

macOS 10.14, Mojaveでにわかに重要になってきた「システム環境設定」>セキュリティとプライバシー>プライバシー>オートメーション 項目の表示を行うAppleScriptです。

もともと、システム環境設定には指定のPreferences Paneを表示する機能が用意されているのですが、最近このシステム環境設定上の項目の移設や統廃合がメジャーバージョンアップごとに行われており、そうした変更にAppleScript系の機能の変更が間に合っていません。

tell application "System Preferences"
  tell pane "com.apple.preference.security"
    get name of every anchor
  end tell
end tell
–> {"Privacy_Reminders", "Privacy_SystemServices", "Privacy_Calendars", "Firewall", "Privacy_Assistive", "Privacy_LinkedIn", "Privacy_LocationServices", "Privacy_Contacts", "General", "Privacy_Diagnostics", "Advanced", "Privacy_Accessibility", "Privacy_Camera", "FDE", "Privacy", "Privacy_AllFiles", "Privacy_Microphone"}

★Click Here to Open This Script 


▲「セキュリティ」項目以下の各anchor。赤く塗った項目はAppleScript用語辞書に用語が用意されていないもの

とくに、この重要な「オートメーション」項目を示す予約語がAppleScript用語辞書に登録されておらず、「フルディスクアクセス」の予約語が用意されているあたり、チェックもれで抜けたものと思われます。

きちんと予約語が存在する項目については、

tell application "System Preferences"
  activate
  
reveal anchor "Privacy_LocationServices" of pane "com.apple.preference.security"
end tell

★Click Here to Open This Script 

のようにして表示できるのですが、前述のとおり「オートメーション」項目の予約語が用意されていません。

そこで、別途URL Event経由で表示させる方法を見つけたのでまとめておきました。

非同期のURL Eventなので、「オートメーション」項目が表示し終わったかどうかといった確認は一切ありません。普通にApple Event経由で実行できるのであれば、表示し終わったという実行結果の確認まで行えるのですが、、、、

AppleScript名:システム環境設定でオートメーションのタブを表示させる
open location "x-apple.systempreferences:com.apple.preference.security?Privacy_Automation"

★Click Here to Open This Script 

Posted in Sandbox System URL | Tagged 10.14savvy System Preferences | Leave a comment

Photosで選択中の写真が指定場所から50メートル以内の場合には書き出してFineReader OCR Proで処理 v2.1

Posted on 10月 30, 2018 by Takaaki Naganoya

Photos(写真).app上で選択中の写真が、指定場所から50メートル以内の場合にはファイルに書き出して、OCRアプリケーション「FineReader OCR Pro」でOCR処理するAppleScriptです。

–> Demo Movie

アーケードゲーム「戦場の絆」のリプレイムービーは、プレイ後の操作により1日に2プレイ分までYouTubeにアップロードされる仕様になっています。プレイ後、ゲーセンのターミナル上で操作してリプレイムービーにアクセスするためのアクセスコード(リプレイID)が表示されるようになっています。

この、ターミナル上のアクセスコードをiPhoneで写真撮影すると、写真に撮影場所のGPSデータが添付されます。写真.app経由でこのGPSデータを取得し、指定場所(ゲームセンター)から50メートル以内であればターミナルで撮影した写真と判定。

この写真をファイル書き出しして、OCRアプリケーションで認識しやすいようにCocoaの機能を用いて階調反転。一昔前ならPhotoshopで処理していましたが、いまならAppleScriptだけで高速に処理できます。デモムービーは実際の速度なので、その速さを体感していただけると思います。写真.appから選択中の写真を取得して反転するまで一瞬です。

反転した画像をMacのOCRアプリケーション「FineReader OCR Pro」でOCR処理し、YouTubeリプレイ再生用のコードを取得します。

あとは、再生用コードをリプレイムービー検索ページのフォームに入れて、実際のYouTube上のリプレイムービーのURLにアクセス。そのまま再生するなり、ダウンロードして保存しておくことになります。


■©創通・サンライズ

本サンプルでは、AppleScriptからコントロール可能なOCRアプリケーション「FineReader OCR Pro」を用いましたが、日本語の文字列を認識しないのであれば、Web APIのOCRサービス(MicrosoftのCognitive Serviceとか)を用いてみてもよいでしょう。

あとは、全国の「戦場の絆」が導入されているゲームセンターの住所情報および緯度経度情報がストックしてあるので、それらのGPSデータと写真撮影地点とのマッチングを行なってみてもよいかもしれません(700箇所程度なので、たいした演算ではありません)。

AppleScript名:Photosで選択中の写真が指定場所から50メートル以内の場合には書き出してFineReader OCR Proで処理 v2.1
— Created 2015-12-04 by Takaaki Naganoya –v2.1
— getDistanceBetweenTwoPlaces : Created 2015-03-03 by Shane Stanley
— convAsFilteredJPEG : Created 2013-12-29 by badcharan@Twitter
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "CoreLocation"
use framework "QuartzCore"

property CIFilter : a reference to current application’s CIFilter
property NSUUID : a reference to current application’s NSUUID
property CIImage : a reference to current application’s CIImage
property NSString : a reference to current application’s NSString
property NSScanner : a reference to current application’s NSScanner
property CLLocation : a reference to current application’s CLLocation
property NSFileManager : a reference to current application’s NSFileManager
property NSCharacterSet : a reference to current application’s NSCharacterSet
property NSJPEGFileType : a reference to current application’s NSJPEGFileType
property NSBitmapImageRep : a reference to current application’s NSBitmapImageRep
property NSMutableCharacterSet : a reference to current application’s NSMutableCharacterSet
property NSRegularExpressionSearch : a reference to current application’s NSRegularExpressionSearch

set targPlace to {35.745769, 139.675565} –Game City Itabashi
set bLoc to getSelectionOnPhotos() of me –Get Location From Photo
set aDist to getDistanceBetweenTwoPlaces(targPlace, bLoc) of me

–指定地点から50メートル以内の距離で撮影された写真であれば、Exportして後続の処理を行う
if aDist is equal to false or aDist > 50 then return false

–選択中の写真のうち最初のものだけExport
set targPhotoAlias to exportSelectedPhotoOnPhotos() of me

–実験に用いた写真はそのままではOCR処理できなかったので、手っ取り早く階調反転を行う
set invertRes to convAsFilteredJPEG(targPhotoAlias, "CIColorInvert") of me
if invertRes = false then
  display dialog "Error in CIImage" with title "Error" buttons {"OK"} default button 1 with icon 2
  
return
end if
set invImage to (POSIX file invertRes) as alias

set outFileName to (NSUUID’s UUID()’s UUIDString() as text) & ".txt"
set outPath to ((path to desktop) as text) & outFileName –sandbox環境ではパスは無視される

tell application id "com.abbyy.FineReaderPro"
  activate
  
  
–Check Ready
  
set getReady to (is finereader controller active)
  
if getReady = false then return
  
  
–set idList to {English} –英語だとスペルチェックされて、"1"と"t"を誤認識するため英語の指定をやめた
  
–Caution: this command is executed asynchronously
  
–Caution: export command was changed in v12.1.4
  
  
set idList to {Basic, Java, Fortran, Cobol, Pascal} –認識ターゲット言語(C++の予約語はあるようだが、指定できないよ!)
  
open invImage — In this version ,we have to open image, at first.
  
export to txt outPath ocr languages enum idList retain layout (as plain text) encoding (utf8)
  
  
–Wait for finish
  
repeat 30 times
    set curStat to (is busy)
    
if curStat = false then exit repeat
    
delay 1
  end repeat
  
  
–sandbox環境(Mac App Store版)の場合にはファイル出力先を別途取得
  
set sandRes to (is sandboxed)
  
if sandRes = true then
    set outDir to (get output dir) as text
    
set outPath to (outDir & outFileName) as text
  end if
  
end tell

–OCR処理した結果のテキストを読み込む
tell current application
  set textRes to read file outPath
end tell

–数字ではじまる行のみを抽出して、リプレイIDを取得
set textList to paragraphs of textRes
set outList to {}
repeat with i in textList
  set j to contents of i
  
  
–1行あたりのテキストが8文字以上か?
  
if length of j > 8 then
    
    
–行頭の文字が数字か?
    
set firstChar to first character of j
    
set nRes to chkNumeric(firstChar) of me
    
if nRes = true then
      set tmp1 to text 2 thru -1 of j –最初の数字を除去
      
      
–数字とアルファベット以外の文字を削除(タブ、スペースなど)
      
set tmp2 to returnNumberAndAlphabetCharsOnly(tmp1) of me
      
if length of tmp2 ≥ 8 then
        set tmp3 to text 1 thru 8 of tmp2
        
–数字とアルファベットの混在の文字列であれば出力する
        
set tmp3Res to chkMixtureOfNumericAndAlphabet(tmp3) of me
        
if tmp3Res = true then
          set the end of outList to tmp3
        end if
      end if
    end if
  end if
end repeat

outList
–> {"4f73vg1v", "v3v32zt3", "yk1z371x", "52yzvn11", "k1ftfvvg"}–Version 1.x (3rd ID is wrong)
–> {"4f73vg1v", "v3v32zt3", "yk1z37tx", "52yzvn11", "k1ftfvvg"}– Version 2.0(Perfect!!!!)
–> {"4f73vg1v", "v3v32zt3", "yk1z37tx", "52yzvn11", "k1ftfvvg"}– Version 2.1(Perfect!!!!)
–> {"51n4gg1f", "2zxt41gg", "57k2txk9", "yy43f3gt", "4f73vg1v"} –Version 2.1(Perfect!!!!)

–Photosで選択中の写真の1枚目(複数時には無視)から緯度、経度情報を取得する
on getSelectionOnPhotos()
  tell application "Photos"
    set aa to selection
    
if aa = {} or aa = missing value then return false
    
set a to first item of aa
    
set aProp to properties of a
    
    
set aLoc to location of aProp
    
return aLoc
  end tell
end getSelectionOnPhotos

–2点間の距離を計算する
on getDistanceBetweenTwoPlaces(aPlaceLoc, bPlaceLoc)
  try
    set {aLat, aLong} to aPlaceLoc
    
set {bLat, bLong} to bPlaceLoc
  on error
    return false
  end try
  
  
set aPlace to CLLocation’s alloc()’s initWithLatitude:aLat longitude:aLong
  
set bPlace to CLLocation’s alloc()’s initWithLatitude:bLat longitude:bLong
  
set distanceInMetres to aPlace’s distanceFromLocation:bPlace
  
return (distanceInMetres as real)
end getDistanceBetweenTwoPlaces

–Photos上で選択中の写真をTemporary Folderに掘ったフォルダに書き出して、そのalias情報を返す
on exportSelectedPhotoOnPhotos()
  set dtPath to (path to temporary items) as text
  
set aUUID to NSUUID’s UUID()’s UUIDString() as text
  
  
set dirPath to ((POSIX path of dtPath) & aUUID)
  
set fileManager to NSFileManager’s defaultManager()
  
set aRes to (fileManager’s createDirectoryAtPath:dirPath withIntermediateDirectories:true attributes:(missing value) |error|:(reference))
  
set dtPath to dtPath & aUUID
  
  
tell application "Photos"
    set a to selection
    
if a = {} then return
    
set aRes to (export a to file dtPath)
  end tell
  
  
tell application "Finder"
    tell folder dtPath
      set fList to (every file) as alias list
    end tell
  end tell
  
  
if fList = {} then return false
  
return first item of fList
end exportSelectedPhotoOnPhotos

–CIFilterをかけたJPEG画像を生成
–参照:http://ashplanning.blogspot.jp/ のうちのどこか
on convAsFilteredJPEG(aPath, aFilterName)
  
  
–aliasをURL(input)とPOSIX path(output) に変換
  
set aURL to (current application’s |NSURL|’s fileURLWithPath:(POSIX path of aPath)) –Input
  
set aPOSIX to (POSIX path of aPath) & "_" & aFilterName & ".jpg" –Output
  
  
–CIImageを生成
  
set aCIImage to CIImage’s alloc()’s initWithContentsOfURL:aURL
  
  
— CIFilter をフィルタの名前で生成
  
set aFilter to CIFilter’s filterWithName:aFilterName
  
aFilter’s setDefaults() –各フィルタのパラメータはデフォルト
  
  
–Filterを実行
  
aFilter’s setValue:aCIImage forKey:"inputImage"
  
set aOutImage to aFilter’s valueForKey:"outputImage"
  
  
— NSBitmapImageRep を CIImage から生成
  
set aRep to NSBitmapImageRep’s alloc()’s initWithCIImage:aOutImage
  
  
— NSBitmapImageRep から JPEG データを取得
  
set jpegData to aRep’s representationUsingType:(NSJPEGFileType) |properties|:(missing value)
  
  
— ファイルに保存
  
set fsRes to jpegData’s writeToFile:aPOSIX atomically:true
  
if (fsRes as boolean) = false then return false –失敗した場合
  
return aPOSIX –成功した場合
  
end convAsFilteredJPEG

–数字とアルファベットの混在状態の時にtrueを返す
on chkMixtureOfNumericAndAlphabet(checkString)
  set a0Res to chkAlphabetAndNumeric(checkString) of me
  
set a1Res to chkNumeric(checkString) of me
  
set a2Res to chkAlphabet(checkString) of me
  
if {a0Res, a1Res, a2Res} = {true, false, false} then
    return true
  else
    return false
  end if
end chkMixtureOfNumericAndAlphabet

–数字のみかを調べて返す
on chkNumeric(checkString)
  set digitCharSet to NSCharacterSet’s characterSetWithCharactersInString:"0123456789"
  
set ret to my chkCompareString:checkString baseString:digitCharSet
  
return ret as boolean
end chkNumeric

— アルファベットのみか調べて返す
on chkAlphabet(checkString)
  set aStr to NSString’s stringWithString:checkString
  
set allCharSet to NSMutableCharacterSet’s alloc()’s init()
  
allCharSet’s addCharactersInRange:(current application’s NSMakeRange(ASCII number of "a", 26))
  
allCharSet’s addCharactersInRange:(current application’s NSMakeRange(ASCII number of "A", 26))
  
set aBool to my chkCompareString:aStr baseString:allCharSet
  
return aBool as boolean
end chkAlphabet

— アルファベットと数字のみか調べて返す
on chkAlphabetAndNumeric(checkString)
  set aStr to NSString’s stringWithString:checkString
  
set allCharSet to NSMutableCharacterSet’s alloc()’s init()
  
allCharSet’s addCharactersInRange:(current application’s NSMakeRange(ASCII number of "0", 10))
  
allCharSet’s addCharactersInRange:(current application’s NSMakeRange(ASCII number of "a", 26))
  
allCharSet’s addCharactersInRange:(current application’s NSMakeRange(ASCII number of "A", 26))
  
set aBool to my chkCompareString:aStr baseString:allCharSet
  
return aBool as boolean
end chkAlphabetAndNumeric

on chkCompareString:checkString baseString:baseString
  set aScanner to NSScanner’s localizedScannerWithString:checkString
  
aScanner’s setCharactersToBeSkipped:(missing value)
  
aScanner’s scanCharactersFromSet:baseString intoString:(missing value)
  
return (aScanner’s isAtEnd()) as boolean
end chkCompareString:baseString:

–文字置換
on repChar(aStr, targStr, repStr)
  set aString to NSString’s stringWithString:aStr
  
set bString to aString’s stringByReplacingOccurrencesOfString:targStr withString:repStr
  
return bString as text
end repChar

–アルファベットと数字以外を削除して返す
on returnNumberAndAlphabetCharsOnly(aStr)
  set anNSString to NSString’s stringWithString:aStr
  
set anNSString to anNSString’s stringByReplacingOccurrencesOfString:"[^0-9A-Za-z]" withString:"" options:(NSRegularExpressionSearch) range:{0, anNSString’s |length|()}
  
return anNSString as text
end returnNumberAndAlphabetCharsOnly

★Click Here to Open This Script 

Posted in file filter geolocation Image list OCR Sandbox | Tagged 10.11savvy 10.12savvy FineReader OCR Pro | Leave a comment

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

Google Search

Popular posts

  • macOS 13, Ventura(継続更新)
  • アラートダイアログ上にWebViewで3Dコンテンツを表示(WebGL+three.js)v3
  • UI Browserがgithub上でソース公開され、オープンソースに
  • macOS 13 TTS Voice環境に変更
  • Xcode 14.2でAppleScript App Templateを復活させる
  • 2022年に書いた価値あるAppleScript
  • ChatGPTで文章のベクトル化(Embedding)
  • 新発売:AppleScriptからSiriを呼び出そう!
  • iWork 12.2がリリースされた
  • 従来と異なるmacOS 13の性格?
  • 新発売:CotEditor Scripting Book with AppleScript
  • macOS 13対応アップデート:AppleScript実践的テクニック集(1)GUI Scripting
  • AS関連データの取り扱いを容易にする(はずの)privateDataTypeLib
  • macOS 13でNSNotFoundバグふたたび
  • macOS 12.5.1、11.6.8でFinderのselectionでスクリーンショット画像をopenできない問題
  • ChatGPTでchatに対する応答文を取得
  • 新発売:iWork Scripting Book with AppleScript
  • Finderの隠し命令openVirtualLocationが発見される
  • macOS 13.1アップデートでスクリプトエディタの挙動がようやくまともに
  • あのコン過去ログビューワー(暫定版)

Tags

10.11savvy (1101) 10.12savvy (1242) 10.13savvy (1390) 10.14savvy (586) 10.15savvy (434) 11.0savvy (277) 12.0savvy (185) 13.0savvy (55) CotEditor (60) Finder (47) iTunes (19) Keynote (98) NSAlert (60) NSArray (51) NSBezierPath (18) NSBitmapImageRep (20) NSBundle (20) NSButton (34) NSColor (51) NSDictionary (27) NSFileManager (23) NSFont (18) 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 (56) Pages (37) Safari (41) Script Editor (20) WKUserContentController (21) WKUserScript (20) WKUserScriptInjectionTimeAtDocumentEnd (18) WKWebView (23) WKWebViewConfiguration (22)

カテゴリー

  • 2D Bin Packing
  • 3D
  • AirDrop
  • AirPlay
  • Animation
  • AppleScript Application on Xcode
  • beta
  • Bluetooth
  • Books
  • boolean
  • bounds
  • Bug
  • Calendar
  • call by reference
  • Clipboard
  • Code Sign
  • Color
  • Custom Class
  • dialog
  • 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
  • Machine Learning
  • Map
  • Markdown
  • Menu
  • Metadata
  • MIDI
  • MIME
  • Natural Language Processing
  • Network
  • news
  • Noification
  • Notarization
  • Number
  • Object control
  • OCR
  • OSA
  • 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)
  • 未分類

アーカイブ

  • 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