Menu

Skip to content
AppleScriptの穴
  • Home
  • Products
  • Books
  • Docs
  • Events
  • Forum
  • About This Blog
  • License
  • 仕事依頼

AppleScriptの穴

Useful & Practical AppleScript archive. Click '★Click Here to Open This Script' Link to download each AppleScript

タグ: 10.13savvy

RTF本文内の色を置換 v2

Posted on 2月 11, 2018 by Takaaki Naganoya

指定のRTF書類の本文中の色を置換するAppleScriptです。

指定のRTF書類内のカラーをざっくりとした色に分類し、同じくざっくりとした色名で置換対象を指定し(blue, green)、指定色(black)に色置換。結果をデスクトップ上に別名で保存します。

AppleScript名:RTF本文内の色を置換 v2
— Created 2018-01-13 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"

property NSData : a reference to current application’s NSData
property NSUUID : a reference to current application’s NSUUID
property NSColor : a reference to current application’s NSColor
property NSString : a reference to current application’s NSString
property NSPredicate : a reference to current application’s NSPredicate
property NSDictionary : a reference to current application’s NSDictionary
property NSMutableArray : a reference to current application’s NSMutableArray
property NSMutableAttributedString : a reference to current application’s NSMutableAttributedString
property NSForegroundColorAttributeName : a reference to current application’s NSForegroundColorAttributeName
property NSDocumentTypeDocumentAttribute : a reference to current application’s NSDocumentTypeDocumentAttribute

set targFilePath to POSIX path of (choose file of type {"public.rtf"})
set targColorNameList to {"blue", "green"} –replace target color names
set toColor to NSColor’s blackColor() –to color
set aRes to replaceRTFColorsByColorName(targFilePath, targColorNameList, toColor, 65535) of me

–指定RTF書類本文中、名称で指定した色の該当箇所を指定色(NSColor)に置換する(複数色)
on replaceRTFColorsByColorName(targFilePath as string, targColorNameList as list, toColor, aColorMax as integer)
  script spd
    property hitList : {}
  end script
  
  
set (hitList of spd) to {}
  
set aFilePath to NSString’s stringWithString:(targFilePath)
  
set aData to NSData’s dataWithContentsOfFile:aFilePath options:0 |error|:(missing value)
  
set theStyledText to NSMutableAttributedString’s alloc()’s initWithData:aData options:(missing value) documentAttributes:(missing value) |error|:(missing value)
  
  
set attrList to getAttributeRunsFromAttrString(theStyledText, aColorMax) of me
  
set attrArray to NSMutableArray’s arrayWithArray:attrList
  
  
theStyledText’s beginEditing() ——
  
repeat with ii in targColorNameList
    set jj to contents of ii
    
set thePred to NSPredicate’s predicateWithFormat_("colorName == %@", jj)
    
set (hitList of spd) to ((attrArray’s filteredArrayUsingPredicate:thePred)’s valueForKey:"rangeVal") as list
    
    
repeat with i in (hitList of spd)
      (theStyledText’s addAttribute:(NSForegroundColorAttributeName) value:toColor range:(contents of i))
    end repeat
    
  end repeat
  
theStyledText’s endEditing() ——
  
  
–Save RTF to desktop
  
set targFol to current application’s NSHomeDirectory()’s stringByAppendingPathComponent:"Desktop"
  
set aRes to saveStyledTextAsRTF(targFol, theStyledText) of me
  
return aRes as boolean
end replaceRTFColorsByColorName

–AttributedStringを書式でlist of record化
on getAttributeRunsFromAttrString(theStyledText, aColorMax)
  script aSpd
    property styleList : {}
  end script
  
  
set (styleList of aSpd) to {} —for output
  
  
set thePureString to theStyledText’s |string|() –pure string from theStyledText
  
  
set theLength to theStyledText’s |length|()
  
set startIndex to 0
  
  
repeat until (startIndex = theLength)
    set {theAtts, theRange} to theStyledText’s attributesAtIndex:startIndex longestEffectiveRange:(reference) inRange:{startIndex, theLength – startIndex}
    
    
–String
    
set aText to (thePureString’s substringWithRange:theRange) as string
    
    
–Color
    
set aColor to (theAtts’s valueForKeyPath:"NSColor")
    
if aColor is not equal to missing value then
      set aSpace to aColor’s colorSpace()
      
      
set aRed to (aColor’s redComponent()) * aColorMax
      
set aGreen to (aColor’s greenComponent()) * aColorMax
      
set aBlue to (aColor’s blueComponent()) * aColorMax
      
      
set colList to {aRed as integer, aGreen as integer, aBlue as integer} –for comparison
      
set colStrForFind to (aRed as integer as string) & " " & (aGreen as integer as string) & " " & (aBlue as integer as string) –for filtering
    else
      set colList to {0, 0, 0}
      
set colStrForFind to "0 0 0"
    end if
    
    
–Color Name
    
set cName to retColorName(aRed, aGreen, aBlue, aColorMax) of me
    
    
–Font
    
set aFont to (theAtts’s valueForKeyPath:"NSFont")
    
if aFont is not equal to missing value then
      set aDFontName to aFont’s displayName()
      
set aDFontSize to aFont’s pointSize()
    end if
    
    
set the end of (styleList of aSpd) to {stringVal:aText, colorStr:colStrForFind, colorVal:colList, fontName:aDFontName as string, fontSize:aDFontSize, rangeVal:theRange, colorName:cName}
    
    
set startIndex to current application’s NSMaxRange(theRange)
    
  end repeat
  
  
return (styleList of aSpd)
end getAttributeRunsFromAttrString

–RGB値から色名称(だいたいの色)を計算する
on retColorName(rCol as integer, gCol as integer, bCol as integer, aColMax as integer)
  set aCol to makeNSColorFromRGBAval(rCol, gCol, bCol, aColMax, aColMax) of me
  
set hueVal to aCol’s hueComponent() as real
  
set satVal to aCol’s saturationComponent() as real
  
set brightVal to aCol’s brightnessComponent() as real
  
  
if satVal ≤ 0.01 then set satVal to 0.0
  
  
if satVal = 0.0 then
    if brightVal ≤ 0.2 then
      set colName to "black"
    else if (brightVal > 0.95) then
      set colName to "white"
    else
      set colName to "gray"
    end if
  else
    if hueVal ≤ (15.0 / 360) or hueVal ≥ (330 / 360) then
      set colName to "red"
    else if hueVal ≤ (45.0 / 360) then
      set colName to "orange"
    else if hueVal < (70.0 / 360) then
      set colName to "yellow"
    else if hueVal < (150.0 / 360) then
      set colName to "green"
    else if hueVal < (190.0 / 360) then
      set colName to "cyan"
    else if (hueVal < 250.0 / 360.0) then
      set colName to "blue"
    else if (hueVal < 290.0 / 360.0) then
      set colName to "purple"
    else
      set colName to "magenta"
    end if
  end if
  
  
return colName
end retColorName

on makeNSColorFromRGBAval(redValue as integer, greenValue as integer, blueValue as integer, alphaValue as integer, aMaxVal as integer)
  set aRedCocoa to (redValue / aMaxVal) as real
  
set aGreenCocoa to (greenValue / aMaxVal) as real
  
set aBlueCocoa to (blueValue / aMaxVal) as real
  
set aAlphaCocoa to (alphaValue / aMaxVal) as real
  
set aColor to NSColor’s colorWithCalibratedRed:aRedCocoa green:aGreenCocoa blue:aBlueCocoa alpha:aAlphaCocoa
  
return aColor
end makeNSColorFromRGBAval

–スタイル付きテキストを指定フォルダ(POSIX path)にRTFで書き出し
on saveStyledTextAsRTF(targFol, aStyledString)
  set bstyledLength to aStyledString’s |string|()’s |length|()
  
set bDict to NSDictionary’s dictionaryWithObject:"NSRTFTextDocumentType" forKey:(NSDocumentTypeDocumentAttribute)
  
set bRTF to aStyledString’s RTFFromRange:(current application’s NSMakeRange(0, bstyledLength)) documentAttributes:bDict
  
  
set theName to (NSUUID’s UUID()’s UUIDString())
  
set thePath to NSString’s stringWithString:targFol
  
set thePath to (thePath’s stringByAppendingPathComponent:theName)’s stringByAppendingPathExtension:"rtf"
  
return (bRTF’s writeToFile:thePath atomically:true) as boolean
end saveStyledTextAsRTF

★Click Here to Open This Script 

Posted in Color RTF Text | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

rtf_rtfdからテキスト抽出

Posted on 2月 11, 2018 by Takaaki Naganoya

RTFないしRTFD(添付ファイルつきRTF)からテキストを抽出するAppleScriptです。

AppleScript名:rtf_rtfdからテキスト抽出
— Created 2018-02-10 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set aFile to choose file of type {"com.apple.rtfd", "public.rtf"}
set aRes to retTextFromRTF(aFile) of me

on retTextFromRTF(aFile)
  set aFilePath to current application’s NSString’s stringWithString:(POSIX path of aFile)
  
set anExt to (aFilePath’s pathExtension()) as string
  
if anExt = "rtfd" then
    set aFilePath to aFilePath’s stringByAppendingString:"TXT.rtf"
  end if
  
  set aData to current application’s NSData’s dataWithContentsOfFile:aFilePath options:0 |error|:(missing value)
  
set theStyledText to current application’s NSMutableAttributedString’s alloc()’s initWithData:aData options:(missing value) documentAttributes:(missing value) |error|:(missing value)
  
  if theStyledText is not equal to missing value then
    return (theStyledText’s |string|()) as string
  else
    return false –Not RTF file
  end if
end retTextFromRTF

★Click Here to Open This Script 

Posted in file RTF Text | Tagged 10.11savvy 10.12savvy 10.13savvy | 1 Comment

RTFを読み込んで書式をDictionary化 v3.0

Posted on 2月 11, 2018 by Takaaki Naganoya

指定のRTF書類の内容を読み取って、書式情報をNSDictionaryに変換するAppleScriptです。

  stringVal:文字列データ
  colorStr:RGBの色データを文字列化したもの
  colorVal:RGBの色データの数値list
  colorDomainName:おおまかな色名称
  fontName:フォント名
  fontSize:フォントサイズ

