Showing posts with label AppleScript. Show all posts
Showing posts with label AppleScript. Show all posts

Saturday, August 17, 2013

AppleScript 로 UI Scripting 하는 법 기초

사운드 preference 에서 체크박스를 토글해주는 애플스크립트를 짜보자.

우선 다음과 같이 해서 "Anchor"의 이름들을 알아낼 수 있다.
 tell application "System Preferences"  
      get the name of every anchor of pane id "com.apple.preference.sound"  
 end tell  

Script Editor 아래쪽의 Output 창에는 다음과 같이 찍힌다.
{"output", "input", "effects"}

원하는 체크박스가 "effects" 라는 anchor 밑에 있음을 알았으므로, 다음과 같이
"effects" anchor 가 나타나게 한 후,
체크박스를 클릭하게 만들면 된다.

 tell application "System Preferences"  
      reveal anchor "effects" of pane id "com.apple.preference.sound"  
 end tell  
 tell application "System Events"  
      tell process "System Preferences"  
           click checkbox 1 of tab group 1 of window 1  
      end tell  
 end tell  

응용예) 다음은 이어폰 모드와 스피커 모드를 전환해주는 애플스크립트.
이어폰을 끼기 전에는 볼륨 레벨을 낮추고 F11/F12 키로 갑자기 볼륨이 변화하는걸 막아줌. 스피커 모드를 선택하면 그 반대로 해줌.

 (*  
 on run  
      tell application "System Preferences"  
           get the name of every anchor of pane id "com.apple.preference.keyboard"  
           --> {"keyboardTab", "shortcutsTab", "keyboardTab_ModifierKeys"}  
      end tell  
 end run  
 *)  
 on run  
      set earphoneVolume to 0.1  
      set dialogResult to myMessageBox2ButtonsAndCancel("Change Sound Volume Mode to :", "Earphone", "Speaker")  
      if (dialogResult = "Cancelled") then  
           display dialog dialogResult giving up after 1  
      else  
           -- Enable Assistive Devices via Terminal   
           do shell script ¬  
                "touch /private/var/db/.AccessibilityAPIEnabled" password "q" with administrator privileges  
           if (dialogResult = "Earphone") then  
                set volume earphoneVolume  
                changeMode(1)  
                display dialog ("EARPHONE mode (Volume settings and Function key settings). volume set to " & earphoneVolume) giving up after 1  
           else  
                set volume (earphoneVolume * 2)  
                changeMode(0)  
                display dialog "SPEAKER mode (Volume settings and Function key settings)" giving up after 1  
           end if  
      end if  
 end run  
 on changeMode(earphoneMode)  
      set headphoneMode to 1 - earphoneMode  
      tell application "System Preferences"  
           set current pane to pane "com.apple.preference.keyboard"  
           reveal anchor "keyboardTab" of pane id "com.apple.preference.keyboard"  
      end tell  
      tell application "System Events"  
           if UI elements enabled then  
                tell tab group 1 of window "Keyboard" of process "System Preferences"  
                     if value of checkbox "Use all F1, F2, etc. keys as standard function keys" is headphoneMode then  
                          click checkbox "Use all F1, F2, etc. keys as standard function keys"  
                          --display dialog "clicked checkbox" giving up after 1  
                     end if  
                end tell  
           else  
                tell application "System Preferences"  
                     set current pane ¬  
                          to pane "com.apple.preference.universalaccess"  
                     display dialog ¬  
                          "UI element scripting is not enabled. Check \"Enable access for assistive devices\""  
                end tell  
           end if  
      end tell  
 end changeMode  
 on myMessageBox2ButtonsAndCancel(msg, buttonL, buttonR)  
      set userCanceled to false  
      try  
           set dialogResult to ¬  
                display dialog msg buttons {"Cancel", buttonL, buttonR} ¬  
                     default button buttonR cancel button ¬  
                     "Cancel" with title ""  
      on error number -128  
           set userCanceled to true  
      end try  
      if userCanceled then  
           return "Cancelled"  
      else  
           button returned of dialogResult  
      end if  
 end myMessageBox2ButtonsAndCancel  


키워드 : UI Scripting
레퍼런스 :
Modifying “User interface sound effects” with applescript
Why does this applescript not actually set the input volume to zero?
AppleScript Essentials - User Interface Scripting by Benjamin S. Waldie
Applescript 10.7:Can’t get anchor “FileVault” of pane id “com.apple.preference.security”

