« [json]QRコードのイメージファイルをデコードする | トップページ | [Safari]リロード »

[WKWebView]QRコードを表示する

webViewの基本構造はこちらを使用しています。
https://macscripter.net/viewtopic.php?pid=209146



#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#webViewベーススクリプト
#https://macscripter.net/viewtopic.php?pid=209146
#
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
##自分環境がos12なので2.8にしているだけです
use AppleScript version "2.8"
use framework "Foundation"
use framework "AppKit"
use framework "WebKit"
use scripting additions

property objMe : a reference to current application
property objNSURL : a reference to objMe's NSURL
property objNSString : a reference to objMe's NSString
set objFileManager to objMe's NSFileManager's defaultManager()

#####################################
set aliasIconPath to POSIX file "/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/BookmarkIcon.icns" as alias
set theResponse to "" as text
try
set objResponse to (display dialog "バーコードの内容を入力" with title "QRコードを作成します" default answer theResponse buttons {"OK", "キャンセル"} default button "OK" cancel button "キャンセル" with icon aliasIconPath giving up after 20 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
###フォルダのパス
###ピクチャーフォルダのパス
set aliasDirPath to (path to pictures folder from user domain) as alias
set strDirPath to POSIX path of aliasDirPath as text
####フォルダ名
set strFolderName to "QRcode" as text
set strDirPath to ("" & strDirPath & strFolderName & "") as text
###NSStringテキスト
set ocidDirPath to objNSString's stringWithString:strDirPath
###フォルダを作る
###途中のフォルダも作る-->true
set boolMakeNewFolder to (objFileManager's createDirectoryAtPath:ocidDirPath withIntermediateDirectories:true attributes:(missing value) |error|:(missing value))

####日付フォーマット
set prefDateFormat to "yyyyMMddHHmmss"
set ocidFormatter to objMe's NSDateFormatter's alloc()'s init()
ocidFormatter's setLocale:(objMe's NSLocale's localeWithLocaleIdentifier:"ja_JP_POSIX")
ocidFormatter's setDateFormat:(prefDateFormat as string)
set strDateAndTime to (ocidFormatter's stringFromDate:(current date)) as text
#####日付をファイル名にする
set strSaveFilePath to strDirPath & "/" & strDateAndTime & ".png"

#####################################
set strInputText to (strText) as text
####テキストをNSString
set ocidInputString to objNSString's stringWithString:strInputText
#####################################
##全角を半角に変換して
set ocidInputStringHalfwidth to (ocidInputString's stringByApplyingTransform:(objMe's NSStringTransformFullwidthToHalfwidth) |reverse|:false)
##制御文字取り除き
set ocidwhitespaceAndNewlineCharacterSet to objMe's NSCharacterSet's whitespaceAndNewlineCharacterSet
set ocidInputString to ocidInputStringHalfwidth's stringByTrimmingCharactersInSet:ocidwhitespaceAndNewlineCharacterSet
##スペース取り除き
set ocidSearchString to objNSString's stringWithString:" "
set ocidReplacementString to objNSString's stringWithString:""
set ocidTrimmingText to ocidInputString's stringByReplacingOccurrencesOfString:ocidSearchString withString:ocidReplacementString
##ハイフン取り除き
set ocidSearchString to objNSString's stringWithString:"-"
set ocidTrimmingText to ocidTrimmingText's stringByReplacingOccurrencesOfString:ocidSearchString withString:ocidReplacementString
#####################################
####テキストをUTF8
set ocidUtf8InputString to ocidTrimmingText's dataUsingEncoding:(objMe's NSUTF8StringEncoding)
####CIQRCodeGenerator初期化
set ocidQRcodeImage to objMe'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の最小サイズ
###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 objMe's CGAffineTransform's CGAffineTransformMakeScale(numWidth, numHight)
##変換スケールを適応(元のサイズに元のサイズのスケール適応しても意味ないけど
set ocidCIImageScaled to ocidCIImage's imageByApplyingTransform:recordScalse
#######元のセルが1x1pxの最小サイズで出したいときはここで処理
##set ocidCIImageScaled to ocidCIImage
###イメージデータを展開
set ocidNSCIImageRep to objMe's NSCIImageRep's imageRepWithCIImage:ocidCIImageScaled
###出力用のイメージの初期化
set ocidNSImageScaled to objMe'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 objMe'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 (objMe's NSBitmapImageRep's alloc()'s initWithBitmapDataPlanes:(missing value) pixelsWide:numPadWidth pixelsHigh:numPadHight bitsPerSample:8 samplesPerPixel:4 hasAlpha:true isPlanar:false colorSpaceName:(objMe's NSCalibratedRGBColorSpace) bitmapFormat:(objMe's NSAlphaFirstBitmapFormat) bytesPerRow:0 bitsPerPixel:32)
###初期化
objMe's NSGraphicsContext's saveGraphicsState()
###ビットマップイメージ
(objMe's NSGraphicsContext's setCurrentContext:(objMe's NSGraphicsContext's graphicsContextWithBitmapImageRep:ocidNSBitmapImagePadRep))
###塗り色を『白』に指定して
objMe's NSColor's whiteColor()'s |set|()
###画像にする
objMe'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:(objMe's NSCompositeSourceOver) fraction:1.0 respectFlipped:true hints:(missing value)
####画像作成終了
objMe's NSGraphicsContext's restoreGraphicsState()

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

#####出力イメージへ変換
set ocidNSInlineData to (ocidNSBitmapImagePadRep's representationUsingType:(objMe's NSBitmapImageFileTypePNG) |properties|:ocidNSSingleEntryDictionary)
(*
NSBitmapImageFileTypeJPEG
NSBitmapImageFileTypePNG
NSBitmapImageFileTypeGIF
NSBitmapImageFileTypeBMP
NSBitmapImageFileTypeTIFF
NSBitmapImageFileTypeJPEG2000
*)
######インラインデータをファイルに書き出し
set boolMakeQrCode to (ocidNSInlineData's writeToFile:strSaveFilePath atomically:true)

set targetURL to ("file://" & strSaveFilePath & "") as text
#####################################
repeat 1 times
####NSMutableDictionaryの初期化
set ocidNSDictionaryM to objMe's NSMutableDictionary's dictionary()
####ウィンドのサイズ
set {numWidth, numHeight} to {600, 600}
tell ocidNSDictionaryM
####画像のパス
its setObject:targetURL forKey:"theURL"
####ウィンドのサイズ
its setObject:numWidth forKey:"width"
its setObject:numHeight forKey:"height"
end tell
if objMe's NSThread's isMainThread() as boolean then
####Webビューを表示する
my performWebView:ocidNSDictionaryM
else
my performSelectorOnMainThread:"performWebView:" withObject:ocidNSDictionaryM waitUntilDone:true
end if
tell ocidNSDictionaryM
activate
end tell
#####10秒間開いたら閉じる
#####ここでこの処理をしたのはスクリプトメニューからの実行を配慮して
delay 10
end repeat



on performWebView:ocidNSDictionaryM
set {width, height} to {ocidNSDictionaryM's objectForKey:"width", ocidNSDictionaryM's objectForKey:"height"}
set strURL to (ocidNSDictionaryM's objectForKey:"theURL")
########
set theConfiguration to objMe's WKWebViewConfiguration's alloc()'s init()
set ocidURL to objNSURL's URLWithString:strURL
set theFetch to objNSString's stringWithContentsOfURL:ocidURL encoding:(objMe's NSUTF8StringEncoding) |error|:(missing value)
set theUserScript to objMe's WKUserScript's alloc()'s initWithSource:theFetch injectionTime:(objMe's WKUserScriptInjectionTimeAtDocumentEnd) forMainFrameOnly:true
set theUserContentController to objMe's WKUserContentController's alloc()'s init()
theUserContentController's addUserScript:theUserScript
theConfiguration's setUserContentController:theUserContentController
set webViewSize to objMe's NSMakeRect(0, 0, width, height)
set webView to objMe's WKWebView's alloc()'s initWithFrame:webViewSize configuration:theConfiguration
webView's setNavigationDelegate:me
webView's setUIDelegate:me
webView's setTranslatesAutoresizingMaskIntoConstraints:true
set theURL to objMe's |NSURL|'s URLWithString:strURL
set theRequest to objMe's NSURLRequest's requestWithURL:theURL
webView's loadRequest:theRequest
set ocidWebView to webView
########
set listWindowSize to objMe's NSMakeRect(0, 0, width, height)
set numStyleMaskNo to (objMe's NSWindowStyleMaskTitled as integer)
set numStyleMaskNo to numStyleMaskNo + (objMe's NSWindowStyleMaskClosable as integer)
set numStyleMaskNo to numStyleMaskNo + (objMe's NSWindowStyleMaskMiniaturizable as integer)
set numStyleMaskNo to numStyleMaskNo + (objMe's NSWindowStyleMaskResizable as integer)
set ocidWindow to objMe's NSWindow's alloc()'s initWithContentRect:listWindowSize styleMask:numStyleMaskNo backing:2 defer:yes
########
ocidWindow's setContentView:ocidWebView
set ocidNSWindowController to objMe's NSWindowController's alloc()'s initWithWindow:ocidWindow
ocidNSWindowController's showWindow:me
ocidNSWindowController's |window|'s |center|()
ocidNSWindowController's |window|'s makeKeyAndOrderFront:me
tell ocidNSDictionaryM to its setObject:ocidWindow forKey:"window"
end performWebView:


|

« [json]QRコードのイメージファイルをデコードする | トップページ | [Safari]リロード »

AppleScript QR」カテゴリの記事

AppleScript NSImage」カテゴリの記事

AppleScript stringByApplyingTransform」カテゴリの記事

AppleScript Barcode」カテゴリの記事