書式情報で抽出しやすくしてあります。複数要素(例:フォント名+色)を一緒にまとめて格納しておくことで、検索パフォーマンスを稼げるはずです。

AppleScript名:RTFを読み込んで書式をDictionary化 v3.0
— Created 2017-12-10 by Takaaki Naganoya
— Modified 2017-12-11 by Shane Stanley
— Modified 2017-12-11 by Nigel Garvey
— Modified 2017-12-12 by Takaaki Naganoya
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"

property NSData : a reference to current application’s NSData
property NSString : a reference to current application’s NSString
property NSAttributedString : a reference to current application’s NSAttributedString

set fRes to choose file of type {"public.rtf"}

set aFilePath to NSString’s stringWithString:(POSIX path of fRes)
set aData to NSData’s dataWithContentsOfFile:aFilePath options:0 |error|:(missing value)
set theStyledText to NSAttributedString’s alloc()’s initWithData:aData options:(missing value) documentAttributes:(missing value) |error|:(missing value)

set attrRes to getAttributeRunsFromAttrString(theStyledText) of me
(*
–>  {​​​​​{​​​​​​​stringVal:"■■■■■■■", ​​​​​​​colorStr:"0 0 0", ​​​​​​​colorVal:{​​​​​​​​​0, ​​​​​​​​​0, ​​​​​​​​​0​​​​​​​}, ​​​​​​​colorDomainName:"black", ​​​​​​​fontName:"ヒラギノ角ゴ ProN W6", ​​​​​​​fontSize:12.0​​​​​}, ​​​​​{​​​​​​​stringVal:"Xxxxxxx", ​​​​​​​colorStr:"217 11 0", ​​​​​​​colorVal:{​​​​​​​​​217, ​​​​​​​​​11, ​​​​​​​​​0​​​​​​​}, ​​​​​​​colorDomainName:"red", ​​​​​​​fontName:"ヒラギノ角ゴ ProN W6", ​​​​​​​fontSize:12.0​​​​​}, …
*)

on getAttributeRunsFromAttrString(theStyledText)
  script aSpd
    property styleList : {}
  end script
  
  
set (styleList of aSpd) to {} —for output
  
  
set thePureString to theStyledText’s |string|() –pure string from theStyledText
  
  
set theLength to theStyledText’s |length|()
  
set startIndex to 0
  
  
repeat until (startIndex = theLength)
    set {theAtts, theRange} to theStyledText’s attributesAtIndex:startIndex longestEffectiveRange:(reference) inRange:{startIndex, theLength – startIndex}
    
    
–String  
    
set aText to (thePureString’s substringWithRange:theRange) as string
    
    
–Color
    
set aColor to (theAtts’s valueForKeyPath:"NSColor")
    
if aColor is not equal to missing value then
      set aSpace to aColor’s colorSpace()
      
      
set aRed to (aColor’s redComponent()) * 255
      
set aGreen to (aColor’s greenComponent()) * 255
      
set aBlue to (aColor’s blueComponent()) * 255
      
      
set colList to {aRed as integer, aGreen as integer, aBlue as integer} –for comparison
      
set colStrForFind to (aRed as integer as string) & " " & (aGreen as integer as string) & " " & (aBlue as integer as string) –for filtering
    else
      set colList to {0, 0, 0}
      
set colStrForFind to "0 0 0"
    end if
    
    
–Color domain name
    
set cdnStr to retColorDomainNameFromNSColor(aColor) of me
    
    
–Font
    
set aFont to (theAtts’s valueForKeyPath:"NSFont")
    
if aFont is not equal to missing value then
      set aDFontName to aFont’s displayName()
      
set aDFontSize to aFont’s pointSize()
    end if
    
    
set the end of (styleList of aSpd) to {stringVal:aText, colorStr:colStrForFind, colorVal:colList, colorDomainName:cdnStr, fontName:aDFontName as string, fontSize:aDFontSize}
    
set startIndex to current application’s NSMaxRange(theRange)
    
  end repeat
  
  
return (styleList of aSpd)
  
end getAttributeRunsFromAttrString

on retColorDomainNameFromNSColor(aCol)
  set hueVal to aCol’s hueComponent()
  
set satVal to aCol’s saturationComponent()
  
set brightVal to aCol’s brightnessComponent()
  
  
if satVal ≤ 0.01 then set satVal to 0.0
  
  
set colName to ""
  
  
if satVal = 0.0 then
    if brightVal ≤ 0.2 then
      set colName to "black"
    else if (brightVal > 0.95) then
      set colName to "white"
    else
      set colName to "gray"
    end if
  else
    if hueVal ≤ (15.0 / 360) or hueVal ≥ (330 / 360) then
      set colName to "red"
    else if hueVal ≤ (45.0 / 360) then
      set colName to "orange"
    else if hueVal < (70.0 / 360) then
      set colName to "yellow"
    else if hueVal < (150.0 / 360) then
      set colName to "green"
    else if hueVal < (190.0 / 360) then
      set colName to "cyan"
    else if (hueVal < 250.0 / 360.0) then
      set colName to "blue"
    else if (hueVal < 290.0 / 360.0) then
      set colName to "purple"
    else
      set colName to "magenta"
    end if
  end if
  
  
return colName
end retColorDomainNameFromNSColor

★Click Here to Open This Script 

Posted in Color list Record RTF | Tagged 10.11savvy 10.12savvy 10.13savvy | 1 Comment

Read Safari Bookmark v2

Posted on 2月 11, 2018 by Takaaki Naganoya

Safariのブックマーク内容からURLとページタイトルを取得してテキスト書き出しするAppleScriptです。

一番のみどころは、Predicate文でURLStringがnilでなければ、という記述を行っている箇所です。AppleScriptのデータに変換するとnilはmissing valueになるので、ここでmissing valueを指定したくなるところですが、nilを指定しました。

実行のためには、AppleScriptの実行プログラム(スクリプトエディタとかScript Debugger)を「システム環境設定」の「セキュリティとプライバシー」>「プライバシー」>「フルディスクアクセス」に登録しておく必要があります。AppleScriptアプレットから実行する場合には、そのAppleScriptアプレットそのものを「フルディスクアクセス」に登録する必要があります。

AppleScript名:Read Safari Bookmark v2
— Created 2016-02-27 by Takaaki Naganoya
— Piyomaru Software 2016
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

script spdBk
  property outList : {}
end script

set (outList of spdBk) to {}
set libPath to (POSIX path of (path to library folder from user domain)) & "Safari/Bookmarks.plist"
set aRec to retDictFromPlist(libPath) of me
set aList to aRec’s Children

set aPredicate to current application’s NSPredicate’s predicateWithFormat:"URLString != nil"
set filteredArray to (aList’s filteredArrayUsingPredicate:aPredicate) as list

repeat with i in filteredArray
  set the end of (outList of spdBk) to "■" & (Title of URIDictionary of i) & return & (URLString of i)
end repeat

set aRes to listToStringUsingTextItemDelimiter(contents of (outList of spdBk), return & return) of me

–Read plist as record
on retDictFromPlist(aPath as text)
  set thePath to current application’s NSString’s stringWithString:aPath
  
set thePath to thePath’s stringByExpandingTildeInPath()
  
set theDict to current application’s NSDictionary’s dictionaryWithContentsOfFile:thePath
  
return theDict
end retDictFromPlist

on listToStringUsingTextItemDelimiter(sourceList, textItemDelimiter)
  set anArray to current application’s NSArray’s arrayWithArray:sourceList
  
set aString to anArray’s componentsJoinedByString:textItemDelimiter
  
return (aString as string)
end listToStringUsingTextItemDelimiter

★Click Here to Open This Script 

Posted in file Internet | Tagged 10.11savvy 10.12savvy 10.13savvy Safari | Leave a comment

Safariで表示中のURLをwebarchive保存

Posted on 2月 11, 2018 by Takaaki Naganoya

Safariで表示中の最前面のウィンドウのURLの内容をデスクトップ上にWebarchive書類として保存するAppleScriptです。

webArchiveはDeprecatedになったので、macOS 10.14あたりまでのOSで使うならOK。今後については何か別の機能が実装されるのかどうか。macOS 10.15で別の何かが紹介されるのでしょうか。

AppleScript名:Safariで表示中のURLをwebarchive保存
— Created 2014-11-13 Shane Stanley
— Modified 2018-02-11 Takaaki Naganoya
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "WebKit"

property theSender : missing value
property thePath : missing value
property loadDone : false –original was "webFrame"
property aWebView : missing value

tell application "Safari"
  if (count every document) = 0 then return
  
tell front document
    set aURL to URL
  end tell
end tell

set aPath to (POSIX path of (path to desktop)) & ((current application’s NSUUID’s UUID()’s UUIDString()) as string) & ".webarchive"
set archRes to archivePageToPathWithoutSearching(aURL, aPath, me, 10) of me

on archivePageToPathWithoutSearching(thePageURL, aPath, sender, timeoutSec)
  –Check If this script runs in foreground
  
if not (current application’s NSThread’s isMainThread()) as boolean then
    display alert "This script must be run from the main thread (Command-Control-R in Script Editor)." buttons {"Cancel"} as critical
    
error number -128
  end if
  
  
set my theSender to sender — store main script so we can call back
  
set my thePath to aPath — store path for use later
  
set my aWebView to missing value
  
set my loadDone to false
  
  
— make a WebView
  
set theView to current application’s WebView’s alloc()’s initWithFrame:{origin:{x:0, y:0}, |size|:{width:100, height:100}}
  
  
— tell it call delegate methods on me
  
theView’s setFrameLoadDelegate:me
  
  
— load the page
  
theView’s setMainFrameURL:thePageURL
  
  
–wait for download & saving
  
repeat timeoutSec * 10 times
    if my loadDone is not equal to false then
      exit repeat
    end if
    
delay 0.1
  end repeat
  
if my loadDone = false then return "timed out"
  
  
  
— the main frame is our interest
  
if (my loadDone) = aWebView’s mainFrame() then
    — get the data and write it to file
    
set theArchiveData to (my loadDone)’s dataSource()’s webArchive()’s |data|()
    
theArchiveData’s writeToFile:thePath atomically:true
    
    
— tell our script it’s all done
    
return "The webarchive was saved"
  end if
end archivePageToPathWithoutSearching

— called when our WebView loads a frame
on WebView:curWebView didFinishLoadForFrame:webFrame
  set my loadDone to webFrame
  
set my aWebView to curWebView
end WebView:didFinishLoadForFrame:

— called when there’s a problem
on WebView:WebView didFailLoadWithError:theError forFrame:webFrame
  — got an error, bail
  
WebView’s stopLoading:me
  
set my loadDone to false
  
error "The webarchive was not saved"
end WebView:didFailLoadWithError:forFrame:

★Click Here to Open This Script 

Posted in file Internet Require Control-Command-R to run | Tagged 10.11savvy 10.12savvy 10.13savvy Safari | 3 Comments

指定URLのページをwebarchive保存 v2

Posted on 2月 11, 2018 by Takaaki Naganoya

指定のURLの内容をデスクトップ上にwebarchive書類として保存するAppleScriptです。

SafariがAppleScript側にwebarchive保存機能を提供していないので、

 (1)GUI Scriptingで無理やりメニューを操作してwebarchive保存
 (2)AppleScriptでCocoaの機能を呼び出してwebarchive保存
 (3)コマンドラインツールを呼び出してwebarchive保存

といった代替策をとる必要があります。本Scriptは(2)を行なったものです。

オリジナルのAppleScriptはShane StanleyがCocoa Scripting普及初期に書いたもので、非同期で処理しておりそのままではAppleScriptのワークフローに組み込むには難がありました(処理結果が正しく実行できたかなど、結果を確実に確認できたほうがよいので)。

そこで、他のワークフローに組み込みやすいように構造を変えてみました。ただ、内部でdelegateによる通知処理を利用しているのでフォアグラウンドでの実行が必須となります(Command-Control-R)。

AppleScript名:指定URLのページをwebarchive保存 v2
— Created 2014-11-13 Shane Stanley
— Modified 2018-02-11 Takaaki Naganoya
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "WebKit"

property theSender : missing value
property thePath : missing value
property theSearchString : missing value
property loadDone : false –original was "webFrame"
property aWebView : missing value

set aPath to (POSIX path of (path to desktop)) & ((current application’s NSUUID’s UUID()’s UUIDString()) as string) & ".webarchive"
set archRes to archivePageToPath("https://www.apple.com/jp/shop/browse/home/specialdeals/mac", aPath, "Mac mini", me, 10) of me

on archivePageToPath(thePageURL, aPath, searchString, sender, timeoutSec)
  –Check If this script runs in foreground
  
if not (current application’s NSThread’s isMainThread()) as boolean then
    display alert "This script must be run from the main thread (Command-Control-R in Script Editor)." buttons {"Cancel"} as critical
    
error number -128
  end if
  
  
set my theSender to sender — store main script so we can call back
  
set my thePath to aPath — store path for use later
  
set my theSearchString to searchString — store for use later
  
set my aWebView to missing value
  
set my loadDone to false
  
  
— make a WebView
  
set theView to current application’s WebView’s alloc()’s initWithFrame:{origin:{x:0, y:0}, |size|:{width:100, height:100}}
  
  
— tell it call delegate methods on me
  
theView’s setFrameLoadDelegate:me
  
  
— load the page
  
theView’s setMainFrameURL:thePageURL
  
  
–wait for download & saving
  
repeat timeoutSec * 10 times
    if my loadDone is not equal to false then
      exit repeat
    end if
    
delay 0.1
  end repeat
  
if my loadDone = false then return "timed out"
  
  
  
— the main frame is our interest
  
if (my loadDone) = aWebView’s mainFrame() then
    
    
— get the text of the page
    
set theText to ((my loadDone)’s DOMDocument()’s documentElement()’s outerText())
    
    
— search it
    
if (theText’s rangeOfString:theSearchString)’s |length|() > 0 then
      
      
— get the data and write it to file
      
set theArchiveData to (my loadDone)’s dataSource()’s webArchive()’s |data|()
      
theArchiveData’s writeToFile:thePath atomically:true
      
      
— tell our script it’s all done
      
return "The webarchive was saved"
    else
      return "Seach string not found"
    end if
  end if
  
end archivePageToPath

— called when our WebView loads a frame
on WebView:curWebView didFinishLoadForFrame:webFrame
  set my loadDone to webFrame
  
set my aWebView to curWebView
end WebView:didFinishLoadForFrame:

— called when there’s a problem
on WebView:WebView didFailLoadWithError:theError forFrame:webFrame
  — got an error, bail
  
WebView’s stopLoading:me
  
set my loadDone to false
  
error "The webarchive was not saved"
end WebView:didFailLoadWithError:forFrame:

★Click Here to Open This Script 

Posted in file Internet Require Control-Command-R to run | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

指定URLをロードしてページ中の画像を取得 v2

Posted on 2月 11, 2018 by Takaaki Naganoya
AppleScript名:指定URLをロードしてページ中の画像を取得 v2
— Created 2015-09-07 by Takaaki Naganoya
— 2015 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "WebKit"

property loadDone : false
property theWebView : missing value

set aURL to "http://piyocast.com/as/archives/1176"
set aRes to getPage(aURL)
set aList to getPageImages() of me
set theWebView to missing value –Purge

aList

–theWebViewにロードしておいたページから画像情報を取得
on getPageImages()
  set aList to {}
  
set imgNum to ((my theWebView)’s stringByEvaluatingJavaScriptFromString:"document.images.length") as integer
  
repeat with i from 0 to (imgNum – 1)
    set jsT to "document.images[" & (i as string) & "].height"
    
set aHeight to ((my theWebView)’s stringByEvaluatingJavaScriptFromString:jsT) as integer
    
    
set jsT to "document.images[" & (i as string) & "].width"
    
set aWidth to ((my theWebView)’s stringByEvaluatingJavaScriptFromString:jsT) as integer
    
    
set jsT to "document.images[" & (i as string) & "].src"
    
set aSRC to ((my theWebView)’s stringByEvaluatingJavaScriptFromString:jsT) as text
    
    
set the end of aList to {aHeight, aWidth, aSRC}
  end repeat
  
return aList
end getPageImages

–theWebViewにロードしておいたページからタイトルを取得
on getPageTitle()
  set x to ((my theWebView)’s stringByEvaluatingJavaScriptFromString:"document.title") as text
  
return x
end getPageTitle

–指定のURLの内容をtheWebViewに取得
on getPage(aURL)
  –Check If this script runs in foreground
  
if not (current application’s NSThread’s isMainThread()) as boolean then
    display alert "This script must be run from the main thread (Command-Control-R in Script Editor)." buttons {"Cancel"} as critical
    
error number -128
  end if
  
  
set my loadDone to false
  
set my theWebView to missing value
  
openURL(aURL)
  
  
set waitLoop to 1000 * 60 –60 seconds
  
  
set hitF to false
  
repeat waitLoop times
    if my loadDone = true then
      set hitF to true
      
exit repeat
    end if
    
current application’s NSThread’s sleepForTimeInterval:("0.001" as real) –delay 0.001
  end repeat
  
if hitF = false then return
  
  
return true
end getPage

–WebViewにURLを読み込む
on openURL(aURL)
  set noter1 to current application’s NSNotificationCenter’s defaultCenter()
  
set my theWebView to current application’s WebView’s alloc()’s init()
  
noter1’s addObserver:me selector:"webLoaded:" |name|:(current application’s WebViewProgressFinishedNotification) object:(my theWebView)
  
my (theWebView’s setMainFrameURL:aURL)
end openURL

–Web Viewのローディング完了時に実行
on webLoaded:aNotification
  set my loadDone to true
end webLoaded:

★Click Here to Open This Script 

Posted in file Internet JavaScript Require Control-Command-R to run | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

指定URLをロードしてtitleを取得

Posted on 2月 11, 2018 by Takaaki Naganoya
AppleScript名:指定URLをロードしてtitleを取得
— Created 2015-09-07 by Takaaki Naganoya
— 2015 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "WebKit"

property loadDone : false
property theWebView : missing value

set aURL to "https://www.youtube.com/watch?v=WuziqYptTyE"
set aTitle to getPageTitle(aURL)
–>  "戦場の絆ポータブル【HD】鉱山都市 オンライン対戦 2015.09.04 – YouTube"

on getPageTitle(aURL)
  –Check If this script runs in foreground
  
if not (current application’s NSThread’s isMainThread()) as boolean then
    display alert "This script must be run from the main thread (Command-Control-R in Script Editor)." buttons {"Cancel"} as critical
    
error number -128
  end if
  
  
set my loadDone to false
  
set my theWebView to missing value
  
openURL(aURL)
  
  
set waitLoop to 1000 * 60 –60 seconds
  
  
set hitF to false
  
repeat waitLoop times
    if my loadDone = true then
      set hitF to true
      
exit repeat
    end if
    
current application’s NSThread’s sleepForTimeInterval:("0.001" as real) –delay 0.001
  end repeat
  
if hitF = false then return
  
  
set jsText to "document.title"
  
set x to ((my theWebView)’s stringByEvaluatingJavaScriptFromString:jsText) as text
  
set my theWebView to missing value
  
  
return x
end getPageTitle

–WebViewにURLを読み込む
on openURL(aURL)
  set noter1 to current application’s NSNotificationCenter’s defaultCenter()
  
set my theWebView to current application’s WebView’s alloc()’s init()
  
noter1’s addObserver:me selector:"webLoaded:" |name|:(current application’s WebViewProgressFinishedNotification) object:(my theWebView)
  
my (theWebView’s setMainFrameURL:aURL)
end openURL

–Web Viewのローディング完了時に実行
on webLoaded:aNotification
  set my loadDone to true
end webLoaded:

★Click Here to Open This Script 

Posted in Internet JavaScript Text | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

web上の画像をローカルにダウンロードして保存

Posted on 2月 11, 2018 by Takaaki Naganoya
AppleScript名:web上の画像をローカルにダウンロードして保存
— Created 2013-12-27 Shane Stanley
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set thePicURL to "http://www.macosxautomation.com/applescript/apps/gfx/EverydayCover300.jpg"
set thePath to POSIX path of ((path to desktop as text) & "Test.jpg")
set aRes to saveImageURLToPath(thePicURL, thePath)

on saveImageURLToPath(thePicURL, thePath)
  set theNSURL to current application’s |NSURL|’s URLWithString:thePicURL
  
set picData to current application’s NSData’s dataWithContentsOfURL:theNSURL
  
picData’s writeToFile:thePath atomically:true
end saveImageURLToPath

★Click Here to Open This Script 

Posted in file Internet | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

URLの妥当性チェック

Posted on 2月 11, 2018 by Takaaki Naganoya
AppleScript名:URLの妥当性チェック
— Created 2015-09-06 by Takaaki Naganoya
— 2015 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
–http://stackoverflow.com/questions/1471201/how-to-validate-an-url-on-the-iphone

set aRes1 to validateURL("http://www.apple.com/jp")
–>  true

set aRes2 to validateURL("http.s://www.gmail.com")
–>  false
set aRes3 to validateURL("https:.//gmailcom")
–>  false
set aRes4 to validateURL("https://gmail.me.")
–>  false
set aRes5 to validateURL("https://www.gmail.me.com.com.com.com")
–>  true
set aRes6 to validateURL("http:/./ww-w.wowone.com")
–>  false
set aRes7 to validateURL("http://.www.wowone")
–>  false
set aRes8 to validateURL("http://www.wow-one.com")
–>  true
set aRes9 to validateURL("http://www.wow_one.com")
–>  true
set aRes10 to validateURL("http://.")
–>  false
set aRes11 to validateURL("http://")
–>  false
set aRes12 to validateURL("http://k")
–>  false

return {aRes2, aRes3, aRes4, aRes5, aRes6, aRes7, aRes8, aRes9, aRes10, aRes11, aRes12}
–>  {​​​​​false, ​​​​​false, ​​​​​false, ​​​​​true, ​​​​​false, ​​​​​false, ​​​​​true, ​​​​​true, ​​​​​false, ​​​​​false, ​​​​​false​​​}

–URLの妥当性チェック
on validateURL(anURL as text)
  –set regEx1 to current application’s NSString’s stringWithString:"(http|https)://((\\w)*|([0-9]*)|([-|_])*)+([\\.|/]((\\w)*|([0-9]*)|([-|_])*))+"
  
set regEx1 to current application’s NSString’s stringWithString:"((https|http)://)((\\w|-)+)(([.]|[/])((\\w|-)+))+"
  
set predicate1 to current application’s NSPredicate’s predicateWithFormat_("SELF MATCHES %@", regEx1)
  
set aPredRes1 to (predicate1’s evaluateWithObject:anURL) as boolean
  
return aPredRes1
end validateURL

★Click Here to Open This Script 

Posted in Internet regexp Text | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

VPN経由のネットワーク接続を切断する

Posted on 2月 11, 2018 by Takaaki Naganoya
AppleScript名:VPN経由のネットワーク接続を切断する
— Created 2017-09-30 by Takaaki Naganoya
— 2017 Piyomaru Software

tell application "System Events"
  tell current location of network preferences
    set sList to every service whose kind is 13 and active is true –種別がVPNのNetwork Serviceで状態がactive(接続中)のものを取得
    
if sList = {} then return false
    
    
if length of sList is not equal to 1 then
      –複数VPNが存在している場合にはユーザー選択
      
set ssRes to choose from list sList
      
if ssRes = false then return false
      
set sRes to first item of ssRes
    else
      set sRes to first item of sList
    end if
    
    
disconnect sRes
  end tell
end tell

★Click Here to Open This Script 

Posted in Internet | Tagged 10.11savvy 10.12savvy 10.13savvy System Events | Leave a comment

VPN経由でネットワーク接続

Posted on 2月 11, 2018 by Takaaki Naganoya

VPN経由でネットワーク接続を行うAppleScriptです。

システム環境設定の「ネットワーク」で「VPN」を追加、定義し、正常にVPN接続できていることを確認してください。本AppleScriptはあらかじめ定義してあるVPN接続先への自動接続を行うものです。

複数のVPN接続を定義してある場合にはユーザーに選択を求めます。

VPN接続関連のAppleScriptの機能に、勝手に新規接続先を定義してVPN接続できるようなものはありません。あくまで、すでにユーザーが定義したVPN接続先に対して接続/切断を行うだけの機能です。

AppleScript名:VPN経由でネットワーク接続
— Created 2017-09-30 by Takaaki Naganoya
— 2017 Piyomaru Software

tell application "System Events"
  tell current location of network preferences
    set sList to every service whose kind is 13 –種別がVPNのNetwork Service
    
if sList = {} then return false
    
    
if length of sList is not equal to 1 then
      –複数VPNが存在している場合にはユーザー選択
      
set ssRes to choose from list sList
      
if ssRes = false then return false
      
set sRes to first item of ssRes
    else
      set sRes to first item of sList
    end if
    
    
connect sRes
  end tell
end tell

★Click Here to Open This Script 

Posted in Internet | Tagged 10.11savvy 10.12savvy 10.13savvy System Events | Leave a comment

(GET)Wikipedia APIでキーワード検索を行う

Posted on 2月 10, 2018 by Takaaki Naganoya
AppleScript名:(GET)Wikipedia APIでキーワード検索を行う
— Created 2016-11-04 by Takaaki Naganoya
— 2016 Piyomaru Software
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
–https://www.mediawiki.org/wiki/API:Main_page/ja

set reqURLStr to "https://jp.wikipedia.org/w/api.php" –Japanese Version

set aRec to {action:"query", titles:"アップル (企業)", |prop|:"revisions", rvprop:"content", |format|:"json"}
set aURL to retURLwithParams(reqURLStr, aRec) of me
set aRes to callRestGETAPIAndParseResults(aURL) of me

set aRESTres to (query of json of aRes)
return aRESTres as list of string or string –as anything

–GET methodのREST APIを呼ぶ
on callRestGETAPIAndParseResults(aURL)
  set aRequest to current application’s NSMutableURLRequest’s requestWithURL:(current application’s |NSURL|’s URLWithString:aURL)
  
  
aRequest’s setHTTPMethod:"GET"
  
aRequest’s setCachePolicy:(current application’s NSURLRequestReloadIgnoringLocalCacheData)
  
aRequest’s setHTTPShouldHandleCookies:false
  
aRequest’s setTimeoutInterval:60
  
aRequest’s setValue:"application/json" forHTTPHeaderField:"Accept"
  
  
set aRes to current application’s NSURLConnection’s sendSynchronousRequest:aRequest returningResponse:(reference) |error|:(missing value)
  
set resList to aRes as list
  
  
set bRes to contents of (first item of resList)
  
set resStr to current application’s NSString’s alloc()’s initWithData:bRes encoding:(current application’s NSUTF8StringEncoding)
  
  
set jsonString to current application’s NSString’s stringWithString:resStr
  
set jsonData to jsonString’s dataUsingEncoding:(current application’s NSUTF8StringEncoding)
  
set aJsonDict to current application’s NSJSONSerialization’s JSONObjectWithData:jsonData options:0 |error|:(missing value)
  
  
–Get Response Code & Header
  
set dRes to contents of second item of resList
  
if dRes is not equal to missing value then
    set resCode to (dRes’s statusCode()) as number
    
set resHeaders to (dRes’s allHeaderFields()) as record
  else
    set resCode to 0
    
set resHeaders to {}
  end if
  
  
return {json:aJsonDict, responseCode:resCode, responseHeader:resHeaders}
end callRestGETAPIAndParseResults

on retURLwithParams(aBaseURL, aRec)
  set aDic to current application’s NSMutableDictionary’s dictionaryWithDictionary:aRec
  
  
set aKeyList to (aDic’s allKeys()) as list
  
set aValList to (aDic’s allValues()) as list
  
set aLen to length of aKeyList
  
  
set qList to {}
  
repeat with i from 1 to aLen
    set aName to contents of item i of aKeyList
    
set aVal to contents of item i of aValList
    
set the end of qList to (current application’s NSURLQueryItem’s queryItemWithName:aName value:aVal)
  end repeat
  
  
set aComp to current application’s NSURLComponents’s alloc()’s initWithString:aBaseURL
  
aComp’s setQueryItems:qList
  
set aURL to (aComp’s |URL|()’s absoluteString()) as text
  
  
return aURL
end retURLwithParams

on urlencodeStr(aStr)
  set aString to current application’s NSString’s stringWithString:aStr
  
set aString to (aString’s stringByAddingPercentEncodingWithAllowedCharacters:(current application’s NSCharacterSet’s URLQueryAllowedCharacterSet())) as text
  
return aString
end urlencodeStr

★Click Here to Open This Script 

Posted in Internet REST API | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

connpassイベントサーチAPIで検索を行うv2

Posted on 2月 10, 2018 by Takaaki Naganoya
AppleScript名:connpassイベントサーチAPIで検索を行うv2
— Created 2016-10-29 by Takaaki Naganoya
— 2016 Piyomaru Software
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
–http://connpass.com/about/api/
–http://piyocast.com/as/archives/4300

set reqURLStr to "https://connpass.com/api/v1/event/"

set aRec to {keyword:"AppleScript", ym:"201611"} –サーチクエリーと対象月
set aURL to retURLwithParams(reqURLStr, aRec) of me
set aRes to callRestGETAPIAndParseResults(aURL) of me

set aRESTres to (json of aRes) as record
return aRESTres
–>
(*
{results_available:1, results_start:1, |events|:{{place:"マイ・スペース MS&BB 池袋西武横店 1号室", event_url:"http://ashole.connpass.com/event/44103/", accepted:2, title:"AppleScript本フィードバック会", limit:7, event_type:"participation", owner_id:64136, ended_at:"2016-11-26T20:30:00+09:00", updated_at:"2016-11-01T09:22:15+09:00", lon:"139.711383200000", waiting:0, event_id:44103, hash_tag:"AppleScript,Mac,macOS,Mac OS X", owner_nickname:"Piyomaru", lat:"35.726486900000", started_at:"2016-11-26T18:30:00+09:00", owner_display_name:"Piyomaru", catch:"「AppleScript最新リファレンス」「AppleScript最新10大技術」についての解説", series:{|url|:"http://ashole.connpass.com/", |id|:3041, title:"AppleScriptの穴"}, address:"〒171-0022 東京都豊島区南池袋1-16-20(ぬかりやビル2階)", |description|:"<p>macOS標準装備で、GUIアプリケーションを操作できるマクロ言語「AppleScript」、その20年以上の歴史をまとめ、最新情報を盛り込んだ電子書籍「AppleScript最新リファレンス」「AppleScript 最新10大技術」を発行いたしました。</p>\n<p>・電子書籍オンライン販売URL\n<a href=\"https://piyomarusoft.booth.pm\" rel=\"nofollow\">https://piyomarusoft.booth.pm</a></p>\n<p>これらの本について、分からない点やもっと知りたい点について、筆者本人と直接お話できる場を設けました。</p>\n<p>参加資格は、AppleScriptを実際に使っている方、興味を持っている方で、筆者の書籍を実際に購入した、あるいは購入しようと考えている方です。事前に内容を読んであることが望ましいです。</p>\n<p>筆者Blog「AppleScriptの穴」\n<a href=\"http://piyocast.com/as/\" rel=\"nofollow\">http://piyocast.com/as/</a></p>"}}, results_returned:1}
*)

–GET methodのREST APIを呼ぶ
on callRestGETAPIAndParseResults(aURL)
  set aRequest to current application’s NSMutableURLRequest’s requestWithURL:(current application’s |NSURL|’s URLWithString:aURL)
  
  
aRequest’s setHTTPMethod:"GET"
  
aRequest’s setCachePolicy:(current application’s NSURLRequestReloadIgnoringLocalCacheData)
  
aRequest’s setHTTPShouldHandleCookies:false
  
aRequest’s setTimeoutInterval:60
  
aRequest’s setValue:"application/json" forHTTPHeaderField:"Accept"
  
  
set aRes to current application’s NSURLConnection’s sendSynchronousRequest:aRequest returningResponse:(reference) |error|:(missing value)
  
set resList to aRes as list
  
  
set bRes to contents of (first item of resList)
  
set resStr to current application’s NSString’s alloc()’s initWithData:bRes encoding:(current application’s NSUTF8StringEncoding)
  
  
set jsonString to current application’s NSString’s stringWithString:resStr
  
set jsonData to jsonString’s dataUsingEncoding:(current application’s NSUTF8StringEncoding)
  
set aJsonDict to current application’s NSJSONSerialization’s JSONObjectWithData:jsonData options:0 |error|:(missing value)
  
  
–Get Response Code & Header
  
set dRes to contents of second item of resList
  
if dRes is not equal to missing value then
    set resCode to (dRes’s statusCode()) as number
    
set resHeaders to (dRes’s allHeaderFields()) as record
  else
    set resCode to 0
    
set resHeaders to {}
  end if
  
  
return {json:aJsonDict, responseCode:resCode, responseHeader:resHeaders}
end callRestGETAPIAndParseResults

on retURLwithParams(aBaseURL, aRec)
  set aDic to current application’s NSMutableDictionary’s dictionaryWithDictionary:aRec
  
  
set aKeyList to (aDic’s allKeys()) as list
  
set aValList to (aDic’s allValues()) as list
  
set aLen to length of aKeyList
  
  
set qList to {}
  
repeat with i from 1 to aLen
    set aName to contents of item i of aKeyList
    
set aVal to contents of item i of aValList
    
set the end of qList to (current application’s NSURLQueryItem’s queryItemWithName:aName value:aVal)
  end repeat
  
  
set aComp to current application’s NSURLComponents’s alloc()’s initWithString:aBaseURL
  
aComp’s setQueryItems:qList
  
set aURL to (aComp’s |URL|()’s absoluteString()) as text
  
  
return aURL
end retURLwithParams

on urlencodeStr(aStr)
  set aString to current application’s NSString’s stringWithString:aStr
  
set aString to (aString’s stringByAddingPercentEncodingWithAllowedCharacters:(current application’s NSCharacterSet’s URLQueryAllowedCharacterSet())) as text
  
return aString
end urlencodeStr

★Click Here to Open This Script 

Posted in Internet REST API | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

TextEditで最前面のドキュメント内で使用されている色情報を抽出して処理対象色を選択(色名の計算機能つき)v3

Posted on 2月 10, 2018 by Takaaki Naganoya

TextEditの最前面の書類本文の色情報を抽出し、ダイアログ上に色選択ポップアップを作成して処理対象色をえらび、該当する色の文字を抽出するAppleScriptです。

DBColorNames.frameworkを用いて、900色程度の色見本から近似の色名称を計算しています。

–> dbColNamesKit.framework

AppleScript名:TextEditで最前面のドキュメント内で使用されている色情報を抽出して処理対象色を選択(色名の計算機能つき)v3
— Created 2017-12-26 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
use framework "AppKit"
use framework "Carbon" — AEInteractWithUser() is in Carbon
use framework "dbColNamesKit" –https://github.com/daniel-beard/DBColorNames/

property NSView : a reference to current application’s NSView
property NSColor : a reference to current application’s NSColor
property NSArray : a reference to current application’s NSArray
property NSMenu : a reference to current application’s NSMenu
property NSImage : a reference to current application’s NSImage
property NSScreen : a reference to current application’s NSScreen
property NSButton : a reference to current application’s NSButton
property NSWindow : a reference to current application’s NSWindow
property NSTextField : a reference to current application’s NSTextField
property NSMenuItem : a reference to current application’s NSMenuItem
property NSBezierPath : a reference to current application’s NSBezierPath
property NSPopUpButton : a reference to current application’s NSPopUpButton
property NSSortDescriptor : a reference to current application’s NSSortDescriptor
property NSWindowController : a reference to current application’s NSWindowController
property NSTitledWindowMask : a reference to current application’s NSTitledWindowMask
property NSRoundedBezelStyle : a reference to current application’s NSRoundedBezelStyle
property NSNormalWindowLevel : a reference to current application’s NSNormalWindowLevel
property NSBackingStoreBuffered : a reference to current application’s NSBackingStoreBuffered
property NSMomentaryLightButton : a reference to current application’s NSMomentaryLightButton

property windisp : false

if current application’s AEInteractWithUser(-1, missing value, missing value) is not equal to 0 then return

tell application "TextEdit"
  set dCount to count every document
  
if dCount = 0 then return
  
tell text of front document
    set aList to color of every attribute run
  end tell
end tell

–1D/2D Listのユニーク化
set ap1List to uniquify1DList(aList, true) of me

–色選択ダイアログを表示してポップアップメニューから色選択
set aButtonMSG to "OK"
set aWindowTitle to "Choose Color"

set aVal to getPopupValues(ap1List, 65535, aButtonMSG, aWindowTitle, 180) of me

if (aVal = false) or (aVal = missing value) then
  display dialog "No Selection" buttons {"OK"} default button 1 with icon 2
  
return
end if

set targColor to item aVal of ap1List
set aRes to pickupColoredText(targColor) of me
set the clipboard to aRes –抽出結果をクリップボードへ
return aRes

on getPopupValues(ap1List, aColMax, aButtonMSG, aWindowMSG, timeOutSecs)
  
  
set (my windisp) to true
  
  
set aView to NSView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, 360, 100))
  
  
–Labelをつくる
  