레퍼런스 (볼륨 관련):
Set incredibly precise volume levels using AppleScript
http://hints.macworld.com/article.php?story=20100226174946948

Applescript to toggle F1-F11 keys as function keys
http://forums.macrumors.com/showthread.php?t=383969

Enable and disable Assistive Devices via Terminal
http://hints.macworld.com/article.php?story=20060203225241914

Friday, July 5, 2013

AppleScript에서의 \r과 \n

AppleScript에서의 carriage return 과 line feed 는
각각 return, linefeed 로 쓰면 된다

예)
set str to "My name is " & linefeed & "Babo"

Saturday, December 22, 2012

Script Objects

Script Objects
A script object is a user-defined object that can combine data (in the form of properties) and actions (in the form of handlers and additional script objects).

AppleScript Tutorial 모음

AppleScript Tutorials

There are over 100 tutorials and articles in unScripted and almost all of them are listed below.

General Information
Tutorial: Non-Scripter's Guide to Using Downloaded AppleScripts by Adam Bell

Tutorials about AppleScript Studio
AppleScript Studio Tutorial - Getting Started by Ben Waldie
AppleScript Studio Tutorial: Getting Started Using Tab Views by Ben Waldie
AppleScript Studio Tutorial - Getting Started - Displaying Progress by Ben Waldie
AppleScript Studio Tutorial - Getting Started with Table Views by Ben Waldie
AppleScript Studio Tutorial - Getting Started with Buttons (Part 1) by Ben Waldie
AppleScript Studio Tutorial - Getting Started with Buttons (Part 2) by Ben Waldie
Tutorial: Variable Scope in Applescript and Applescript Studio by Kevin Bradley
Applescript Studio Tutorial: Polishing Your Application by Kevin Bradley
Applescript Tutorial: Polishing an App 2 - Secrets Not In The Manual by Kevin Bradley
Applescript Studio: About the About Box by T.J. Mahaffey
Applescript Studio FAQ 1 by T.J. Mahaffey

Tutorials for Beginning Scripters
AppleScript Tutorial for Beginners I - Get Started & Script Editor by Craig Smith
AppleScript Tutorial for Beginners II - Variables and Dictionaries by Craig Smith
AppleScript Tutorial for Beginners III - The Power of Lists by Craig Smith
AppleScript Tutorial for Beginners IV - Records & Repeats by Craig Smith
AppleScript Tutorial for Beginners V - Testing & Shorthand by Craig Smith
AppleScript Tutorial for Beginners VI - User Interaction by Craig Smith
AppleScript Tutorial for Beginners VII - Errors by Craig Smith
AppleScript Tutorial for Beginners VIII - More on User Interaction by Adam Bell
AppleScript Tutorial for Beginners IX - Getting the Drop on Droplets by Craig Smith
AppleScript Tutorial for Beginners X - Math by Craig Smith
Applescript Tutorial: All AppleScript, All the Time by Craig Smith
Applescript Tutorial - Using Applescript Dictionaries by Kevin Bradley
AppleScript for Automators by Kevin Wolfe
Automator for AppleScripters by Kevin Wolfe
Tutorial on Building Automator Droplets by Craig Smith
Tutorial on Improving Your AppleScripts: Structured Programming by Kevin Bradley
Cooking with Data Types - Part 1 by T.J. Mahaffey
Cooking with Data Types - Part 2: Coercion by T.J. Mahaffey

