Contacts

[CNContactStore]自分のメールアドレス


AppleScript サンプルコード

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

AppleScript サンプルソース(参考)
行番号ソース
001#!/usr/bin/osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003#com.cocolog-nifty.quicktimer.icefloe
004#
005----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
006use AppleScript version "2.8"
007use framework "Foundation"
008use framework "AppKit"
009use framework "Contacts"
010use scripting additions
011
012property refMe : a reference to current application
013
014set appContactStore to refMe's CNContactStore's new()
015set ocidID to appContactStore's defaultContainerIdentifier()
016log ocidID as text
017-->アカウントID ABAccount
018set ocidKeyArray to refMe's NSMutableArray's alloc()'s initWithCapacity:(0)
019ocidKeyArray's addObject:(refMe's CNContactGivenNameKey)
020ocidKeyArray's addObject:(refMe's CNContactFamilyNameKey)
021ocidKeyArray's addObject:(refMe's CNContactPhoneNumbersKey)
022ocidKeyArray's addObject:(refMe's CNContactEmailAddressesKey)
023ocidKeyArray's addObject:(refMe's CNContactIdentifierKey)
024#MeContact
025set listResponse to (appContactStore's unifiedMeContactWithKeysToFetch:(ocidKeyArray) |error| :(reference))
026set ocidMyContact to (item 1 of listResponse)
027log ocidMyContact's identifier() as text
028-->コンタクトID ABPerson
029#メールアドレス戻り値がリスト
030set ocidEmailArray to ocidMyContact's emailAddresses()
031
032repeat with itemEmail in ocidEmailArray
033  set ocidEmailLabel to itemEmail's label()
034  -->ラベルを取得して
035  set booliCloud to (ocidEmailLabel's isEqualToString:(refMe's CNLabelEmailiCloud))
036  set boolHome to (ocidEmailLabel's isEqualToString:(refMe's CNLabelHome))
037  set boolWork to (ocidEmailLabel's isEqualToString:(refMe's CNLabelWork))
038  -->比較して対象を取得
039  if boolHome is true then
040    log itemEmail's value() as text
041  else if booliCloud is true then
042    log itemEmail's value() as text
043  else if boolWork is true then
044    log itemEmail's value() as text
045  end if
046end repeat
047
048return 0
AppleScriptで生成しました

|