set a1TF to NSTextField’s alloc()’s initWithFrame:(current application’s NSMakeRect(30, 60, 80, 20))
  
a1TF’s setEditable:false
  
a1TF’s setStringValue:"Color:"
  
a1TF’s setDrawsBackground:false
  
a1TF’s setBordered:false
  
  
–Ppopup Buttonをつくる
  
set a1Button to NSPopUpButton’s alloc()’s initWithFrame:(current application’s NSMakeRect(80, 60, 200, 20)) pullsDown:false
  
a1Button’s removeAllItems()
  
  
set a1Menu to NSMenu’s alloc()’s init()
  
  
set iCount to 1
  
repeat with i in ap1List
    copy i to {rCol, gCol, bCol}
    
set j to contents of i
    
    
set aCocoaList to retCocoaColorList(j, aColMax) of me
    
set nsCol to (NSColor’s colorFromRGBAArray:aCocoaList)
    
    
set anImage to makeNSImageWithFilledWithColor(32, 20, nsCol) of me
    
    
set aColName to retColorDetailName(rCol, gCol, bCol, 65535) of me
    
set aTitle to "#" & (iCount as string) & " " & aColName
    
set aMenuItem to (NSMenuItem’s alloc()’s initWithTitle:aTitle action:"actionHandler:" keyEquivalent:"")
    (
aMenuItem’s setImage:anImage)
    (
aMenuItem’s setEnabled:true)
    (
a1Menu’s addItem:aMenuItem)
    
    
set iCount to iCount + 1
  end repeat
  
  
