AppleScript QR

TSV2QRバーコード(タブ区切りテキストからQRバーコードを生成する)

サンプルデータ入り

ダウンロード - maketsv2qr.zip


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

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
(*
com.cocolog-nifty.quicktimer.icefloe
TSVタブ区切りテキストからQRコードを生成します
*)
----+----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 refNSNotFound : a reference to 9.22337203685477E+18 + 5807
##QRバーコードの最大幅
##(QRコード+クワイエットゾーンがあるのでひとまわり大きくなります)
property numMaxSize : 720 as integer

#################################
### 【1】入力ファイル
#################################
#ダイアログ
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 appFileManager to refMe's NSFileManager's defaultManager()
set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSDesktopDirectory) inDomains:(refMe's NSUserDomainMask))
set ocidDesktopDirPathURL to ocidURLsArray's firstObject()
set aliasDesktopDirPath to (ocidDesktopDirPathURL's absoluteURL()) as alias
#
set listUTI to {"public.tab-separated-values-text"}
set strMes to ("ファイルを選んでください") as text
set strPrompt to ("ファイルを選んでください") as text
try
  ### ファイル選択時
  set aliasFilePath to (choose file strMes with prompt strPrompt default location aliasDesktopDirPath of type listUTI with invisibles and showing package contents without multiple selections allowed) as alias
on error
log "エラーしました"
return "エラーしました"
end try
if aliasFilePath is (missing value) then
return "選んでください"
end if
#パス
set strFilePath to (POSIX path of aliasFilePath) 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)
#################################
### 【2】保存先
#################################
set ocidContainerDirPathURL to ocidFilePathURL's URLByDeletingLastPathComponent()
set aliasContainerDirPath to (ocidContainerDirPathURL's absoluteURL()) as alias
set strMes to "フォルダを選んでください" as text
set strPrompt to "QRコードの保存先フォルダを選択してください\n同名ファイルがある場合\n『上書き』になります" as text
try
  ###ダイアログを前面に出す
  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 aliasResponse to (choose folder strMes with prompt strPrompt default location aliasContainerDirPath with invisibles and showing package contents without multiple selections allowed) as alias
on error
log "エラーしました"
return "エラーしました"
end try
#戻り値エイリアスをURLに
set strSaveDirPath to (POSIX path of aliasResponse) as text
set ocidSaveDirPathStr to (refMe's NSString's stringWithString:(strSaveDirPath))
set ocidSaveDirPath to ocidSaveDirPathStr's stringByStandardizingPath()
set ocidSaveDirPathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidSaveDirPath) isDirectory:true)
#################################
### 【3】本処理
#################################
#ファイル読み込み
set listResponse to (refMe's NSString's alloc()'s initWithContentsOfURL:(ocidFilePathURL) usedEncoding:(refMe's NSUTF8StringEncoding) |error|:(reference))
set ocidReadString to (item 1 of listResponse)
if ocidReadString = (missing value) then
  set strFileName to ocidFilePathURL's lastPathComponent() as text
  set strMes to ("文字コードを判定出来ませんでした : " & strFileName & "\n処理を中止します") as text