[VCARD]連絡先登録用バーコード (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/Contacts")
##フォルダ作成
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"} 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)
#####################
### VCARDデータ整形
set strChl to "BEGIN:VCARD\nVERSION:3.0" 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 %@)", "FN:")
set ocidFullName to ocidStringsArray's filteredArrayUsingPredicate:(codiPridic)
###
if (count of ocidFullName) = 0 then
return "【エラー】フルネームが取得できませんでした"
else
  set ocidFullNameArray to (ocidFullName's firstObject())'s componentsSeparatedByString:(":")
  set strFullName to (last item of ocidFullNameArray) as list
  ##ファイル名に開始日時を使う
  set strSaveFileName to ("VcardQR_" & strFullName & ".png") as text
  set ocidSaveFilePathURL to ocidSaveDirPathURL's URLByAppendingPathComponent:(strSaveFileName)
  ##
  set strChl to (strChl & "\n" & (ocidFullName's firstObject() as text)) as text
end if
####
set codiPridic to refMe's NSPredicate's predicateWithFormat_("(SELF BEGINSWITH %@)", "N:")
set ocidN to ocidStringsArray's filteredArrayUsingPredicate:(codiPridic)
if (count of ocidN) > 0 then
  set strChl to (strChl & "\n" & (ocidN's firstObject() as text)) as text
end if
####
set codiPridic to refMe's NSPredicate's predicateWithFormat_("(SELF CONTAINS %@)", "EMAIL;")
set ocidEMAIL to ocidStringsArray's filteredArrayUsingPredicate:(codiPridic)
if (count of ocidEMAIL) = 1 then
  set strChl to (strChl & "\n" & (ocidEMAIL's firstObject() as text)) as text
else if (count of ocidEMAIL) > 1 then
  set strChl to (strChl & "\n" & (ocidEMAIL's firstObject() as text)) as text
  set strChl to (strChl & "\n" & (ocidEMAIL's lastObject() as text)) as text
end if
##
set codiPridic to refMe's NSPredicate's predicateWithFormat_("(SELF BEGINSWITH %@)", "TEL;")
set ocidTEL to ocidStringsArray's filteredArrayUsingPredicate:(codiPridic)
if (count of ocidTEL) = 1 then
  set strChl to (strChl & "\n" & (ocidTEL's firstObject() as text)) as text
else if (count of ocidTEL) > 1 then
  set strChl to (strChl & "\n" & (ocidTEL's firstObject() as text)) as text
  set strChl to (strChl & "\n" & (ocidTEL's lastObject() as text)) as text
end if
##
set strChl to (strChl & "\n" & "END:VCARD") 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|())

return true

---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


|

[VCARD]連絡先登録用バーコード (CoreImage利用)


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

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#com.cocolog-nifty.quicktimer.icefloe
#
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
use AppleScript version "2.8"
use framework "Foundation"
use framework "AppKit"
use framework "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/Contacts")
##フォルダ作成
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"} 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)
#####################
### データ整形
set strChl to "BEGIN:VCARD\nVERSION:3.0" 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 %@)", "FN:")
set ocidFullName to ocidStringsArray's filteredArrayUsingPredicate:(codiPridic)
###
if (count of ocidFullName) = 0 then
return "【エラー】フルネームが取得できませんでした"
else
  set ocidFullNameArray to (ocidFullName's firstObject())'s componentsSeparatedByString:(":")
  set strFullName to (last item of ocidFullNameArray) as list
  ##ファイル名に使う
  set strSaveFileName to ("VcardQR_" & strFullName & ".png") as text
  set ocidSaveFilePathURL to ocidSaveDirPathURL's URLByAppendingPathComponent:(strSaveFileName)
  ##
  set strChl to (strChl & "\n" & (ocidFullName's firstObject() as text)) as text
end if
####
set codiPridic to refMe's NSPredicate's predicateWithFormat_("(SELF BEGINSWITH %@)", "N:")
set ocidN to ocidStringsArray's filteredArrayUsingPredicate:(codiPridic)
if (count of ocidN) > 0 then
  set strChl to (strChl & "\n" & (ocidN's firstObject() as text)) as text
end if
####
set codiPridic to refMe's NSPredicate's predicateWithFormat_("(SELF BEGINSWITH %@)", "EMAIL;")
set ocidEMAIL to ocidStringsArray's filteredArrayUsingPredicate:(codiPridic)
if (count of ocidEMAIL) = 1 then
  set strChl to (strChl & "\n" & (ocidEMAIL's firstObject() as text)) as text
else if (count of ocidEMAIL) > 1 then
  set strChl to (strChl & "\n" & (ocidEMAIL's firstObject() as text)) as text
  set strChl to (strChl & "\n" & (ocidEMAIL's lastObject() as text)) as text
end if
##
set codiPridic to refMe's NSPredicate's predicateWithFormat_("(SELF BEGINSWITH %@)", "TEL;")
set ocidTEL to ocidStringsArray's filteredArrayUsingPredicate:(codiPridic)
if (count of ocidTEL) = 1 then
  set strChl to (strChl & "\n" & (ocidTEL's firstObject() as text)) as text
else if (count of ocidTEL) > 1 then
  set strChl to (strChl & "\n" & (ocidTEL's firstObject() as text)) as text
  set strChl to (strChl & "\n" & (ocidTEL's lastObject() as text)) as text
end if
##
set strChl to (strChl & "\n" & "END:VCARD") as text
######################################
### 色決め 切り捨ての都合上指定のニア
######################################
###URLの取得に失敗しているパターン
###ダイアログ
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
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

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

####テキストを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


|

[VCARD]連絡先登録用バーコード (CoreImage利用 背景配色あり)


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

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
use AppleScript version "2.8"
use framework "Foundation"
use framework "AppKit"
#use framework "Carbon"
use framework "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"} 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)
#####################
###
### データ整形
set strChl to "BEGIN:VCARD\nVERSION:3.0" 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 %@)", "FN:")
set ocidFullName to ocidStringsArray's filteredArrayUsingPredicate:(codiPridic)
###
if (count of ocidFullName) = 0 then
return "【エラー】フルネームが取得できませんでした"
else
  set ocidFullNameArray to (ocidFullName's firstObject())'s componentsSeparatedByString:(":")
  set strFullName to (last item of ocidFullNameArray) as text
  ##
  set strChl to (strChl & "\n" & (ocidFullName's firstObject() as text)) as text
end if
####
set codiPridic to refMe's NSPredicate's predicateWithFormat_("(SELF BEGINSWITH %@)", "N:")
set ocidN to ocidStringsArray's filteredArrayUsingPredicate:(codiPridic)
if (count of ocidN) > 0 then
  set strChl to (strChl & "\n" & (ocidN's firstObject() as text)) as text
end if
####
set codiPridic to refMe's NSPredicate's predicateWithFormat_("(SELF BEGINSWITH %@)", "EMAIL;")
set ocidEMAIL to ocidStringsArray's filteredArrayUsingPredicate:(codiPridic)
if (count of ocidEMAIL) = 1 then
  set strChl to (strChl & "\n" & (ocidEMAIL's firstObject() as text)) as text
else if (count of ocidEMAIL) > 1 then
  set strChl to (strChl & "\n" & (ocidEMAIL's firstObject() as text)) as text
  set strChl to (strChl & "\n" & (ocidEMAIL's lastObject() as text)) as text
end if
##
set codiPridic to refMe's NSPredicate's predicateWithFormat_("(SELF BEGINSWITH %@)", "TEL;")
set ocidTEL to ocidStringsArray's filteredArrayUsingPredicate:(codiPridic)
if (count of ocidTEL) = 1 then
  set strChl to (strChl & "\n" & (ocidTEL's firstObject() as text)) as text
else if (count of ocidTEL) > 1 then
  set strChl to (strChl & "\n" & (ocidTEL's firstObject() as text)) as text
  set strChl to (strChl & "\n" & (ocidTEL's lastObject() as text)) as text
end if
##
set strQRContents to (strChl & "\n" & "END:VCARD") as text


#####################
###出来上がったVCARDテキスト
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:("VCARD 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:(strFullName))
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 1052624) 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/Contacts")
##フォルダ作成
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 ("Vcard." & (strFullName) & "." & strDateNo & ".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


|

連絡先から自分の電話番号を取得する


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

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

property refMe : a reference to current application

#####################################
### 本処理
#####################################
###選択中のカード
tell application "Contacts"
  tell my card
    ###VCARD取り出し
    set strVcardText to vcard as text
  end tell
end tell
######通常WINDOWS改行
set AppleScript's text item delimiters to "\r\n"
set listVcardText to every text item of strVcardText
set AppleScript's text item delimiters to ""
set numCntList to (count of listVcardText) as integer
if numCntList = 1 then
  ###UNIX改行
  set AppleScript's text item delimiters to "\n"
  set listVcardText to every text item of strVcardText
  set AppleScript's text item delimiters to ""
  set numCntList to (count of listVcardText) as integer
  if numCntList = 1 then
    ###Mac改行
    set AppleScript's text item delimiters to "\r"
    set listVcardText to every text item of strVcardText
    set AppleScript's text item delimiters to ""
    set numCntList to (count of listVcardText) as integer
    if numCntList ≤ 1 then
return "【エラー】カードの取得に失敗しました"
    end if
  end if
end if
######電話番号取り出し
set listTelNo to {} as list
repeat with itemVcardLineText in listVcardText
  set strVcardLineText to itemVcardLineText as text
  if strVcardLineText contains "TEL" then
    set AppleScript's text item delimiters to ":"
    set listVcardLineText to every text item of strVcardLineText
    set AppleScript's text item delimiters to ""
    set strTelNo to (item 2 of listVcardLineText) as text
    set end of listTelNo to strTelNo
  end if
end repeat
if (count of listTelNo) = 0 then
return "【エラー】電話番号の取得に失敗しました"
else
  log listTelNo
end if


|

[Contacts]自分のメールアドレスの取得(スクリプトメニュー用)


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

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

property refMe : a reference to current application

tell application id "com.apple.AddressBook"
  ###自分のカード
  tell my card
    set strVcardText to vcard as text
  end tell
end tell
####Vcardの内容をリスト化(改行がWINDOWS)
set AppleScript's text item delimiters to "\r\n"
set listVcardText to every text item of strVcardText
set AppleScript's text item delimiters to ""
###EMAIL取得用
set listEmailAdd to {} as list
set strHomeEmail to "" as text
set strWORKEmail to "" as text
####Vcardの数だけ繰り返し
repeat with itemVcardText in listVcardText
  ##テキストで確定させて
  set strItemVcardText to itemVcardText as text
  ##EMAILから始まる場合
  if strItemVcardText starts with "EMAIL" then
    ###カンマで区切って
    set AppleScript's text item delimiters to ":"
    set listItemVcardText to every text item of strItemVcardText
    set AppleScript's text item delimiters to ""
    set strType to (item 1 of listItemVcardText) as text
    ###後半部分が電番
    set strEmail to (item 2 of listItemVcardText) as text
    ####リストに格納して
    copy strEmail to end of listEmailAdd
  end if
end repeat
#####ダイアログを前面に
tell current application
  set strName to name as text
end tell
####スクリプトメニューから実行したら
if strName is "osascript" then
  tell application "Finder" to activate
else
  tell current application to activate
end if
try
  set listResponse to (choose from list listEmailAdd with title "選んでください" with prompt "メールを選んでください" default items (item 1 of listEmailAdd) OK button name "クリップボードにコピー" cancel button name "キャンセル" without multiple selections allowed and empty selection allowed) as list
on error
  log "エラーしました"
return "エラーしました"
end try
if listResponse is false then
return "キャンセルしました"
end if

set strText to (item 1 of listResponse) as text

####ペーストボード宣言
set appPasteboard to refMe's NSPasteboard's generalPasteboard()
set ocidText to (refMe's NSString's stringWithString:(strText))
appPasteboard's clearContents()
appPasteboard's setString:(ocidText) forType:(refMe's NSPasteboardTypeString)

|

[Contacts]自分のメールアドレスの取得


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

#!/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.6"
use framework "Foundation"
use scripting additions

tell application id "com.apple.AddressBook"
  ###自分のカード
  tell my card
    set strVcardText to vcard as text
  end tell
end tell
####Vcardの内容をリスト化(改行がWINDOWS)
set AppleScript's text item delimiters to "\r\n"
set listVcardText to every text item of strVcardText
set AppleScript's text item delimiters to ""
###EMAIL取得用
set listEmailAdd to {} as list
set strHomeEmail to "" as text
set strWORKEmail to "" as text
####Vcardの数だけ繰り返し
repeat with itemVcardText in listVcardText
  ##テキストで確定させて
  set strItemVcardText to itemVcardText as text
  ##EMAILから始まる場合
  if strItemVcardText starts with "EMAIL" then
    ###カンマで区切って
    set AppleScript's text item delimiters to ":"
    set listItemVcardText to every text item of strItemVcardText
    set AppleScript's text item delimiters to ""
    set strType to (item 1 of listItemVcardText) as text
    if strType contains "HOME" then
      set strHomeEmail to (item 2 of listItemVcardText) as text
    else if strType contains "WORK" then
      set strWORKEmail to (item 2 of listItemVcardText) as text
    else
      ###後半部分が電番
      set strEmail to (item 2 of listItemVcardText) as text
      ####リストに格納して
      copy strEmail to end of listEmailAdd
    end if
  end if
end repeat

log "自宅;" & strHomeEmail
log "職場:" & strWORKEmail
log "以外:" & listEmailAdd

###一つに絞る場合
if strWORKEmail is not "" then
  set strSendAdd to strWORKEmail
else if strHomeEmail is not "" then
  set strSendAdd to strHomeEmail
else
  set strSendAdd to (item 1 of listEmailAdd)
end if

return strSendAdd & "\r自宅;" & strHomeEmail & "\r職場:" & strWORKEmail & "\r以外:" & listEmailAdd & "\r"




|

[my card]自分の電話番号を連絡先から取得

tell application "Contacts"
    launch
    ###起動を待つ
    repeat
        set boolUnSaved to unsaved
        if boolUnSaved is (missing value) then
            delay 1
        else
            exit repeat
        end if
    end repeat
    
    ###自分のカード
    tell my card
        set strMyName to name as text
        set strVcardText to vcard as text
    end tell
end tell
####Vcardの内容をリスト化(改行がWINDOWS)
set AppleScript's text item delimiters to "\r\n"
set listVcardText to every text item of strVcardText
set AppleScript's text item delimiters to ""

###電番取得用のリスト
set listTelNo to {}

####Vcardの数だけ繰り返し
repeat with itemVcardText in listVcardText
    ##テキストで確定させて
    set strItemVcardText to itemVcardText as text
    ##telから始まる場合
    if strItemVcardText starts with "tel" then
        ###カンマで区切って
        set AppleScript's text item delimiters to ":"
        set listItemVcardText to every text item of strItemVcardText
        set AppleScript's text item delimiters to ""
        ###後半部分が電番
        set strTelNo to (item 2 of listItemVcardText) as text
        ####リストに格納して
        copy strTelNo to end of listTelNo
    end if
end repeat

try
    set listResponse to (choose from list listTelNo with title "選んでください" with prompt "電話番号を選んでください" default items (item 1 of listTelNo) OK button name "OK" cancel button name "キャンセル" without multiple selections allowed and empty selection allowed) as list
on error
    log "エラーしました"
    return "エラーしました"
end try
if listResponse is false then
    return "キャンセルしました"
end if

set strResponse to (item 1 of listResponse) as text

|

[Vcard]連絡先をVカードで保存する

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#
#
#
#                       com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
##自分環境がos12なので2.8にしているだけです
use AppleScript version "2.8"
use framework "Foundation"
use scripting additions

property refMe : a reference to current application

set objFileManager to refMe's NSFileManager's defaultManager()


#####################################
### 保存先パス関連 localizedフォルダとして作成
#####################################

###書類フォルダ
set ocidDocumentDirectoryPathArray to (objFileManager's URLsForDirectory:(refMe's NSDocumentDirectory) inDomains:(refMe's NSUserDomainMask))
set ocidDocumentDirectoryPathURL to item 1 of ocidDocumentDirectoryPathArray
####Contactsフォルダ
set ocidSaveDirPathURL to ocidDocumentDirectoryPathURL's URLByAppendingPathComponent:"Contacts.localized"
####フォルダを作る
set ocidAttrDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
ocidAttrDict's setValue:511 forKey:(refMe's NSFilePosixPermissions)
set listlResults to objFileManager's createDirectoryAtURL:(ocidSaveDirPathURL) withIntermediateDirectories:true attributes:(ocidAttrDict) |error|:(reference)

####localizedフォルダ
set ocidLocalizedDirPathURL to ocidSaveDirPathURL's URLByAppendingPathComponent:".localized"
####フォルダを作る
set ocidAttrDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
ocidAttrDict's setValue:511 forKey:(refMe's NSFilePosixPermissions)
set listlResults to objFileManager's createDirectoryAtURL:(ocidLocalizedDirPathURL) withIntermediateDirectories:true attributes:(ocidAttrDict) |error|:(reference)

####localized strings
set ocidLocalizedFilePathURL to ocidLocalizedDirPathURL's URLByAppendingPathComponent:"ja.strings"
set strEnName to "Contacts" as text
set strJpName to "連絡先" as text
set ocidPlistDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
ocidPlistDict's setObject:strJpName forKey:strEnName
set ocidNSbplist to refMe's NSPropertyListBinaryFormat_v1_0
set ocidPlistEditDataArray to refMe's NSPropertyListSerialization's dataWithPropertyList:ocidPlistDict format:ocidNSbplist options:0 |error|:(reference)
set ocidPlistEditData to item 1 of ocidPlistEditDataArray
set listlResults to ocidPlistEditData's writeToURL:ocidLocalizedFilePathURL options:0 |error|:(reference)

#####################################
### 本処理
#####################################

###選択中のカード
tell application "Contacts"
    set listOfSelection to selection as list
end tell

####連絡先
tell application "Contacts"
    ###選んだカードの数だけ繰り返し
    repeat with objSelection in listOfSelection
        tell objSelection
            (* プロパティを選択してVカードを生成する事もできます
            set objOrgProperties to properties
            set strLastName to last name
            set strSuffix to suffix
            set strTittle to title
            set strCompany to company
            set strFirstName to first name
            set strImage to image
            set strNickName to nickname
            set strOrganization to organization
            set strMaidenName to maiden name
            set strHomePage to home page
            set strJobTitle to job title
            set strModification to modification date
            set strPhoneticMiddleName to phonetic middle name
            set strDepartment to department
            set strMiddleName to middle name
            set strBirthDay to birth date
            set strPoneticLastName to phonetic last name
            *)
            ####名前-->ファイル名に
            set strName to name as text
            ####Vcardの内容を書き出します
            set strVacard to vcard as text
        end tell
        
        ###ファイル名
        set strFileName to ("" & strName & ".vcf") as text
        ####保存ファイルのパスURL
        set ocidVcfFilePathURL to (ocidSaveDirPathURL's URLByAppendingPathComponent:strFileName)
        ###保存データ
        set ocidVacardData to (refMe's NSString's stringWithString:strVacard)
        ###保存
        set listlResults to (ocidVacardData's writeToURL:ocidVcfFilePathURL atomically:false encoding:(refMe's NSUTF8StringEncoding) |error|:(specifier))
    end repeat
end tell
###保存先を知らせる
set aliasSaveDirPathURL to ocidSaveDirPathURL as alias
tell application "Finder"
    select aliasSaveDirPathURL
end tell



|

[macOS13.0.1]ContactsにApple Eventsを送信する権限がありません。

連絡先の
これは、たぶんバグではなからろうか?と…

例:Skypeから連絡先へのアクセス時に、許可を確認するダイアログが出ない
-->なのに連絡先へのアクセスが可能


ContactsにApple Eventsを送信する権限がありません。

tell application "Contacts"
launch
activate
get properties
--> error number -1743 from properties
###結果:
error "ContactsApple Eventsを送信する権限がありません。" number -1743 from properties
end tell

|

その他のカテゴリー

Accessibility Acrobat Acrobat 2020 Acrobat 2024 Acrobat AddOn Acrobat Annotation Acrobat AppleScript Acrobat ARMDC Acrobat AV2 Acrobat BookMark Acrobat Classic Acrobat DC Acrobat Dialog Acrobat Distiller Acrobat Form Acrobat GentechAI Acrobat JS Acrobat JS Word Search Acrobat Maintenance Acrobat Manifest Acrobat Menu Acrobat Merge Acrobat Open Acrobat PDFPage Acrobat Plugin Acrobat Preferences Acrobat Preflight Acrobat Print Acrobat Python Acrobat Reader Acrobat Reader Localized Acrobat Reference Acrobat Registered Products Acrobat SCA Acrobat SCA Updater Acrobat Sequ Acrobat Sign Acrobat Stamps Acrobat URL List Mac Acrobat URL List Windows Acrobat Watermark Acrobat Windows Acrobat Windows Reader Admin Admin Account Admin Apachectl Admin ConfigCode Admin configCode Admin Device Management Admin LaunchServices Admin Locationd Admin loginitem Admin Maintenance Admin Mobileconfig Admin NetWork Admin Permission Admin Pkg Admin Power Management Admin Printer Admin Printer Basic Admin Printer Custompapers Admin SetUp Admin SMB Admin softwareupdate Admin Support Admin System Information Admin TCC Admin Tools Admin Umask Admin Users Admin Volumes Admin XProtect Adobe Adobe AUSST Adobe Bridge Adobe Documents Adobe FDKO Adobe Fonts Adobe Reference Adobe RemoteUpdateManager Adobe Sap Code AppKit Apple AppleScript AppleScript Duplicate AppleScript entire contents AppleScript List AppleScript ObjC AppleScript Osax AppleScript PDF AppleScript Pictures AppleScript record AppleScript Video Applications AppStore Archive Archive Keka Attributes Automator BackUp Barcode Barcode Decode Barcode QR Bash Basic Basic Path Bluetooth BOX Browser Calendar CD/DVD Choose Chrome Chromedriver CIImage CityCode CloudStorage Color Color NSColor Color NSColorList com.apple.LaunchServices.OpenWith Console Contacts CotEditor CURL current application Date&Time delimiters Desktop Desktop Position Device Diff Disk do shell script Dock Dock Launchpad DropBox Droplet eMail Encode % Encode Decode Encode HTML Entity Encode UTF8 Error EXIFData exiftool ffmpeg File File Name Finder Finder Window Firefox Folder FolderAction Font List FontCollections Fonts Fonts Asset_Font Fonts ATS Fonts Emoji Fonts Maintenance Fonts Morisawa Fonts Python Fonts Variable Foxit GIF github Guide HTML Icon Icon Assets.car Illustrator Image Events ImageOptim Input Dictionary iPhone iWork Javascript Jedit Ω Json Label Language Link locationd lsappinfo m3u8 Mail Map Math Media Media AVAsset Media AVconvert Media AVFoundation Media AVURLAsset Media Movie Media Music Memo Messages Microsoft Microsoft Edge Microsoft Excel Microsoft Fonts Microsoft Office Microsoft Office Link Microsoft OneDrive Microsoft Teams Mouse Music Node Notes NSArray NSArray Sort NSAttributedString NSBezierPath NSBitmapImageRep NSBundle NSCFBoolean NSCharacterSet NSData NSDecimalNumber NSDictionary NSError NSEvent NSFileAttributes NSFileManager NSFileManager enumeratorAtURL NSFont NSFontManager NSGraphicsContext NSGraphicsContext Crop NSImage NSIndex NSKeyedArchiver NSKeyedUnarchiver NSLocale NSMetadataItem NSMutableArray NSMutableDictionary NSMutableString NSNotFound NSNumber NSOpenPanel NSPasteboard NSpoint NSPredicate NSRange NSRect NSRegularExpression NSRunningApplication NSScreen NSSet NSSize NSString NSString stringByApplyingTransform NSStringCompareOptions NSTask NSTimeZone NSUbiquitous NSURL NSURL File NSURLBookmark NSURLComponents NSURLResourceKey NSURLSession NSUserDefaults NSUUID NSView NSWorkspace Numbers OAuth PDF PDF Image2PDF PDF MakePDF PDF nUP PDF Pymupdf PDF Pypdf PDFContext PDFDisplayBox PDFImageRep PDFKit PDFKit Annotation PDFKit AnnotationWidget PDFKit DocumentPermissions PDFKit OCR PDFKit Outline PDFKit Start PDFPage PDFPage Rotation PDFView perl Photoshop PlistBuddy pluginkit plutil postalcode PostScript PowerShell prefPane Preview Python Python eyed3 Python pip QuickLook QuickTime ReadMe Regular Expression Reminders ReName Repeat RTF Safari SaveFile ScreenCapture ScreenSaver Script Editor Script Menu SF Symbols character id SF Symbols Entity Shortcuts Shortcuts Events sips Skype Slack Sound Spotlight sqlite StandardAdditions StationSearch Subtitles LRC Subtitles SRT Subtitles VTT Swift swiftDialog System Events System Settings TemporaryItems Terminal Text Text CSV Text MD Text TSV TextEdit Tools Translate Trash Twitter Typography UI Unit Conversion UTType valueForKeyPath Video VisionKit Visual Studio Code VMware Fusion Wacom Weather webarchive webp Wifi Windows XML XML EPUB XML HTML XML LSSharedFileList XML LSSharedFileList sfl2 XML LSSharedFileList sfl3 XML objectsForXQuery XML OPML XML Plist XML Plist System Events XML RSS XML savedSearch XML SVG XML TTML XML webloc XML xmllint XML XMP YouTube Zero Padding zoom