a1Button’s setMenu:a1Menu
  
  
  
–Buttonをつくる
  
set bButton to (NSButton’s alloc()’s initWithFrame:(current application’s NSMakeRect(80, 10, 140, 40)))
  
bButton’s setButtonType:(current application’s NSMomentaryLightButton)
  
bButton’s setBezelStyle:(current application’s NSRoundedBezelStyle)
  
bButton’s setTitle:aButtonMSG
  
bButton’s setTarget:me
  
bButton’s setAction:("clicked:")
  
bButton’s setKeyEquivalent:(return)
  
  
aView’s addSubview:a1TF
  
  
aView’s addSubview:a1Button
  
aView’s addSubview:bButton
  
aView’s setNeedsDisplay:true
  
  
–NSWindowControllerを作ってみた
  
set aWin to (my makeWinWithView(aView, 300, 100, aWindowMSG))
  
  
set wController to NSWindowController’s alloc()
  
wController’s initWithWindow:aWin
  
  
wController’s showWindow:me
  
  
set aCount to timeOutSecs * 100
  
  
set hitF to false
  
repeat aCount times
    if (my windisp) = false then
      set hitF to true
      
exit repeat
    end if
    
delay 0.01
    
set aCount to aCount – 1
  end repeat
  
  
my closeWin:aWin
  
  
if hitF = true then
    set s1Val to (a1Button’s indexOfSelectedItem() as integer) + 1
  else
    set s1Val to false
  end if
  
  