display alert strMes
return
end if
##############################
#改行コード判定
set ocidCrRange to (ocidReadString's rangeOfString:("\r"))'s location()
set ocidLfRange to (ocidReadString's rangeOfString:("\n"))'s location()
if ocidCrRange = refNSNotFound then
log "Mac改行は無い"
  if ocidLfRange = refNSNotFound then
log "Mac改行もUNIX改行は無い=改行の無い1行か空のテキスト"
    set ocidLength to ocidReadString's |length|
    if ocidLength = (refMe's NSNumber's numberWithInteger:0) then
log "空のテキスト"
      set ocidNewLineChar to ocidSetNewLineChar
    else
log "改行無しの1行テキスト"
      set ocidNewLineChar to ocidSetNewLineChar
    end if
  else
log "Mac改行無+UNIX改行あり=UNIX改行"
    set ocidNewLineChar to (refMe's NSString's stringWithString:("\n"))
  end if
else
  if ocidLfRange = refNSNotFound then
log "MacがあるUNIX改行は無い=Mac改行"
    set ocidNewLineChar to (refMe's NSString's stringWithString:("\r"))
  else
log "Mac改行ある+UNIX改行あり=Windows改行"
    set ocidNewLineChar to (refMe's NSString's stringWithString:("\r\n"))
  end if
end if
#改行毎でリストにする
set ocidLineArray to (ocidReadString's componentsSeparatedByString:(ocidNewLineChar))
#################################
### 【4】ダイアログ
#################################
set ocidFirstLineString to ocidLineArray's firstObject()
set ocidFirstLineArray to (ocidFirstLineString's componentsSeparatedByString:("\t"))
set listFirstLineArray to ocidFirstLineArray as list
set strName to (name of current application) as text
if strName is "osascript" then
  tell application "Finder" to activate
  # tell application id "com.apple.appkit.xpc.openAndSavePanelService" to activate
else
  tell current application to activate
end if
###
set strTitle to ("選んでください") as text
set strPrompt to ("どの項目で作成しますか?") as text
try
  set listResponse to (choose from list listFirstLineArray with title strTitle with prompt strPrompt default items (item 1 of listFirstLineArray) 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 "キャンセルしましたA"
else if (item 1 of listResponse) is "キャンセル" then
return "キャンセルしましたB"
end if
set strResponse to (item 1 of listResponse) as text
##何番目を選んだ?
set ocidIndex to ocidFirstLineArray's indexOfObject:(strResponse)
#Arrayの項目数
set numCntListLine to (count of ocidLineArray) as integer
#処理番号のカウント
set numCntRowNo to 1 as integer
#行毎処理
repeat with itemIntNo from 1 to (numCntListLine - 1) by 1
  set ocidLineData to (ocidLineArray's objectAtIndex:(itemIntNo))
  if (ocidLineData as text) is "" then
    exit repeat
  end if
  #行毎にタブ区切りでリスト化して
  set ocidRowLineArray to (ocidLineData's componentsSeparatedByString:("\t"))
  #選んだ項目をとりだす
  set ocidMakeString to (ocidRowLineArray's objectAtIndex:(ocidIndex))
  if strResponse contains "電話" then
    set strMakeString to ("tel:" & ocidMakeString) as text
  else if strResponse contains "メール" then
    set strMakeString to ("maileto:" & ocidMakeString) as text
  else
    set strMakeString to ocidMakeString as text
  end if
  #ファイル名に処理番号入れる場合
  set strFileName to (numCntRowNo & "-" & ocidMakeString) as text
  set ocidFileName to (refMe's NSString's stringWithString:(strFileName))
  #ファイル名に使えない文字を置換
  set ocidInvalidChar to (refMe's NSString's stringWithString:("[\\\\/:*?\"<>|]"))
  set ocidRegex to (refMe's NSRegularExpression's regularExpressionWithPattern:(ocidInvalidChar) options:(refMe's NSRegularExpressionCaseInsensitive) |error|:(reference))
  set ocidLength to refMe's NSMakeRange(0, (ocidFileName's |length|))
  set ocidSafeFileName to (ocidFileName's stringByReplacingOccurrencesOfString:(ocidInvalidChar) withString:("_") options:(refMe's NSRegularExpressionSearch) range:(ocidLength))
  #保存ファイル名とURLを定義しておく
  set ocidBaseSaveFilePathURL to (ocidSaveDirPathURL's URLByAppendingPathComponent:(ocidSafeFileName))
  set ocidSaveFilePathURL to (ocidBaseSaveFilePathURL's URLByAppendingPathExtension:("png"))
  #QRコード生成を実行する
log doMakeQRcode(strMakeString, ocidSaveFilePathURL)
  set numCntRowNo to (numCntRowNo + 1) as integer
end repeat

set ocidSaveDirPathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidSaveDirPath) isDirectory:true)

#################################
### 【サブ】QRコード生成
#################################
to doMakeQRcode(argText, argSaveFilePathURL)
  #############################
  ### 【1】QRバーコード画像生成
  #############################
  #QRの内容になるテキスト
  set ocidInputString to refMe's NSString's stringWithString:(argText)
  #データに
  set ocidInputData to ocidInputString's dataUsingEncoding:(refMe's NSUTF8StringEncoding)
  ####CIQRCodeGenerator初期化
  set ocidQRcodeImage to refMe's CIFilter's filterWithName:("CIQRCodeGenerator")
ocidQRcodeImage's setDefaults()
  ###テキスト設定
ocidQRcodeImage's setValue:(ocidInputData) forKey:("inputMessage")
  ###読み取り誤差値設定L, M, Q, H
ocidQRcodeImage's setValue:("Q") forKey:("inputCorrectionLevel")
  ###QRコード本体のイメージ
  set ocidQRImage to ocidQRcodeImage's outputImage()
  ###QRコードの縦横取得 この数値が縦横のセル数
  set ocidQRDimension to ocidQRImage's extent()
  set listQRorigin to (item 1 of ocidQRDimension) as list
  set listQRsize to (item 2 of ocidQRDimension) as list
  set numQRsize to (item 1 of listQRsize) as integer
  ##############################
  
  ###整数で拡大しないとアレなので↑の値のニアなサイズになります
  ##この数値倍する
  set numScale to ((numMaxSize / numQRsize) div 1) as integer
  ####変換スケール作成-->拡大
  set recordScalse to refMe's CGAffineTransform's CGAffineTransformMakeScale(numScale, numScale)
  ##変換スケールを適応(元のサイズに元のサイズのスケール適応しても意味ないけど
  set ocidQRScaledImage to ocidQRImage's imageByApplyingTransform:(recordScalse)
  ###イメージデータを展開 拡大したQRコードのサイズ
  set ocidQRScaledRep to refMe's NSCIImageRep's imageRepWithCIImage:(ocidQRScaledImage)
  set ocidQRScaledSize to ocidQRScaledRep's |size|()
  set numQRScaledSize to (ocidQRScaledSize's width) as integer
  ##############################
  ###出力用のイメージの初期化
  set ocidNSImageScaled to refMe's NSImage's alloc()'s initWithSize:(ocidQRScaledSize)
  ###イメージデータを合成
ocidNSImageScaled's addRepresentation:(ocidQRScaledRep)
  ###出来上がったデータはOS_dispatch_data
  set ocidQRDispatchData to ocidNSImageScaled's TIFFRepresentation()
  ####NSBitmapImageRepに
  set ocidQRScaledBmpRep to refMe's NSBitmapImageRep's imageRepWithData:(ocidQRDispatchData)
  ###quiet zone用に画像をパディングする
  set numPadSize to (numQRScaledSize + (numScale * 6)) as integer
  ###左右に3セル分づつ余白 quiet zoneを足す
  ####まずは元のQRコードのサイズに3x2セルサイズ分足したサイズの画像を作って
  #QRコード自体に1セルクワイエットゾーンがあるので合計4セル分のクワイエットゾーンになる
  set ocidBaseRep to (refMe's NSBitmapImageRep's alloc()'s initWithBitmapDataPlanes:(missing value) pixelsWide:(numPadSize) pixelsHigh:(numPadSize) bitsPerSample:8 samplesPerPixel:4 hasAlpha:true isPlanar:false colorSpaceName:(refMe's NSCalibratedRGBColorSpace) bitmapFormat:(refMe's NSAlphaFirstBitmapFormat) bytesPerRow:0 bitsPerPixel:32)
  ###初期化
refMe's NSGraphicsContext's saveGraphicsState()
  ###Context
  set ocidContext to (refMe's NSGraphicsContext's graphicsContextWithBitmapImageRep:(ocidBaseRep))
  ###ビットマップイメージ
(refMe's NSGraphicsContext's setCurrentContext:(ocidContext))
  ###塗り色を『白』に指定して
refMe's NSColor's whiteColor()'s |set|()
  ###画像にする
refMe's NSRectFill({origin:{x:0, y:0}, |size|:{width:numPadSize, height:numPadSize}})
  ###出来上がった画像にQRバーコードを左右3セル分ずらした位置にCompositeSourceOverする
  set numPxWidth to ocidQRScaledBmpRep's pixelsWide()
  set numPadPxSize to (numPadSize - numPxWidth) / 2 as integer
ocidQRScaledBmpRep's drawInRect:{origin:{x:(numPadPxSize), y:(numPadPxSize)}, |size|:{width:numPadSize, Hight:numPadSize}} fromRect:{origin:{x:0, y:0}, |size|:{width:numPadSize, height:numPadSize}} operation:(refMe's NSCompositeSourceOver) fraction:1.0 respectFlipped:true hints:(missing value)
  ####画像作成終了
refMe's NSGraphicsContext's restoreGraphicsState()
  ####PNG用のプロパティ
  #保存用オプション
  set ocidPropertyDict to (refMe's NSMutableDictionary's alloc()'s initWithCapacity:0)
(ocidPropertyDict's setObject:(refMe's NSNumber's numberWithBool:(false)) forKey:(refMe's NSImageInterlaced))
(ocidPropertyDict's setObject:(refMe's NSNumber's numberWithFloat:(1 / 2.2)) forKey:(refMe's NSImageGamma))
  set ocidImageType to (refMe's NSBitmapImageFileTypePNG)
  #インラインデータに変換して
  set ocidSaveImageData to (ocidBaseRep's representationUsingType:(ocidImageType) |properties|:(ocidPropertyDict))
  #保存
  set listDone to (ocidSaveImageData's writeToURL:(argSaveFilePathURL) options:0 |error|:(reference))
end doMakeQRcode

|

QRコード

1:作成する
2:内容を読み取る(デコード)



1:作成する
カテゴリ
https://quicktimer.cocolog-nifty.com/icefloe/cat76026037/index.html
2:内容を読み取る(デコード)
カテゴリ
https://quicktimer.cocolog-nifty.com/icefloe/cat76054001/index.html


1:作成する
1−1:WEBサービスを利用する
1−2:アプリケーションを利用する
1−3:スクリプト等で作成する
1−4:種類別


1−1:WEBサービスを利用する作成する
Google
https://developers.google.com/chart/infographics/docs/qr_codes?hl=ja
Adobe svg保存あり
https://new.express.adobe.com/tools/generate-qr-code
QRQR(denso系)EPS保存あり
https://m.qrqrq.com/
tec-it QRコード以外も豊富なラインナップで作成できます ※おすすめ
https://barcode.tec-it.com/en/QRCode


1−2:アプリケーションを利用する
ショートカットを利用する
https://quicktimer.cocolog-nifty.com/icefloe/2024/02/post-79e2f8.html
tec-it  QRコード以外も豊富なラインナップ(有料だが高機能)
Barcode Studio
https://www.tec-it.com/en/download/barcode-studio/mac-os-x/Download.aspx
QR Code Studio(非商用なら無料)
https://www.tec-it.com/en/download/free-software/qrcode-studio/Download.aspx
Barcode Generator (有料)
https://boxshot.com/barcode/
iBarcoder (ベクトル保存あり 有料 お試しあり)
https://cristallight.com/iBarcoder/


1−3:作成する
Python
[pyqrcode]QRコードを生成する
https://quicktimer.cocolog-nifty.com/icefloe/2024/02/post-aabb60.html
[qrcode]QRコードを生成する
https://quicktimer.cocolog-nifty.com/icefloe/2024/02/post-b8a0c5.html
Bash
libqrencodeを使う 比較的簡単にMakeできますしおすすめです
https://fukuchi.org/works/qrencode/


1−4:種類別
1:Text URL
2:Mail
3:Tel
4:SMS
5:Vcard
6:Event
7:Map
8:Wifi


1:URL
[URL]URLリンク用バーコード (GoogleChart利用)
https://quicktimer.cocolog-nifty.com/icefloe/2023/09/post-874e67.html
[URL]URLリンク用バーコード (CoreImage利用)
https://quicktimer.cocolog-nifty.com/icefloe/2023/09/post-764eea.html
[URL]URLリンク用バーコード (CoreImage利用 背景配色あり)
https://quicktimer.cocolog-nifty.com/icefloe/2023/09/post-817481.html
2:Mail
[QR]MAILTO形式のURL型メール送信用QRバーコード(一般的にはこの形式)
https://quicktimer.cocolog-nifty.com/icefloe/2024/01/post-dc0be0.html
[QR] MATMSG形式のメール送信用QR
https://quicktimer.cocolog-nifty.com/icefloe/2024/01/post-09ddc0.html
3:Tel
[TEL]電番リンク用バーコード (CoreImage利用)
https://quicktimer.cocolog-nifty.com/icefloe/2023/09/post-aa6cf7.html
[TEL]電番リンク用バーコード (GoogleChart利用)
https://quicktimer.cocolog-nifty.com/icefloe/2023/09/post-6eb0e4.html
[TEL]電番リンク用バーコード (CoreImage利用 背景配色あり)
https://quicktimer.cocolog-nifty.com/icefloe/2023/09/post-cc5d40.html
4:SMS
[SMS]SMS送信用バーコード (CoreImage利用 背景配色あり)
https://quicktimer.cocolog-nifty.com/icefloe/2023/09/post-24ed0c.html
[SMS]SMS送信用バーコード (CoreImage利用)
https://quicktimer.cocolog-nifty.com/icefloe/2023/09/post-0754d1.html
[SMS]SMS送信用バーコード (GoogleChart利用)
https://quicktimer.cocolog-nifty.com/icefloe/2023/09/post-e180d0.html
[QR] SMS送信用バーコード生成
https://quicktimer.cocolog-nifty.com/icefloe/2023/03/post-d38c42.html
5:Vcard
[VCARD]連絡先登録用バーコード (GoogleChart利用)
https://quicktimer.cocolog-nifty.com/icefloe/2023/09/post-b473f7.html
[VCARD]連絡先登録用バーコード (CoreImage利用)
https://quicktimer.cocolog-nifty.com/icefloe/2023/09/post-7a4a71.html
[VCARD]連絡先登録用バーコード (CoreImage利用 背景配色あり)
https://quicktimer.cocolog-nifty.com/icefloe/2023/09/post-eb42ec.html
6:Event
[Event]ICSカレンダーイベント送信用バーコード (GoogleChart利用)
https://quicktimer.cocolog-nifty.com/icefloe/2023/09/post-3f84cf.html
[Event]ICSカレンダーイベント送信用バーコード (CoreImage利用)
https://quicktimer.cocolog-nifty.com/icefloe/2023/09/post-f03b55.html
[Event]ICSカレンダーイベント送信用バーコード (CoreImage利用 背景配色あり)
https://quicktimer.cocolog-nifty.com/icefloe/2023/09/post-2b7799.html
7:Map
緯度情報を取得する方法+表示させるURLの組み合わせが無限…
https://github.com/force4u/AppleScript/tree/main/Script%20Menu/Pictures/MakeQR/Map
8:Wifi
[WIFI]WIFIバーコード (CoreImage利用 背景配色あり)
https://quicktimer.cocolog-nifty.com/icefloe/2023/09/post-bf12f4.html
[WIFI]WIFIバーコード (CoreImage利用)
https://quicktimer.cocolog-nifty.com/icefloe/2023/09/post-437b60.html
[WIFI]WIFIバーコード (chart.googleapis利用)
https://quicktimer.cocolog-nifty.com/icefloe/2023/09/post-bf12f4.html



001_20240218144201

|

[qrcode]QRコードを生成する


【セットアップスクリプトを実行してください】|


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

#!/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 strFilePath to ("~/Desktop/makeQRcode.png") as text

set strMaekString to ("美しい日本語") as text


set ocidFilePathStr to refMe's NSString's stringWithString:(strFilePath)
set ocidFilePath to ocidFilePathStr's stringByStandardizingPath()
set strFilePath to ocidFilePath as text
set strExtension to ocidFilePath's pathExtension() as text


set strCommandText to ("/usr/bin/python3 -c \"import qrcode;qrdata = qrcode.make('" & strMaekString & "'); type(qrdata);qrdata.save('" & strFilePath & "');\"") as text


log strCommandText
do shell script strCommandText

|

[pyqrcode]QRコードを生成する

【セットアップスクリプトを実行してください】|


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

#!/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 strFilePath to ("~/Desktop/makeQRcode.png") as text

set strMaekString to ("美しい日本語") as text


set ocidFilePathStr to refMe's NSString's stringWithString:(strFilePath)
set ocidFilePath to ocidFilePathStr's stringByStandardizingPath()
set strFilePath to ocidFilePath as text
set strExtension to ocidFilePath's pathExtension() as text

if strExtension is "svg" then
  set strCommandText to ("/usr/bin/python3 -c \"import pyqrcode;qrdata = pyqrcode.create('" & strMaekString & "', encoding='utf-8', error='M'); qrdata.svg('" & strFilePath & "', scale=6, background='#eee', module_color='#36C', quiet_zone=3);\"") as text
else if strExtension is "png" then
  set strCommandText to ("/usr/bin/python3 -c \"import pyqrcode;qrdata = pyqrcode.create('" & strMaekString & "', encoding='utf-8', error='M'); qrdata.png('" & strFilePath & "', scale=6, background='#eee', module_color='#36C', quiet_zone=3);\"") as text
else if strExtension is "eps" then
  set strCommandText to ("/usr/bin/python3 -c \"import pyqrcode;qrdata = pyqrcode.create('" & strMaekString & "', encoding='utf-8', error='M'); qrdata.eps('" & strFilePath & "', scale=6, background='#eee', module_color='#36C', quiet_zone=3);\"") as text
  
end if

log strCommandText
do shell script strCommandText


|

[QR] MAILTO形式のURL型メール送信用QRバーコード(一般的にはこの形式)


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

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
(* 使用フォント
San Francisco SF Pro
https://developer.apple.com/fonts/ 
*)
# 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 "CoreImage"
use scripting additions

property refMe : a reference to current application
property refNSNotFound : a reference to 9.22337203685477E+18 + 5807


#####################
### 設定項目 boolUseQueryをtrueに変更すると反映されます
set boolUseQuery to false as boolean
set strSubject to ("[QR]QRコードの読み取り返信です") as text
set strBody to ("私のメールアドレスはこのメールの送信アドレスになります") as text
set strCCemail to ("fooCC@hoge.com") as text
set strBccemail to ("fooBCC@hoge.com") as text

#####################
### QRコード保存先 NSPicturesDirectory
set appFileManager to refMe's NSFileManager's defaultManager()
set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSPicturesDirectory) inDomains:(refMe's NSUserDomainMask))
set ocidPicturesDirURL to ocidURLsArray's firstObject()
set ocidSaveDirPathURL to ocidPicturesDirURL's URLByAppendingPathComponent:("QRcode/eMail")
##フォルダ作成
set ocidAttrDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
# 777-->511 755-->493 700-->448 766-->502
ocidAttrDict's setValue:(448) forKey:(refMe's NSFilePosixPermissions)
set listBoolMakeDir to appFileManager's createDirectoryAtURL:(ocidSaveDirPathURL) withIntermediateDirectories:true attributes:(ocidAttrDict) |error|:(reference)
#####################
### ペーストボード初期化
set appPasteboard to refMe's NSPasteboard's generalPasteboard()
##ペーストボードからテキストを取り出す
set ocidStringData to appPasteboard's stringForType:("public.utf8-plain-text")
if ocidStringData is (missing value) then
  set strDefaultAnswer to "foo@hoge.com" as text
else
  set strDefaultAnswer to (refMe's NSString's stringWithString:(ocidStringData)) as text
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 aliasIconPath to POSIX file "/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/BookmarkIcon.icns" as alias
try
  set objResponse to (display dialog "メールアドレスを入力してください" with title "QRコードを作成します" default answer strDefaultAnswer buttons {"OK", "キャンセル"} default button "OK" cancel button "キャンセル" with icon aliasIconPath giving up after 30 without hidden answer)
on error
log "エラーしました"
return
end try
if true is equal to (gave up of objResponse) then
return "時間切れですやりなおしてください"
end if
if "OK" is equal to (button returned of objResponse) then
  set strText to (text returned of objResponse) as text
else
return "キャンセル"
end if
if strText starts with "mailto" then
  set strQRContents to (strText) as text
else if strText contains "@" then
  set strQRContents to (strText) as text
else
return "メールアドレス専用です"
end if
##############################
set ocidQRContents to refMe's NSString's stringWithString:(strQRContents)
###改行とタブだけは取っておく
set ocidURLM to refMe's NSMutableString's alloc()'s initWithCapacity:(0)
ocidURLM's setString:(ocidQRContents)
set ocidURLM to ocidURLM's stringByReplacingOccurrencesOfString:("\n") withString:("")
set ocidURLM to ocidURLM's stringByReplacingOccurrencesOfString:("\r") withString:("")
set ocidURLM to ocidURLM's stringByReplacingOccurrencesOfString:("\t") withString:("")

###クエリー追加
if boolUseQuery is true then
  set ocidEmailComponents to refMe's NSURLComponents's alloc()'s init()
ocidEmailComponents's setScheme:("mailto")
ocidEmailComponents's setPath:(ocidURLM)
  set ocidQueryItemArray to refMe's NSMutableArray's alloc()'s initWithCapacity:0
  set ocidQueryItem to refMe's NSURLQueryItem's alloc()'s initWithName:("subject") value:(strSubject)
ocidQueryItemArray's addObject:ocidQueryItem
  set ocidQueryItem to refMe's NSURLQueryItem's alloc()'s initWithName:("body") value:(strBody)
ocidQueryItemArray's addObject:ocidQueryItem
  set ocidQueryItem to refMe's NSURLQueryItem's alloc()'s initWithName:("cc") value:(strCCemail)
ocidQueryItemArray's addObject:ocidQueryItem
  set ocidQueryItem to refMe's NSURLQueryItem's alloc()'s initWithName:("bcc") value:(strBccemail)
ocidQueryItemArray's addObject:ocidQueryItem
ocidEmailComponents's setQueryItems:(ocidQueryItemArray)
  set ocidReadURL to ocidEmailComponents's |URL|
  set strEmailAdd to ocidURLM as text
  set strURL to ocidReadURL's absoluteString() as text
else
  set ocidEmailComponents to refMe's NSURLComponents's alloc()'s init()
ocidEmailComponents's setScheme:("mailto")
ocidEmailComponents's setPath:(ocidURLM)
  set ocidReadURL to ocidEmailComponents's |URL|
  set strEmailAdd to ocidURLM as text
  set strURL to ocidReadURL's absoluteString() as text
end if


###保存ファイル名
set strDateNo to doGetDateNo({"yyyyMMddhhmmss", 1})
set strSaveFileName to ("MAILTO" & "." & strEmailAdd & "." & strDateNo & ".png") as text
set ocidSaveFilePathURL to ocidSaveDirPathURL's URLByAppendingPathComponent:(strSaveFileName)
######################################
### 色決め 切り捨ての都合上指定のニア
######################################
tell application "Finder"
  set the listRGB16bitColor to (choose color default color {0, 0, 0, 1}) as list
end tell
##########Color Picker Value 16Bit
set numRcolor16Bit to item 1 of listRGB16bitColor as number
set numGcolor16Bit to item 2 of listRGB16bitColor as number
set numBcolor16Bit to item 3 of listRGB16bitColor as number
set numAcolor16Bit to 65535 as number
##########Standard RGB Value 8Bit
set numRcolor8Bit to numRcolor16Bit / 256 div 1 as number
set numGcolor8Bit to numGcolor16Bit / 256 div 1 as number
set numBcolor8Bit to numBcolor16Bit / 256 div 1 as number
set numAcolor8Bit to numAcolor16Bit / 256 div 1 as number
##########NSColorValue Float
set numRcolorFloat to numRcolor8Bit / 255 as number
set numGcolorFloat to numGcolor8Bit / 255 as number
set numBcolorFloat to numBcolor8Bit / 255 as number
set numAcolorFloat to numAcolor8Bit / 255 as number
####色指定
## 色指定値はこちらを利用
## https://quicktimer.cocolog-nifty.com/icefloe/2023/06/post-d68270.html
###色指定する場合
## set ocidQrColor to refMe's CIColor's colorWithRed:0.101960784314 green:0.752941176471 blue:0.262745098039 alpha:1.0
###
set ocidQrColor to refMe's CIColor's colorWithRed:(numRcolorFloat) green:(numGcolorFloat) blue:(numBcolorFloat) alpha:(numAcolorFloat)
#############################
### 【1】QRバーコード画像生成
#############################
####テキストをNSStringに
set ocidInputString to refMe's NSString's stringWithString:(strURL)
####テキストをUTF8に
set ocidUtf8InputString to ocidInputString's dataUsingEncoding:(refMe's NSUTF8StringEncoding)
####CIQRCodeGenerator初期化
set ocidQRcodeImage to refMe's CIFilter's filterWithName:"CIQRCodeGenerator"
ocidQRcodeImage's setDefaults()
###テキスト設定
ocidQRcodeImage's setValue:ocidUtf8InputString forKey:"inputMessage"
###読み取り誤差値設定L, M, Q, H
ocidQRcodeImage's setValue:"Q" forKey:"inputCorrectionLevel"
###QRコード本体のイメージ
set ocidCIImage to ocidQRcodeImage's outputImage()
-->ここで生成されるのはQRのセルが1x1pxの最小サイズ
##############
### 色の置き換え
### 置き換わる色=この場合は黒
set ocidBlackColor to refMe's CIColor's colorWithRed:1.0 green:1.0 blue:1.0 alpha:0.0
###CIFalseColorで色を塗ります
set ocidFilterColor to refMe's CIFilter's filterWithName:("CIFalseColor")
ocidFilterColor's setDefaults()
ocidFilterColor's setValue:ocidQrColor forKey:("inputColor0")
ocidFilterColor's setValue:ocidBlackColor forKey:("inputColor1")
ocidFilterColor's setValue:ocidCIImage forKey:("inputImage")
###フィルタをかけた画像をoutputImageから取り出します
set ocidCIImage to ocidFilterColor's valueForKey:("outputImage")
###QRコードの縦横取得
set ocidCIImageDimension to ocidCIImage's extent()
set ocidCIImageWidth to (item 1 of item 2 of ocidCIImageDimension) as integer
set ocidCIImageHight to (item 2 of item 2 of ocidCIImageDimension) as integer
###最終的に出力したいpxサイズ
set numScaleMax to 500
###整数で拡大しないとアレなので↑の値のニアなサイズになります
set numWidth to ((numScaleMax / ocidCIImageWidth) div 1) as integer
set numHight to ((numScaleMax / ocidCIImageHight) div 1) as integer
###↑サイズの拡大縮小する場合はここで値を調整すれば良い
####変換スケール作成-->拡大
set recordScalse to refMe's CGAffineTransform's CGAffineTransformMakeScale(numWidth, numHight)
##変換スケールを適応(元のサイズに元のサイズのスケール適応しても意味ないけど
set ocidCIImageScaled to ocidCIImage's imageByApplyingTransform:(recordScalse)
#######元のセルが1x1pxの最小サイズで出したいときはここで処理
##set ocidCIImageScaled to ocidCIImage
###イメージデータを展開
set ocidNSCIImageRep to refMe's NSCIImageRep's imageRepWithCIImage:(ocidCIImageScaled)
###出力用のイメージの初期化
set ocidNSImageScaled to refMe's NSImage's alloc()'s initWithSize:(ocidNSCIImageRep's |size|())
###イメージデータを合成
ocidNSImageScaled's addRepresentation:(ocidNSCIImageRep)
###出来上がったデータはOS_dispatch_data
set ocidOsDispatchData to ocidNSImageScaled's TIFFRepresentation()
####NSBitmapImageRepに
set ocidQRImageRep to refMe's NSBitmapImageRep's imageRepWithData:(ocidOsDispatchData)

#############################
### 【2】QRコードの背景部
###(ホワイトスペースパディング配慮)
#############################
##画像サイズ
set numQRSize to 520 as integer
##画像生成開始
set ocidBitmapFormat to refMe's NSBitmapFormatAlphaFirst
set ocidColorSpaceName to refMe's NSCalibratedRGBColorSpace
### NSBitmapImageRep
set ocidCodeBaseRep to (refMe's NSBitmapImageRep's alloc()'s initWithBitmapDataPlanes:(missing value) pixelsWide:(numQRSize) pixelsHigh:(numQRSize) bitsPerSample:8 samplesPerPixel:4 hasAlpha:true isPlanar:false colorSpaceName:(ocidColorSpaceName) bitmapFormat:(ocidBitmapFormat) bytesPerRow:0 bitsPerPixel:32)
#############################
### 初期化 CodeBase
refMe's NSGraphicsContext's saveGraphicsState()
###Context
set ocidContext to (refMe's NSGraphicsContext's graphicsContextWithBitmapImageRep:(ocidCodeBaseRep))
###生成された画像でNSGraphicsContext初期化
(refMe's NSGraphicsContext's setCurrentContext:(ocidContext))
###ここが背景色の塗り色
##色を個別に指定する場合 値は0が暗 1が明
set ocidSetColor to (refMe's NSColor's colorWithSRGBRed:(1) green:(1) blue:(1) alpha:(1.0))
ocidSetColor's |set|()
###画像生成
refMe's NSRectFill({origin:{x:0, y:0}, |size|:{width:(numQRSize), height:(numQRSize)}})
####画像作成終了
refMe's NSGraphicsContext's restoreGraphicsState()
#############################
### 【3】QRバーコードパディング処理
### 1で作ったQRバーコード画像を
### 2で作った画像にペースト
###(ホワイトスペースパディング配慮)
#############################
###
set numPxWidth to ocidQRImageRep's pixelsWide()
set numPxHight to ocidQRImageRep's pixelsHigh()
###画像合成位置計算パディング配慮
set numPadSize to (numQRSize - numPxWidth) / 2 as integer
#############################
### 初期化 CodeBase
refMe's NSGraphicsContext's saveGraphicsState()
###Context
set ocidContext to (refMe's NSGraphicsContext's graphicsContextWithBitmapImageRep:(ocidCodeBaseRep))
###生成された画像でNSGraphicsContext初期化
(refMe's NSGraphicsContext's setCurrentContext:(ocidContext))
###出来上がった画像にQRバーコードをCompositeSourceOverする
ocidQRImageRep's drawInRect:{origin:{x:(numPadSize), y:(numPadSize)}, |size|:{width:(numPxWidth), Hight:(numPxWidth)}} fromRect:{origin:{x:0, y:0}, |size|:{width:(numPxWidth), height:(numPxHight)}} operation:(refMe's NSCompositeSourceOver) fraction:1.0 respectFlipped:true hints:(missing value)
####画像作成終了
refMe's NSGraphicsContext's restoreGraphicsState()
#############################
### 【4】最終的な出力画像生成
### ArtBoardになる画像の生成
#############################
### 背景 ARTBORD
set ocidBitmapFormat to refMe's NSBitmapFormatAlphaFirst
set ocidColorSpaceName to refMe's NSCalibratedRGBColorSpace
### NSBitmapImageRep
set ocidArtBoardRep to (refMe's NSBitmapImageRep's alloc()'s initWithBitmapDataPlanes:(missing value) pixelsWide:(580) pixelsHigh:(680) bitsPerSample:8 samplesPerPixel:4 hasAlpha:true isPlanar:false colorSpaceName:(ocidColorSpaceName) bitmapFormat:(ocidBitmapFormat) bytesPerRow:0 bitsPerPixel:32)
#############################
### 初期化 ArtBoard
refMe's NSGraphicsContext's saveGraphicsState()
###Context
set ocidContext to (refMe's NSGraphicsContext's graphicsContextWithBitmapImageRep:(ocidArtBoardRep))
###生成された画像でNSGraphicsContext初期化
(refMe's NSGraphicsContext's setCurrentContext:(ocidContext))
###ここが背景色の塗り色
##色を個別に指定する場合 値は0が暗 1が明
set ocidSetColor to (refMe's NSColor's colorWithSRGBRed:(numRcolorFloat) green:(numGcolorFloat) blue:(numBcolorFloat) alpha:(numAcolorFloat))
## 透過の場合
## set ocidSetColor to refMe's NSColor's clearColor()
## 白
## set ocidSetColor to refMe's NSColor's whiteColor()
ocidSetColor's |set|()
###画像生成
refMe's NSRectFill({origin:{x:0, y:0}, |size|:{width:(580), height:(680)}})
####画像作成終了
refMe's NSGraphicsContext's restoreGraphicsState()
#############################
### 【5】QRコードペースト
### 3で作ったパディング済みQRコードを
### 4で作ったArtBoardにペースト
#############################
### 初期化 バーコードを ocidArtBoardRep にペースト
refMe's NSGraphicsContext's saveGraphicsState()
###ビットマップイメージ
(refMe's NSGraphicsContext's setCurrentContext:(refMe's NSGraphicsContext's graphicsContextWithBitmapImageRep:(ocidArtBoardRep)))
###画像合成位置計算
###左右位置センタリング
set numLeftPad to ((580 - numQRSize) / 2) as integer
###左右のパディング幅と同じサイズで上部パディング
set numbottomPad to (680 - numQRSize - numLeftPad)
###出来上がった画像にQRバーコードを左右3セル分ずらした位置にCompositeSourceOverする
ocidCodeBaseRep's drawInRect:{origin:{x:(numLeftPad), y:(numbottomPad)}, |size|:{width:numQRSize, Hight:numQRSize}} fromRect:{origin:{x:0, y:0}, |size|:{width:numQRSize, height:numQRSize}} operation:(refMe's NSCompositeSourceOver) fraction:1.0 respectFlipped:true hints:(missing value)
####画像作成終了
refMe's NSGraphicsContext's restoreGraphicsState()
#############################
### 【6】テキスト描画
### 5で生成された画像に対して
### テキスト画像を描画する
#############################
###フォント初期化
set appFontManager to refMe's NSFontManager
set appSharedMaanager to appFontManager's sharedFontManager()
###設定用のレコード
set ocidTextAttr to (refMe's NSMutableDictionary's alloc()'s initWithCapacity:0)
###共通項目
set ocidStyle to refMe's NSParagraphStyle's defaultParagraphStyle
(ocidTextAttr's setObject:(ocidStyle) forKey:(refMe's NSParagraphStyleAttributeName))
###画像の明暗判定
set numColorBD to (numRcolorFloat + numGcolorFloat + numBcolorFloat + numAcolorFloat) as number
log numColorBD
if numColorBD > 3.5 then
  ##明るいバーコード色の時は文字色は黒
  set ocidTextColor to (refMe's NSColor's colorWithSRGBRed:(0) green:(0) blue:(0) alpha:(1.0))
(ocidTextAttr's setObject:(ocidTextColor) forKey:(refMe's NSForegroundColorAttributeName))
  ##文字色黒の時はドロップシャドウを入れる
  set ocidShadow to refMe's NSShadow's alloc()'s init()
  set ocidShadowColor to (ocidTextColor's colorWithAlphaComponent:0.8)
(ocidShadow's setShadowColor:(ocidShadowColor))
(ocidShadow's setShadowOffset:(refMe's NSMakeSize(1, -1)))
(ocidShadow's setShadowBlurRadius:4)
(ocidTextAttr's setObject:(ocidShadow) forKey:(refMe's NSShadowAttributeName))
else
  ##暗いバーコード色の時は文字色白
  set ocidTextColor to (refMe's NSColor's colorWithSRGBRed:(1) green:(1) blue:(1) alpha:(1.0))
(ocidTextAttr's setObject:(ocidTextColor) forKey:(refMe's NSForegroundColorAttributeName))
end if

#############################
###初期化
refMe's NSGraphicsContext's saveGraphicsState()
####NSGraphicsContextは透明アートボード
set ocidContext to (refMe's NSGraphicsContext's graphicsContextWithBitmapImageRep:(ocidArtBoardRep))
###ArtBoardでNSGraphicsContext初期化
(refMe's NSGraphicsContext's setCurrentContext:(ocidContext))
##############
set ocidText to (refMe's NSString's stringWithString:("eMAIL QR"))
set ocidFont to (refMe's NSFont's fontWithName:("Helvetica-Bold") |size|:(52))
(ocidTextAttr's setObject:(ocidFont) forKey:(refMe's NSFontAttributeName))
(ocidTextAttr's setObject:(-1.8) forKey:(refMe's NSKernAttributeName))
set ocidTextOrigin to refMe's NSMakePoint((30), (45))
(ocidText's drawAtPoint:(ocidTextOrigin) withAttributes:(ocidTextAttr))
##############
## set strDrawText to ("mailto:" & strQRContents) as text
set ocidText to (refMe's NSString's stringWithString:(strEmailAdd))
set ocidFont to (refMe's NSFont's fontWithName:("Menlo-Regular") |size|:(18))
(ocidTextAttr's setObject:(ocidFont) forKey:(refMe's NSFontAttributeName))
(ocidTextAttr's setObject:(0) forKey:(refMe's NSKernAttributeName))
set ocidTextOrigin to refMe's NSMakePoint((33), (20))
(ocidText's drawAtPoint:(ocidTextOrigin) withAttributes:(ocidTextAttr))
(*
ここのキャラクターIDは
こちらを参照してください
https://quicktimer.cocolog-nifty.com/icefloe/cat76056068/index.html
*)
set strIconText to (character id 1049430) as text
set ocidText to (refMe's NSString's stringWithString:(strIconText))
set ocidFont to (refMe's NSFont's fontWithName:("SFPro-Bold") |size|:(72))
(ocidTextAttr's setObject:(ocidFont) forKey:(refMe's NSFontAttributeName))
(ocidTextAttr's setObject:(0) forKey:(refMe's NSKernAttributeName))
set ocidTextOrigin to refMe's NSMakePoint((450), (25))
(ocidText's drawAtPoint:(ocidTextOrigin) withAttributes:(ocidTextAttr))

####画像作成終了
refMe's NSGraphicsContext's restoreGraphicsState()

#############################
### 【7】画像データ保存
### 6で生成された画像に対を
### 指定のフォルダに保存する
#############################
####PNG用の圧縮プロパティ
set ocidNSSingleEntryDictionary to refMe's NSDictionary's dictionaryWithObject:true forKey:(refMe's NSImageInterlaced)
#####出力イメージへ変換
set ocidNSInlineData to (ocidArtBoardRep's representationUsingType:(refMe's NSBitmapImageFileTypePNG) |properties|:ocidNSSingleEntryDictionary)
(*
NSBitmapImageFileTypeJPEG
NSBitmapImageFileTypePNG
NSBitmapImageFileTypeGIF
NSBitmapImageFileTypeBMP
NSBitmapImageFileTypeTIFF
NSBitmapImageFileTypeJPEG2000
*)
### 保存
set ocidOption to (refMe's NSDataWritingAtomic)
set boolDone to ocidNSInlineData's writeToURL:(ocidSaveFilePathURL) options:(ocidOption) |error|:(reference)
set aliasSaveFilePath to (ocidSaveFilePathURL's absoluteURL()) as alias

#############################
### 【8】表示
#############################
###Preview で開く
tell application "Preview"
launch
activate
open file aliasSaveFilePath
end tell
###
#####################
### Finderで保存先を開く
set appSharedWorkspace to refMe's NSWorkspace's sharedWorkspace()
set boolDone to appSharedWorkspace's selectFile:(ocidSaveFilePathURL's |path|()) inFileViewerRootedAtPath:(ocidSaveDirPathURL's |path|())

return true



################################
# 日付 doGetDateNo(argDateFormat,argCalendarNO)
# argCalendarNO 1 NSCalendarIdentifierGregorian 西暦
# argCalendarNO 2 NSCalendarIdentifierJapanese 和暦
################################
to doGetDateNo({argDateFormat, argCalendarNO})
  ##渡された値をテキストで確定させて
  set strDateFormat to argDateFormat as text
  set intCalendarNO to argCalendarNO as integer
  ###日付情報の取得
  set ocidDate to current application's NSDate's |date|()
  ###日付のフォーマットを定義(日本語)
  set ocidFormatterJP to current application's NSDateFormatter's alloc()'s init()
  ###和暦 西暦 カレンダー分岐
  if intCalendarNO = 1 then
    set ocidCalendarID to (current application's NSCalendarIdentifierGregorian)
  else if intCalendarNO = 2 then
    set ocidCalendarID to (current application's NSCalendarIdentifierJapanese)
  else
    set ocidCalendarID to (current application's NSCalendarIdentifierISO8601)
  end if
  set ocidCalendarJP to current application's NSCalendar's alloc()'s initWithCalendarIdentifier:(ocidCalendarID)
  set ocidTimezoneJP to current application's NSTimeZone's alloc()'s initWithName:("Asia/Tokyo")
  set ocidLocaleJP to current application's NSLocale's alloc()'s initWithLocaleIdentifier:("ja_JP_POSIX")
  ###設定
ocidFormatterJP's setTimeZone:(ocidTimezoneJP)
ocidFormatterJP's setLocale:(ocidLocaleJP)
ocidFormatterJP's setCalendar:(ocidCalendarJP)
  # ocidFormatterJP's setDateStyle:(current application's NSDateFormatterNoStyle)
  # ocidFormatterJP's setDateStyle:(current application's NSDateFormatterShortStyle)
  # ocidFormatterJP's setDateStyle:(current application's NSDateFormatterMediumStyle)
  # ocidFormatterJP's setDateStyle:(current application's NSDateFormatterLongStyle)
ocidFormatterJP's setDateStyle:(current application's NSDateFormatterFullStyle)
  ###渡された値でフォーマット定義
ocidFormatterJP's setDateFormat:(strDateFormat)
  ###フォーマット適応
  set ocidDateAndTime to ocidFormatterJP's stringFromDate:(ocidDate)
  ###テキストで戻す
  set strDateAndTime to ocidDateAndTime as text
return strDateAndTime
end doGetDateNo


---URLエンコードのサブルーチン
####################################
###### %エンコード
####################################
on doUrlEncode(argText)
  ##テキスト
  set ocidArgText to refMe's NSString's stringWithString:(argText)
  ##キャラクタセットを指定
  set ocidChrSet to refMe's NSCharacterSet's URLQueryAllowedCharacterSet
  ##キャラクタセットで変換
  set ocidArgTextEncoded to ocidArgText's stringByAddingPercentEncodingWithAllowedCharacters:(ocidChrSet)
  ######## 置換 %エンコードの追加処理
  ###置換レコード
  set recordPercentMap to {|+|:"%2B", |=|:"%3D", |&|:"%26", |$|:"%24"} as record
  ###ディクショナリにして
  set ocidPercentMap to refMe's NSDictionary's alloc()'s initWithDictionary:(recordPercentMap)
  ###キーの一覧を取り出します
  set ocidAllKeys to ocidPercentMap's allKeys()
  ###取り出したキー一覧を順番に処理
  repeat with itemAllKey in ocidAllKeys
    ##キーの値を取り出して
    set ocidMapValue to (ocidPercentMap's valueForKey:(itemAllKey))
    ##置換
    set ocidEncodedText to (ocidArgTextEncoded's stringByReplacingOccurrencesOfString:(itemAllKey) withString:(ocidMapValue))
    ##次の変換に備える
    set ocidArgTextEncoded to ocidEncodedText
  end repeat
  ##テキスト形式に確定
  set strTextToEncode to ocidEncodedText as text
  ###値を戻す
return strTextToEncode
end doUrlEncode


|

[QR] MATMSG形式のメール送信用QR


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

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
(* 使用フォント
San Francisco SF Pro
https://developer.apple.com/fonts/ 
*)
# 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 "CoreImage"
use scripting additions

property refMe : a reference to current application
property refNSNotFound : a reference to 9.22337203685477E+18 + 5807

#####################
### 設定項目
set strSubject to ("件名をここに") as text
set strBody to ("本文をここに")
#####################
### QRコード保存先 NSPicturesDirectory
set appFileManager to refMe's NSFileManager's defaultManager()
set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSPicturesDirectory) inDomains:(refMe's NSUserDomainMask))
set ocidPicturesDirURL to ocidURLsArray's firstObject()
set ocidSaveDirPathURL to ocidPicturesDirURL's URLByAppendingPathComponent:("QRcode/eMail")
##フォルダ作成
set ocidAttrDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
# 777-->511 755-->493 700-->448 766-->502
ocidAttrDict's setValue:(448) forKey:(refMe's NSFilePosixPermissions)
set listBoolMakeDir to appFileManager's createDirectoryAtURL:(ocidSaveDirPathURL) withIntermediateDirectories:true attributes:(ocidAttrDict) |error|:(reference)
#####################
### ペーストボード初期化
set appPasteboard to refMe's NSPasteboard's generalPasteboard()
##ペーストボードからテキストを取り出す
set ocidStringData to appPasteboard's stringForType:("public.utf8-plain-text")
if ocidStringData is (missing value) then
  set strDefaultAnswer to "foo@hoge.com" as text
else
  set strDefaultAnswer to (refMe's NSString's stringWithString:(ocidStringData)) as text
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 aliasIconPath to POSIX file "/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/BookmarkIcon.icns" as alias
try
  set objResponse to (display dialog "メールアドレスを入力してください" with title "QRコードを作成します" default answer strDefaultAnswer buttons {"OK", "キャンセル"} default button "OK" cancel button "キャンセル" with icon aliasIconPath giving up after 30 without hidden answer)
on error
log "エラーしました"
return
end try
if true is equal to (gave up of objResponse) then
return "時間切れですやりなおしてください"
end if
if "OK" is equal to (button returned of objResponse) then
  set strText to (text returned of objResponse) as text
else
return "キャンセル"
end if
if strText starts with "mailto" then
  set strQRContents to (strText) as text
else if strText contains "@" then
  set strQRContents to ("" & strText) as text
else
return "メールアドレス専用です"
end if
##############################
###メールアドレスを一旦NSURLにしてからメールアドレスを確定させる
set ocidQRContents to refMe's NSString's stringWithString:(strQRContents)
###改行とタブだけは取っておく
set ocidQRContentsM to refMe's NSMutableString's alloc()'s initWithCapacity:(0)
ocidQRContentsM's setString:(ocidQRContents)
set ocidQRContentsM to ocidQRContentsM's stringByReplacingOccurrencesOfString:("\n") withString:("")
set ocidQRContentsM to ocidQRContentsM's stringByReplacingOccurrencesOfString:("\r") withString:("")
set ocidQRContentsM to ocidQRContentsM's stringByReplacingOccurrencesOfString:("\t") withString:("")
set ocidURL to refMe's NSURL's alloc()'s initWithString:(ocidQRContentsM)
###
set ocidComponent to refMe's NSURLComponents's componentsWithURL:(ocidURL) resolvingAgainstBaseURL:(false)
set strEmailAdd to ocidComponent's |path|() as text
set strURL to ocidURL's absoluteString() as text
###
set strQRstrings to ("MATMSG:TO:" & strURL & ";") as text
#CCとBCCは対応していない様子
# set strQRstrings to (strQRstrings & "CC:qzu04435@nifty.com;") as text
# set strQRstrings to (strQRstrings & "BCC:qzu04435@nifty.com;") as text
###件名が必要な場合
set strQRstrings to (strQRstrings & "SUB:" & strSubject & ";") as text
###本文書き出しが必要な場合
set strQRstrings to (strQRstrings & "BODY:" & strBody & ";") as text
set strQRstrings to (strQRstrings & ";") as text

###保存ファイル名
set strDateNo to doGetDateNo({"yyyyMMddhhmmss", 1})
set strSaveFileName to ("MATMSG" & "." & strEmailAdd & "." & strDateNo & ".png") as text
set ocidSaveFilePathURL to ocidSaveDirPathURL's URLByAppendingPathComponent:(strSaveFileName)
######################################
### 色決め 切り捨ての都合上指定のニア
######################################
tell application "Finder"
  set the listRGB16bitColor to (choose color default color {0, 0, 0, 1}) as list
end tell
##########Color Picker Value 16Bit
set numRcolor16Bit to item 1 of listRGB16bitColor as number
set numGcolor16Bit to item 2 of listRGB16bitColor as number
set numBcolor16Bit to item 3 of listRGB16bitColor as number
set numAcolor16Bit to 65535 as number
##########Standard RGB Value 8Bit
set numRcolor8Bit to numRcolor16Bit / 256 div 1 as number
set numGcolor8Bit to numGcolor16Bit / 256 div 1 as number
set numBcolor8Bit to numBcolor16Bit / 256 div 1 as number
set numAcolor8Bit to numAcolor16Bit / 256 div 1 as number
##########NSColorValue Float
set numRcolorFloat to numRcolor8Bit / 255 as number
set numGcolorFloat to numGcolor8Bit / 255 as number
set numBcolorFloat to numBcolor8Bit / 255 as number
set numAcolorFloat to numAcolor8Bit / 255 as number
####色指定
## 色指定値はこちらを利用
## https://quicktimer.cocolog-nifty.com/icefloe/2023/06/post-d68270.html
###色指定する場合
## set ocidQrColor to refMe's CIColor's colorWithRed:0.101960784314 green:0.752941176471 blue:0.262745098039 alpha:1.0
###
set ocidQrColor to refMe's CIColor's colorWithRed:(numRcolorFloat) green:(numGcolorFloat) blue:(numBcolorFloat) alpha:(numAcolorFloat)
#############################
### 【1】QRバーコード画像生成
#############################
####テキストをNSStringに
set ocidInputString to refMe's NSString's stringWithString:(strQRstrings)
####テキストをUTF8に
set ocidUtf8InputString to ocidInputString's dataUsingEncoding:(refMe's NSUTF8StringEncoding)
####CIQRCodeGenerator初期化
set ocidQRcodeImage to refMe's CIFilter's filterWithName:"CIQRCodeGenerator"
ocidQRcodeImage's setDefaults()
###テキスト設定
ocidQRcodeImage's setValue:ocidUtf8InputString forKey:"inputMessage"
###読み取り誤差値設定L, M, Q, H
ocidQRcodeImage's setValue:"Q" forKey:"inputCorrectionLevel"
###QRコード本体のイメージ
set ocidCIImage to ocidQRcodeImage's outputImage()
-->ここで生成されるのはQRのセルが1x1pxの最小サイズ
##############
### 色の置き換え
### 置き換わる色=この場合は黒
set ocidBlackColor to refMe's CIColor's colorWithRed:1.0 green:1.0 blue:1.0 alpha:0.0
###CIFalseColorで色を塗ります
set ocidFilterColor to refMe's CIFilter's filterWithName:("CIFalseColor")
ocidFilterColor's setDefaults()
ocidFilterColor's setValue:ocidQrColor forKey:("inputColor0")
ocidFilterColor's setValue:ocidBlackColor forKey:("inputColor1")
ocidFilterColor's setValue:ocidCIImage forKey:("inputImage")
###フィルタをかけた画像をoutputImageから取り出します
set ocidCIImage to ocidFilterColor's valueForKey:("outputImage")
###QRコードの縦横取得
set ocidCIImageDimension to ocidCIImage's extent()
set ocidCIImageWidth to (item 1 of item 2 of ocidCIImageDimension) as integer
set ocidCIImageHight to (item 2 of item 2 of ocidCIImageDimension) as integer
###最終的に出力したいpxサイズ
set numScaleMax to 500
###整数で拡大しないとアレなので↑の値のニアなサイズになります
set numWidth to ((numScaleMax / ocidCIImageWidth) div 1) as integer
set numHight to ((numScaleMax / ocidCIImageHight) div 1) as integer
###↑サイズの拡大縮小する場合はここで値を調整すれば良い
####変換スケール作成-->拡大
set recordScalse to refMe's CGAffineTransform's CGAffineTransformMakeScale(numWidth, numHight)
##変換スケールを適応(元のサイズに元のサイズのスケール適応しても意味ないけど
set ocidCIImageScaled to ocidCIImage's imageByApplyingTransform:(recordScalse)
#######元のセルが1x1pxの最小サイズで出したいときはここで処理
##set ocidCIImageScaled to ocidCIImage
###イメージデータを展開
set ocidNSCIImageRep to refMe's NSCIImageRep's imageRepWithCIImage:(ocidCIImageScaled)
###出力用のイメージの初期化
set ocidNSImageScaled to refMe's NSImage's alloc()'s initWithSize:(ocidNSCIImageRep's |size|())
###イメージデータを合成
ocidNSImageScaled's addRepresentation:(ocidNSCIImageRep)
###出来上がったデータはOS_dispatch_data
set ocidOsDispatchData to ocidNSImageScaled's TIFFRepresentation()
####NSBitmapImageRepに
set ocidQRImageRep to refMe's NSBitmapImageRep's imageRepWithData:(ocidOsDispatchData)

#############################
### 【2】QRコードの背景部
###(ホワイトスペースパディング配慮)
#############################
##画像サイズ
set numQRSize to 520 as integer
##画像生成開始
set ocidBitmapFormat to refMe's NSBitmapFormatAlphaFirst
set ocidColorSpaceName to refMe's NSCalibratedRGBColorSpace
### NSBitmapImageRep
set ocidCodeBaseRep to (refMe's NSBitmapImageRep's alloc()'s initWithBitmapDataPlanes:(missing value) pixelsWide:(numQRSize) pixelsHigh:(numQRSize) bitsPerSample:8 samplesPerPixel:4 hasAlpha:true isPlanar:false colorSpaceName:(ocidColorSpaceName) bitmapFormat:(ocidBitmapFormat) bytesPerRow:0 bitsPerPixel:32)
#############################
### 初期化 CodeBase
refMe's NSGraphicsContext's saveGraphicsState()
###Context
set ocidContext to (refMe's NSGraphicsContext's graphicsContextWithBitmapImageRep:(ocidCodeBaseRep))
###生成された画像でNSGraphicsContext初期化
(refMe's NSGraphicsContext's setCurrentContext:(ocidContext))
###ここが背景色の塗り色
##色を個別に指定する場合 値は0が暗 1が明
set ocidSetColor to (refMe's NSColor's colorWithSRGBRed:(1) green:(1) blue:(1) alpha:(1.0))
ocidSetColor's |set|()
###画像生成
refMe's NSRectFill({origin:{x:0, y:0}, |size|:{width:(numQRSize), height:(numQRSize)}})
####画像作成終了
refMe's NSGraphicsContext's restoreGraphicsState()
#############################
### 【3】QRバーコードパディング処理
### 1で作ったQRバーコード画像を
### 2で作った画像にペースト
###(ホワイトスペースパディング配慮)
#############################
###
set numPxWidth to ocidQRImageRep's pixelsWide()
set numPxHight to ocidQRImageRep's pixelsHigh()
###画像合成位置計算パディング配慮
set numPadSize to (numQRSize - numPxWidth) / 2 as integer
#############################
### 初期化 CodeBase
refMe's NSGraphicsContext's saveGraphicsState()
###Context
set ocidContext to (refMe's NSGraphicsContext's graphicsContextWithBitmapImageRep:(ocidCodeBaseRep))
###生成された画像でNSGraphicsContext初期化
(refMe's NSGraphicsContext's setCurrentContext:(ocidContext))
###出来上がった画像にQRバーコードをCompositeSourceOverする
ocidQRImageRep's drawInRect:{origin:{x:(numPadSize), y:(numPadSize)}, |size|:{width:(numPxWidth), Hight:(numPxWidth)}} fromRect:{origin:{x:0, y:0}, |size|:{width:(numPxWidth), height:(numPxHight)}} operation:(refMe's NSCompositeSourceOver) fraction:1.0 respectFlipped:true hints:(missing value)
####画像作成終了
refMe's NSGraphicsContext's restoreGraphicsState()
#############################
### 【4】最終的な出力画像生成
### ArtBoardになる画像の生成
#############################
### 背景 ARTBORD
set ocidBitmapFormat to refMe's NSBitmapFormatAlphaFirst
set ocidColorSpaceName to refMe's NSCalibratedRGBColorSpace
### NSBitmapImageRep
set ocidArtBoardRep to (refMe's NSBitmapImageRep's alloc()'s initWithBitmapDataPlanes:(missing value) pixelsWide:(580) pixelsHigh:(680) bitsPerSample:8 samplesPerPixel:4 hasAlpha:true isPlanar:false colorSpaceName:(ocidColorSpaceName) bitmapFormat:(ocidBitmapFormat) bytesPerRow:0 bitsPerPixel:32)
#############################
### 初期化 ArtBoard
refMe's NSGraphicsContext's saveGraphicsState()
###Context
set ocidContext to (refMe's NSGraphicsContext's graphicsContextWithBitmapImageRep:(ocidArtBoardRep))
###生成された画像でNSGraphicsContext初期化
(refMe's NSGraphicsContext's setCurrentContext:(ocidContext))
###ここが背景色の塗り色
##色を個別に指定する場合 値は0が暗 1が明
set ocidSetColor to (refMe's NSColor's colorWithSRGBRed:(numRcolorFloat) green:(numGcolorFloat) blue:(numBcolorFloat) alpha:(numAcolorFloat))
## 透過の場合
## set ocidSetColor to refMe's NSColor's clearColor()
## 白
## set ocidSetColor to refMe's NSColor's whiteColor()
ocidSetColor's |set|()
###画像生成
refMe's NSRectFill({origin:{x:0, y:0}, |size|:{width:(580), height:(680)}})
####画像作成終了
refMe's NSGraphicsContext's restoreGraphicsState()
#############################
### 【5】QRコードペースト
### 3で作ったパディング済みQRコードを
### 4で作ったArtBoardにペースト
#############################
### 初期化 バーコードを ocidArtBoardRep にペースト
refMe's NSGraphicsContext's saveGraphicsState()
###ビットマップイメージ
(refMe's NSGraphicsContext's setCurrentContext:(refMe's NSGraphicsContext's graphicsContextWithBitmapImageRep:(ocidArtBoardRep)))
###画像合成位置計算
###左右位置センタリング
set numLeftPad to ((580 - numQRSize) / 2) as integer
###左右のパディング幅と同じサイズで上部パディング
set numbottomPad to (680 - numQRSize - numLeftPad)
###出来上がった画像にQRバーコードを左右3セル分ずらした位置にCompositeSourceOverする
ocidCodeBaseRep's drawInRect:{origin:{x:(numLeftPad), y:(numbottomPad)}, |size|:{width:numQRSize, Hight:numQRSize}} fromRect:{origin:{x:0, y:0}, |size|:{width:numQRSize, height:numQRSize}} operation:(refMe's NSCompositeSourceOver) fraction:1.0 respectFlipped:true hints:(missing value)
####画像作成終了
refMe's NSGraphicsContext's restoreGraphicsState()
#############################
### 【6】テキスト描画
### 5で生成された画像に対して
### テキスト画像を描画する
#############################
###フォント初期化
set appFontManager to refMe's NSFontManager
set appSharedMaanager to appFontManager's sharedFontManager()
###設定用のレコード
set ocidTextAttr to (refMe's NSMutableDictionary's alloc()'s initWithCapacity:0)
###共通項目
set ocidStyle to refMe's NSParagraphStyle's defaultParagraphStyle
(ocidTextAttr's setObject:(ocidStyle) forKey:(refMe's NSParagraphStyleAttributeName))
###画像の明暗判定
set numColorBD to (numRcolorFloat + numGcolorFloat + numBcolorFloat + numAcolorFloat) as number
log numColorBD
if numColorBD > 3.5 then
  ##明るいバーコード色の時は文字色は黒
  set ocidTextColor to (refMe's NSColor's colorWithSRGBRed:(0) green:(0) blue:(0) alpha:(1.0))
(ocidTextAttr's setObject:(ocidTextColor) forKey:(refMe's NSForegroundColorAttributeName))
  ##文字色黒の時はドロップシャドウを入れる
  set ocidShadow to refMe's NSShadow's alloc()'s init()
  set ocidShadowColor to (ocidTextColor's colorWithAlphaComponent:0.8)
(ocidShadow's setShadowColor:(ocidShadowColor))
(ocidShadow's setShadowOffset:(refMe's NSMakeSize(1, -1)))
(ocidShadow's setShadowBlurRadius:4)
(ocidTextAttr's setObject:(ocidShadow) forKey:(refMe's NSShadowAttributeName))
else
  ##暗いバーコード色の時は文字色白
  set ocidTextColor to (refMe's NSColor's colorWithSRGBRed:(1) green:(1) blue:(1) alpha:(1.0))
(ocidTextAttr's setObject:(ocidTextColor) forKey:(refMe's NSForegroundColorAttributeName))
end if

#############################
###初期化
refMe's NSGraphicsContext's saveGraphicsState()
####NSGraphicsContextは透明アートボード
set ocidContext to (refMe's NSGraphicsContext's graphicsContextWithBitmapImageRep:(ocidArtBoardRep))
###ArtBoardでNSGraphicsContext初期化
(refMe's NSGraphicsContext's setCurrentContext:(ocidContext))
##############
set ocidText to (refMe's NSString's stringWithString:("MATMSG QR"))
set ocidFont to (refMe's NSFont's fontWithName:("Helvetica-Bold") |size|:(52))
(ocidTextAttr's setObject:(ocidFont) forKey:(refMe's NSFontAttributeName))
(ocidTextAttr's setObject:(-1.8) forKey:(refMe's NSKernAttributeName))
set ocidTextOrigin to refMe's NSMakePoint((30), (45))
(ocidText's drawAtPoint:(ocidTextOrigin) withAttributes:(ocidTextAttr))
##############
## set strDrawText to ("mailto:" & strQRContents) as text
set ocidText to (refMe's NSString's stringWithString:(strEmailAdd))
set ocidFont to (refMe's NSFont's fontWithName:("Menlo-Regular") |size|:(18))
(ocidTextAttr's setObject:(ocidFont) forKey:(refMe's NSFontAttributeName))
(ocidTextAttr's setObject:(0) forKey:(refMe's NSKernAttributeName))
set ocidTextOrigin to refMe's NSMakePoint((33), (20))
(ocidText's drawAtPoint:(ocidTextOrigin) withAttributes:(ocidTextAttr))
(*
ここのキャラクターIDは
こちらを参照してください
https://quicktimer.cocolog-nifty.com/icefloe/cat76056068/index.html
*)
set strIconText to (character id 1049430) as text
set ocidText to (refMe's NSString's stringWithString:(strIconText))
set ocidFont to (refMe's NSFont's fontWithName:("SFPro-Bold") |size|:(72))
(ocidTextAttr's setObject:(ocidFont) forKey:(refMe's NSFontAttributeName))
(ocidTextAttr's setObject:(0) forKey:(refMe's NSKernAttributeName))
set ocidTextOrigin to refMe's NSMakePoint((450), (25))
(ocidText's drawAtPoint:(ocidTextOrigin) withAttributes:(ocidTextAttr))

####画像作成終了
refMe's NSGraphicsContext's restoreGraphicsState()

#############################
### 【7】画像データ保存
### 6で生成された画像に対を
### 指定のフォルダに保存する
#############################
####PNG用の圧縮プロパティ
set ocidNSSingleEntryDictionary to refMe's NSDictionary's dictionaryWithObject:true forKey:(refMe's NSImageInterlaced)
#####出力イメージへ変換
set ocidNSInlineData to (ocidArtBoardRep's representationUsingType:(refMe's NSBitmapImageFileTypePNG) |properties|:ocidNSSingleEntryDictionary)
(*
NSBitmapImageFileTypeJPEG
NSBitmapImageFileTypePNG
NSBitmapImageFileTypeGIF
NSBitmapImageFileTypeBMP
NSBitmapImageFileTypeTIFF
NSBitmapImageFileTypeJPEG2000
*)
### 保存
set ocidOption to (refMe's NSDataWritingAtomic)
set boolDone to ocidNSInlineData's writeToURL:(ocidSaveFilePathURL) options:(ocidOption) |error|:(reference)
set aliasSaveFilePath to (ocidSaveFilePathURL's absoluteURL()) as alias

#############################
### 【8】表示
#############################
###Preview で開く
tell application "Preview"
launch
activate
open file aliasSaveFilePath
end tell
###
#####################
### Finderで保存先を開く
set appSharedWorkspace to refMe's NSWorkspace's sharedWorkspace()
set boolDone to appSharedWorkspace's selectFile:(ocidSaveFilePathURL's |path|()) inFileViewerRootedAtPath:(ocidSaveDirPathURL's |path|())

return true



################################
# 日付 doGetDateNo(argDateFormat,argCalendarNO)
# argCalendarNO 1 NSCalendarIdentifierGregorian 西暦
# argCalendarNO 2 NSCalendarIdentifierJapanese 和暦
################################
to doGetDateNo({argDateFormat, argCalendarNO})
  ##渡された値をテキストで確定させて
  set strDateFormat to argDateFormat as text
  set intCalendarNO to argCalendarNO as integer
  ###日付情報の取得
  set ocidDate to current application's NSDate's |date|()
  ###日付のフォーマットを定義(日本語)
  set ocidFormatterJP to current application's NSDateFormatter's alloc()'s init()
  ###和暦 西暦 カレンダー分岐
  if intCalendarNO = 1 then
    set ocidCalendarID to (current application's NSCalendarIdentifierGregorian)
  else if intCalendarNO = 2 then
    set ocidCalendarID to (current application's NSCalendarIdentifierJapanese)
  else
    set ocidCalendarID to (current application's NSCalendarIdentifierISO8601)
  end if
  set ocidCalendarJP to current application's NSCalendar's alloc()'s initWithCalendarIdentifier:(ocidCalendarID)
  set ocidTimezoneJP to current application's NSTimeZone's alloc()'s initWithName:("Asia/Tokyo")
  set ocidLocaleJP to current application's NSLocale's alloc()'s initWithLocaleIdentifier:("ja_JP_POSIX")
  ###設定
ocidFormatterJP's setTimeZone:(ocidTimezoneJP)
ocidFormatterJP's setLocale:(ocidLocaleJP)
ocidFormatterJP's setCalendar:(ocidCalendarJP)
  # ocidFormatterJP's setDateStyle:(current application's NSDateFormatterNoStyle)
  # ocidFormatterJP's setDateStyle:(current application's NSDateFormatterShortStyle)
  # ocidFormatterJP's setDateStyle:(current application's NSDateFormatterMediumStyle)
  # ocidFormatterJP's setDateStyle:(current application's NSDateFormatterLongStyle)
ocidFormatterJP's setDateStyle:(current application's NSDateFormatterFullStyle)
  ###渡された値でフォーマット定義
ocidFormatterJP's setDateFormat:(strDateFormat)
  ###フォーマット適応
  set ocidDateAndTime to ocidFormatterJP's stringFromDate:(ocidDate)
  ###テキストで戻す
  set strDateAndTime to ocidDateAndTime as text
return strDateAndTime
end doGetDateNo


---URLエンコードのサブルーチン
####################################
###### %エンコード
####################################
on doUrlEncode(argText)
  ##テキスト
  set ocidArgText to refMe's NSString's stringWithString:(argText)
  ##キャラクタセットを指定
  set ocidChrSet to refMe's NSCharacterSet's URLQueryAllowedCharacterSet
  ##キャラクタセットで変換
  set ocidArgTextEncoded to ocidArgText's stringByAddingPercentEncodingWithAllowedCharacters:(ocidChrSet)
  ######## 置換 %エンコードの追加処理
  ###置換レコード
  set recordPercentMap to {|+|:"%2B", |=|:"%3D", |&|:"%26", |$|:"%24"} as record
  ###ディクショナリにして
  set ocidPercentMap to refMe's NSDictionary's alloc()'s initWithDictionary:(recordPercentMap)
  ###キーの一覧を取り出します
  set ocidAllKeys to ocidPercentMap's allKeys()
  ###取り出したキー一覧を順番に処理
  repeat with itemAllKey in ocidAllKeys
    ##キーの値を取り出して
    set ocidMapValue to (ocidPercentMap's valueForKey:(itemAllKey))
    ##置換
    set ocidEncodedText to (ocidArgTextEncoded's stringByReplacingOccurrencesOfString:(itemAllKey) withString:(ocidMapValue))
    ##次の変換に備える
    set ocidArgTextEncoded to ocidEncodedText
  end repeat
  ##テキスト形式に確定
  set strTextToEncode to ocidEncodedText as text
  ###値を戻す
return strTextToEncode
end doUrlEncode


|

[Event]ICSカレンダーイベント送信用バーコード (CoreImage利用 背景配色あり)


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

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
(* 使用フォント
San Francisco SF Pro
https://developer.apple.com/fonts/ 
*)
# 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 "CoreImage"
use scripting additions

property refMe : a reference to current application
property refNSNotFound : a reference to 9.22337203685477E+18 + 5807


#####################
set appFileManager to refMe's NSFileManager's defaultManager()
###ダイアログのデフォルトロケーション
set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSDesktopDirectory) inDomains:(refMe's NSUserDomainMask))
set ocidDesktopDirPathURL to ocidURLsArray's firstObject()
set aliasDefaultLocation to (ocidDesktopDirPathURL's absoluteURL()) as alias
#######
###ダイアログ
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 strPrompt to "QRコードを作成します。"
set strMes to "QRコードを作成します。"

set listUTI to {"public.vcard", "com.apple.ical.ics", "public.calendar-event", "public.ics", "com.apple.ical.vcs"} as list
set aliasFilePath to (choose file strMes with prompt strPrompt default location (aliasDefaultLocation) of type listUTI without invisibles, showing package contents and multiple selections allowed) as alias

#####################
### カレンダーファイルのパス
set strFilePath to (POSIX path of aliasFilePath) 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 listReadString to refMe's NSString's alloc()'s initWithContentsOfURL:(ocidFilePathURL) encoding:(refMe's NSUTF8StringEncoding) |error|:(reference)
set ocidReadString to (item 1 of listReadString)
#####################
### EVENTデータ整形
set strChl to "BEGIN:VEVENT" as text
###
set ocidChrSet to refMe's NSCharacterSet's newlineCharacterSet()
set ocidStringsArray to ocidReadString's componentsSeparatedByCharactersInSet:(ocidChrSet)
###
set codiPridic to refMe's NSPredicate's predicateWithFormat_("(SELF BEGINSWITH %@)", "DTSTART;")
set ocidDTSTART to ocidStringsArray's filteredArrayUsingPredicate:(codiPridic)
set strDTSTART to ocidDTSTART as text

set AppleScript's text item delimiters to ":"
set listDTSTART to every text item of strDTSTART
set AppleScript's text item delimiters to ""
set strDateAndTimeNo to item 2 of listDTSTART

###
if (count of ocidDTSTART) = 0 then
return "【エラー】イベントの開始日時を取得出来ませんでした"
else
  set ocidStartDateArray to (ocidDTSTART's firstObject())'s componentsSeparatedByString:(":")
  set strStartDate to (last item of ocidStartDateArray) as list
  ##ファイル名に開始日時を使う
  ## set strSaveFileName to ("eventQR_" & strStartDate & ".png") as text
  ## set ocidSaveFilePathURL to ocidSaveDirPathURL's URLByAppendingPathComponent:(strSaveFileName)
  ##
  set strChl to (strChl & "\n" & (ocidDTSTART's firstObject() as text)) as text
end if
####
set codiPridic to refMe's NSPredicate's predicateWithFormat_("(SELF BEGINSWITH %@)", "SEQUENCE")
set ocidSEQUENCE to ocidStringsArray's filteredArrayUsingPredicate:(codiPridic)
if (count of ocidSEQUENCE) > 0 then
  set strChl to (strChl & "\n" & (ocidSEQUENCE's firstObject() as text)) as text
end if
##
set codiPridic to refMe's NSPredicate's predicateWithFormat_("(SELF BEGINSWITH %@)", "LOCATION")
set ocidLOCATION to ocidStringsArray's filteredArrayUsingPredicate:(codiPridic)
if (count of ocidLOCATION) > 0 then
  set strChl to (strChl & "\n" & (ocidLOCATION's firstObject() as text)) as text
end if
##
set codiPridic to refMe's NSPredicate's predicateWithFormat_("(SELF BEGINSWITH %@)", "DESCRIPTION")
set ocidDESCRIPTION to ocidStringsArray's filteredArrayUsingPredicate:(codiPridic)
if (count of ocidDESCRIPTION) > 0 then
  set strChl to (strChl & "\n" & (ocidDESCRIPTION's firstObject() as text)) as text
end if
##
set codiPridic to refMe's NSPredicate's predicateWithFormat_("(SELF BEGINSWITH %@)", "SUMMARY")
set ocidSUMMARY to ocidStringsArray's filteredArrayUsingPredicate:(codiPridic)
if (count of ocidSUMMARY) > 0 then
  set strChl to (strChl & "\n" & (ocidSUMMARY's firstObject() as text)) as text
end if
##
set codiPridic to refMe's NSPredicate's predicateWithFormat_("(SELF BEGINSWITH %@)", "URL")
set ocidURL to ocidStringsArray's filteredArrayUsingPredicate:(codiPridic)
if (count of ocidURL) > 0 then
  set strChl to (strChl & "\n" & (ocidURL's firstObject() as text)) as text
end if
##
set codiPridic to refMe's NSPredicate's predicateWithFormat_("(SELF BEGINSWITH %@)", "DTEND")
set ocidDTEND to ocidStringsArray's filteredArrayUsingPredicate:(codiPridic)
if (count of ocidDTEND) > 0 then
  set strChl to (strChl & "\n" & (ocidDTEND's firstObject() as text)) as text
end if
##
set strQRContents to (strChl & "\n" & "END:VEVENT") as text

#####################
###出来上がったEventテキスト
set ocidInputString to refMe's NSString's stringWithString:(strChl)

######################################
### 色決め 切り捨ての都合上指定のニア
######################################
tell application "Finder"
  set the listRGB16bitColor to (choose color default color {0, 0, 0, 1}) as list
end tell
##########Color Picker Value 16Bit
set numRcolor16Bit to item 1 of listRGB16bitColor as number
set numGcolor16Bit to item 2 of listRGB16bitColor as number
set numBcolor16Bit to item 3 of listRGB16bitColor as number
set numAcolor16Bit to 65535 as number
##########Standard RGB Value 8Bit
set numRcolor8Bit to numRcolor16Bit / 256 div 1 as number
set numGcolor8Bit to numGcolor16Bit / 256 div 1 as number
set numBcolor8Bit to numBcolor16Bit / 256 div 1 as number
set numAcolor8Bit to numAcolor16Bit / 256 div 1 as number
##########NSColorValue Float
set numRcolorFloat to numRcolor8Bit / 255 as number
set numGcolorFloat to numGcolor8Bit / 255 as number
set numBcolorFloat to numBcolor8Bit / 255 as number
set numAcolorFloat to numAcolor8Bit / 255 as number
####色指定
## 色指定値はこちらを利用
## https://quicktimer.cocolog-nifty.com/icefloe/2023/06/post-d68270.html
###色指定する場合
## set ocidQrColor to refMe's CIColor's colorWithRed:0.101960784314 green:0.752941176471 blue:0.262745098039 alpha:1.0
###
set ocidQrColor to refMe's CIColor's colorWithRed:(numRcolorFloat) green:(numGcolorFloat) blue:(numBcolorFloat) alpha:(numAcolorFloat)
#############################
### 【1】QRバーコード画像生成
#############################
####テキストをNSStringに
set ocidInputString to refMe's NSString's stringWithString:(strQRContents)
####テキストをUTF8に
set ocidUtf8InputString to ocidInputString's dataUsingEncoding:(refMe's NSUTF8StringEncoding)
####CIQRCodeGenerator初期化
set ocidQRcodeImage to refMe's CIFilter's filterWithName:"CIQRCodeGenerator"
ocidQRcodeImage's setDefaults()
###テキスト設定
ocidQRcodeImage's setValue:ocidUtf8InputString forKey:"inputMessage"
###読み取り誤差値設定L, M, Q, H
ocidQRcodeImage's setValue:"Q" forKey:"inputCorrectionLevel"
###QRコード本体のイメージ
set ocidCIImage to ocidQRcodeImage's outputImage()
-->ここで生成されるのはQRのセルが1x1pxの最小サイズ
##############
### 色の置き換え
### 置き換わる色=この場合は黒
set ocidBlackColor to refMe's CIColor's colorWithRed:1.0 green:1.0 blue:1.0 alpha:0.0
###CIFalseColorで色を塗ります
set ocidFilterColor to refMe's CIFilter's filterWithName:("CIFalseColor")
ocidFilterColor's setDefaults()
ocidFilterColor's setValue:ocidQrColor forKey:("inputColor0")
ocidFilterColor's setValue:ocidBlackColor forKey:("inputColor1")
ocidFilterColor's setValue:ocidCIImage forKey:("inputImage")
###フィルタをかけた画像をoutputImageから取り出します
set ocidCIImage to ocidFilterColor's valueForKey:("outputImage")
###QRコードの縦横取得
set ocidCIImageDimension to ocidCIImage's extent()
set ocidCIImageWidth to (item 1 of item 2 of ocidCIImageDimension) as integer
set ocidCIImageHight to (item 2 of item 2 of ocidCIImageDimension) as integer
###最終的に出力したいpxサイズ
set numScaleMax to 500
###整数で拡大しないとアレなので↑の値のニアなサイズになります
set numWidth to ((numScaleMax / ocidCIImageWidth) div 1) as integer
set numHight to ((numScaleMax / ocidCIImageHight) div 1) as integer
###↑サイズの拡大縮小する場合はここで値を調整すれば良い
####変換スケール作成-->拡大
set recordScalse to refMe's CGAffineTransform's CGAffineTransformMakeScale(numWidth, numHight)
##変換スケールを適応(元のサイズに元のサイズのスケール適応しても意味ないけど
set ocidCIImageScaled to ocidCIImage's imageByApplyingTransform:(recordScalse)
#######元のセルが1x1pxの最小サイズで出したいときはここで処理
##set ocidCIImageScaled to ocidCIImage
###イメージデータを展開
set ocidNSCIImageRep to refMe's NSCIImageRep's imageRepWithCIImage:(ocidCIImageScaled)
###出力用のイメージの初期化
set ocidNSImageScaled to refMe's NSImage's alloc()'s initWithSize:(ocidNSCIImageRep's |size|())
###イメージデータを合成
ocidNSImageScaled's addRepresentation:(ocidNSCIImageRep)
###出来上がったデータはOS_dispatch_data
set ocidOsDispatchData to ocidNSImageScaled's TIFFRepresentation()
####NSBitmapImageRepに
set ocidQRImageRep to refMe's NSBitmapImageRep's imageRepWithData:(ocidOsDispatchData)

#############################
### 【2】QRコードの背景部
###(ホワイトスペースパディング配慮)
#############################
##画像サイズ
set numQRSize to 520 as integer
##画像生成開始
set ocidBitmapFormat to refMe's NSBitmapFormatAlphaFirst
set ocidColorSpaceName to refMe's NSCalibratedRGBColorSpace
### NSBitmapImageRep
set ocidCodeBaseRep to (refMe's NSBitmapImageRep's alloc()'s initWithBitmapDataPlanes:(missing value) pixelsWide:(numQRSize) pixelsHigh:(numQRSize) bitsPerSample:8 samplesPerPixel:4 hasAlpha:true isPlanar:false colorSpaceName:(ocidColorSpaceName) bitmapFormat:(ocidBitmapFormat) bytesPerRow:0 bitsPerPixel:32)
#############################
### 初期化 CodeBase
refMe's NSGraphicsContext's saveGraphicsState()
###Context
set ocidContext to (refMe's NSGraphicsContext's graphicsContextWithBitmapImageRep:(ocidCodeBaseRep))
###生成された画像でNSGraphicsContext初期化
(refMe's NSGraphicsContext's setCurrentContext:(ocidContext))
###ここが背景色の塗り色
##色を個別に指定する場合 値は0が暗 1が明
set ocidSetColor to (refMe's NSColor's colorWithSRGBRed:(1) green:(1) blue:(1) alpha:(1.0))
ocidSetColor's |set|()
###画像生成
refMe's NSRectFill({origin:{x:0, y:0}, |size|:{width:(numQRSize), height:(numQRSize)}})
####画像作成終了
refMe's NSGraphicsContext's restoreGraphicsState()
#############################
### 【3】QRバーコードパディング処理
### 1で作ったQRバーコード画像を
### 2で作った画像にペースト
###(ホワイトスペースパディング配慮)
#############################
###
set numPxWidth to ocidQRImageRep's pixelsWide()
set numPxHight to ocidQRImageRep's pixelsHigh()
###画像合成位置計算パディング配慮
set numPadSize to (numQRSize - numPxWidth) / 2 as integer
#############################
### 初期化 CodeBase
refMe's NSGraphicsContext's saveGraphicsState()
###Context
set ocidContext to (refMe's NSGraphicsContext's graphicsContextWithBitmapImageRep:(ocidCodeBaseRep))
###生成された画像でNSGraphicsContext初期化
(refMe's NSGraphicsContext's setCurrentContext:(ocidContext))
###出来上がった画像にQRバーコードをCompositeSourceOverする
ocidQRImageRep's drawInRect:{origin:{x:(numPadSize), y:(numPadSize)}, |size|:{width:(numPxWidth), Hight:(numPxWidth)}} fromRect:{origin:{x:0, y:0}, |size|:{width:(numPxWidth), height:(numPxHight)}} operation:(refMe's NSCompositeSourceOver) fraction:1.0 respectFlipped:true hints:(missing value)
####画像作成終了
refMe's NSGraphicsContext's restoreGraphicsState()
#############################
### 【4】最終的な出力画像生成
### ArtBoardになる画像の生成
#############################
### 背景 ARTBORD
set ocidBitmapFormat to refMe's NSBitmapFormatAlphaFirst
set ocidColorSpaceName to refMe's NSCalibratedRGBColorSpace
### NSBitmapImageRep
set ocidArtBoardRep to (refMe's NSBitmapImageRep's alloc()'s initWithBitmapDataPlanes:(missing value) pixelsWide:(580) pixelsHigh:(680) bitsPerSample:8 samplesPerPixel:4 hasAlpha:true isPlanar:false colorSpaceName:(ocidColorSpaceName) bitmapFormat:(ocidBitmapFormat) bytesPerRow:0 bitsPerPixel:32)
#############################
### 初期化 ArtBoard
refMe's NSGraphicsContext's saveGraphicsState()
###Context
set ocidContext to (refMe's NSGraphicsContext's graphicsContextWithBitmapImageRep:(ocidArtBoardRep))
###生成された画像でNSGraphicsContext初期化
(refMe's NSGraphicsContext's setCurrentContext:(ocidContext))
###ここが背景色の塗り色
##色を個別に指定する場合 値は0が暗 1が明
set ocidSetColor to (refMe's NSColor's colorWithSRGBRed:(numRcolorFloat) green:(numGcolorFloat) blue:(numBcolorFloat) alpha:(numAcolorFloat))
## 透過の場合
## set ocidSetColor to refMe's NSColor's clearColor()
## 白
## set ocidSetColor to refMe's NSColor's whiteColor()
ocidSetColor's |set|()
###画像生成
refMe's NSRectFill({origin:{x:0, y:0}, |size|:{width:(580), height:(680)}})
####画像作成終了
refMe's NSGraphicsContext's restoreGraphicsState()
#############################
### 【5】QRコードペースト
### 3で作ったパディング済みQRコードを
### 4で作ったArtBoardにペースト
#############################
### 初期化 バーコードを ocidArtBoardRep にペースト
refMe's NSGraphicsContext's saveGraphicsState()
###ビットマップイメージ
(refMe's NSGraphicsContext's setCurrentContext:(refMe's NSGraphicsContext's graphicsContextWithBitmapImageRep:(ocidArtBoardRep)))
###画像合成位置計算
###左右位置センタリング
set numLeftPad to ((580 - numQRSize) / 2) as integer
###左右のパディング幅と同じサイズで上部パディング
set numbottomPad to (680 - numQRSize - numLeftPad)
###出来上がった画像にQRバーコードを左右3セル分ずらした位置にCompositeSourceOverする
ocidCodeBaseRep's drawInRect:{origin:{x:(numLeftPad), y:(numbottomPad)}, |size|:{width:numQRSize, Hight:numQRSize}} fromRect:{origin:{x:0, y:0}, |size|:{width:numQRSize, height:numQRSize}} operation:(refMe's NSCompositeSourceOver) fraction:1.0 respectFlipped:true hints:(missing value)
####画像作成終了
refMe's NSGraphicsContext's restoreGraphicsState()
#############################
### 【6】テキスト描画
### 5で生成された画像に対して
### テキスト画像を描画する
#############################
###フォント初期化
set appFontManager to refMe's NSFontManager
set appSharedMaanager to appFontManager's sharedFontManager()
###設定用のレコード
set ocidTextAttr to (refMe's NSMutableDictionary's alloc()'s initWithCapacity:0)
###共通項目
set ocidStyle to refMe's NSParagraphStyle's defaultParagraphStyle
(ocidTextAttr's setObject:(ocidStyle) forKey:(refMe's NSParagraphStyleAttributeName))
###画像の明暗判定
set numColorBD to (numRcolorFloat + numGcolorFloat + numBcolorFloat + numAcolorFloat) as number
log numColorBD
if numColorBD > 3.5 then
  ##明るいバーコード色の時は文字色は黒
  set ocidTextColor to (refMe's NSColor's colorWithSRGBRed:(0) green:(0) blue:(0) alpha:(1.0))
(ocidTextAttr's setObject:(ocidTextColor) forKey:(refMe's NSForegroundColorAttributeName))
  ##文字色黒の時はドロップシャドウを入れる
  set ocidShadow to refMe's NSShadow's alloc()'s init()
  set ocidShadowColor to (ocidTextColor's colorWithAlphaComponent:0.8)
(ocidShadow's setShadowColor:(ocidShadowColor))
(ocidShadow's setShadowOffset:(refMe's NSMakeSize(1, -1)))
(ocidShadow's setShadowBlurRadius:4)
(ocidTextAttr's setObject:(ocidShadow) forKey:(refMe's NSShadowAttributeName))
else
  ##暗いバーコード色の時は文字色白
  set ocidTextColor to (refMe's NSColor's colorWithSRGBRed:(1) green:(1) blue:(1) alpha:(1.0))
(ocidTextAttr's setObject:(ocidTextColor) forKey:(refMe's NSForegroundColorAttributeName))
end if

#############################
###初期化
refMe's NSGraphicsContext's saveGraphicsState()
####NSGraphicsContextは透明アートボード
set ocidContext to (refMe's NSGraphicsContext's graphicsContextWithBitmapImageRep:(ocidArtBoardRep))
###ArtBoardでNSGraphicsContext初期化
(refMe's NSGraphicsContext's setCurrentContext:(ocidContext))
##############
set ocidText to (refMe's NSString's stringWithString:("EVENT QR"))
set ocidFont to (refMe's NSFont's fontWithName:("Helvetica-Bold") |size|:(52))
(ocidTextAttr's setObject:(ocidFont) forKey:(refMe's NSFontAttributeName))
(ocidTextAttr's setObject:(-1.8) forKey:(refMe's NSKernAttributeName))
set ocidTextOrigin to refMe's NSMakePoint((30), (45))
(ocidText's drawAtPoint:(ocidTextOrigin) withAttributes:(ocidTextAttr))
##############
set ocidText to (refMe's NSString's stringWithString:(strDateAndTimeNo))
set ocidFont to (refMe's NSFont's fontWithName:("ヒラギノ角ゴシック W3") |size|:(24))
(ocidTextAttr's setObject:(ocidFont) forKey:(refMe's NSFontAttributeName))
(ocidTextAttr's setObject:(-1) forKey:(refMe's NSKernAttributeName))
set ocidTextOrigin to refMe's NSMakePoint((35), (15))
(ocidText's drawAtPoint:(ocidTextOrigin) withAttributes:(ocidTextAttr))
(*
ここのキャラクターIDは
こちらを参照してください
https://quicktimer.cocolog-nifty.com/icefloe/cat76056068/index.html
*)
set strIconText to (character id 1049646) as text
set ocidText to (refMe's NSString's stringWithString:(strIconText))
set ocidFont to (refMe's NSFont's fontWithName:("SFPro-Bold") |size|:(72))
(ocidTextAttr's setObject:(ocidFont) forKey:(refMe's NSFontAttributeName))
(ocidTextAttr's setObject:(0) forKey:(refMe's NSKernAttributeName))
set ocidTextOrigin to refMe's NSMakePoint((460), (20))
(ocidText's drawAtPoint:(ocidTextOrigin) withAttributes:(ocidTextAttr))


####画像作成終了
refMe's NSGraphicsContext's restoreGraphicsState()

#############################
### 【7】画像データ保存
### 6で生成された画像に対を
### 指定のフォルダに保存する
#############################
####PNG用の圧縮プロパティ
set ocidNSSingleEntryDictionary to refMe's NSDictionary's dictionaryWithObject:true forKey:(refMe's NSImageInterlaced)
#####出力イメージへ変換
set ocidNSInlineData to (ocidArtBoardRep's representationUsingType:(refMe's NSBitmapImageFileTypePNG) |properties|:ocidNSSingleEntryDictionary)
(*
NSBitmapImageFileTypeJPEG
NSBitmapImageFileTypePNG
NSBitmapImageFileTypeGIF
NSBitmapImageFileTypeBMP
NSBitmapImageFileTypeTIFF
NSBitmapImageFileTypeJPEG2000
*)

#####################
### QRコード保存先 NSPicturesDirectory
set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSPicturesDirectory) inDomains:(refMe's NSUserDomainMask))
set ocidPicturesDirURL to ocidURLsArray's firstObject()
set ocidSaveDirPathURL to ocidPicturesDirURL's URLByAppendingPathComponent:("QRcode/Event")
##フォルダ作成
set ocidAttrDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
# 777-->511 755-->493 700-->448 766-->502
ocidAttrDict's setValue:(448) forKey:(refMe's NSFilePosixPermissions)
set listBoolMakeDir to appFileManager's createDirectoryAtURL:(ocidSaveDirPathURL) withIntermediateDirectories:true attributes:(ocidAttrDict) |error|:(reference)
###保存ファイル名
set strDateNo to doGetDateNo({"yyyyMMddhhmmss", 1})
set strSaveFileName to ("EVENT." & (strDateAndTimeNo) & ".png") as text
set ocidSaveFilePathURL to ocidSaveDirPathURL's URLByAppendingPathComponent:(strSaveFileName)
### 保存
set ocidOption to (refMe's NSDataWritingAtomic)
set boolDone to ocidNSInlineData's writeToURL:(ocidSaveFilePathURL) options:(ocidOption) |error|:(reference)
set aliasSaveFilePath to (ocidSaveFilePathURL's absoluteURL()) as alias

#############################
### 【8】表示
#############################
###Preview で開く
tell application "Preview"
  launch
  activate
  open file aliasSaveFilePath
end tell
###
#####################
### Finderで保存先を開く
set appSharedWorkspace to refMe's NSWorkspace's sharedWorkspace()
set boolDone to appSharedWorkspace's selectFile:(ocidSaveFilePathURL's |path|()) inFileViewerRootedAtPath:(ocidSaveDirPathURL's |path|())

return true



################################
# 日付 doGetDateNo(argDateFormat,argCalendarNO)
# argCalendarNO 1 NSCalendarIdentifierGregorian 西暦
# argCalendarNO 2 NSCalendarIdentifierJapanese 和暦
################################
to doGetDateNo({argDateFormat, argCalendarNO})
  ##渡された値をテキストで確定させて
  set strDateFormat to argDateFormat as text
  set intCalendarNO to argCalendarNO as integer
  ###日付情報の取得
  set ocidDate to current application's NSDate's |date|()
  ###日付のフォーマットを定義(日本語)
  set ocidFormatterJP to current application's NSDateFormatter's alloc()'s init()
  ###和暦 西暦 カレンダー分岐
  if intCalendarNO = 1 then
    set ocidCalendarID to (current application's NSCalendarIdentifierGregorian)
  else if intCalendarNO = 2 then
    set ocidCalendarID to (current application's NSCalendarIdentifierJapanese)
  else
    set ocidCalendarID to (current application's NSCalendarIdentifierISO8601)
  end if
  set ocidCalendarJP to current application's NSCalendar's alloc()'s initWithCalendarIdentifier:(ocidCalendarID)
  set ocidTimezoneJP to current application's NSTimeZone's alloc()'s initWithName:("Asia/Tokyo")
  set ocidLocaleJP to current application's NSLocale's alloc()'s initWithLocaleIdentifier:("ja_JP_POSIX")
  ###設定
ocidFormatterJP's setTimeZone:(ocidTimezoneJP)
ocidFormatterJP's setLocale:(ocidLocaleJP)
ocidFormatterJP's setCalendar:(ocidCalendarJP)
  # ocidFormatterJP's setDateStyle:(current application's NSDateFormatterNoStyle)
  # ocidFormatterJP's setDateStyle:(current application's NSDateFormatterShortStyle)
  # ocidFormatterJP's setDateStyle:(current application's NSDateFormatterMediumStyle)
  # ocidFormatterJP's setDateStyle:(current application's NSDateFormatterLongStyle)
ocidFormatterJP's setDateStyle:(current application's NSDateFormatterFullStyle)
  ###渡された値でフォーマット定義
ocidFormatterJP's setDateFormat:(strDateFormat)
  ###フォーマット適応
  set ocidDateAndTime to ocidFormatterJP's stringFromDate:(ocidDate)
  ###テキストで戻す
  set strDateAndTime to ocidDateAndTime as text
return strDateAndTime
end doGetDateNo


---URLエンコードのサブルーチン
####################################
###### %エンコード
####################################
on doUrlEncode(argText)
  ##テキスト
  set ocidArgText to refMe's NSString's stringWithString:(argText)
  ##キャラクタセットを指定
  set ocidChrSet to refMe's NSCharacterSet's URLQueryAllowedCharacterSet
  ##キャラクタセットで変換
  set ocidArgTextEncoded to ocidArgText's stringByAddingPercentEncodingWithAllowedCharacters:(ocidChrSet)
  ######## 置換 %エンコードの追加処理
  ###置換レコード
  set recordPercentMap to {|+|:"%2B", |=|:"%3D", |&|:"%26", |$|:"%24"} as record
  ###ディクショナリにして
  set ocidPercentMap to refMe's NSDictionary's alloc()'s initWithDictionary:(recordPercentMap)
  ###キーの一覧を取り出します
  set ocidAllKeys to ocidPercentMap's allKeys()
  ###取り出したキー一覧を順番に処理
  repeat with itemAllKey in ocidAllKeys
    ##キーの値を取り出して
    set ocidMapValue to (ocidPercentMap's valueForKey:(itemAllKey))
    ##置換
    set ocidEncodedText to (ocidArgTextEncoded's stringByReplacingOccurrencesOfString:(itemAllKey) withString:(ocidMapValue))
    ##次の変換に備える
    set ocidArgTextEncoded to ocidEncodedText
  end repeat
  ##テキスト形式に確定
  set strTextToEncode to ocidEncodedText as text
  ###値を戻す
return strTextToEncode
end doUrlEncode


|

[Event]ICSカレンダーイベント送信用バーコード (CoreImage利用)


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

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#com.cocolog-nifty.quicktimer.icefloe
(*

ICSファイルからQRコードを生成
イベント登録用のQRを作成します。
QRコードとしては、たぶんiOS専用 

20190714 初回作成
20190715 phpのエラー処理追加
20220106 phpでの%エンコードの処理をpython3に置き換え
20220122 繰り返しイベントのSEQUENCEを追加 処理を一部修正
20230828 python3の処理をocに置換
APIの仕様は
https://developers.google.com/chart/infographics/docs/qr_codes

*)
#
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
use AppleScript version "2.8"
use framework "Foundation"
use framework "AppKit"
use framework "CoreImage"
use scripting additions

property refMe : a reference to current application
property refNSNotFound : a reference to 9.22337203685477E+18 + 5807
#####################
### QRコード保存先 NSPicturesDirectory
set appFileManager to refMe's NSFileManager's defaultManager()
set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSPicturesDirectory) inDomains:(refMe's NSUserDomainMask))
set ocidPicturesDirURL to ocidURLsArray's firstObject()
set ocidSaveDirPathURL to ocidPicturesDirURL's URLByAppendingPathComponent:("QRcode/Event")
##フォルダ作成
set ocidAttrDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
# 777-->511 755-->493 700-->448 766-->502
ocidAttrDict's setValue:(448) forKey:(refMe's NSFilePosixPermissions)
set listBoolMakeDir to appFileManager's createDirectoryAtURL:(ocidSaveDirPathURL) withIntermediateDirectories:true attributes:(ocidAttrDict) |error|:(reference)
#####################
###ダイアログのデフォルトロケーション
set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSDesktopDirectory) inDomains:(refMe's NSUserDomainMask))
set ocidDesktopDirPathURL to ocidURLsArray's firstObject()
set aliasDefaultLocation to (ocidDesktopDirPathURL's absoluteURL()) as alias
#######
###ダイアログ
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 strPrompt to "QRコードを作成します。"
set strMes to "QRコードを作成します。"

set listUTI to {"public.vcard", "com.apple.ical.ics", "public.calendar-event", "public.ics", "com.apple.ical.vcs"} as list
set aliasFilePath to (choose file strMes with prompt strPrompt default location (aliasDefaultLocation) of type listUTI without invisibles, showing package contents and multiple selections allowed) as alias
#####################
### カレンダーファイルのパス
set strFilePath to (POSIX path of aliasFilePath) 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 listReadString to refMe's NSString's alloc()'s initWithContentsOfURL:(ocidFilePathURL) encoding:(refMe's NSUTF8StringEncoding) |error|:(reference)
set ocidReadString to (item 1 of listReadString)
#####################
### EVENTデータ整形
set strChl to "BEGIN:VEVENT" as text
###
set ocidChrSet to refMe's NSCharacterSet's newlineCharacterSet()
set ocidStringsArray to ocidReadString's componentsSeparatedByCharactersInSet:(ocidChrSet)
###
set codiPridic to refMe's NSPredicate's predicateWithFormat_("(SELF BEGINSWITH %@)", "DTSTART;")
set ocidDTSTART to ocidStringsArray's filteredArrayUsingPredicate:(codiPridic)
###
if (count of ocidDTSTART) = 0 then
return "【エラー】イベントの開始日時を取得出来ませんでした"
else
  set ocidStartDateArray to (ocidDTSTART's firstObject())'s componentsSeparatedByString:(":")
  set strStartDate to (last item of ocidStartDateArray) as list
  ##ファイル名に開始日時を使う
  set strSaveFileName to ("eventQR_" & strStartDate & ".png") as text
  set ocidSaveFilePathURL to ocidSaveDirPathURL's URLByAppendingPathComponent:(strSaveFileName)
  ##
  set strChl to (strChl & "\n" & (ocidDTSTART's firstObject() as text)) as text
end if
####
set codiPridic to refMe's NSPredicate's predicateWithFormat_("(SELF BEGINSWITH %@)", "SEQUENCE")
set ocidSEQUENCE to ocidStringsArray's filteredArrayUsingPredicate:(codiPridic)
if (count of ocidSEQUENCE) > 0 then
  set strChl to (strChl & "\n" & (ocidSEQUENCE's firstObject() as text)) as text
end if
##
set codiPridic to refMe's NSPredicate's predicateWithFormat_("(SELF BEGINSWITH %@)", "LOCATION")
set ocidLOCATION to ocidStringsArray's filteredArrayUsingPredicate:(codiPridic)
if (count of ocidLOCATION) > 0 then
  set strChl to (strChl & "\n" & (ocidLOCATION's firstObject() as text)) as text
end if
##
set codiPridic to refMe's NSPredicate's predicateWithFormat_("(SELF BEGINSWITH %@)", "DESCRIPTION")
set ocidDESCRIPTION to ocidStringsArray's filteredArrayUsingPredicate:(codiPridic)
if (count of ocidDESCRIPTION) > 0 then
  set strChl to (strChl & "\n" & (ocidDESCRIPTION's firstObject() as text)) as text
end if
##
set codiPridic to refMe's NSPredicate's predicateWithFormat_("(SELF BEGINSWITH %@)", "SUMMARY")
set ocidSUMMARY to ocidStringsArray's filteredArrayUsingPredicate:(codiPridic)
if (count of ocidSUMMARY) > 0 then
  set strChl to (strChl & "\n" & (ocidSUMMARY's firstObject() as text)) as text
end if
##
set codiPridic to refMe's NSPredicate's predicateWithFormat_("(SELF BEGINSWITH %@)", "URL")
set ocidURL to ocidStringsArray's filteredArrayUsingPredicate:(codiPridic)
if (count of ocidURL) > 0 then
  set strChl to (strChl & "\n" & (ocidURL's firstObject() as text)) as text
end if
##
set codiPridic to refMe's NSPredicate's predicateWithFormat_("(SELF BEGINSWITH %@)", "DTEND")
set ocidDTEND to ocidStringsArray's filteredArrayUsingPredicate:(codiPridic)
if (count of ocidDTEND) > 0 then
  set strChl to (strChl & "\n" & (ocidDTEND's firstObject() as text)) as text
end if
##
set strChl to (strChl & "\n" & "END:VEVENT") as text
#####################
###出来上がったEventテキスト
log strChl
set ocidInputString to refMe's NSString's stringWithString:(strChl)
######################################
### 色決め 切り捨ての都合上指定のニア
######################################
tell application "Finder"
  set the listRGB16bitColor to (choose color default color {0, 0, 0, 1}) as list
end tell
##########Color Picker Value 16Bit
set numRcolor16Bit to item 1 of listRGB16bitColor as number
set numGcolor16Bit to item 2 of listRGB16bitColor as number
set numBcolor16Bit to item 3 of listRGB16bitColor as number
set numAcolor16Bit to 65535 as number
##########Standard RGB Value 8Bit
set numRcolor8Bit to numRcolor16Bit / 256 div 1 as number
set numGcolor8Bit to numGcolor16Bit / 256 div 1 as number
set numBcolor8Bit to numBcolor16Bit / 256 div 1 as number
set numAcolor8Bit to numAcolor16Bit / 256 div 1 as number
##########NSColorValue Float
set numRcolorFloat to numRcolor8Bit / 255 as number
set numGcolorFloat to numGcolor8Bit / 255 as number
set numBcolorFloat to numBcolor8Bit / 255 as number
set numAcolorFloat to numAcolor8Bit / 255 as number
####色指定
## 色指定値はこちらを利用
## https://quicktimer.cocolog-nifty.com/icefloe/2023/06/post-d68270.html
###色指定する場合
## set ocidQrColor to refMe's CIColor's colorWithRed:0.101960784314 green:0.752941176471 blue:0.262745098039 alpha:1.0
###
set ocidQrColor to refMe's CIColor's colorWithRed:numRcolorFloat green:numGcolorFloat blue:numBcolorFloat alpha:numAcolorFloat
############################
####テキストをUTF8に
set ocidUtf8InputString to ocidInputString's dataUsingEncoding:(refMe's NSUTF8StringEncoding)
####CIQRCodeGenerator初期化
set ocidQRcodeImage to refMe's CIFilter's filterWithName:"CIQRCodeGenerator"
ocidQRcodeImage's setDefaults()
###テキスト設定
ocidQRcodeImage's setValue:ocidUtf8InputString forKey:"inputMessage"
###読み取り誤差値設定L, M, Q, H
ocidQRcodeImage's setValue:"Q" forKey:"inputCorrectionLevel"
###QRコード本体のイメージ
set ocidCIImage to ocidQRcodeImage's outputImage()
-->ここで生成されるのはQRのセルが1x1pxの最小サイズ
###################################
#####色の置き換え
###################################

###置き換わる色=この場合は黒
set ocidBlackColor to refMe's CIColor's colorWithRed:1.0 green:1.0 blue:1.0 alpha:0.0
###CIFalseColorで色を塗ります
set ocidFilterColor to refMe's CIFilter's filterWithName:"CIFalseColor"
ocidFilterColor's setDefaults()
ocidFilterColor's setValue:ocidQrColor forKey:"inputColor0"
ocidFilterColor's setValue:ocidBlackColor forKey:"inputColor1"
ocidFilterColor's setValue:ocidCIImage forKey:"inputImage"
###フィルタをかけた画像をoutputImageから取り出します
set ocidCIImage to ocidFilterColor's valueForKey:"outputImage"
###QRコードの縦横取得
set ocidCIImageDimension to ocidCIImage's extent()
set ocidCIImageWidth to (item 1 of item 2 of ocidCIImageDimension) as integer
set ocidCIImageHight to (item 2 of item 2 of ocidCIImageDimension) as integer
###最終的に出力したいpxサイズ
set numScaleMax to 580
###整数で拡大しないとアレなので↑の値のニアなサイズになります
set numWidth to ((numScaleMax / ocidCIImageWidth) div 1) as integer
set numHight to ((numScaleMax / ocidCIImageHight) div 1) as integer
###↑サイズの拡大縮小する場合はここで値を調整すれば良い
####変換スケール作成-->拡大
set recordScalse to refMe's CGAffineTransform's CGAffineTransformMakeScale(numWidth, numHight)
##変換スケールを適応(元のサイズに元のサイズのスケール適応しても意味ないけど
set ocidCIImageScaled to ocidCIImage's imageByApplyingTransform:recordScalse
#######元のセルが1x1pxの最小サイズで出したいときはここで処理
##set ocidCIImageScaled to ocidCIImage
###イメージデータを展開
set ocidNSCIImageRep to refMe's NSCIImageRep's imageRepWithCIImage:ocidCIImageScaled
###出力用のイメージの初期化
set ocidNSImageScaled to refMe's NSImage's alloc()'s initWithSize:(ocidNSCIImageRep's |size|())
###イメージデータを合成
ocidNSImageScaled's addRepresentation:ocidNSCIImageRep
###出来上がったデータはOS_dispatch_data
set ocidOsDispatchData to ocidNSImageScaled's TIFFRepresentation()
####NSBitmapImageRepに
set ocidNSBitmapImageRep to refMe's NSBitmapImageRep's imageRepWithData:ocidOsDispatchData
#################################################################
###quiet zone用に画像をパディングする
set numPadWidth to ((ocidCIImageWidth * numWidth) + (numWidth * 6)) as integer
set numPadHight to ((ocidCIImageHight * numHight) + (numHight * 6)) as integer
###左右に4セル分づつ余白 quiet zoneを足す
####まずは元のQRコードのサイズに8セルサイズ分足したサイズの画像を作って
set ocidNSBitmapImagePadRep to (refMe's NSBitmapImageRep's alloc()'s initWithBitmapDataPlanes:(missing value) pixelsWide:numPadWidth pixelsHigh:numPadHight bitsPerSample:8 samplesPerPixel:4 hasAlpha:true isPlanar:false colorSpaceName:(refMe's NSCalibratedRGBColorSpace) bitmapFormat:(refMe's NSAlphaFirstBitmapFormat) bytesPerRow:0 bitsPerPixel:32)
###初期化
refMe's NSGraphicsContext's saveGraphicsState()
###ビットマップイメージ
(refMe's NSGraphicsContext's setCurrentContext:(refMe's NSGraphicsContext's graphicsContextWithBitmapImageRep:ocidNSBitmapImagePadRep))
###塗り色を『白』に指定して
refMe's NSColor's whiteColor()'s |set|()
###画像にする
refMe's NSRectFill({origin:{x:0, y:0}, |size|:{width:numPadWidth, height:numPadHight}})
###出来上がった画像にQRバーコードを左右3セル分ずらした位置にCompositeSourceOverする
ocidNSBitmapImageRep's drawInRect:{origin:{x:(numWidth * 3), y:(numHight * 3)}, |size|:{width:numPadWidth, Hight:numPadHight}} fromRect:{origin:{x:0, y:0}, |size|:{width:numPadWidth, height:numPadHight}} operation:(refMe's NSCompositeSourceOver) fraction:1.0 respectFlipped:true hints:(missing value)
####画像作成終了
refMe's NSGraphicsContext's restoreGraphicsState()

#################################################################
####JPEG用の圧縮プロパティ
##set ocidNSSingleEntryDictionary to refMe's NSDictionary's dictionaryWithObject:1 forKey:(refMe's NSImageCompressionFactor)
####PNG用の圧縮プロパティ
set ocidNSSingleEntryDictionary to refMe's NSDictionary's dictionaryWithObject:true forKey:(refMe's NSImageInterlaced)

#####出力イメージへ変換
set ocidNSInlineData to (ocidNSBitmapImagePadRep's representationUsingType:(refMe's NSBitmapImageFileTypePNG) |properties|:ocidNSSingleEntryDictionary)
(*
NSBitmapImageFileTypeJPEG
NSBitmapImageFileTypePNG
NSBitmapImageFileTypeGIF
NSBitmapImageFileTypeBMP
NSBitmapImageFileTypeTIFF
NSBitmapImageFileTypeJPEG2000
*)
### 保存
set ocidOption to (refMe's NSDataWritingAtomic)
set boolDone to ocidNSInlineData's writeToURL:(ocidSaveFilePathURL) options:(ocidOption) |error|:(reference)
set aliasSaveFilePath to (ocidSaveFilePathURL's absoluteURL()) as alias
#####################
###Preview で開く
###
tell application "Preview"
  launch
  activate
  open aliasSaveFilePath
end tell

#####################
### Finderで保存先を開く
set appSharedWorkspace to refMe's NSWorkspace's sharedWorkspace()
set boolDone to appSharedWorkspace's selectFile:(ocidSaveFilePathURL's |path|()) inFileViewerRootedAtPath:(ocidSaveDirPathURL's |path|())

---URLエンコードのサブルーチン
####################################
###### %エンコード
####################################
on doUrlEncode(argText)
  ##テキスト
  set ocidArgText to refMe's NSString's stringWithString:(argText)
  ##キャラクタセットを指定
  set ocidChrSet to refMe's NSCharacterSet's URLQueryAllowedCharacterSet
  ##キャラクタセットで変換
  set ocidArgTextEncoded to ocidArgText's stringByAddingPercentEncodingWithAllowedCharacters:(ocidChrSet)
  ######## 置換 %エンコードの追加処理
  ###置換レコード
  set recordPercentMap to {|+|:"%2B", |=|:"%3D", |&|:"%26", |$|:"%24", |\\n|:"%0A", |\\r|:"%0D"} as record
  ###ディクショナリにして
  set ocidPercentMap to refMe's NSDictionary's alloc()'s initWithDictionary:(recordPercentMap)
  ###キーの一覧を取り出します
  set ocidAllKeys to ocidPercentMap's allKeys()
  ###取り出したキー一覧を順番に処理
  repeat with itemAllKey in ocidAllKeys
    ##キーの値を取り出して
    set ocidMapValue to (ocidPercentMap's valueForKey:(itemAllKey))
    ##置換
    set ocidEncodedText to (ocidArgTextEncoded's stringByReplacingOccurrencesOfString:(itemAllKey) withString:(ocidMapValue))
    ##次の変換に備える
    set ocidArgTextEncoded to ocidEncodedText
  end repeat
  ##テキスト形式に確定
  set strTextToEncode to ocidEncodedText as text
  ###値を戻す
return strTextToEncode
end doUrlEncode


|

[Event]ICSカレンダーイベント送信用バーコード (GoogleChart利用)


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

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#com.cocolog-nifty.quicktimer.icefloe
(*

ICSファイルからQRコードを生成
イベント登録用のQRを作成します。
QRコードとしては、たぶんiOS専用 

20190714 初回作成
20190715 phpのエラー処理追加
20220106 phpでの%エンコードの処理をpython3に置き換え
20220122 繰り返しイベントのSEQUENCEを追加 処理を一部修正
20230828 python3の処理をocに置換
APIの仕様は
https://developers.google.com/chart/infographics/docs/qr_codes

*)
#
----+----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 refNSNotFound : a reference to 9.22337203685477E+18 + 5807
#####################
### QRコード保存先 NSPicturesDirectory
set appFileManager to refMe's NSFileManager's defaultManager()
set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSPicturesDirectory) inDomains:(refMe's NSUserDomainMask))
set ocidPicturesDirURL to ocidURLsArray's firstObject()
set ocidSaveDirPathURL to ocidPicturesDirURL's URLByAppendingPathComponent:("QRcode/Event")
##フォルダ作成
set ocidAttrDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
# 777-->511 755-->493 700-->448 766-->502
ocidAttrDict's setValue:(448) forKey:(refMe's NSFilePosixPermissions)
set listBoolMakeDir to appFileManager's createDirectoryAtURL:(ocidSaveDirPathURL) withIntermediateDirectories:true attributes:(ocidAttrDict) |error|:(reference)
#####################
###ダイアログのデフォルトロケーション
set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSDesktopDirectory) inDomains:(refMe's NSUserDomainMask))
set ocidDesktopDirPathURL to ocidURLsArray's firstObject()
set aliasDefaultLocation to (ocidDesktopDirPathURL's absoluteURL()) as alias
#######
###ダイアログ
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 strPrompt to "QRコードを作成します。"
set strMes to "QRコードを作成します。"

set listUTI to {"public.vcard", "com.apple.ical.ics", "public.calendar-event", "public.ics", "com.apple.ical.vcs"} as list
set aliasFilePath to (choose file strMes with prompt strPrompt default location (aliasDefaultLocation) of type listUTI without invisibles, showing package contents and multiple selections allowed) as alias
#####################
### カレンダーファイルのパス
set strFilePath to (POSIX path of aliasFilePath) 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 listReadString to refMe's NSString's alloc()'s initWithContentsOfURL:(ocidFilePathURL) encoding:(refMe's NSUTF8StringEncoding) |error|:(reference)
set ocidReadString to (item 1 of listReadString)
#####################
### EVENTデータ整形
set strChl to "BEGIN:VEVENT" as text
###
set ocidChrSet to refMe's NSCharacterSet's newlineCharacterSet()
set ocidStringsArray to ocidReadString's componentsSeparatedByCharactersInSet:(ocidChrSet)
###
set codiPridic to refMe's NSPredicate's predicateWithFormat_("(SELF BEGINSWITH %@)", "DTSTART;")
set ocidDTSTART to ocidStringsArray's filteredArrayUsingPredicate:(codiPridic)
###
if (count of ocidDTSTART) = 0 then
return "【エラー】イベントの開始日時を取得出来ませんでした"
else
  set ocidStartDateArray to (ocidDTSTART's firstObject())'s componentsSeparatedByString:(":")
  set strStartDate to (last item of ocidStartDateArray) as list
  ##ファイル名に開始日時を使う
  set strSaveFileName to ("eventQR_" & strStartDate & ".png") as text
  set ocidSaveFilePathURL to ocidSaveDirPathURL's URLByAppendingPathComponent:(strSaveFileName)
  ##
  set strChl to (strChl & "\n" & (ocidDTSTART's firstObject() as text)) as text
end if
####
set codiPridic to refMe's NSPredicate's predicateWithFormat_("(SELF BEGINSWITH %@)", "SEQUENCE")
set ocidSEQUENCE to ocidStringsArray's filteredArrayUsingPredicate:(codiPridic)
if (count of ocidSEQUENCE) > 0 then
  set strChl to (strChl & "\n" & (ocidSEQUENCE's firstObject() as text)) as text
end if
##
set codiPridic to refMe's NSPredicate's predicateWithFormat_("(SELF BEGINSWITH %@)", "LOCATION")
set ocidLOCATION to ocidStringsArray's filteredArrayUsingPredicate:(codiPridic)
if (count of ocidLOCATION) > 0 then
  set strChl to (strChl & "\n" & (ocidLOCATION's firstObject() as text)) as text
end if
##
set codiPridic to refMe's NSPredicate's predicateWithFormat_("(SELF BEGINSWITH %@)", "DESCRIPTION")
set ocidDESCRIPTION to ocidStringsArray's filteredArrayUsingPredicate:(codiPridic)
if (count of ocidDESCRIPTION) > 0 then
  set strChl to (strChl & "\n" & (ocidDESCRIPTION's firstObject() as text)) as text
end if
##
set codiPridic to refMe's NSPredicate's predicateWithFormat_("(SELF BEGINSWITH %@)", "SUMMARY")
set ocidSUMMARY to ocidStringsArray's filteredArrayUsingPredicate:(codiPridic)
if (count of ocidSUMMARY) > 0 then
  set strChl to (strChl & "\n" & (ocidSUMMARY's firstObject() as text)) as text
end if
##
set codiPridic to refMe's NSPredicate's predicateWithFormat_("(SELF BEGINSWITH %@)", "URL")
set ocidURL to ocidStringsArray's filteredArrayUsingPredicate:(codiPridic)
if (count of ocidURL) > 0 then
  set strChl to (strChl & "\n" & (ocidURL's firstObject() as text)) as text
end if
##
set codiPridic to refMe's NSPredicate's predicateWithFormat_("(SELF BEGINSWITH %@)", "DTEND")
set ocidDTEND to ocidStringsArray's filteredArrayUsingPredicate:(codiPridic)
if (count of ocidDTEND) > 0 then
  set strChl to (strChl & "\n" & (ocidDTEND's firstObject() as text)) as text
end if
##
set strChl to (strChl & "\n" & "END:VEVENT") as text
#####################
###出来上がったEventテキスト
log strChl
##Vcardの内容テキストエンコード済み
set strChlEnc to doUrlEncode(strChl) as text
##BASE URL
set theApiUrl to "https://chart.googleapis.com/chart?" as text
##API名
set theCht to "qr" as text
##仕上がりサイズpx(72の倍数推奨) 72 144 288 360 576 720 1080
set theChs to "540x540" as text
## テキストのエンコード ガラ携対応するならSJISを選択
set theChoe to "UTF-8" as text
##誤差補正 L M Q R
set theChld to "M" as text
##URLを整形
set strURL to ("" & theApiUrl & "&cht=" & theCht & "&chs=" & theChs & "&choe=" & theChoe & "&chld=" & theChld & "&chl=" & strChlEnc & "") as text
log strURL
#####################
### NSURL
set ocidURLString to refMe's NSString's stringWithString:(strURL)
set ocidURL to refMe's NSURL's alloc()'s initWithString:(ocidURLString)
#####################
### データを読み込む
set ocidOption to (refMe's NSDataReadingMappedIfSafe)
set listReadData to refMe's NSData's alloc()'s initWithContentsOfURL:(ocidURL) options:(ocidOption) |error|:(reference)
set ocidReadData to (item 1 of listReadData)
set ocidOption to (refMe's NSDataWritingAtomic)
### 保存
set boolDone to ocidReadData's writeToURL:(ocidSaveFilePathURL) options:(ocidOption) |error|:(reference)
set strFilePath to ocidSaveFilePathURL's absoluteString() as text

#####################
###サファリで開く
tell application "Safari"
  activate
  make new document with properties {name:"QR-CODE by Google API"}
  tell front window
    open location strFilePath
  end tell
end tell

#####################
### Finderで保存先を開く
set appSharedWorkspace to refMe's NSWorkspace's sharedWorkspace()
set boolDone to appSharedWorkspace's selectFile:(ocidSaveFilePathURL's |path|()) inFileViewerRootedAtPath:(ocidSaveDirPathURL's |path|())

---URLエンコードのサブルーチン
####################################
###### %エンコード
####################################
on doUrlEncode(argText)
  ##テキスト
  set ocidArgText to refMe's NSString's stringWithString:(argText)
  ##キャラクタセットを指定
  set ocidChrSet to refMe's NSCharacterSet's URLQueryAllowedCharacterSet
  ##キャラクタセットで変換
  set ocidArgTextEncoded to ocidArgText's stringByAddingPercentEncodingWithAllowedCharacters:(ocidChrSet)
  ######## 置換 %エンコードの追加処理
  ###置換レコード
  set recordPercentMap to {|+|:"%2B", |=|:"%3D", |&|:"%26", |$|:"%24", |\\n|:"%0A", |\\r|:"%0D"} as record
  ###ディクショナリにして
  set ocidPercentMap to refMe's NSDictionary's alloc()'s initWithDictionary:(recordPercentMap)
  ###キーの一覧を取り出します
  set ocidAllKeys to ocidPercentMap's allKeys()
  ###取り出したキー一覧を順番に処理
  repeat with itemAllKey in ocidAllKeys
    ##キーの値を取り出して
    set ocidMapValue to (ocidPercentMap's valueForKey:(itemAllKey))
    ##置換
    set ocidEncodedText to (ocidArgTextEncoded's stringByReplacingOccurrencesOfString:(itemAllKey) withString:(ocidMapValue))
    ##次の変換に備える
    set ocidArgTextEncoded to ocidEncodedText
  end repeat
  ##テキスト形式に確定
  set strTextToEncode to ocidEncodedText as text
  ###値を戻す
return strTextToEncode
end doUrlEncode


|

[SMS]SMS送信用バーコード (GoogleChart利用)


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

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
(*
APIの仕様は
https://developers.google.com/chart/infographics/docs/qr_codes
*)
#
# 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 "CoreImage"
use scripting additions

property refMe : a reference to current application
property refNotFound : a reference to 9.22337203685477E+18 + 5807

#####################
###設定項目:メッセージの内容
set strDefMes to ("XXXです。アドレス登録用の空メールです")

#####################
### QRコード保存先 NSPicturesDirectory
set appFileManager to refMe's NSFileManager's defaultManager()
set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSPicturesDirectory) inDomains:(refMe's NSUserDomainMask))
set ocidPicturesDirURL to ocidURLsArray's firstObject()
set ocidSaveDirPathURL to ocidPicturesDirURL's URLByAppendingPathComponent:("QRcode/SMS")
##フォルダ作成
set ocidAttrDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
# 777-->511 755-->493 700-->448 766-->502
ocidAttrDict's setValue:(448) forKey:(refMe's NSFilePosixPermissions)
set listBoolMakeDir to appFileManager's createDirectoryAtURL:(ocidSaveDirPathURL) withIntermediateDirectories:true attributes:(ocidAttrDict) |error|:(reference)


#####################
### ペーストボード初期化
set appPasteboard to refMe's NSPasteboard's generalPasteboard()
##ペーストボードからテキストを取り出す
set ocidStringData to appPasteboard's stringForType:("public.utf8-plain-text")
if ocidStringData is (missing value) then
  set strDefaultAnswer to "080" as text
else
  set strDefaultAnswer to (refMe's NSString's stringWithString:(ocidStringData)) as text
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 aliasIconPath to POSIX file "/System/Applications/Messages.app/Contents/Resources/AppIcon.icns" as alias
try
  set objResponse to (display dialog "SMSの送信電番を入力してください" with title "SMS送信用のQRコードを作成します" default answer strDefaultAnswer buttons {"OK", "キャンセル"} default button "OK" cancel button "キャンセル" with icon aliasIconPath giving up after 30 without hidden answer)
on error
  log "エラーしました"
return
end try
if true is equal to (gave up of objResponse) then
return "時間切れですやりなおしてください"
end if
if "OK" is equal to (button returned of objResponse) then
  set strText to (text returned of objResponse) as text
else
return "キャンセル"
end if

##############################
###0以外やエンコードされていない場合の対応
if strText starts with "0" then
  set ocidTelNo to refMe's NSString's alloc()'s initWithString:(strText)
else
return "電番以外は処理しません"
end if
###改行とタブだけは取っておく
set ocidTextM to refMe's NSMutableString's alloc()'s initWithCapacity:(0)
ocidTextM's setString:(ocidTelNo)
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 strTelNo to ocidTextM as text
###保存ファイル名
set strDateNo to doGetDateNo({"yyyyMMddhhmmss", 1})
set strSaveFileName to ("SMS." & strTelNo & "." & strDateNo & ".png") as text
set ocidSaveFilePathURL to ocidSaveDirPathURL's URLByAppendingPathComponent:(strSaveFileName)
#####################
###SMSTOメッセージ
set strSMSTO to "SMSTO:" & strTelNo & ":" & strDefMes as text

#####################
##URLの内容テキストエンコード済み
set strChlEnc to doUrlEncode(strSMSTO) as text
##BASE URL
set theApiUrl to "https://chart.googleapis.com/chart?" as text
##API名
set theCht to "qr" as text
##仕上がりサイズpx(72の倍数推奨) 72 144 288 360 576 720 1080
set theChs to "540x540" as text
## テキストのエンコード ガラ携対応するならSJISを選択
set theChoe to "UTF-8" as text
##誤差補正 L M Q R
set theChld to "M" as text
##URLを整形
set strURL to ("" & theApiUrl & "&cht=" & theCht & "&chs=" & theChs & "&choe=" & theChoe & "&chld=" & theChld & "&chl=" & strChlEnc & "") as text
log strURL
#####################
### NSURL
set ocidURLString to refMe's NSString's stringWithString:(strURL)
set ocidURL to refMe's NSURL's alloc()'s initWithString:(ocidURLString)
#####################
### データを読み込む
set ocidOption to (refMe's NSDataReadingMappedIfSafe)
set listReadData to refMe's NSData's alloc()'s initWithContentsOfURL:(ocidURL) options:(ocidOption) |error|:(reference)
set ocidReadData to (item 1 of listReadData)
set ocidOption to (refMe's NSDataWritingAtomic)
### 保存
set boolDone to ocidReadData's writeToURL:(ocidSaveFilePathURL) options:(ocidOption) |error|:(reference)
set strFilePath to ocidSaveFilePathURL's absoluteString() as text



#####################
###サファリで開く
tell application "Safari"
  activate
  make new document with properties {name:"QR-CODE by Google API"}
  tell front window
    open location strFilePath
  end tell
end tell
###
#####################
### Finderで保存先を開く
set appSharedWorkspace to refMe's NSWorkspace's sharedWorkspace()
set boolDone to appSharedWorkspace's selectFile:(ocidSaveFilePathURL's |path|()) inFileViewerRootedAtPath:(ocidSaveDirPathURL's |path|())

return true



################################
# 日付 doGetDateNo(argDateFormat,argCalendarNO)
# argCalendarNO 1 NSCalendarIdentifierGregorian 西暦
# argCalendarNO 2 NSCalendarIdentifierJapanese 和暦
################################
to doGetDateNo({argDateFormat, argCalendarNO})
  ##渡された値をテキストで確定させて
  set strDateFormat to argDateFormat as text
  set intCalendarNO to argCalendarNO as integer
  ###日付情報の取得
  set ocidDate to current application's NSDate's |date|()
  ###日付のフォーマットを定義(日本語)
  set ocidFormatterJP to current application's NSDateFormatter's alloc()'s init()
  ###和暦 西暦 カレンダー分岐
  if intCalendarNO = 1 then
    set ocidCalendarID to (current application's NSCalendarIdentifierGregorian)
  else if intCalendarNO = 2 then
    set ocidCalendarID to (current application's NSCalendarIdentifierJapanese)
  else
    set ocidCalendarID to (current application's NSCalendarIdentifierISO8601)
  end if
  set ocidCalendarJP to current application's NSCalendar's alloc()'s initWithCalendarIdentifier:(ocidCalendarID)
  set ocidTimezoneJP to current application's NSTimeZone's alloc()'s initWithName:("Asia/Tokyo")
  set ocidLocaleJP to current application's NSLocale's alloc()'s initWithLocaleIdentifier:("ja_JP_POSIX")
  ###設定
ocidFormatterJP's setTimeZone:(ocidTimezoneJP)
ocidFormatterJP's setLocale:(ocidLocaleJP)
ocidFormatterJP's setCalendar:(ocidCalendarJP)
  # ocidFormatterJP's setDateStyle:(current application's NSDateFormatterNoStyle)
  # ocidFormatterJP's setDateStyle:(current application's NSDateFormatterShortStyle)
  # ocidFormatterJP's setDateStyle:(current application's NSDateFormatterMediumStyle)
  # ocidFormatterJP's setDateStyle:(current application's NSDateFormatterLongStyle)
ocidFormatterJP's setDateStyle:(current application's NSDateFormatterFullStyle)
  ###渡された値でフォーマット定義
ocidFormatterJP's setDateFormat:(strDateFormat)
  ###フォーマット適応
  set ocidDateAndTime to ocidFormatterJP's stringFromDate:(ocidDate)
  ###テキストで戻す
  set strDateAndTime to ocidDateAndTime as text
return strDateAndTime
end doGetDateNo


---URLエンコードのサブルーチン
####################################
###### %エンコード
####################################
on doUrlEncode(argText)
  ##テキスト
  set ocidArgText to refMe's NSString's stringWithString:(argText)
  ##キャラクタセットを指定
  set ocidChrSet to refMe's NSCharacterSet's URLQueryAllowedCharacterSet
  ##キャラクタセットで変換
  set ocidArgTextEncoded to ocidArgText's stringByAddingPercentEncodingWithAllowedCharacters:(ocidChrSet)
  ######## 置換 %エンコードの追加処理
  ###置換レコード
  set recordPercentMap to {|+|:"%2B", |=|:"%3D", |&|:"%26", |$|:"%24"} as record
  ###ディクショナリにして
  set ocidPercentMap to refMe's NSDictionary's alloc()'s initWithDictionary:(recordPercentMap)
  ###キーの一覧を取り出します
  set ocidAllKeys to ocidPercentMap's allKeys()
  ###取り出したキー一覧を順番に処理
  repeat with itemAllKey in ocidAllKeys
    ##キーの値を取り出して
    set ocidMapValue to (ocidPercentMap's valueForKey:(itemAllKey))
    ##置換
    set ocidEncodedText to (ocidArgTextEncoded's stringByReplacingOccurrencesOfString:(itemAllKey) withString:(ocidMapValue))
    ##次の変換に備える
    set ocidArgTextEncoded to ocidEncodedText
  end repeat
  ##テキスト形式に確定
  set strTextToEncode to ocidEncodedText as text
  ###値を戻す
return strTextToEncode
end doUrlEncode


|

より以前の記事一覧

その他のカテゴリー

Acrobat Acrobat Annotation Acrobat Dialog Acrobat Form Acrobat JS Acrobat Open Acrobat Plugin Acrobat python Acrobat Reader Acrobat Sequ 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 Apple AppleScript AppleScript Guide AppleScript Accessibility AppleScript AppKit AppleScript Applications AppleScript AppStore AppleScript Archive AppleScript Attributes 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 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 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 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 Plist System Events 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 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 SVG AppleScript XML TTML AppleScript XML webloc AppleScript YouTube AppleScript Zero Suppress Applications Barcode OnLine Tools CityCode Design 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