AppleScripting Tools & Techniques
Subroutines - Part 1 by T.J. Mahaffey
Subroutines - Part 2 by T.J. Mahaffey
Getting Started with Handlers (Part 1 of 3-part Tutorial) by Ben Waldie
Getting Started with Handlers (Part 2 of 3-part Tutorial) by Ben Waldie
Getting Started with Handlers (Part 3 of 3-part Tutorial) by Ben Waldie
Applescript Tutorial - Using Applescript Dictionaries by Kevin Bradley
A Tutorial to Improve your Applescripts: Return to iTunes Scripting by Kevin Bradley
The Ins & Outs of File Read/Write in AppleScript by Nigel Garvey
Tutorial on Using Growl from your AppleScripts by Adam Bell
Tutorial: Some Lessons & Fun with "do shell script" in AppleScripts by Adam Bell
An AppleScript Tutorial on a Common Folder Action Problem by Kevin Bradley
Dates & Times in AppleScripts by Adam Bell
Tutorial for Using AppleScript's Text Item Delimiters by Adam Bell
A Tutorial on Parsing HTML from a Web Site by Adam Bell
Tutorial: a Beginner's Introduction to AppleScript Libraries by Adam Bell
A Tutorial to Improve your Applescripts: Return to iTunes Scripting by Kevin Bradley
Applescript Tutorial: Advanced iTunes Scripting with Libraries by Kevin Bradley
Applescript Tutorial: All Your Database Are Belong To Applescript by Kevin Bradley
Applescript Tutorial: Script Properties by Chris Moore
A "Quick 'n Dirty" Applescript Tutorial by Kevin Bradley
Tutorial on Improving Your AppleScripts: Structured Programming by Kevin Bradley
A Tutorial to Improve your Applescripts: Data Structures by Kevin Bradley
A Tutorial to Improve your Applescripts: Data Structures - Stacks by Kevin Bradley
AppleScript Tutorial on Range References with Text and Lists by Nigel Garvey
A Tutorial to Improve your Applescripts: Sorting - The Big "O" by Kevin Bradley
A Tutorial on Doing Structured Text Generation in AppleScript by chrys

Application Scripting
A Tutorial on AppleScripting Finder Search Windows by Adam Bell
A Tutorial for Using Spotlight in your AppleScripts by Adam Bell
A Tutorial on AppleScripting a mySQL Database by Craig Smith
Applescript Tutorial: Working With Images Using Image Events by Kevin Bradley
Automator Tutorial - Working With Images (Redux) by Kevin Bradley
Automating Mug Shots to Filemaker from iSight: AppleScript Tutorial by Diana Simonson
Applescript Tutorial: iCal Alarms! by Kevin Bradley
Applescript Tutorial: Appointments, Alarms & To Dos in iCal by Kevin Bradley
Applescript Tutorial: Talkin' The Talk with Apple's Speech Tools by Kevin Bradley
Tutorial & Review: Scripting Clickable Bliss' Billable by Adam Bell
A Tutorial Introduction to SQLite3 - a Simple Database Engine by Adam Bell
Synching iView to MySQL to update a website using Applescript by Diana Simonson
Using Applescript to Parse Data from one Filemaker format to Another by Diana Simonson
Automator for AppleScripters -- by Kevin Wolfe

Other Tips & Tricks in AppleScript
Applescript Tutorial: Building Script Applications by Kevin Bradley
Tutorial: A Single Dialog to Handle Multiple Entries by kai
An Introduction to Extracting Elements & Properties from Objects by kai
AppleScript Tutorial on Scripting System Preferences by kai
Automator Tutorial: Bindings by Kevin Wolfe
A Tutorial to Improve Your AppleScripts: Putting It All Together by Kevin Bradley
Protection for AppleScripts Compiled as Run-Only Applications by jj
Automate iWeb Uploads to Multiple Servers by Kevin Wolfe
Using launchd with AppleScript to Access a Flash Drive Automatically by Craig Smith
A Tutorial on Constructors & Handlers Containing Script Objects by jj
Object Pattern: the Object Switch -- by Chris Moore
Script Libraries -- by Chris Moore
Encrypting Messages (Pt 1) by Scott Lewis
Encrypting Messages (Pt 2) by Scott Lewis
Encrypting Messages (Pt 3) by Scott Lewis
Writing Cleaner Code by T.J. Mahaffey
Using Object Properties by Scott Lewis
Text Item Delimiters are De-limitless by T.J. Mahaffey
Idle Handlers by T.J. Mahaffey
AppleScript Toolbox Secrets: Dialog Alternatives by T.J. Mahaffey
UI Browser preview & MacOS X GUI Scripting by T.J. Mahaffey

Sunday, December 9, 2012

AppleScript에서 외부 스크립트 파일 사용하는 법

      set dirname to myGetAppleScriptRootPath()  
      set filepath to dirname & "/" & scriptFilename  
      set myScript to load script (filepath as POSIX file)  