return s1Val
  
end getPopupValues

on clicked:aSender
  set (my windisp) to false
end clicked:

–make Window for Display
on makeWinWithView(aView, aWinWidth, aWinHeight, aTitle)
  set aScreen to NSScreen’s mainScreen()
  
set aFrame to {{0, 0}, {aWinWidth, aWinHeight}}
  
  
set aBacking to current application’s NSTitledWindowMask
  
  
set aDefer to current application’s NSBackingStoreBuffered
  
  
— Window
  
set aWin to NSWindow’s alloc()
  (
aWin’s initWithContentRect:aFrame styleMask:aBacking backing:aDefer defer:false screen:aScreen)
  
–aWin’s setBackgroundColor:(current application’s NSColor’s whiteColor())
  
  
aWin’s setTitle:aTitle
  
aWin’s setDelegate:me
  
aWin’s setDisplaysWhenScreenProfileChanges:true
  
aWin’s setHasShadow:true
  
aWin’s setIgnoresMouseEvents:false
  
aWin’s setLevel:(current application’s NSNormalWindowLevel)
  
aWin’s setOpaque:false
  
aWin’s setReleasedWhenClosed:true
  
aWin’s |center|()
  
–aWin’s makeKeyAndOrderFront:(me)
  
  
aWin’s setContentView:aView
  
  
return aWin
  
end makeWinWithView

–close win
on closeWin:aWindow
  repeat with n from 10 to 1 by -1
    (aWindow’s setAlphaValue:n / 10)
    
delay 0.02
  end repeat
  
aWindow’s |close|()
end closeWin:

–Popup Action Handler
on actionHandler:sender
  set aTag to tag of sender as integer
  
set aTitle to title of sender as string
end actionHandler:

on makeNSColorFromRGBAval(redValue as integer, greenValue as integer, blueValue as integer, alphaValue as integer, aMaxVal as integer)
  set aRedCocoa to (redValue / aMaxVal) as real
  
set aGreenCocoa to (greenValue / aMaxVal) as real
  
set aBlueCocoa to (blueValue / aMaxVal) as real
  
set aAlphaCocoa to (alphaValue / aMaxVal) as real
  
set aColor to NSColor’s colorWithCalibratedRed:aRedCocoa green:aGreenCocoa blue:aBlueCocoa alpha:aAlphaCocoa
  
return aColor
end makeNSColorFromRGBAval

–1D Listをユニーク化
on uniquify1DList(theList as list, aBool as boolean)
  set aArray to NSArray’s arrayWithArray:theList
  
set bArray to aArray’s valueForKeyPath:"@distinctUnionOfObjects.self"
  
set bList to bArray as list
  
return bList
end uniquify1DList

–指定サイズのNSImageを作成し、指定色で塗って返す
on makeNSImageWithFilledWithColor(aWidth, aHeight, fillColor)
  set anImage to NSImage’s alloc()’s initWithSize:(current application’s NSMakeSize(aWidth, aHeight))
  
anImage’s lockFocus()
  
—
  
set theRect to {{x:0, y:0}, {height:aHeight, width:aWidth}}
  
set theNSBezierPath to NSBezierPath’s bezierPath
  
theNSBezierPath’s appendBezierPathWithRect:theRect
  
—
  
fillColor’s |set|() –色設定
  
theNSBezierPath’s fill() –ぬりつぶし
  
—
  
anImage’s unlockFocus()
  
—
  
return anImage
end makeNSImageWithFilledWithColor

on pickupColoredText(aColList)
  set outStrList to ""
  
  
tell application "TextEdit"
    tell text of front document
      set colorList to color of every attribute run
      
set textList to characters of every attribute run
      
      
set aCount to length of colorList
      
      
repeat with i from 1 to aCount
        set aColCon to item i of colorList
        
if aColCon is equal to aColList then –指定色の箇所
          set outStrList to outStrList & ((contents of item i of textList) as string) & return
        end if
      end repeat
      
    end tell
  end tell
  
  
return outStrList
end pickupColoredText

on retColorDetailName(rCol as integer, gCol as integer, bCol as integer, aColorMax)
  set aColor to makeNSColorFromRGBAval(rCol, gCol, bCol, aColorMax, aColorMax) of me
  
set aCDB to current application’s DBColorNames’s alloc()’s init()
  
set aColorStr to (aCDB’s nameForColor:aColor) as string
  
return aColorStr
end retColorDetailName

on retCocoaColorList(aColorList as list, aMax as integer)
  set tmpList to {}
  
repeat with i in aColorList
    set j to (contents of i)
    
    
if j = 0 then
      set the end of tmpList to 0
    else
      set the end of tmpList to (j / aMax) as real
    end if
    
  end repeat
  
set the end of tmpList to 1.0
  
return tmpList
end retCocoaColorList

–数値の1D List with Recordをソート
on sort1DRecList(aList as list, aKey as string, ascendingF as boolean)
  set aArray to NSArray’s arrayWithArray:aList
  
set desc1 to NSSortDescriptor’s sortDescriptorWithKey:aKey ascending:ascendingF selector:"compare:"
  
set bList to (aArray’s sortedArrayUsingDescriptors:{desc1}) as list
  
return bList
end sort1DRecList

★Click Here to Open This Script 

Posted in Color file GUI | Tagged 10.11savvy 10.12savvy 10.13savvy TextEdit | Leave a comment

TextEditの文章のうち赤っぽい色でマークされた箇所をピックアップする v2

Posted on 2月 9, 2018 by Takaaki Naganoya

TextEditの最前面の書類本文のうち、指定の色名称の色(red)に分類できる文字を出力するAppleScriptです。

AppleScript名:TextEditの文章のうち赤っぽい色でマークされた行をカウントする v2
— Created 2018-01-08 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"

property NSColor : a reference to current application’s NSColor

set rNum to 0
set colMax to 65535

tell application "TextEdit"
  tell text of document 1
    set pCount to (count paragraphs)
    
    
repeat with i from 1 to pCount
      set {rCol, gCol, bCol} to color of paragraph i
      
set cName to retColorDomainName(rCol, gCol, bCol, colMax) of me
      
      
if cName = "red" then –{r, g, b}
        set rNum to rNum + 1
      end if
    end repeat
    
  end tell
end tell

return {pCount, rNum}

on retColorDomainName(rCol as integer, gCol as integer, bCol as integer, aColorMax)
  set aCol to makeNSColorFromRGBAval(rCol, gCol, bCol, aColorMax, aColorMax) of me
  
set hueVal to aCol’s hueComponent()
  
set satVal to aCol’s saturationComponent()
  
set brightVal to aCol’s brightnessComponent()
  
  
if satVal ≤ 0.01 then set satVal to 0.0
  
  
set colName to ""
  
  
if satVal = 0.0 then
    if brightVal ≤ 0.2 then
      set colName to "black"
    else if (brightVal > 0.95) then
      set colName to "white"
    else
      set colName to "gray"
    end if
  else
    if hueVal ≤ (15.0 / 360) or hueVal ≥ (330 / 360) then
      set colName to "red"
    else if hueVal ≤ (45.0 / 360) then
      set colName to "orange"
    else if hueVal < (70.0 / 360) then
      set colName to "yellow"
    else if hueVal < (150.0 / 360) then
      set colName to "green"
    else if hueVal < (190.0 / 360) then
      set colName to "cyan"
    else if (hueVal < 250.0 / 360.0) then
      set colName to "blue"
    else if (hueVal < 290.0 / 360.0) then
      set colName to "purple"
    else
      set colName to "magenta"
    end if
  end if
  
  
return colName
end retColorDomainName

on makeNSColorFromRGBAval(redValue as integer, greenValue as integer, blueValue as integer, alphaValue as integer, aMaxVal as integer)
  set aRedCocoa to (redValue / aMaxVal) as real
  
set aGreenCocoa to (greenValue / aMaxVal) as real
  
set aBlueCocoa to (blueValue / aMaxVal) as real
  
set aAlphaCocoa to (alphaValue / aMaxVal) as real
  
set aColor to NSColor’s colorWithCalibratedRed:aRedCocoa green:aGreenCocoa blue:aBlueCocoa alpha:aAlphaCocoa
  
return aColor
end makeNSColorFromRGBAval

★Click Here to Open This Script 

Posted in Color file | Tagged 10.11savvy 10.12savvy 10.13savvy TextEdit | 2 Comments

TextEditで本文中の使用色をリストアップ(色判定つき)v3

Posted on 2月 9, 2018 by Takaaki Naganoya

TextEditの最前面のドキュメントの本文色を取得して名称に変換して返すAppleScriptです。

本文中で「だいたいこの系統の色」が使われているかをリストアップします。

–> {“blue”, “red”, “green”}

ただし、いろいろ編集していると改行文字の箇所に意図しない色がついていることがあり、見た目だけではわからない色が検出されるケースもあります。そのような場合には、TextEditの文章のうち赤っぽい色でマークされた箇所をピックアップする v2を使って指定色に該当する箇所の文字データを抽出して確認してください(ペアで使うことを前提に書いたので)。

AppleScript名:TextEditで本文中の使用色をリストアップ(色判定つき)v3
— Created 2018-02-06 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
use framework "AppKit"

property NSColor : a reference to current application’s NSColor
property NSArray : a reference to current application’s NSArray
property NSSortDescriptor : a reference to current application’s NSSortDescriptor

set colMax to 65535

tell application "TextEdit"
  set dCount to count every document
  
if dCount = 0 then return
  
tell text of front document
    set aList to color of every attribute run
  end tell
end tell

set ap1List to uniquify1DList(aList, true) of me