이렇게 한 후 myScript's functionName() 과 같이 호출해서 쓰면 됨.
참고로 현재 스크립트의 패스를 얻는 myGetAppleScriptRootPath() 는 다음과 같음

 on myGetAppleScriptRootPath()  
      set thisScriptPath to POSIX path of (path to me)  
      set dirname to do shell script "dirname " & quoted form of thisScriptPath  
      return dirname  
 end myGetAppleScriptRootPath  

키워드 : 외부 라이브러리

Sunday, December 2, 2012

AppleScript에서 외부 텍스트에디터로 new document 만드는 법

AppleScript에서 특정 텍스트를  외부 텍스트에디터로 새 도큐먼트 만들어서 열어주는 방법

      tell application "TextWrangler"  
           activate  
           make new document  
           set documentText to text of document 1  
           set textBits to text items of documentText  
           set text of document 1 to "This is my text" as text  
      end tell  

레퍼런스 :If all you're doing is stripping quotation marks out of a CSV file..

Thursday, November 29, 2012

AppleScript Library

AppleScript Library
스트링 공백문자 trim 해주는 등의 String Library 등이 있음
키워드 : whitespace

Wednesday, November 28, 2012

AppleScript Editor에서 한줄을 여러줄로 나눠서 쓰는 법

Option + Return 하고 아랫줄에 계속 이어 쓰면 된다.
키워드 : 라인, line, 분할, 개행, 개행문자

문자열에서 한글 받침이 있나 없나 판별하는 법

방법 :
1. 문자열이 UTF-16이 아니라면, UTF-16으로 변환
2. 문자열의 마지막 2바이트 즉 마지막 글자를 얻어서
3. 그 글자의 값이 한글코드범위(AC00~D7A3)에 속하면서
    유니코드 한글 범위 : 0xAC00(44032) ~ 0xD7A3(55203)
4. (글자값 - AC00) % 28 가 0 이 아니라면 받침이 있는 것임

원리 :
    한글코드 = 종성 + 중성*28 + 초성*588 + 44032
인데 이를 다음과 같이 변형해보면
    한글코드-44032 = 종성 + 중성*28 + 초성*588
    한글코드-44032 = 종성 + (중성 + 초성*21)*28
와 같이 된다. 따라서
    종성=(한글코드-44032)%28
가 되는것임

키워드 : 종성 유무 판단
레퍼런스 :
문자열에서 한글 종성(받침) 유무 판별하기
한글 받침의 유무를 알아내는 법..?

Tuesday, December 20, 2011

Run Applescripts with Keyboard Shortcuts

Run Applescripts with Keyboard Shortcuts
In the Keyboard and Mouse section of System Preferences there is a Keyboard shortcuts tab that allows you to assign a keyboard shortcut to any menu item. This is great, but unfortunately it doesn’t work everywhere...
Luckily you can use Quicksilver to assign keyboard shortcuts to AppleScripts.

Monday, December 5, 2011

AppleScript 에서 16진수를 10진수로 변환하는 방법?

질문 : AppleScript 에서 Hexadecimal <--> Decimal Conversion 하는 방법?
답 :
This code converts a decimal number into a hexdecimal string:
set nDec to 1000
set nHex to do shell script "perl -e 'printf(\"%x\", " & nDec & ")'" --> "3e8"

To get uppercase letters, use %X instead of %x
set nHex to do shell script "perl -e 'printf(\"%X\", " & nDec & ")'" --> "3E8"

To get additional leading zeros, use e.g. %04X for "add zeros for four-digit output"
set nHex to do shell script "perl -e 'printf(\"%04X\", " & nDec & ")'" --> "03E8"

And this code converts a hexdecimal string into a decimal number:
set nHex to "03E8"
set nDec to (do shell script "perl -e 'printf(hex(\"" & nHex & "\"))'") as number --> 1000

레퍼런스 : http://macscripter.net/viewtopic.php?id=19442

Saturday, September 10, 2011

AppleScript 디버깅시 팁 - 정의되지 않은 변수

실행이 중간에서 exit 해버리는 경우, 어디가 잘못됐는지 혼란스러울 수 있다.

이런 문제는 대체로
  1. 변수가 정의되지 않은 상태로 사용되는 경우가 많다.
  2. 함수 호출시 argument 수를 다르게 써서 정의되지 않은 함수를 호출하는 셈이 돼버리는 경우
  3. 함수 호출시 package 명을 지정하지 않아 정의되지 않은 함수를 호출하는 셈이 돼버리는 경우
와 같은 것이 있다. 이들 모두 실행은 중간에서 exit 해버리는데,
컴파일러에만 익숙한 사람은 에러를 잡기 힘들다.

코드를 고치다보면 자주 생기는 실수이므로 주의.

Wednesday, May 4, 2011

AppleScript 에서 try catch block 쓰는 법

질문 : AppleScript 에서 try catch block 사용법
답 :
try
[실행]
on error
[에러처리]
end try
참고 : [실행] 에 do shell script 가 들어가도 에러를 캐치한다.
즉 do shell script 가 단순히 외부 프로그램 호출하는 식으로 작동하는게 아니라는 얘기
(실행 결과가 에러인지 성공인지 캐치한다는 것)
키워드 : exception handling

Saturday, April 30, 2011

AppleScript 실행시 Can't make some data into the expected data type

질문 : AppleScript 실행시 Can't make some data into the expected data type 가 생기는데 해결법은?
답 : 말 그대로 타입 에러이며 발생 이유는 보통, repeat 문에서 다루는 데이터가 예상치 못한 타입일 경우이다. 타입이 안맞는 경우 처리할 필요가 없다면 repeat 문 안쪽을 try block 으로 감싸주면 된다.
예 : 예를 들면 다음과 같은 코드에서 종종 생기는데
repeat with this_item in theSelected
set filepath to FinderUtil's myFinderGetSelectedItemsFilepath(this_item)
set end of filepaths to filepath
end repeat
이는 다음과 같이 try 를 이용하면 해결된다
repeat with this_item in theSelected
try
set filepath to FinderUtil's myFinderGetSelectedItemsFilepath(this_item)
set end of filepaths to filepath
end try
end repeat

Friday, April 1, 2011

AppleScript 에서 한글 모아쓰기 해주는 법

질문 : 파일명을 복사할때 한글 자모가 모두 떨어지는데 모아쓰기 해주려면?
요약 : 클립보드를 이용하면 간단하다.
답 :
on myHangulMoaSSugi(txt)
set temp to the clipboard --클립보드 피신
set the clipboard to txt -- 한글 모아주기를 위해 클립보드로 옮김
set txt to the clipboard as string -- 한글 모아주기가 완성.
set the clipboard to temp -- 클립보드 restore
return txt
end myHangulMoaSSugi
키워드 : copy paste 클립보드 myHangunMoaSSugi
관련링크 : AppleScript에서 Clipboard 사용하기

Friday, March 25, 2011

AppleScript 에서 file exists 여부 파악하기

set msg to "no"
tell application "Finder" to if exists "/usr/bin/gzip" as POSIX file then set msg to "yes"
display dialog msg

출처 : Check if file exists

Friday, March 11, 2011

in-house tool 만들때 간편하게 에러처리하는 법

요약 : 에러를 리턴하는 간편한 방법으로, "-666ΩΩΩΩΩ" 같이 입력할 가능성이 거의 없는 스트링을 리턴하게 하는 방법이 있다. 별도의 처리를 안해줘도 하나의 리턴값으로 처리 가능하므로 코드가 깨끗해진다. 판매용이 아닌 회사 내부에서만 쓸 툴을 짤 때 쓰기 좋은 방법이다.
키워드 : error handling, 에러 핸들링, return value

Saturday, November 20, 2010

AppleScript 오랜만에 짤때 실수하기 쉬운 것 : set 과 = 혼동

set a to b + c
로 써야 하는 것을
a = b + c
같이 쓰는 실수를 하기 쉬운데 후자의 것은 비교문으로, 에러 메시지도 뜨지 않아 알기 힘들다

AppleScript의 loop에서 continue 하는 법?

질문 : AppleScript의 loop에서 continue 하려면? (C 처럼)
답 : 할수 없다. continue에 정확히 매치되는 명령은 없다.

레퍼런스 : Applescript equivalent of “continue”?

Tuesday, June 1, 2010

AppleScript의 repeat 문에서 break 에 해당하는 것은?

질문 : AppleScript의 repeat 문에서 break 에 해당하는 것은?

답 : exit repeat 하면 된다