set cList to {}
repeat with i in ap1List
  copy i to {rCol, gCol, bCol}
  
set cName to retColorDomainName(rCol, gCol, bCol, colMax) of me
  
if cName is not in cList then
    set the end of cList to cName
  end if
end repeat

return cList
–> {"blue", "red", "green"}

–1D Listをユニーク化
on uniquify1DList(theList as list, aBool as boolean)
  set aArray to NSArray’s arrayWithArray:theList
  
set bArray to aArray’s valueForKeyPath:"@distinctUnionOfObjects.self"
  
set bList to bArray as list
  
return bList
end uniquify1DList

on retColorDomainName(rCol as integer, gCol as integer, bCol as integer, aColorMax)
  set aCol to makeNSColorFromRGBAval(rCol, gCol, bCol, aColorMax, aColorMax) of me
  
set hueVal to aCol’s hueComponent()
  
set satVal to aCol’s saturationComponent()
  
set brightVal to aCol’s brightnessComponent()
  
  
if satVal ≤ 0.01 then set satVal to 0.0
  
  
set colName to ""
  
  
if satVal = 0.0 then
    if brightVal ≤ 0.2 then
      set colName to "black"
    else if (brightVal > 0.95) then
      set colName to "white"
    else
      set colName to "gray"
    end if
  else
    if hueVal ≤ (15.0 / 360) or hueVal ≥ (330 / 360) then
      set colName to "red"
    else if hueVal ≤ (45.0 / 360) then
      set colName to "orange"
    else if hueVal < (70.0 / 360) then
      set colName to "yellow"
    else if hueVal < (150.0 / 360) then
      set colName to "green"
    else if hueVal < (190.0 / 360) then
      set colName to "cyan"
    else if (hueVal < 250.0 / 360.0) then
      set colName to "blue"
    else if (hueVal < 290.0 / 360.0) then
      set colName to "purple"
    else
      set colName to "magenta"
    end if
  end if
  
  
return colName
end retColorDomainName

on makeNSColorFromRGBAval(redValue as integer, greenValue as integer, blueValue as integer, alphaValue as integer, aMaxVal as integer)
  set aRedCocoa to (redValue / aMaxVal) as real
  
set aGreenCocoa to (greenValue / aMaxVal) as real
  
set aBlueCocoa to (blueValue / aMaxVal) as real
  
set aAlphaCocoa to (alphaValue / aMaxVal) as real
  
set aColor to NSColor’s colorWithCalibratedRed:aRedCocoa green:aGreenCocoa blue:aBlueCocoa alpha:aAlphaCocoa
  
return aColor
end makeNSColorFromRGBAval

–数値の1D List with Recordをソート
on sort1DRecList(aList as list, aKey as string, ascendingF as boolean)
  set aArray to NSArray’s arrayWithArray:aList
  
set desc1 to NSSortDescriptor’s sortDescriptorWithKey:aKey ascending:ascendingF selector:"compare:"
  
set bList to (aArray’s sortedArrayUsingDescriptors:{desc1}) as list
  
return bList
end sort1DRecList

★Click Here to Open This Script 

Posted in Color file | Tagged 10.11savvy 10.12savvy 10.13savvy TextEdit | Leave a comment

TextEditで本文色をポスタライズ v2

Posted on 2月 9, 2018 by Takaaki Naganoya


▲Before


▲After

AppleScript名:TextEditで本文色をポスタライズ v2
— Created 2018-01-08 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"
use bPlus : script "BridgePlus" –https://www.macosxautomation.com/applescript/apps/BridgePlus.html

property NSColor : a reference to current application’s NSColor
property NSArray : a reference to current application’s NSArray
property NSSortDescriptor : a reference to current application’s NSSortDescriptor

script spd
  property colList : {}
  
property attList : {}
end script

load framework

set cList to retTextEditColors() of me
set dList to {}

repeat with i in cList
  copy i to {rVal, gVal, bVal}
  
set newColList to posterizeColor(rVal, gVal, bVal, 65535) of me
  
repTextEditColor(i, newColList) of me
end repeat

on repTextEditColor(targColor, newColor)
  set hitIndex to {}
  
  
tell application "TextEdit"
    tell text of front document
      set colList to color of every attribute run
    end tell
  end tell
  
  
set hitIndex to (current application’s SMSForder’s indexesOfItem:targColor inArray:(colList) inverting:false) as list
  
  
tell application "TextEdit"
    tell text of front document
      repeat with i in hitIndex
        ignoring application responses
          set color of attribute run (i + 1) to newColor –0 based index to 1 based index conversion
        end ignoring
      end repeat
    end tell
  end tell
end repTextEditColor

on posterizeColor(rCol as integer, gCol as integer, bCol as integer, aColorMax)
  set aCol to makeNSColorFromRGBAval(rCol, gCol, bCol, aColorMax, aColorMax) of me
  
set hueVal to aCol’s hueComponent()
  
set satVal to aCol’s saturationComponent()
  
set brightVal to aCol’s brightnessComponent()
  
  
if satVal ≤ 0.01 then set satVal to 0.0
  
  
if satVal = 0.0 then
    if brightVal ≤ 0.2 then
      set colVal to {0, 0, 0} –Black
    else if (brightVal > 0.95) then
      set colVal to {65535, 65535, 65535} –White
    else
      set colVal to {32768, 32768, 32768} –Gray
    end if
  else
    if hueVal ≤ (15.0 / 360) or hueVal ≥ (330 / 360) then
      set colVal to {65535, 0, 0} –red
    else if hueVal ≤ (45.0 / 360) then
      set colVal to {65535, 32768, 0} –orange
    else if hueVal < (70.0 / 360) then
      set colVal to {65533, 63639, 2654} –yellow
    else if hueVal < (150.0 / 360) then
      set colVal to {4626, 35488, 17789} –green
    else if hueVal < (190.0 / 360) then
      set colVal to {0, 60802, 65535} –cyan, light blue
    else if (hueVal < 250.0 / 360.0) then
      set colVal to {0, 0, 65535} –blue
    else if (hueVal < 290.0 / 360.0) then
      set colVal to {32768, 0, 32768} –purple
    else
      set colVal to {65535, 0, 65535} –magenta, pink
    end if
  end if
  
  
return colVal
end posterizeColor

on makeNSColorFromRGBAval(redValue as integer, greenValue as integer, blueValue as integer, alphaValue as integer, aMaxVal as integer)
  set aRedCocoa to (redValue / aMaxVal) as real
  
set aGreenCocoa to (greenValue / aMaxVal) as real
  
set aBlueCocoa to (blueValue / aMaxVal) as real
  
set aAlphaCocoa to (alphaValue / aMaxVal) as real
  
set aColor to NSColor’s colorWithCalibratedRed:aRedCocoa green:aGreenCocoa blue:aBlueCocoa alpha:aAlphaCocoa
  
return aColor
end makeNSColorFromRGBAval

on retTextEditColors()
  tell application "TextEdit"
    set dCount to count every document
    
if dCount = 0 then return
    
tell text of front document
      set aList to color of every character
    end tell
  end tell
  
  
set ap1List to uniquify1DList(aList, true) of me
  
set cList to {}
  
repeat with i in ap1List
    set the end of cList to contents of i
  end repeat
  
  
return cList
end retTextEditColors

–1D Listをユニーク化
on uniquify1DList(theList as list, aBool as boolean)
  set aArray to NSArray’s arrayWithArray:theList
  
set bArray to aArray’s valueForKeyPath:"@distinctUnionOfObjects.self"
  
set bList to bArray as list
  
return bList
end uniquify1DList

★Click Here to Open This Script 

Posted in Color file | Tagged 10.11savvy 10.12savvy 10.13savvy TextEdit | Leave a comment

TextEditの文章のうち赤っぽい色でマークされた行をカウントする v2

Posted on 2月 9, 2018 by Takaaki Naganoya

TextEditでオープン中の最前面のドキュメント本文の色情報にアクセスして、「赤っぽい色」でマークされた行をカウントするAppleScriptです。

TextEdit本文から色情報を抽出しただけでは、RGB色の配列データで合っているかどうか、直接の値の比較を行う程度の処理になってしまうため、色データの値がちょっとズレただけでも「赤」として認識されません。

RGB色からHSB色に変換して、おおよその色の名前を計算することで、「赤っぽい色でマークされた行」を抽出してカウントできるようにしてみました。

テストのためにTextEditで処理してみましたが、PagesでもKeynoteでも、InDesignでもIllustratorでも同様のアプローチで色を数値から「だいたいの色」に抽象化することで、高度な判定処理を行うことが可能になります。

AppleScript名:TextEditの文章のうち赤っぽい色でマークされた行をカウントする v2
— Created 2018-01-08 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"

property NSColor : a reference to current application’s NSColor

set rNum to 0
set colMax to 65535

tell application "TextEdit"
  tell text of document 1
    set pCount to (count paragraphs)
    
    
repeat with i from 1 to pCount
      set {rCol, gCol, bCol} to color of paragraph i
      
set cName to retColorDomainName(rCol, gCol, bCol, colMax) of me
      
      
if cName = "red" then –{r, g, b}
        set rNum to rNum + 1
      end if
    end repeat
    
  end tell
end tell

return {pCount, rNum}

on retColorDomainName(rCol as integer, gCol as integer, bCol as integer, aColorMax)
  set aCol to makeNSColorFromRGBAval(rCol, gCol, bCol, aColorMax, aColorMax) of me
  
set hueVal to aCol’s hueComponent()
  
set satVal to aCol’s saturationComponent()
  
set brightVal to aCol’s brightnessComponent()
  
  
if satVal ≤ 0.01 then set satVal to 0.0
  
  
set colName to ""
  
  
if satVal = 0.0 then
    if brightVal ≤ 0.2 then
      set colName to "black"
    else if (brightVal > 0.95) then
      set colName to "white"
    else
      set colName to "gray"
    end if
  else
    if hueVal ≤ (15.0 / 360) or hueVal ≥ (330 / 360) then
      set colName to "red"
    else if hueVal ≤ (45.0 / 360) then
      set colName to "orange"
    else if hueVal < (70.0 / 360) then
      set colName to "yellow"
    else if hueVal < (150.0 / 360) then
      set colName to "green"
    else if hueVal < (190.0 / 360) then
      set colName to "cyan"
    else if (hueVal < 250.0 / 360.0) then
      set colName to "blue"
    else if (hueVal < 290.0 / 360.0) then
      set colName to "purple"
    else
      set colName to "magenta"
    end if
  end if
  
  
return colName
end retColorDomainName

on makeNSColorFromRGBAval(redValue as integer, greenValue as integer, blueValue as integer, alphaValue as integer, aMaxVal as integer)
  set aRedCocoa to (redValue / aMaxVal) as real
  
set aGreenCocoa to (greenValue / aMaxVal) as real
  
set aBlueCocoa to (blueValue / aMaxVal) as real
  
set aAlphaCocoa to (alphaValue / aMaxVal) as real
  
set aColor to NSColor’s colorWithCalibratedRed:aRedCocoa green:aGreenCocoa blue:aBlueCocoa alpha:aAlphaCocoa
  
return aColor
end makeNSColorFromRGBAval

★Click Here to Open This Script 

Posted in Color file | Tagged 10.11savvy 10.12savvy 10.13savvy TextEdit | 1 Comment

ColorCubeによる頻出色の抽出

Posted on 2月 9, 2018 by Takaaki Naganoya

ColorCube.frameworkを呼び出して、指定画像の頻出色を抽出するAppleScriptです。

抽出した色数をダイアログ表示したあとに、抽出した色をchoose colorダイアログで抽出色分だけプレビューします。JPEG画像からの色抽出はうまくできましたが、透過色つきのPNG画像の演算結果は納得行かないものがありました。JPEG推奨です。

ColorCubeには除外色の指定を明示的に(flagsではなく)指定できるはずですが、NSColor’s whiteColor()などで指定してもエラーになったので、flagsによる制御を推奨します。

–> ColorCube.framework

AppleScript名:ColorCubeによる頻出色の抽出
— Created 2018-02-05 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"
use framework "ColorCube" –https://github.com/pixelogik/ColorCube

property CCOnlyBrightColors : 1
property CCOnlyDarkColors : 2
property CCOnlyDistinctColors : 4
property CCOrderByBrightness : 8
property CCOrderByDarkness : 16
property CCAvoidWhite : 32
property CCAvoidBlack : 64

–List up frequent colors from image
set aFile to POSIX path of (choose file of type {"public.image"})
set targImage to current application’s NSImage’s alloc()’s initWithContentsOfFile:aFile
set colorCube to current application’s CCColorCube’s alloc()’s init()

–set imgColors to (colorCube’s extractColorsFromImage:targImage flags:(CCOnlyDistinctColors + CCAvoidWhite)) as list
set imgColors to (colorCube’s extractColorsFromImage:targImage flags:(CCAvoidWhite) |count|:4) as list

display dialog (length of imgColors) as string

repeat with i in imgColors
  set r2Val to i’s redComponent()
  
set g2Val to i’s greenComponent()
  
set b2Val to i’s blueComponent()
  
set a2Val to i’s alphaComponent()
  
  
set r2Val to r2Val * 65535
  
set g2Val to g2Val * 65535
  
set b2Val to b2Val * 65535
  
  
choose color default color {r2Val, g2Val, b2Val}
end repeat

★Click Here to Open This Script 

Posted in Color file Image | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

Post navigation

  • Older posts
  • Newer posts

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

Google Search

Popular posts

  • 開発機としてM2 Mac miniが来たのでガチレビュー
  • macOS 15, Sequoia
  • 指定のWordファイルをPDFに書き出す
  • Pages本執筆中に、2つの書類モード切り替えに気がついた
  • Numbersで選択範囲のセルの前後の空白を削除
  • メキシカンハットの描画
  • Pixelmator Pro v3.6.4でAppleScriptからの操作時の挙動に違和感が
  • AdobeがInDesign v19.4からPOSIX pathを採用
  • AppleScriptによる並列処理
  • Safariで「プロファイル」機能を使うとAppleScriptの処理に影響
  • Cocoa Scripting Course 続刊計画
  • macOS 14.xでScript Menuの実行速度が大幅に下がるバグ
  • AppleScript入門③AppleScriptを使った「自動化」とは?
  • Keynote/Pagesで選択中の表カラムの幅を均等割
  • macOS 15でも変化したText to Speech環境
  • デフォルトインストールされたフォント名を取得するAppleScript
  • macOS 15 リモートApple Eventsにバグ?
  • AppleScript入門① AppleScriptってなんだろう?
  • macOS 14で変更になったOSバージョン取得APIの返り値
  • Numbersで最前面の書類のすべてのシート上の表の行数を合計

Tags

10.11savvy (1101) 10.12savvy (1242) 10.13savvy (1391) 10.14savvy (587) 10.15savvy (438) 11.0savvy (283) 12.0savvy (212) 13.0savvy (194) 14.0savvy (147) 15.0savvy (132) CotEditor (66) Finder (51) iTunes (19) Keynote (117) NSAlert (61) NSArray (51) NSBitmapImageRep (20) NSBundle (20) NSButton (34) NSColor (53) NSDictionary (28) NSFileManager (23) NSFont (21) NSImage (41) NSJSONSerialization (21) NSMutableArray (63) NSMutableDictionary (22) NSPredicate (36) NSRunningApplication (56) NSScreen (30) NSScrollView (22) NSString (119) NSURL (98) NSURLRequest (23) NSUTF8StringEncoding (30) NSView (33) NSWorkspace (20) Numbers (76) Pages (55) Safari (44) Script Editor (27) WKUserContentController (21) WKUserScript (20) WKWebView (23) WKWebViewConfiguration (22)

カテゴリー

  • 2D Bin Packing
  • 3D
  • AirDrop
  • AirPlay
  • Animation
  • AppleScript Application on Xcode
  • Beginner
  • Benchmark
  • beta
  • Bluetooth
  • Books
  • boolean
  • bounds
  • Bug
  • Calendar
  • call by reference
  • check sum
  • Clipboard
  • Cocoa-AppleScript Applet
  • Code Sign
  • Color
  • Custom Class
  • date
  • dialog
  • diff
  • drive
  • Droplet
  • exif
  • file
  • File path
  • filter
  • folder
  • Font
  • Font
  • GAME
  • geolocation
  • GUI
  • GUI Scripting
  • Hex
  • History
  • How To
  • iCloud
  • Icon
  • Image
  • Input Method
  • Internet
  • iOS App
  • JavaScript
  • JSON
  • JXA
  • Keychain
  • Keychain
  • Language
  • Library
  • list
  • Locale
  • Localize
  • Machine Learning
  • Map
  • Markdown
  • Menu
  • Metadata
  • MIDI
  • MIME
  • Natural Language Processing
  • Network
  • news
  • Noification
  • Notarization
  • Number
  • Object control
  • OCR
  • OSA
  • parallel processing
  • PDF
  • Peripheral
  • PRODUCTS
  • QR Code
  • Raw AppleEvent Code
  • Record
  • rectangle
  • recursive call
  • regexp
  • Release
  • Remote Control
  • Require Control-Command-R to run
  • REST API
  • Review
  • RTF
  • Sandbox
  • Screen Saver
  • Script Libraries
  • sdef
  • search
  • Security
  • selection
  • shell script
  • Shortcuts Workflow
  • Sort
  • Sound
  • Spellchecker
  • Spotlight
  • SVG
  • System
  • Tag
  • Telephony
  • Text
  • Text to Speech
  • timezone
  • Tools
  • Update
  • URL
  • UTI
  • Web Contents Control
  • WiFi
  • XML
  • XML-RPC
  • イベント(Event)
  • 未分類

アーカイブ

  • 2025年5月
  • 2025年4月
  • 2025年3月
  • 2025年2月
  • 2025年1月
  • 2024年12月
  • 2024年11月
  • 2024年10月
  • 2024年9月
  • 2024年8月
  • 2024年7月
  • 2024年6月
  • 2024年5月
  • 2024年4月
  • 2024年3月
  • 2024年2月
  • 2024年1月
  • 2023年12月
  • 2023年11月
  • 2023年10月
  • 2023年9月
  • 2023年8月
  • 2023年7月
  • 2023年6月
  • 2023年5月
  • 2023年4月
  • 2023年3月
  • 2023年2月
  • 2023年1月
  • 2022年12月
  • 2022年11月
  • 2022年10月
  • 2022年9月
  • 2022年8月
  • 2022年7月
  • 2022年6月
  • 2022年5月
  • 2022年4月
  • 2022年3月
  • 2022年2月
  • 2022年1月
  • 2021年12月
  • 2021年11月
  • 2021年10月
  • 2021年9月
  • 2021年8月
  • 2021年7月
  • 2021年6月
  • 2021年5月
  • 2021年4月
  • 2021年3月
  • 2021年2月
  • 2021年1月
  • 2020年12月
  • 2020年11月
  • 2020年10月
  • 2020年9月
  • 2020年8月
  • 2020年7月
  • 2020年6月
  • 2020年5月
  • 2020年4月
  • 2020年3月
  • 2020年2月
  • 2020年1月
  • 2019年12月
  • 2019年11月
  • 2019年10月
  • 2019年9月
  • 2019年8月
  • 2019年7月
  • 2019年6月
  • 2019年5月
  • 2019年4月
  • 2019年3月
  • 2019年2月
  • 2019年1月
  • 2018年12月
  • 2018年11月
  • 2018年10月
  • 2018年9月
  • 2018年8月
  • 2018年7月
  • 2018年6月
  • 2018年5月
  • 2018年4月
  • 2018年3月
  • 2018年2月

https://piyomarusoft.booth.pm/items/301502

メタ情報

  • ログイン
  • 投稿フィード
  • コメントフィード
  • WordPress.org

Forum Posts

  • 人気のトピック
  • 返信がないトピック

メタ情報

  • ログイン
  • 投稿フィード
  • コメントフィード
  • WordPress.org
Proudly powered by WordPress
Theme: Flint by Star Verte LLC