update to use notification center instead of growl

on control(keyCode)
  set code to "var keyCode = " & keyCode & ";
    var event = document.createEvent('Events');
    event.initEvent('keydown', true, true);
    event.keyCode = keyCode;
    event.which = keyCode;

    document.dispatchEvent(event);
  "

  set targetTab to activeTab() of me
  executeJavaScript(targetTab, code) of me
end control

on notifyCurrentSong()
  set targetTab to activeTab() of me

  set songCode to "document.querySelector('#playerSongTitle').innerHTML"
  set song to executeJavaScript(targetTab, songCode) of me

  set artistCode to "document.querySelector('.player-artist-album-wrapper').innerText"
  set artist to executeJavaScript(targetTab, artistCode) of me

  notify(song, artist) of me
end notifyCurrentSong

on notify(name, message)
  display notification message with title name
end notify

on activeTab()
  set targetTab to null

  tell application "Google Chrome"
    repeat with theWindow in every window
      repeat with theTab in every tab of theWindow
        if theTab's title ends with "- Google Play Music" then
          set targetTab to theTab
          exit repeat
        end if
      end repeat
    end repeat
  end tell

  return targetTab
end activeTab

on executeJavaScript(activeTab, code)
  set result to null

  tell application "Google Chrome"
    set result to execute activeTab javascript code
  end tell

  return result
end executeJavaScript

on control(keyCode)
  set code to "var keyCode = " & keyCode & ";
    var event = document.createEvent('Events');
    event.initEvent('keydown', true, true);
    event.keyCode = keyCode;
    event.which = keyCode;

    document.dispatchEvent(event);
  "

  set targetTab to activeTab() of me
  executeJavaScript(targetTab, code) of me
end control

on notifyCurrentSong()
  set targetTab to activeTab() of me

  set songCode to "document.querySelector('.playerSongTitle .fade-out-content').innerHTML"
  set song to executeJavaScript(targetTab, songCode) of me

  set artistCode to "document.querySelector('.playerArtist .fade-out-content').innerHTML"
  set artist to executeJavaScript(targetTab, artistCode) of me

  notify(song, artist) of me
end notifyCurrentSong

on notify(name, message)
  set command to "/usr/local/bin/growlnotify -n " & quoted form of name & " -m " & quoted form of message
  do shell script command
end notify

on activeTab()
  set targetTab to null

  tell application "Google Chrome"
    repeat with theWindow in every window
      repeat with theTab in every tab of theWindow
        if theTab's title ends with "- Google Play Music" then
          set targetTab to theTab
          exit repeat
        end if
      end repeat
    end repeat
  end tell

  return targetTab
end activeTab

on executeJavaScript(activeTab, code)
  set result to null

  tell application "Google Chrome"
    set result to execute activeTab javascript code
  end tell

  return result
end executeJavaScript


Update inbox applescript

Update inbox applescript

FasdUAS 1.101.10
k
l
i

	I
.aevtoappnull****

Q
k

r
n

I
0inputdialoginputDialog
mEnter task:
m
f
o
0	task_text
n

I"0addentrytoinboxaddEntryToInbox !
 o
0	task_text!"
"m##$$
f

R
.ascrerr ********%&
%l&'(
'i)*
)I+
.aevtodocnullalis
+o0
dropped_files
*XH,-
,kC../0
/r12
1n34
31

strq
4n56
51

psxp
6o
0	file_path
2o0afileaFile078
7r!9:
9I;
.sysoexecTEXTTEXT
;b<=
<m>>??basename
=o0afileaFile
:o0filename8@
@Q"CAB
Ak%:CCDE
Dr%2FG
Fn%0HI
HI&0J0inputdialoginputDialogJKL
Kb&+MN
Mb&)OP
Om&'QQRR Task related to
Po'(0filename
Nm)*SSTT:LU
Uo+,0filename
If%&
Go
0	task_textEV
Vn3:WX
WI4:Y"0addentrytoinboxaddEntryToInboxYZ[
Zo45
0	task_text[\
\o560afileaFile
Xf34
BR
.ascrerr ********
0	file_path
-o0
dropped_files(]^
]l^_`
_iab
aIc"0addentrytoinboxaddEntryToInboxcde
do
0	task_textef
fo
0	file_path
bk+gghi
hrjk
jIl
.sysoexecTEXTTEXT
lmmmnnNdefaults read inbox.app.plist inbox_cmd
ko
0	inbox_cmdiop
oZqrs
q=tu
to
0	file_path
um
vvww
rrxy
xmzz{{
yo0file_ref
sr|}
|b~
~m file://
o
0	file_path
}o0file_refp
r#
b!
b
b
o
0	inbox_cmd
m
o
0	task_text
o 0file_ref
o0cmd
o$%0cmd
I&+
.sysoexecTEXTTEXT
o&'0cmd`
l
i
I0inputdialoginputDialog
o	0title
o0default_text
k
r
l
I
.sysodlogaskrTEXT
l

o	0title

dtxt
l

o0default_text

disp
l

m

btns
l

J

mCancel
mOK

dflt
mOK
o0	thedialog	theDialog
r
n
1

ttxt
o0	thedialog	theDialog
o0
text_typed
L
o0
text_typed
l
l
~}
.aevtoappnull****
.aevtodocnullalis"0addentrytoinboxaddEntryToInbox0inputdialoginputDialog
0	task_text~}|
{zy
|.aevtoappnull****{zxw#vutx0inputdialoginputDialogw
0	task_textv"0addentrytoinboxaddEntryToInboxuty)l+EO)l+WXhs*rqp
s.aevtodocnullalisr0
dropped_filesqonmlko0
dropped_filesn
0	file_pathm0afileaFilel0filenamek
0	task_text
jihgf>eQSdcba
j
kocl
i
cobj
h.corecnte********
g
psxp
f
strq
e.sysoexecTEXTTEXTd0inputdialoginputDialogc"0addentrytoinboxaddEntryToInboxbapIG[lkh,,EO%jEO)%%l+	EO)l+
WXh[OY`b_^]`"0addentrytoinboxaddEntryToInbox_\\[Z[
0	task_textZ
0	file_path^YXWVUY
0	task_textX
0	file_pathW
0	inbox_cmdV0file_refU0cmdmTvz
T.sysoexecTEXTTEXT],jEOEY%EO%%%EOOjSRQPS0inputdialoginputDialogROONMN	0titleM0default_textQLKJIL	0titleK0default_textJ0	thedialog	theDialogI0
text_typed
HGFEDCB
H
dtxt
G
disp
F
btns
E
dfltD
C.sysodlogaskrTEXT
B
ttxtPklvEO,EOfooascr
ޭ

FasdUAS 1.101.10
k
l
i

	I
.aevtoappnull****

Q
k

r
n

I
0inputdialoginputDialog
mEnter task:
m
f
o
0	task_text
n

I"0addentrytoinboxaddEntryToInbox !
 o
0	task_text!"
"m##$$
f

R
.ascrerr ********%&
%l&'(
'i)*
)I+
.aevtodocnullalis
+o0
dropped_files
*XH,-
,kC../0
/r12
1n34
31

strq
4n56
51

psxp
6o
0	file_path
2o0afileaFile078
7r!9:
9I;
.sysoexecTEXTTEXT
;b<=
<m>>??basename
=o0afileaFile
:o0filename8@
@Q"CAB
Ak%:CCDE
Dr%2FG
Fn%0HI
HI&0J0inputdialoginputDialogJKL
Kb&+MN
Mb&)OP
Om&'QQRR Task related to
Po'(0filename
Nm)*SSTT:LU
Uo+,0filename
If%&
Go
0	task_textEV
Vn3:WX
WI4:Y"0addentrytoinboxaddEntryToInboxYZ[
Zo45
0	task_text[\
\o560afileaFile
Xf34
BR
.ascrerr ********
0	file_path
-o0
dropped_files(]^
]l^_`
_iab
aIc"0addentrytoinboxaddEntryToInboxcde
do
0	task_textef
fo
0	file_path
bk+gghi
hrjk
jIl
.sysoexecTEXTTEXT
lmmmnnNdefaults read inbox.app.plist inbox_cmd
ko
0	inbox_cmdiop
oZqrs
q=tu
to
0	file_path
um
vvww
rrxy
xmzz{{
yo0file_ref
sr|}
|b~
~m file://
o
0	file_path
}o0file_refp
r#
b!
b
b
o
0	inbox_cmd
m
o
0	task_text
o 0file_ref
o0cmd
o$%0cmd
I&+
.sysoexecTEXTTEXT
o&'0cmd`
l
i
I0inputdialoginputDialog
o	0title
o0default_text
k
r
l
I
.sysodlogaskrTEXT
l

o	0title

dtxt
l

o0default_text

disp
l

m

btns
l

J

mCancel
mOK

dflt
mOK
o0	thedialog	theDialog
r
n
1

ttxt
o0	thedialog	theDialog
o0
text_typed
L
o0
text_typed
l
l
~}
.aevtoappnull****
.aevtodocnullalis"0addentrytoinboxaddEntryToInbox0inputdialoginputDialog
0	task_text~}|
{zy
|.aevtoappnull****{zxw#vutx0inputdialoginputDialogw
0	task_textv"0addentrytoinboxaddEntryToInboxuty)l+EO)l+WXhs*rqp
s.aevtodocnullalisr0
dropped_filesqonmlko0
dropped_filesn
0	file_pathm0afileaFilel0filenamek
0	task_text
jihgf>eQSdcba
j
kocl
i
cobj
h.corecnte********
g
psxp
f
strq
e.sysoexecTEXTTEXTd0inputdialoginputDialogc"0addentrytoinboxaddEntryToInboxbapIG[lkh,,EO%jEO)%%l+	EO)l+
WXh[OY`b_^]`"0addentrytoinboxaddEntryToInbox_\\[Z[
0	task_textZ
0	file_path^YXWVUY
0	task_textX
0	file_pathW
0	inbox_cmdV0file_refU0cmdmTvz
T.sysoexecTEXTTEXT],jEOEY%EO%%%EOOjSRQPS0inputdialoginputDialogROONMN	0titleM0default_textQLKJIL	0titleK0default_textJ0	thedialog	theDialogI0
text_typed
HGFEDCB
H
dtxt
G
disp
F
btns
E
dfltD
C.sysodlogaskrTEXT
B
ttxtPklvEO,EOFooascr
ޭ


Went back to just toggling DnD

Went back to just toggling DnD

on run {arg}
	-- TOGGLE Do Not Disturb Off
	-- NEEDS keyboard shortcut: http://apple.stackexchange.com/a/145491
	ignoring application responses
		tell application "System Events" to keystroke "D" using {command down, shift down, option down, control down}
	end ignoring

	-- if (arg is "on") then
	-- 	-- Turn Do Not Disturb On
	-- 	do shell script "defaults -currentHost write ~/Library/Preferences/ByHost/com.apple.notificationcenterui doNotDisturb -boolean true"
	-- 	set theDate to quoted form of (do shell script "date -u +\"%Y-%m-%d %H:%M:%S +0000\"")
	-- 	do shell script "defaults -currentHost write ~/Library/Preferences/ByHost/com.apple.notificationcenterui doNotDisturbDate -date " & theDate
	-- 	do shell script "killall NotificationCenter"

	-- else
	-- 	-- TOGGLE Do Not Disturb Off
	-- 	-- NEEDS keyboard shortcut: http://apple.stackexchange.com/a/145491
	-- 	ignoring application responses
	-- 		tell application "System Events" to keystroke "D" using {command down, shift down, option down, control down}
	-- 	end ignoring

	-- 	-- Turn Do Not Disturb Off
	-- 	do shell script "defaults -currentHost write ~/Library/Preferences/ByHost/com.apple.notificationcenterui doNotDisturb -boolean false"
	-- 	try
	-- 		do shell script "defaults -currentHost delete ~/Library/Preferences/ByHost/com.apple.notificationcenterui doNotDisturbDate"
	-- 	end try
	-- 	do shell script "killall NotificationCenter"
	-- end if
end run

on run {arg}
	if (arg is "on") then
		-- Turn Do Not Disturb On
		do shell script "defaults -currentHost write ~/Library/Preferences/ByHost/com.apple.notificationcenterui doNotDisturb -boolean true"
		set theDate to quoted form of (do shell script "date -u +\"%Y-%m-%d %H:%M:%S +0000\"")
		do shell script "defaults -currentHost write ~/Library/Preferences/ByHost/com.apple.notificationcenterui doNotDisturbDate -date " & theDate
		do shell script "killall NotificationCenter"
	else
	-- TOGGLE Do Not Disturb Off
	-- NEEDS keyboard shortcut: http://apple.stackexchange.com/a/145491
	ignoring application responses
		tell application "System Events" to keystroke "D" using {command down, shift down, option down, control down}
	end ignoring
	-- 	-- Turn Do Not Disturb Off
	-- 	do shell script "defaults -currentHost write ~/Library/Preferences/ByHost/com.apple.notificationcenterui doNotDisturb -boolean false"
	-- 	try
	-- 		do shell script "defaults -currentHost delete ~/Library/Preferences/ByHost/com.apple.notificationcenterui doNotDisturbDate"
	-- 	end try
	-- 	do shell script "killall NotificationCenter"
	end if
end run


Loop through all windows in iTerm and all sessions in windows This fixes the issue where when multiple iTerm windows are opened quickly only the front one gets the correct color scheme This also allows the use of `colorize` to correct all open iTerm window's colors to be fixed


multiple buttons in fmClip - Button Info from Clipboard

Scripts/fmClip - Button Info from Clipboard.applescript


Remove unused osx_install_patch.applescript


mail mate debug

mail mate debug

on dlog(myObj)
	set txt to quoted form of (myObj as string)
	log txt
	do shell script "logger -t 'LaunchBar.MailMate' " & txt
end dlog

on urlencode(theText)
	set theTextEnc to ""
	repeat with eachChar in characters of theText
		set useChar to eachChar
		set eachCharNum to ASCII number of eachChar
		if eachCharNum = 32 or eachCharNum > 127 then
			set useChar to "%20"
		else if (eachCharNum ≠ 42) and (eachCharNum ≠ 95) and (eachCharNum < 45 or eachCharNum > 46) and (eachCharNum < 48 or eachCharNum > 57) and (eachCharNum < 65 or eachCharNum > 90) and (eachCharNum < 97 or eachCharNum > 122) then
			set firstDig to round (eachCharNum / 16) rounding down
			set secondDig to eachCharNum mod 16
			if firstDig > 9 then
				set aNum to firstDig + 55
				set firstDig to ASCII character aNum
			end if
			if secondDig > 9 then
				set aNum to secondDig + 55
				set secondDig to ASCII character aNum
			end if
			set numHex to ("%" & (firstDig as string) & (secondDig as string)) as string
			set useChar to numHex
		end if
		set theTextEnc to theTextEnc & useChar as string
	end repeat
	return theTextEnc
end urlencode

on makeTo(_emailAddresses)
	set _to to ""
	repeat with addr in _emailAddresses
		set _to to _to & "&to=" & urlencode(addr)
	end repeat
	return _to
end makeTo

on basename(thePath) -- Requires POSIX path
	set ASTID to AppleScript's text item delimiters
	set AppleScript's text item delimiters to "/"
	set thePath to text item -1 of thePath
	set AppleScript's text item delimiters to ASTID
	return thePath
end basename

on sendFiles(_files, _emailAddresses)
  dlog("in sendFiles " & _files)
	try
		set _mailto to "mailto:?send-now=no" & makeTo(_emailAddresses)
		set _names to ""
		repeat with _file in _files
			set _filePath to POSIX path of _file
			set _names to _names & " " & basename(_filePath)
			set _mailto to _mailto & "&attachment-url=file://" & urlencode(_filePath)
		end repeat
		set _mailto to _mailto & "&subject=File:" & urlencode(_names) & "&body=" & urlencode("File attached")
		tell application "MailMate" to open location _mailto with trust
		tell application "MailMate" to activate
	on error error_message number error_number
		set msg to "LaunchBar.MailMate.sendFiles ERROR: " & error_message & " #" & error_number
		dlog(msg)
		display dialog msg
	end try
end sendFiles

on sendText(txt, _emailAddresses)
  dlog("in sendText")
	try
		if txt starts with "➤" then
			set myName to text 2 thru ((offset of "⬅" in txt) - 1) of txt
			set myURL to text ((offset of "⬅" in txt) + 1) thru end of txt
			set mySubj to "Link: " & myName
			set myBody to myName & return & myURL & return & return & "Enjoy," & return & "P"
			set _mailto to "mailto:?send-now=yes&subject=" & urlencode(mySubj) & makeTo(_emailAddresses) & "&body=" & urlencode(myBody)
			tell application "MailMate" to open location _mailto with trust
		else
			set _mailto to "mailto:?send-now=no&" & makeTo(_emailAddresses) & "&body=" & urlencode(txt)
			tell application "MailMate" to open location _mailto
		end if
	on error error_message number error_number
	  set msg to "LaunchBar.MailMate.sendText ERROR: " & error_message & " #" & error_number
	  dlog(msg)
		display dialog msg
	end try
end sendText

on dlog(myObj)
  set txt to quoted form of (myObj as string)
  log txt
  do shell script "logger -t 'LaunchBar.MailMate' " & txt
end dlog

on urlencode(theText)
  set theTextEnc to ""
  repeat with eachChar in characters of theText
    set useChar to eachChar
    set eachCharNum to ASCII number of eachChar
    if eachCharNum = 32 or eachCharNum > 127 then
      set useChar to "%20"
    else if (eachCharNum ≠ 42) and (eachCharNum ≠ 95) and (eachCharNum < 45 or eachCharNum > 46) and (eachCharNum < 48 or eachCharNum > 57) and (eachCharNum < 65 or eachCharNum > 90) and (eachCharNum < 97 or eachCharNum > 122) then
      set firstDig to round (eachCharNum / 16) rounding down
      set secondDig to eachCharNum mod 16
      if firstDig > 9 then
        set aNum to firstDig + 55
        set firstDig to ASCII character aNum
      end if
      if secondDig > 9 then
        set aNum to secondDig + 55
        set secondDig to ASCII character aNum
      end if
      set numHex to ("%" & (firstDig as string) & (secondDig as string)) as string
      set useChar to numHex
    end if
    set theTextEnc to theTextEnc & useChar as string
  end repeat
  return theTextEnc
end urlencode

on makeTo(_emailAddresses)
  set _to to ""
  repeat with addr in _emailAddresses
    set _to to _to & "&to=" & urlencode(addr)
  end repeat
  return _to
end makeTo

on basename(thePath) -- Requires POSIX path
  set ASTID to AppleScript's text item delimiters
  set AppleScript's text item delimiters to "/"
  set thePath to text item -1 of thePath
  set AppleScript's text item delimiters to ASTID
  return thePath
end basename

on sendFiles(_files, _emailAddresses)
  try
    set _mailto to "mailto:?send-now=no" & makeTo(_emailAddresses)
    set _names to ""
    repeat with _file in _files
      set _filePath to POSIX path of _file
      set _names to _names & " " & basename(_filePath)
      set _mailto to _mailto & "&attachment-url=file://" & urlencode(_filePath)
    end repeat
    set _mailto to _mailto & "&subject=File:" & urlencode(_names) & "&body=" & urlencode("File attached")
    tell application "MailMate" to open location _mailto with trust
    tell application "MailMate" to activate
  on error error_message number error_number
    display dialog "LaunchBar.MailMate.sendFiles ERROR: " & error_message & " #" & error_number
  end try
end sendFiles

on sendText(txt, _emailAddresses)
  try
    if txt starts with "➤" then
      set myName to text 2 thru ((offset of "⬅" in txt) - 1) of txt
      set myURL to text ((offset of "⬅" in txt) + 1) thru end of txt
      set mySubj to "Link: " & myName
      set myBody to myName & return & myURL & return & return & "Enjoy," & return & "P"
      set _mailto to "mailto:?send-now=yes&subject=" & urlencode(mySubj) & makeTo(_emailAddresses) & "&body=" & urlencode(myBody)
      tell application "MailMate" to open location _mailto with trust
    else
      set _mailto to "mailto:?send-now=no&" & makeTo(_emailAddresses) & "&body=" & urlencode(txt)
      tell application "MailMate" to open location _mailto
    end if
  on error error_message number error_number
    display dialog "LaunchBar.MailMate.sendText ERROR: " & error_message & " #" & error_number
  end try
end sendText


Be pedantic and hide the file extensions for the license in the dmg

-- This Applescript sets up the installer disk image: size, background image,
--   icon view, background image, icon positioning.
-- Usage: osascript installer-dmg.applescript <volume-name>
-- where <volume-name> is the volume name of the disk image.

on run (volumeName)
	tell application "Finder"
		tell disk (volumeName as string)
			open

			set theXOrigin to 400
			set theYOrigin to 100
			set theWidth to 500
			set theHeight to 600
			set iconSize to 100

			set theBottomRightX to (theXOrigin + theWidth)
			set theBottomRightY to (theYOrigin + theHeight)
			set dsStore to "\"" & "/Volumes/" & volumeName & "/" & ".DS_STORE\""

			tell container window
				set current view to icon view
				set toolbar visible to false
				set statusbar visible to false
				set the bounds to {theXOrigin, theYOrigin, theBottomRightX, theBottomRightY}
				set statusbar visible to false

				set file_list to every file
				repeat with i in file_list
					if the name of i is "Applications" then
						set the position of i to {345, 125}
					else if the name of i ends with ".app" then
						set the position of i to {145, 125}
					else if the name of i is "LGPL License.txt" then
						set the position of i to {145, 225}
						set the extension hidden of i to true
					else if the name of i is "Vivox Acceptable Use Policy.txt" then
						set the position of i to {345, 225}
						set the extension hidden of i to true
					end if
					-- Change the 7 to change the color: 0 is no label, then red,
					-- orange, yellow, green, blue, purple, or gray.
					set the label index of i to 7
				end repeat
			-- This close-open hack is nessesary to save positions on 10.6 Snow Leopard
			close
			open
			end tell

			set opts to the icon view options of container window
			tell opts
				set icon size to iconSize
				set arrangement to not arranged
			end tell

			set background picture of opts to file "background.png"

			update without registering applications
			-- Force saving of the size
			delay 1

			tell container window
				set statusbar visible to false
				set the bounds to {theXOrigin, theYOrigin, theBottomRightX - 10, theBottomRightY - 10}
			end tell

			update without registering applications
		end tell

		delay 1

		tell disk (volumeName as string)
			tell container window
				set statusbar visible to false
				set the bounds to {theXOrigin, theYOrigin, theBottomRightX, theBottomRightY}
			end tell

			update without registering applications
		end tell

		--give the finder some time to write the .DS_Store file
		delay 3

		set waitTime to 0
		set ejectMe to false
		repeat while ejectMe is false
			delay 1
			set waitTime to waitTime + 1

			if (do shell script "[ -f " & dsStore & " ]; echo $?") = "0" then set ejectMe to true
		end repeat
		log "waited " & waitTime & " seconds for .DS_STORE to be created."
	end tell
end run

-- This Applescript sets up the installer disk image: size, background image,
--   icon view, background image, icon positioning.
-- Usage: osascript installer-dmg.applescript <volume-name>
-- where <volume-name> is the volume name of the disk image.

on run (volumeName)
	tell application "Finder"
		tell disk (volumeName as string)
			open

			set theXOrigin to 400
			set theYOrigin to 100
			set theWidth to 500
			set theHeight to 600
			set iconSize to 100

			set theBottomRightX to (theXOrigin + theWidth)
			set theBottomRightY to (theYOrigin + theHeight)
			set dsStore to "\"" & "/Volumes/" & volumeName & "/" & ".DS_STORE\""

			tell container window
				set current view to icon view
				set toolbar visible to false
				set statusbar visible to false
				set the bounds to {theXOrigin, theYOrigin, theBottomRightX, theBottomRightY}
				set statusbar visible to false

				set file_list to every file
				repeat with i in file_list
					if the name of i is "Applications" then
						set the position of i to {345, 125}
					else if the name of i ends with ".app" then
						set the position of i to {145, 125}
					else if the name of i is "LGPL License.txt" then
						set the position of i to {145, 225}
					else if the name of i is "Vivox Acceptable Use Policy.txt" then
						set the position of i to {345, 225}
					end if
					-- Change the 7 to change the color: 0 is no label, then red,
					-- orange, yellow, green, blue, purple, or gray.
					set the label index of i to 7
				end repeat
			-- This close-open hack is nessesary to save positions on 10.6 Snow Leopard
			close
			open
			end tell

			set opts to the icon view options of container window
			tell opts
				set icon size to iconSize
				set arrangement to not arranged
			end tell

			set background picture of opts to file "background.png"

			update without registering applications
			-- Force saving of the size
			delay 1

			tell container window
				set statusbar visible to false
				set the bounds to {theXOrigin, theYOrigin, theBottomRightX - 10, theBottomRightY - 10}
			end tell

			update without registering applications
		end tell

		delay 1

		tell disk (volumeName as string)
			tell container window
				set statusbar visible to false
				set the bounds to {theXOrigin, theYOrigin, theBottomRightX, theBottomRightY}
			end tell

			update without registering applications
		end tell

		--give the finder some time to write the .DS_Store file
		delay 3

		set waitTime to 0
		set ejectMe to false
		repeat while ejectMe is false
			delay 1
			set waitTime to waitTime + 1

			if (do shell script "[ -f " & dsStore & " ]; echo $?") = "0" then set ejectMe to true
		end repeat
		log "waited " & waitTime & " seconds for .DS_STORE to be created."
	end tell
end run


[NEW] Finder 10.5 and Xcode 2.5 compatibility tweaks. Hopefully this doesn't break 10.4 and 2.4.

tell application "Xcode"
	if not (exists active project document) then
		error "No active project. Please open an Xcode project and re-run the script."
	my updateProjectXmod(project of active project document)
end tell

on updateProjectXmod(_project)
	tell application "Xcode"
		-- Iterate over every .xcdatamodel in the project.
		set modelList to every file reference of _project whose file kind is "wrapper.xcdatamodel"
		repeat with modelIt in modelList
			set modelSrcDir to my modelSrcDirPath(full path of modelIt)
			set targetList to my everyTargetWithBuildFilePath(_project, full path of modelIt)

			-- Create the .xcdatamodel related source group if necessary.
			if not (exists (every item reference of group of modelIt whose full path is modelSrcDir)) then
				tell group of modelIt
					make new group with properties {full path:modelSrcDir, name:text 1 thru -13 of ((name of modelIt) as string)}
				end tell
			end if
			set modelSrcGroup to item 1 of (every item reference of group of modelIt whose full path is modelSrcDir)
			tell modelSrcGroup to delete every item reference -- clear it out for population in case we didn't just create it

			--	Meat.
			do shell script "/usr/bin/mogenerator --model '" & full path of modelIt & "' --output-dir '" & modelSrcDir & "'"

			--	Build a list of resulting source files.
			tell application "System Events"
				set humanFileList to (every file of (POSIX file modelSrcDir as alias) whose (name ends with ".m" or name ends with ".mm") and name does not start with "_")
				set machineFileList to (every file of (POSIX file modelSrcDir as alias) whose (name ends with ".m" or name ends with ".mm") and name starts with "_")
				set fileList to humanFileList & machineFileList
				set pathList to {}
				repeat with fileItem in fileList
					set pathList to pathList & POSIX path of fileItem
				end repeat
			end tell

			--	Add the source files to the model's source group and the model's targets.
			repeat with pathIt in pathList
				tell modelSrcGroup
					set modelSrcFileRef to make new file reference with properties {full path:pathIt, name:name of (info for POSIX file pathIt)}
					repeat with targetIt in targetList
						add modelSrcFileRef to (targetIt as anything)
					end repeat
				end tell
			end repeat
		end repeat
	end tell
end updateProjectXmod

on updateModelXmod(_project, _modelFilePath)
	tell application "Xcode"
	end tell
end updateModelXmod

on everyTargetWithBuildFilePath(_project, _buildFilePath)
	set theResult to {}
	tell application "Xcode"
		repeat with targetIt in (every target of _project)
			repeat with buildFileIt in build files of targetIt
				if full path of file reference of buildFileIt is _buildFilePath then set theResult to theResult & {(targetIt as anything)}
			end repeat
		end repeat
	end tell
	return theResult
end everyTargetWithBuildFilePath

on modelSrcDirPath(modelFilePath)
	set modelFilePath to POSIX file modelFilePath
	tell application "Finder"
		set modelFileFolder to folder of (modelFilePath as file)
		set modelFileName to name of (modelFilePath as file)
		set modelSrcFolderName to text 1 thru -13 of modelFileName -- pull off the .xcdatamodel extension
		if not (exists folder modelSrcFolderName of modelFileFolder) then
			make folder at modelFileFolder with properties {name:modelSrcFolderName}
		end if
		set modelSrcFolder to folder modelSrcFolderName of modelFileFolder
	end tell
	return text 1 thru -2 of (POSIX path of (modelSrcFolder as alias)) -- kill the trailing slash
end modelSrcDirPath

tell application "Xcode"
	if not (exists active project document) then
		error "No active project. Please open an Xcode project and re-run the script."
	my updateProjectXmod(project of active project document)
end tell

on updateProjectXmod(_project)
	tell application "Xcode"
		-- Iterate over every .xcdatamodel in the project.
		set modelList to every file reference of _project whose file kind is "wrapper.xcdatamodel"
		repeat with modelIt in modelList
			set modelSrcDir to my modelSrcDirPath(full path of modelIt)
			set targetList to my everyTargetWithBuildFilePath(_project, full path of modelIt)

			-- Create the .xcdatamodel related source group if necessary.
			if not (exists (every item reference of group of modelIt whose full path is modelSrcDir)) then
				tell group of modelIt
					make new group with properties {full path:modelSrcDir, name:text 1 thru -13 of ((name of modelIt) as string)}
				end tell
			end if
			set modelSrcGroup to item 1 of (every item reference of group of modelIt whose full path is modelSrcDir)
			tell modelSrcGroup to delete every item reference -- clear it out for population in case we didn't just create it

			--	Meat.
			do shell script "/usr/bin/mogenerator --model '" & full path of modelIt & "' --output-dir '" & modelSrcDir & "'"

			--	Build a list of resulting source files.
			tell application "System Events"
				set humanFileList to (every file of (POSIX file modelSrcDir as alias) whose (name ends with ".m" or name ends with ".mm") and name does not start with "_")
				set machineFileList to (every file of (POSIX file modelSrcDir as alias) whose (name ends with ".m" or name ends with ".mm") and name starts with "_")
				set fileList to humanFileList & machineFileList
				set pathList to {}
				repeat with fileItem in fileList
					set pathList to pathList & POSIX path of fileItem
				end repeat
			end tell

			--	Add the source files to the model's source group and the model's targets.
			repeat with pathIt in pathList
				tell modelSrcGroup
					set modelSrcFileRef to make new file reference with properties {full path:pathIt, name:name of (info for POSIX file pathIt)}
					repeat with targetIt in targetList
						add modelSrcFileRef to (targetIt as anything)
					end repeat
				end tell
			end repeat
		end repeat
	end tell
end updateProjectXmod

on updateModelXmod(_project, _modelFilePath)
	tell application "Xcode"
	end tell
end updateModelXmod

on everyTargetWithBuildFilePath(_project, _buildFilePath)
	set theResult to {}
	tell application "Xcode"
		repeat with targetIt in (every target of _project)
			repeat with buildFileIt in build files of targetIt
				if full path of file reference of buildFileIt is _buildFilePath then set theResult to theResult & {targetIt}
			end repeat
		end repeat
	end tell
	return theResult
end everyTargetWithBuildFilePath

on modelSrcDirPath(modelFilePath)
	set modelFilePath to POSIX file modelFilePath
	tell application "Finder"
		set modelFileFolder to folder of modelFilePath
		set modelFileName to name of modelFilePath
		set modelSrcFolderName to text 1 thru -13 of modelFileName -- pull off the .xcdatamodel extension
		if not (exists folder modelSrcFolderName of modelFileFolder) then
			make folder at modelFileFolder with properties {name:modelSrcFolderName}
		end if
		set modelSrcFolder to folder modelSrcFolderName of modelFileFolder
	end tell
	return text 1 thru -2 of (POSIX path of (modelSrcFolder as alias)) -- kill the trailing slash
end modelSrcDirPath


Changes the togglevpn.applescript file, so that activating it while in the process of connecting, cancels the connection

tell application "Viscosity"
    if the state of the first connection is not "Disconnected" then
        disconnect the first connection
    else
        connect the first connection
    end if
end tell

tell application "Viscosity"
    if the state of the first connection is "Connected" then
        disconnect the first connection
    else
        connect the first connection
    end if
end tell


try 2nd time to click-and-wait for popup menu setting

-- fmGUI_Popup_SelectByCommand({objRef:"", objValue:"", calcValue:null, selectCommand:"", clickIfAlreadySet:""})
-- Daniel A. Shockley, NYHTC
-- Selects a choice from a popup menu

(*
REQUIRES:
	clickObjectByCoords
	fmGUI_SpecifyCalcWindowSet

HISTORY:
	2020-05-21 ( dshockley ): Try a 2nd time to click-and-wait for the menu to appear.
	1.4.1 - 2018-04-30 ( eshagdar ): tell FM to click on the value since it might not be visible ( and unclickable by CLI ).
	1.4 - 2017-09-22 ( eshagdar ): set calc using handler.
	1.3 - 2017-09-06 ( eshagdar ): added calcValue param that sets a calc in the 'Specify Calculation' that comes up.
	1.2 - 2017-09-05 ( eshagdar ): clicking done by handler
	1.1 - 2017-06-29 ( eshagdar ): prefs must be a record. incoming param may be a string, so ensure that it's an object reference.
	1.0 - created
*)

on run
	tell application "System Events"
		tell application process "FileMaker Pro Advanced"
			set frontmost to true
			delay 1
			--set popUpButtonRef to pop up button "Available menu commands:" of window 1
			set popUpButtonRef to pop up button "View" of window 1
		end tell
	end tell

	fmGUI_Popup_SelectByCommand({objRef:popUpButtonRef, objValue:"limited...", calcValue:"If ( True; True; GetAsNumber ( \"1\" ) )", clickIfAlreadySet:true})

end run

--------------------
-- START OF CODE
--------------------

on fmGUI_Popup_SelectByCommand(prefs)
	-- version 2020-05-21-1231

	set defaultPrefs to {objRef:null, objValue:null, calcValue:null, selectCommand:"is", clickIfAlreadySet:false}
	set prefs to prefs & defaultPrefs

	set objRef to ensureObjectRef(objRef of prefs)
	set selectCommand to selectCommand of prefs
	set objValue to objValue of prefs
	set clickIfAlreadySet to clickIfAlreadySet of prefs -- re-select even if popup is the requested value.

	try
		tell application "System Events"
			if not (exists objRef) then error "The specified objRef does not exist." number 1024

			-- the objRef DOES exist
			set mustPick to false
			if not (exists value of objRef) then
				-- first check if the value of the objRef exists - if it doesn't, then we can't test it directly
				set mustPick to true

			else -- we can see the value without 'picking' the menu, so test it:
				-- note that our selection might be one of several 'matching' commands:
				if clickIfAlreadySet then
					-- RE-SELECT even if popup already is the requested value.
					set mustPick to true

				else if selectCommand is equal to "is" then
					if value of objRef is not objValue then
						set mustPick to true
					end if

				else if selectCommand is equal to "contains" then
					if value of objRef does not contain objValue then
						set mustPick to true
					end if

				else if selectCommand is equal to "startsWith" then
					if value of objRef does not start with objValue then
						set mustPick to true
					end if

				else if selectCommand is equal to "beginsWith" then
					if value of objRef does not start with objValue then
						set mustPick to true
					end if

				else if selectCommand is equal to "endsWith" then
					if value of objRef does not end with objValue then
						set mustPick to true
					end if

				end if
			end if
		end tell

		if mustPick then
			if objValue is not null then
				-- click pop up button so the menu becomes available
				delay 0.3 -- short delay to make sure click can happen:
				clickObjectByCoords(objRef)

				-- wait to see if menu becomes available
				repeat 100 times
					try
						tell application "System Events"
							tell application process "FileMaker Pro Advanced"
								if exists (menu 1 of objRef) then exit repeat
							end tell
						end tell
					on error
						delay 0.5
					end try
				end repeat

				if not (exists (menu 1 of objRef)) then
					-- SECOND attempt to click-then-wait for menu to be available, but give up sooner:

					-- click pop up button so the menu becomes available
					clickObjectByCoords(objRef)

					--wait until menu is available
					repeat 20 times
						try
							tell application "System Events"
								tell application process "FileMaker Pro Advanced"
									if exists (menu 1 of objRef) then exit repeat
								end tell
							end tell
						on error
							delay 0.5
						end try
					end repeat
				end if

				-- now pick an item from the pop up
				tell application "System Events"
					objRef
					if selectCommand is equal to "is" then
						set objValue to first menu item of menu 1 of objRef whose name is objValue
					else if selectCommand is equal to "contains" then
						set objValue to first menu item of menu 1 of objRef whose name contains objValue
					else if selectCommand is equal to "beginsWith" then
						set objValue to first menu item of menu 1 of objRef whose name starts with objValue
					else if selectCommand is equal to "endsWith" then
						set objValue to first menu item of menu 1 of objRef whose name ends with objValue
					else
						error "unable to pick objValue because select command is failed" number -1024
					end if

					tell process "FileMaker Pro Advanced"
						click objValue
					end tell
				end tell

				-- must tell FM to click since the value might now be available ( need to scroll )
				--clickObjectByCoords(objValue)
			end if

			-- set calc if there is one
			if calcValue of prefs is not null then fmGUI_SpecifyCalcWindowSet({calcValue:calcValue of prefs})
		end if

		return true
	on error errMsg number errNum
		error "unable to fmGUI_Popup_SelectByCommand ( value _" & selectCommand & "_ '" & objValue & "' in popup ) - " & errMsg number errNum
	end try
end fmGUI_Popup_SelectByCommand

--------------------
-- END OF CODE
--------------------

on clickObjectByCoords(objRef)
	tell application "htcLib" to clickObjectByCoords(my coerceToString(objRef))
end clickObjectByCoords

on fmGUI_SpecifyCalcWindowSet(prefs)
	tell application "htcLib" to fmGUI_SpecifyCalcWindowSet(prefs)
end fmGUI_SpecifyCalcWindowSet

on coerceToString(incomingObject)
	-- 2017-07-12 ( eshagdar ): bootstrap code to bring a coerceToString into this file for the sample to run ( instead of having a copy of the handler locally ).

	tell application "Finder" to set coercePath to (container of (container of (path to me)) as text) & "text parsing:coerceToString.applescript"
	set codeCoerce to read file coercePath as text
	tell application "htcLib" to set codeCoerce to "script codeCoerce " & return & getTextBetween({sourceText:codeCoerce, beforeText:"-- START OF CODE", afterText:"-- END OF CODE"}) & return & "end script" & return & "return codeCoerce"
	set codeCoerce to run script codeCoerce
	tell codeCoerce to coerceToString(incomingObject)
end coerceToString

on ensureObjectRef(someObjectRef)
	-- 2017-07-12 ( eshagdar ): bootstrap code to bring a ensureObjectRef into this file for the sample to run ( instead of having a copy of the handler locally ).

	tell application "Finder" to set ensureObjPath to (container of (container of (path to me)) as text) & "text parsing:ensureObjectRef.applescript"
	set codeEnsureObj to read file ensureObjPath as text
	tell application "htcLib" to set codeEnsureObj to "script codeEnsureObj " & return & getTextBetween({sourceText:codeEnsureObj, beforeText:"-- START OF CODE", afterText:"-- END OF CODE"}) & return & "end script" & return & "return codeEnsureObj"
	set codeEnsureObj to run script codeEnsureObj
	tell codeEnsureObj to ensureObjectRef(someObjectRef)
end ensureObjectRef

-- fmGUI_Popup_SelectByCommand({objRef:"", objValue:"", calcValue:null, selectCommand:"", clickIfAlreadySet:""})
-- Daniel A. Shockley, NYHTC
-- Selects a choice from a popup menu

(*
REQUIRES:
	clickObjectByCoords
	fmGUI_SpecifyCalcWindowSet

HISTORY:
	1.4.1 - 2018-04-30 ( eshagdar ): tell FM to click on the value since it might not be visible ( and unclickable by CLI ).
	1.4 - 2017-09-22 ( eshagdar ): set calc using handler.
	1.3 - 2017-09-06 ( eshagdar ): added calcValue param that sets a calc in the 'Specify Calculation' that comes up.
	1.2 - 2017-09-05 ( eshagdar ): clicking done by handler
	1.1 - 2017-06-29 ( eshagdar ): prefs must be a record. incoming param may be a string, so ensure that it's an object reference.
	1.0 - created
*)

on run
	tell application "System Events"
		tell application process "FileMaker Pro Advanced"
			set frontmost to true
			delay 1
			--set popUpButtonRef to pop up button "Available menu commands:" of window 1
			set popUpButtonRef to pop up button "View" of window 1
		end tell
	end tell

	fmGUI_Popup_SelectByCommand({objRef:popUpButtonRef, objValue:"limited...", calcValue:"If ( True; True; GetAsNumber ( \"1\" ) )", clickIfAlreadySet:true})

end run

--------------------
-- START OF CODE
--------------------

on fmGUI_Popup_SelectByCommand(prefs)
	-- version 1.4.1

	set defaultPrefs to {objRef:null, objValue:null, calcValue:null, selectCommand:"is", clickIfAlreadySet:false}
	set prefs to prefs & defaultPrefs

	set objRef to ensureObjectRef(objRef of prefs)
	set selectCommand to selectCommand of prefs
	set objValue to objValue of prefs
	set clickIfAlreadySet to clickIfAlreadySet of prefs -- re-select even if popup is the requested value.
	set calcBoxWindowName to "Specify Calculation"

	try
		tell application "System Events"
			if not (exists objRef) then error "The specified objRef does not exist." number 1024

			-- the objRef DOES exist
			set mustPick to false
			if not (exists value of objRef) then
				-- first check if the value of the objRef exists - if it doesn't, then we can't test it directly
				set mustPick to true

			else -- we can see the value without 'picking' the menu, so test it:
				-- note that our selection might be one of several 'matching' commands:
				if clickIfAlreadySet then
					-- RE-SELECT even if popup already is the requested value.
					set mustPick to true

				else if selectCommand is equal to "is" then
					if value of objRef is not objValue then
						set mustPick to true
					end if

				else if selectCommand is equal to "contains" then
					if value of objRef does not contain objValue then
						set mustPick to true
					end if

				else if selectCommand is equal to "startsWith" then
					if value of objRef does not start with objValue then
						set mustPick to true
					end if

				else if selectCommand is equal to "beginsWith" then
					if value of objRef does not start with objValue then
						set mustPick to true
					end if

				else if selectCommand is equal to "endsWith" then
					if value of objRef does not end with objValue then
						set mustPick to true
					end if

				end if
			end if
		end tell

		if mustPick then
			if objValue is not null then
				-- click pop up button so the menu becomes available
				clickObjectByCoords(objRef)

				--wait until menu is available
				repeat 100 times
					try
						tell application "System Events"
							tell application process "FileMaker Pro Advanced"
								if exists (menu 1 of objRef) then exit repeat
							end tell
						end tell
					on error
						delay 0.5
					end try
				end repeat

				-- now pick an item from the pop up
				tell application "System Events"
					objRef
					if selectCommand is equal to "is" then
						set objValue to first menu item of menu 1 of objRef whose name is objValue
					else if selectCommand is equal to "contains" then
						set objValue to first menu item of menu 1 of objRef whose name contains objValue
					else if selectCommand is equal to "beginsWith" then
						set objValue to first menu item of menu 1 of objRef whose name starts with objValue
					else if selectCommand is equal to "endsWith" then
						set objValue to first menu item of menu 1 of objRef whose name ends with objValue
					else
						error "unable to pick objValue because select command is failed" number -1024
					end if

					tell process "FileMaker Pro Advanced"
						click objValue
					end tell
				end tell

				-- must tell FM to click since the value might now be available ( need to scroll )
				--clickObjectByCoords(objValue)
			end if

			-- set calc if there is one
			if calcValue of prefs is not null then fmGUI_SpecifyCalcWindowSet({calcValue:calcValue of prefs})
		end if

		return true
	on error errMsg number errNum
		error "unable to fmGUI_Popup_SelectByCommand ( value _" & selectCommand & "_ '" & objValue & "' in popup ) - " & errMsg number errNum
	end try
end fmGUI_Popup_SelectByCommand

--------------------
-- END OF CODE
--------------------

on clickObjectByCoords(objRef)
	tell application "htcLib" to clickObjectByCoords(my coerceToString(objRef))
end clickObjectByCoords

on fmGUI_SpecifyCalcWindowSet(prefs)
	tell application "htcLib" to fmGUI_SpecifyCalcWindowSet(prefs)
end fmGUI_SpecifyCalcWindowSet

on coerceToString(incomingObject)
	-- 2017-07-12 ( eshagdar ): bootstrap code to bring a coerceToString into this file for the sample to run ( instead of having a copy of the handler locally ).

	tell application "Finder" to set coercePath to (container of (container of (path to me)) as text) & "text parsing:coerceToString.applescript"
	set codeCoerce to read file coercePath as text
	tell application "htcLib" to set codeCoerce to "script codeCoerce " & return & getTextBetween({sourceText:codeCoerce, beforeText:"-- START OF CODE", afterText:"-- END OF CODE"}) & return & "end script" & return & "return codeCoerce"
	set codeCoerce to run script codeCoerce
	tell codeCoerce to coerceToString(incomingObject)
end coerceToString

on ensureObjectRef(someObjectRef)
	-- 2017-07-12 ( eshagdar ): bootstrap code to bring a ensureObjectRef into this file for the sample to run ( instead of having a copy of the handler locally ).

	tell application "Finder" to set ensureObjPath to (container of (container of (path to me)) as text) & "text parsing:ensureObjectRef.applescript"
	set codeEnsureObj to read file ensureObjPath as text
	tell application "htcLib" to set codeEnsureObj to "script codeEnsureObj " & return & getTextBetween({sourceText:codeEnsureObj, beforeText:"-- START OF CODE", afterText:"-- END OF CODE"}) & return & "end script" & return & "return codeEnsureObj"
	set codeEnsureObj to run script codeEnsureObj
	tell codeEnsureObj to ensureObjectRef(someObjectRef)
end ensureObjectRef


Remove sorting algo in favor of current sort order

-- core configuration --

-- configurable options --

-- limit number of songs to improve efficiency
property resultLimit : 25
-- whether or not to retrieve/display album artwork for each result
property albumArtEnabled : true

-- workflow parameters --

property homeFolder : (path to home folder as text)
property libraryFolder : (path to library folder from user domain as text)
property cacheFolder : (libraryFolder & "Caches:")
property alfredWorkflowDataFolder : (cacheFolder & "com.runningwithcrayons.Alfred-3:Workflow Data:")
property bundleId : "com.calebevans.playsong"
property workflowCacheFolder : (alfredWorkflowDataFolder & bundleId & ":") as text
property artworkCacheFolderName : "Album Artwork"
property artworkCachePath : (workflowCacheFolder & artworkCacheFolderName & ":")
property songArtworkNameSep : " | "
property defaultIconName : "resources/icon-noartwork.png"
-- the name of the playlist used by the workflow for playing songs
property workflowPlaylistName : "Alfred Play Song"
-- the text used to determine if a track is an audio file
property songDescriptor : "audio"
-- list of Alfred results
property resultList : {}

-- replaces substring in string with another substring
on replace(replaceThis, replaceWith, theString)

	set oldDelims to AppleScript's text item delimiters
	set AppleScript's text item delimiters to replaceThis
	set strItems to text items of theString
	set AppleScript's text item delimiters to replaceWith
	set newString to strItems as text
	set AppleScript's text item delimiters to oldDelims
	return newString

end replace

-- retrieve the plural/singular form of a quantity based on the given number
on quantifyNumber(theNumber, quantityName, pluralQuantityName)

	if theNumber is 1 then

		set theString to (theNumber as text) & space & quantityName

	else

		set theString to (theNumber as text) & space & pluralQuantityName

	end if

	return theString

end quantifyNumber

-- encodes JSON reserved characters in the given string
on encodeFeedbackChars(theString)

	set theString to replace("\\", "\\\\", theString)
	set theString to replace("\"", "\\\"", theString)
	return theString

end encodeFeedbackChars

-- decodes JSON reserved characters in the given string
on decodeFeedbackChars(theString)

	set theString to replace("\\\\", "\\", theString)
	set theString to replace("\\\"", "\"", theString)
	return theString

end decodeFeedbackChars

-- adds Alfred result to result list
on addResult(theResult)

	copy theResult to the end of resultList

end addResult

-- adds item for "No Results" message
on addNoResultsItem(query, queryType)

	addResult({uid:"no-results", valid:"no", title:"No Results Found", subtitle:("No " & queryType & "s matching '" & query & "'"), icon:defaultIconName})

end addNoResultsItem

on resultListIsFull()

	return (length of resultList is resultLimit)

end resultListIsFull

on resultListIsEmpty()

	return (length of resultList is 0)

end resultListIsFull

-- builds Alfred result item as JSON
on getResultFeedback(theResult)

	-- encode reserved JSON characters
	set resultUid to encodeFeedbackChars(uid of theResult)
	set resultValid to (valid of theResult) as text
	set resultTitle to encodeFeedbackChars(title of theResult)
	set resultSubtitle to encodeFeedbackChars(subtitle of theResult)

	if (icon of theResult) contains ":" then

		set resultIcon to encodeFeedbackChars(POSIX path of icon of theResult)

	else

		set resultIcon to icon of theResult

	end if

	set json to "{"
	set json to json & "\"uid\":\"" & resultUid & "\","
	set json to json & "\"arg\":\"" & resultUid & "\","
	set json to json & "\"valid\":\"" & resultValid & "\","
	set json to json & "\"title\":\"" & resultTitle & "\","
	set json to json & "\"subtitle\":\"" & resultSubtitle & "\","
	set json to json & "\"icon\":{\"path\":\"" & resultIcon & "\"}"
	set json to json & "}"
	return json

end getResultFeedback

-- retrieves JSON document for Alfred results
on getResultListFeedback()

	set json to "{\"items\": ["

	repeat with theResult in resultList

		set json to json & getResultFeedback(theResult)
		set json to json & ","

	end repeat

	-- remove trailing comma after last item
	set json to text 1 thru (length of json - 1) of json
	set json to json & "]}"
	return json

end getResultListFeedback

-- writes the given content to the given file
on fileWrite(theFile, theContent)

	set fileRef to open for access theFile with write permission
	try
		set eof of fileRef to 0
		write theContent to fileRef starting at eof
		close access fileRef
	on error
		close access fileRef
	end try

end fileWrite

-- builds path to album art for the given song
on getSongArtworkPath(theSong)

	if albumArtEnabled is false then return defaultIconName

	tell application "iTunes"

		set songArtist to artist of theSong
		set songAlbum to album of theSong
		-- generate a unique identifier for that album
		set songArtworkName to (songArtist & songArtworkNameSep & songAlbum) as text
		-- remove forbidden path characters
		set songArtworkName to replace(":", "", songArtworkName) of me
		set songArtworkName to replace("/", "", songArtworkName) of me
		set songArtworkName to replace(".", "", songArtworkName) of me
		set songArtworkPath to (artworkCachePath & songArtworkName & ".jpg")

	end tell

	tell application "Finder"

		-- cache artwork if it's not already cached
		if not (songArtworkPath exists) then

			tell application "iTunes"

				set songArtworks to artworks of theSong
				-- only save artwork if artwork exists for this song
				if (length of songArtworks) is 0 then

					-- use default iTunes icon if song has no artwork
					set songArtworkPath to defaultIconName

				else

					-- save artwork to file
					set songArtwork to data of (item 1 of songArtworks)
					fileWrite(songArtworkPath, songArtwork) of me

				end if

			end tell

		end if

	end tell

	return songArtworkPath

end getSongArtworkPath

-- creates album artwork cache
on createWorkflowPlaylist()

	tell application "iTunes"

		if not (user playlist workflowPlaylistName exists) then

			make new user playlist with properties {name:workflowPlaylistName, shuffle:false}

		end if

	end tell

end createWorkflowPlaylist

on clearQueue()

	tell application "iTunes"

		if user playlist workflowPlaylistName exists then

			delete tracks of user playlist workflowPlaylistName

		end if

	end tell

end clearQueue

on queueSongs(theSongs)

	tell application "iTunes"

		repeat with theSong in theSongs

			duplicate theSong to user playlist workflowPlaylistName

		end repeat

	end tell

end queueSongs

on playQueue()

	tell application "iTunes"

		if number of tracks in user playlist workflowPlaylistName is not 0 then

			play user playlist workflowPlaylistName

		end if

	end tell

end playQueue

on getPlaylist(playlistId)

	tell application "iTunes"

		return (first playlist whose id is playlistId)

	end tell

end getPlaylist

on getPlaylistSongs(playlistId)

	tell application "iTunes"

		set thePlaylist to getPlaylist(playlistId) of me
		set theSongs to every track of thePlaylist

	end tell

	return theSongs

end getPlaylistSongs

-- retrieves list of artist names for the given genre
on getGenreArtists(genreName)

	tell application "iTunes"

		set theSongs to every track of playlist 2 whose genre is genreName and kind contains songDescriptor
		set artistNames to {}

		repeat with theSong in theSongs

			if (artist of theSong) is not in artistNames then

				set artistNames to artistNames & (artist of theSong)

			end if

		end repeat

	end tell

	return artistNames

end getGenreArtists

-- retrieves list of songs within the given genre, sorted by artist
on getGenreSongs(genreName)

	set artistNames to getGenreArtists(genreName) of me
	set theSongs to {}

	repeat with artistName in artistNames

		set theSongs to theSongs & getArtistSongs(artistName) of me

	end repeat

	return theSongs

end getGenreSongs

-- retrieves list of album names for the given artist
on getArtistAlbums(artistName)

	tell application "iTunes"

		set theSongs to every track of playlist 2 whose artist is artistName and kind contains songDescriptor
		set albumNames to {}

		repeat with theSong in theSongs

			if (album of theSong) is not in albumNames then

				set albumNames to albumNames & (album of theSong)

			end if

		end repeat

	end tell

	return albumNames

end getArtistAlbums

-- retrieves list of songs by the given artist, sorted by album
on getArtistSongs(artistName)

	tell application "iTunes"

		set albumNames to getArtistAlbums(artistName) of me
		set theSongs to {}

		repeat with albumName in albumNames

			set albumSongs to (every track of playlist 2 whose artist is artistName and album is albumName and kind contains songDescriptor)
			set theSongs to theSongs & albumSongs

		end repeat

	end tell

	return theSongs

end getArtistSongs

-- retrieves list of songs in the given album
on getAlbumSongs(albumName)

	tell application "iTunes"

		set theSongs to every track of playlist 2 whose album is albumName and kind contains songDescriptor

	end tell

	return theSongs

end getAlbumSongs

-- retrieves the song with the given ID
on getSong(songId)

	tell application "iTunes"

		set theSong to first track of playlist 2 whose database ID is songId and kind contains songDescriptor

	end tell

	return theSong

end getSong

-- retrieves a list of objects or names matching the given query and type
on getResultsFromQuery(query, queryType)

	set evalScript to run script "
	script

		on findResults(query, queryType, resultLimit, songDescriptor)

			tell application \"iTunes\"

				set theSongs to (get every track in playlist 2 whose " & queryType & " starts with query and kind contains songDescriptor)

				if length of theSongs < resultLimit then

					set theSongs to theSongs & (get every track in playlist 2 whose " & queryType & " contains (space & query) and " & queryType & " does not start with query and kind contains songDescriptor)

				end if

				if length of theSongs < resultLimit then

					set theSongs to theSongs & (get every track in playlist 2 whose " & queryType & " contains query and " & queryType & " does not start with query and " & queryType & " does not contain (space & query) and kind contains songDescriptor)

				end if

				if length of theSongs is 0 then

					if queryType is \"name\" then

						set theSongs to theSongs & (search playlist 2 for query only songs)

					else if queryType is not \"genre\" then

						set theSongs to theSongs & (search playlist 2 for query only " & queryType & "s)

					end if

				end if

				if queryType is \"name\" then

					if length of theSongs > resultLimit then

						set theSongs to items 1 thru resultLimit of theSongs

					end if

					set theResults to theSongs

				else

					set theResults to {}

					repeat with theSong in theSongs

						if length of theResults is resultLimit then exit repeat

						set theResult to " & queryType & " of theSong

						if theResult is not in theResults then

							set theResults to theResults & theResult

						end if

					end repeat

				end if

			end tell

			return theResults

		end findResults

	end script
	"

	evalScript's findResults(query, queryType, resultLimit, songDescriptor)

end getResultsFromQuery

-- returns the given string with leading and trailing whitespace removed
on trimWhitespace(theString)

	-- trim leading whitespace
	repeat while theString begins with space

		if length of theString is 1 then return ""
		set theString to text 2 thru end of theString

	end repeat

	-- trim trailing whitespace
	repeat while theString ends with space

		set theString to text 1 thru ((length of theString) - 1) of theString

	end repeat

	return theString

end trimWhitespace

-- queues the song with the given ID
on queueSong(songId)

	set theSong to getSong(songId)
	queueSongs({theSong})

end queueSong

-- queues all songs belonging to the given album
on queueAlbum(albumName)

	set albumName to decodeFeedbackChars(albumName)
	set theSongs to getAlbumSongs(albumName)
	queueSongs(theSongs)

end queueAlbum

-- queues all songs by the given artist
on queueArtist(artistName)

	set artistName to decodeFeedbackChars(artistName)
	set theSongs to getArtistSongs(artistName)
	queueSongs(theSongs)

end queueArtist

-- queues all songs within the given genre
on queueGenre(genreName)

	set genreName to decodeFeedbackChars(genreName)
	set theSongs to getGenreSongs(genreName)
	queueSongs(theSongs)

end queueGenre

-- queues all songs in the given playlist
on queuePlaylist(playlistId)

	set theSongs to getPlaylistSongs(playlistId)
	queueSongs(theSongs)

end queuePlaylist

-- parses the given result query to retrieve type and id of item to queue
on parseResultQuery(query)

	set pos to offset of "-" in query
	set theType to text 1 thru (pos - 1) of query
	set theId to text (pos + 1) thru end of query
	return {type:theType, id:theId}

end parseResultQuery

on queue(query)

	set typeAndId to parseResultQuery(query)
	set theType to type of typeAndId
	set theId to id of typeAndId

	createWorkflowPlaylist()

	if theType is "song" then
		queueSong(theId)
	else if theType is "album" then
		queueAlbum(theId)
	else if theType is "artist" then
		queueArtist(theId)
	else if theType is "genre" then
		queueGenre(theId)
	else if theType is "playlist" then
		queuePlaylist(theId)
	else
		log "Unknown type: " & theType
	end if

end queue

on play(query)

	clearQueue()
	queue(query)
	playQueue()

end play

-- core configuration --

-- configurable options --

-- limit number of songs to improve efficiency
property resultLimit : 25
-- whether or not to retrieve/display album artwork for each result
property albumArtEnabled : true

-- workflow parameters --

property homeFolder : (path to home folder as text)
property libraryFolder : (path to library folder from user domain as text)
property cacheFolder : (libraryFolder & "Caches:")
property alfredWorkflowDataFolder : (cacheFolder & "com.runningwithcrayons.Alfred-3:Workflow Data:")
property bundleId : "com.calebevans.playsong"
property workflowCacheFolder : (alfredWorkflowDataFolder & bundleId & ":") as text
property artworkCacheFolderName : "Album Artwork"
property artworkCachePath : (workflowCacheFolder & artworkCacheFolderName & ":")
property songArtworkNameSep : " | "
property defaultIconName : "resources/icon-noartwork.png"
-- the name of the playlist used by the workflow for playing songs
property workflowPlaylistName : "Alfred Play Song"
-- the text used to determine if a track is an audio file
property songDescriptor : "audio"
-- list of Alfred results
property resultList : {}

-- replaces substring in string with another substring
on replace(replaceThis, replaceWith, theString)

	set oldDelims to AppleScript's text item delimiters
	set AppleScript's text item delimiters to replaceThis
	set strItems to text items of theString
	set AppleScript's text item delimiters to replaceWith
	set newString to strItems as text
	set AppleScript's text item delimiters to oldDelims
	return newString

end replace

-- retrieve the plural/singular form of a quantity based on the given number
on quantifyNumber(theNumber, quantityName, pluralQuantityName)

	if theNumber is 1 then

		set theString to (theNumber as text) & space & quantityName

	else

		set theString to (theNumber as text) & space & pluralQuantityName

	end if

	return theString

end quantifyNumber

-- encodes JSON reserved characters in the given string
on encodeFeedbackChars(theString)

	set theString to replace("\\", "\\\\", theString)
	set theString to replace("\"", "\\\"", theString)
	return theString

end encodeFeedbackChars

-- decodes JSON reserved characters in the given string
on decodeFeedbackChars(theString)

	set theString to replace("\\\\", "\\", theString)
	set theString to replace("\\\"", "\"", theString)
	return theString

end decodeFeedbackChars

-- adds Alfred result to result list
on addResult(theResult)

	copy theResult to the end of resultList

end addResult

-- adds item for "No Results" message
on addNoResultsItem(query, queryType)

	addResult({uid:"no-results", valid:"no", title:"No Results Found", subtitle:("No " & queryType & "s matching '" & query & "'"), icon:defaultIconName})

end addNoResultsItem

on resultListIsFull()

	return (length of resultList is resultLimit)

end resultListIsFull

on resultListIsEmpty()

	return (length of resultList is 0)

end resultListIsFull

-- builds Alfred result item as JSON
on getResultFeedback(theResult)

	-- encode reserved JSON characters
	set resultUid to encodeFeedbackChars(uid of theResult)
	set resultValid to (valid of theResult) as text
	set resultTitle to encodeFeedbackChars(title of theResult)
	set resultSubtitle to encodeFeedbackChars(subtitle of theResult)

	if (icon of theResult) contains ":" then

		set resultIcon to encodeFeedbackChars(POSIX path of icon of theResult)

	else

		set resultIcon to icon of theResult

	end if

	set json to "{"
	set json to json & "\"uid\":\"" & resultUid & "\","
	set json to json & "\"arg\":\"" & resultUid & "\","
	set json to json & "\"valid\":\"" & resultValid & "\","
	set json to json & "\"title\":\"" & resultTitle & "\","
	set json to json & "\"subtitle\":\"" & resultSubtitle & "\","
	set json to json & "\"icon\":{\"path\":\"" & resultIcon & "\"}"
	set json to json & "}"
	return json

end getResultFeedback

-- retrieves JSON document for Alfred results
on getResultListFeedback()

	set json to "{\"items\": ["

	repeat with theResult in resultList

		set json to json & getResultFeedback(theResult)
		set json to json & ","

	end repeat

	-- remove trailing comma after last item
	set json to text 1 thru (length of json - 1) of json
	set json to json & "]}"
	return json

end getResultListFeedback

-- writes the given content to the given file
on fileWrite(theFile, theContent)

	set fileRef to open for access theFile with write permission
	try
		set eof of fileRef to 0
		write theContent to fileRef starting at eof
		close access fileRef
	on error
		close access fileRef
	end try

end fileWrite

-- builds path to album art for the given song
on getSongArtworkPath(theSong)

	if albumArtEnabled is false then return defaultIconName

	tell application "iTunes"

		set songArtist to artist of theSong
		set songAlbum to album of theSong
		-- generate a unique identifier for that album
		set songArtworkName to (songArtist & songArtworkNameSep & songAlbum) as text
		-- remove forbidden path characters
		set songArtworkName to replace(":", "", songArtworkName) of me
		set songArtworkName to replace("/", "", songArtworkName) of me
		set songArtworkName to replace(".", "", songArtworkName) of me
		set songArtworkPath to (artworkCachePath & songArtworkName & ".jpg")

	end tell

	tell application "Finder"

		-- cache artwork if it's not already cached
		if not (songArtworkPath exists) then

			tell application "iTunes"

				set songArtworks to artworks of theSong
				-- only save artwork if artwork exists for this song
				if (length of songArtworks) is 0 then

					-- use default iTunes icon if song has no artwork
					set songArtworkPath to defaultIconName

				else

					-- save artwork to file
					set songArtwork to data of (item 1 of songArtworks)
					fileWrite(songArtworkPath, songArtwork) of me

				end if

			end tell

		end if

	end tell

	return songArtworkPath

end getSongArtworkPath

-- creates album artwork cache
on createWorkflowPlaylist()

	tell application "iTunes"

		if not (user playlist workflowPlaylistName exists) then

			make new user playlist with properties {name:workflowPlaylistName, shuffle:false}

		end if

	end tell

end createWorkflowPlaylist

on clearQueue()

	tell application "iTunes"

		if user playlist workflowPlaylistName exists then

			delete tracks of user playlist workflowPlaylistName

		end if

	end tell

end clearQueue

on queueSongs(theSongs)

	tell application "iTunes"

		repeat with theSong in theSongs

			duplicate theSong to user playlist workflowPlaylistName

		end repeat

	end tell

end queueSongs

on playQueue()

	tell application "iTunes"

		if number of tracks in user playlist workflowPlaylistName is not 0 then

			play user playlist workflowPlaylistName

		end if

	end tell

end playQueue

on getPlaylist(playlistId)

	tell application "iTunes"

		return (first playlist whose id is playlistId)

	end tell

end getPlaylist

on getPlaylistSongs(playlistId)

	tell application "iTunes"

		set thePlaylist to getPlaylist(playlistId) of me
		set theSongs to every track of thePlaylist

	end tell

	return theSongs

end getPlaylistSongs

-- retrieves list of artist names for the given genre
on getGenreArtists(genreName)

	tell application "iTunes"

		set theSongs to every track of playlist 2 whose genre is genreName and kind contains songDescriptor
		set artistNames to {}

		repeat with theSong in theSongs

			if (artist of theSong) is not in artistNames then

				set artistNames to artistNames & (artist of theSong)

			end if

		end repeat

	end tell

	return artistNames

end getGenreArtists

-- retrieves list of songs within the given genre, sorted by artist
on getGenreSongs(genreName)

	set artistNames to getGenreArtists(genreName) of me
	set theSongs to {}

	repeat with artistName in artistNames

		set theSongs to theSongs & getArtistSongs(artistName) of me

	end repeat

	return theSongs

end getGenreSongs

-- retrieves list of album names for the given artist
on getArtistAlbums(artistName)

	tell application "iTunes"

		set theSongs to every track of playlist 2 whose artist is artistName and kind contains songDescriptor
		set albumNames to {}

		repeat with theSong in theSongs

			if (album of theSong) is not in albumNames then

				set albumNames to albumNames & (album of theSong)

			end if

		end repeat

	end tell

	return albumNames

end getArtistAlbums

-- retrieves list of songs by the given artist, sorted by album
on getArtistSongs(artistName)

	tell application "iTunes"

		set albumNames to getArtistAlbums(artistName) of me
		set theSongs to {}

		repeat with albumName in albumNames

			set albumSongs to (every track of playlist 2 whose artist is artistName and album is albumName and kind contains songDescriptor)
			set albumSongs to sortSongsByAlbumOrder(albumSongs) of me
			set theSongs to theSongs & albumSongs

		end repeat

	end tell

	return theSongs

end getArtistSongs

-- retrieves list of songs in the given album
on getAlbumSongs(albumName)

	tell application "iTunes"

		set theSongs to every track of playlist 2 whose album is albumName and kind contains songDescriptor
		set theSongs to sortSongsByAlbumOrder(theSongs) of me

	end tell

	return theSongs

end getAlbumSongs

-- sorts songs from the same album by track number
on sortSongsByAlbumOrder(theSongs)

	tell application "iTunes"

		if length of theSongs is not greater than 1 then
			return theSongs
		end if

		set trackCount to track count of (item 1 of theSongs)
		set discCount to disc count of (item 1 of theSongs)

		if trackCount is 0 or discCount is 0 then
			return theSongs
		end if

		set theSongsSorted to {} as list

		repeat with discIndex from 1 to discCount

			repeat with songIndex from 1 to trackCount

				repeat with theSong in theSongs

					if (disc number of theSong is discIndex or (disc number of theSong is 0 and discIndex is 1)) and track number of theSong is songIndex then

						set nextSong to theSong
						copy nextSong to the end of theSongsSorted

					end if

				end repeat

			end repeat

		end repeat

	end tell

	return theSongsSorted

end sortSongsByAlbumOrder

-- retrieves the song with the given ID
on getSong(songId)

	tell application "iTunes"

		set theSong to first track of playlist 2 whose database ID is songId and kind contains songDescriptor

	end tell

	return theSong

end getSong

-- retrieves a list of objects or names matching the given query and type
on getResultsFromQuery(query, queryType)

	set evalScript to run script "
	script

		on findResults(query, queryType, resultLimit, songDescriptor)

			tell application \"iTunes\"

				set theSongs to (get every track in playlist 2 whose " & queryType & " starts with query and kind contains songDescriptor)

				if length of theSongs < resultLimit then

					set theSongs to theSongs & (get every track in playlist 2 whose " & queryType & " contains (space & query) and " & queryType & " does not start with query and kind contains songDescriptor)

				end if

				if length of theSongs < resultLimit then

					set theSongs to theSongs & (get every track in playlist 2 whose " & queryType & " contains query and " & queryType & " does not start with query and " & queryType & " does not contain (space & query) and kind contains songDescriptor)

				end if

				if length of theSongs is 0 then

					if queryType is \"name\" then

						set theSongs to theSongs & (search playlist 2 for query only songs)

					else if queryType is not \"genre\" then

						set theSongs to theSongs & (search playlist 2 for query only " & queryType & "s)

					end if

				end if

				if queryType is \"name\" then

					if length of theSongs > resultLimit then

						set theSongs to items 1 thru resultLimit of theSongs

					end if

					set theResults to theSongs

				else

					set theResults to {}

					repeat with theSong in theSongs

						if length of theResults is resultLimit then exit repeat

						set theResult to " & queryType & " of theSong

						if theResult is not in theResults then

							set theResults to theResults & theResult

						end if

					end repeat

				end if

			end tell

			return theResults

		end findResults

	end script
	"

	evalScript's findResults(query, queryType, resultLimit, songDescriptor)

end getResultsFromQuery

-- returns the given string with leading and trailing whitespace removed
on trimWhitespace(theString)

	-- trim leading whitespace
	repeat while theString begins with space

		if length of theString is 1 then return ""
		set theString to text 2 thru end of theString

	end repeat

	-- trim trailing whitespace
	repeat while theString ends with space

		set theString to text 1 thru ((length of theString) - 1) of theString

	end repeat

	return theString

end trimWhitespace

-- queues the song with the given ID
on queueSong(songId)

	set theSong to getSong(songId)
	queueSongs({theSong})

end queueSong

-- queues all songs belonging to the given album
on queueAlbum(albumName)

	set albumName to decodeFeedbackChars(albumName)
	set theSongs to getAlbumSongs(albumName)
	queueSongs(theSongs)

end queueAlbum

-- queues all songs by the given artist
on queueArtist(artistName)

	set artistName to decodeFeedbackChars(artistName)
	set theSongs to getArtistSongs(artistName)
	queueSongs(theSongs)

end queueArtist

-- queues all songs within the given genre
on queueGenre(genreName)

	set genreName to decodeFeedbackChars(genreName)
	set theSongs to getGenreSongs(genreName)
	queueSongs(theSongs)

end queueGenre

-- queues all songs in the given playlist
on queuePlaylist(playlistId)

	set theSongs to getPlaylistSongs(playlistId)
	queueSongs(theSongs)

end queuePlaylist

-- parses the given result query to retrieve type and id of item to queue
on parseResultQuery(query)

	set pos to offset of "-" in query
	set theType to text 1 thru (pos - 1) of query
	set theId to text (pos + 1) thru end of query
	return {type:theType, id:theId}

end parseResultQuery

on queue(query)

	set typeAndId to parseResultQuery(query)
	set theType to type of typeAndId
	set theId to id of typeAndId

	createWorkflowPlaylist()

	if theType is "song" then
		queueSong(theId)
	else if theType is "album" then
		queueAlbum(theId)
	else if theType is "artist" then
		queueArtist(theId)
	else if theType is "genre" then
		queueGenre(theId)
	else if theType is "playlist" then
		queuePlaylist(theId)
	else
		log "Unknown type: " & theType
	end if

end queue

on play(query)

	clearQueue()
	queue(query)
	playQueue()

end play


Rewrite openDictionary.applescript

Rewrite openDictionary.applescript

Avoid calling Finder for Sandbox.

(*
 ==============================================================================
 openDictionary.applescript

 CotEditor
 http://coteditor.com

 Created on 2014-12-02 by 1024jp
 ------------------------------------------------------------------------------

 © 2014 1024jp

 This program is free software; you can redistribute it and/or modify it under
 the terms of the GNU General Public License as published by the Free Software
 Foundation; either version 2 of the License, or (at your option) any later
 version.

 This program is distributed in the hope that it will be useful, but WITHOUT
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

 You should have received a copy of the GNU General Public License along with
 this program; if not, write to the Free Software Foundation, Inc., 59 Temple
 Place - Suite 330, Boston, MA  02111-1307, USA.

 ==============================================================================
 *)

set theApp to frontmost application
set scriptEditor to application id "com.apple.ScriptEditor2"

ignoring application responses
    tell scriptEditor to open (path to theApp)
end ignoring

(*
このスクリプトは、下記のソースを参考にさせていただきました。
http://piza.2ch.net/log2/mac/kako/957/957215209.html
*)
tell application "Finder"
	set the script_editor to application file id "ToyS"
	set file_path to path to frontmost application
	ignoring application responses
		open file_path using script_editor
	end ignoring
end tell


Scripts update

Scripts update

FasdUAS 1.101.10
k
i
I	0resize_app_window

o0app_name

o0win_position

o0win_size
Z=
=
n
1

prun
4

capp
o0app_name
m
boovtrue
O9
O8
k7
r&
J  !
 n"#
"4$

cobj
$m
#o0win_position!%
%n&'
&4(

cobj
(m
'o0win_position
n)*
)1#%

posn
*l #+
+2 #

cwin,
,r'7-.
-J'1//01
0n'+23
24(+4

cobj
4m)*
3o'(0win_size15
5n+/67
64,/8

cobj
8m-.
7o+,0win_size
.n9:
9146

ptsz
:l14;
;214

cwin
4<

prcs
<o0app_name
m==sevsalis\Macintosh HDBDSystem Events.app
 cuCoreServices0/:System:Library:CoreServices:System Events.app/$System Events.appMacintosh HD-System/Library/CoreServices/System Events.app/>?
>l?@A
@lB
BrCD
CJEEFG
FmGH
Hm(
Do0wide_center_positionAIJ
Il
K
Kr
LM
LJNNOP
OmPQ
Qm	Q
Mo0wide_center_sizeJRS
RlSTU
TlV
VIW0resize_app_windowWXY
XmZZ[[1Password 7Y\]
\o0wide_center_position]^
^o0wide_center_sizeU_`
_la
aIb0resize_app_windowbcd
cmeeffCalendardgh
go0wide_center_positionhi
io0wide_center_size`jk
jl (l
lI (m0resize_app_windowmno
nm!"ppqqDiscordors
ro"#0wide_center_positionst
to#$0wide_center_sizekuv
ul)1w
wI)1x0resize_app_windowxyz
ym*+{{||Fantasticalz}~
}o+,0wide_center_position~
o,-0wide_center_sizev
l2:
I2:0resize_app_window
m34Google Chrome
o450wide_center_position
o560wide_center_size
l;C
I;C0resize_app_window
m<=Linear
o=>0wide_center_position
o>?0wide_center_size
lDL
IDL0resize_app_window
mEFMail
oFG0wide_center_position
oGH0wide_center_size
lM[
IM[0resize_app_window
mNOMessages
JOS
mOP
mPQ(
JSW
mST?
mTUQ
l\f
I\f0resize_app_window
m]`
Music
o`a0wide_center_position
oab0wide_center_size
lgq
Igq0resize_app_window
mhk
Notes
okl0wide_center_position
olm~~0wide_center_size
lr|}|
Ir|{z{0resize_app_window
msvPreview
ovwyy0wide_center_positionx
owxww0wide_center_sizexz}|
l}vu
I}tst0resize_app_window
m~Reflect
orr0wide_center_positionq
opp0wide_center_sizeqsvu
lon
Imlm0resize_app_window
mSafari
okk0wide_center_positionj
oii0wide_center_sizejlon
lhg
Ifef0resize_app_window
mSiftie
odd0wide_center_positionc
obb0wide_center_sizecehg
la`
I_^_0resize_app_window
m
Slack
o]]0wide_center_position\
o[[0wide_center_size\^a`
lZY
IXWX0resize_app_window
mSpotify

	oVV0wide_center_position
U
oTT0wide_center_sizeUWZY

lSR
IQPQ0resize_app_window
mTextEdit
J
mOON
mMMNL
J
mKKJ
mIIJLPSR
H
l GF
 IE!DE0resize_app_window!"#
"m$$%%Tweetbot#&'
&J(()*
)mCC*+B
+mAA(B',@
,J--./
.m???/0>
0m==Q>@DGFH<12345<1;:98;0resize_app_window
:.aevtoappnull****90wide_center_position80wide_center_size276567470resize_app_window6383821020app_name10win_position00win_size56/.-/0app_name.0win_position-0win_size7,+=*)('&
,
capp
+
prun
*
prcs
)
cobj
(
cwin
'
posn
&
ptsz4>*/,e3+*/#k/l/lv*-,FOk/l/lv*-,FUUYh3%9$#:;"
%.aevtoappnull****
9k<<@==I>>T??_@@jAAuBBCCDDEEFFGGHHIIJJKKLLMMNNOO!!$#:; Zep{$ (0wide_center_positionQ0wide_center_size0resize_app_window?"lvEOlvEO*m+O*m+O*m+O*m+O*m+O*m+O*m+O*lvlvm+O*am+O*am+O*am+O*am+O*am+O*am+O*am+O*am+O*aalvaalvm+O*alvlvm+4PP(5QQQascr
ޭ

FasdUAS 1.101.10
k
i
I	0resize_app_window

o0app_name

o0win_position

o0win_size
Z=
=
n
1

prun
4

capp
o0app_name
m
boovtrue
O9
O8
k7
r&
J  !
 n"#
"4$

cobj
$m
#o0win_position!%
%n&'
&4(

cobj
(m
'o0win_position
n)*
)1#%

posn
*l #+
+2 #

cwin,
,r'7-.
-J'1//01
0n'+23
24(+4

cobj
4m)*
3o'(0win_size15
5n+/67
64,/8

cobj
8m-.
7o+,0win_size
.n9:
9146

ptsz
:l14;
;214

cwin
4<

prcs
<o0app_name
m==sevsalis\Macintosh HDBDSystem Events.app
 cuCoreServices0/:System:Library:CoreServices:System Events.app/$System Events.appMacintosh HD-System/Library/CoreServices/System Events.app/>?
>l?@A
@lB
BrCD
CJEEFG
FmGH
Hm(
Do0wide_center_positionAIJ
Il
K
Kr
LM
LJNNOP
OmPQ
Qm	Q
Mo0wide_center_sizeJRS
RlSTU
TlV
VIW0resize_app_windowWXY
XmZZ[[1Password 7Y\]
\o0wide_center_position]^
^o0wide_center_sizeU_`
_la
aIb0resize_app_windowbcd
cmeeffCalendardgh
go0wide_center_positionhi
io0wide_center_size`jk
jl (l
lI (m0resize_app_windowmno
nm!"ppqqFantasticalors
ro"#0wide_center_positionst
to#$0wide_center_sizekuv
ul)1w
wI)1x0resize_app_windowxyz
ym*+{{||Google Chromez}~
}o+,0wide_center_position~
o,-0wide_center_sizev
l2:
I2:0resize_app_window
m34Linear
o450wide_center_position
o560wide_center_size
l;C
I;C0resize_app_window
m<=Mail
o=>0wide_center_position
o>?0wide_center_size
lDR
IDR0resize_app_window
mEFMessages
JFJ
mFG
mGH(
JJN
mJK?
mKLQ
lS[
IS[0resize_app_window
mTU
Music
oUV0wide_center_position
oVW0wide_center_size
l\f
I\f0resize_app_window
m]`
Notes
o`a0wide_center_position
oab0wide_center_size
lgq
Igq0resize_app_window
mhkNotion
okl0wide_center_position
olm~~0wide_center_size
lr|}|
Ir|{z{0resize_app_window
msvPreview
ovwyy0wide_center_positionx
owxww0wide_center_sizexz}|
l}vu
I}tst0resize_app_window
m~Safari
orr0wide_center_positionq
opp0wide_center_sizeqsvu
lon
Imlm0resize_app_window
mSiftie
okk0wide_center_positionj
oii0wide_center_sizejlon
lhg
Ifef0resize_app_window
m
Slack
odd0wide_center_positionc
obb0wide_center_sizecehg
la`
I_^_0resize_app_window
mSpotify
o]]0wide_center_position\
o[[0wide_center_size\^a`
lZY
IXWX0resize_app_window
mTextEdit

	J

mVV
U
mTTU
S
J
mRRQ
mPPQSWZYO
lNM
ILKL0resize_app_window
mTweetbot
J
mJJ I
 mHH(I!G
!J""#$
#mFF?$%E
%mDDQEGKNMOC&'()*C&BA@?B0resize_app_window
A.aevtoappnull****@0wide_center_position?0wide_center_size'>=<+,;>0resize_app_window=:-:-98790app_name80win_position70win_size<+65460app_name50win_position40win_size,32=10/.-
3
capp
2
prun
1
prcs
0
cobj
/
cwin
.
posn
-
ptsz;>*/,e3+*/#k/l/lv*-,FOk/l/lv*-,FUUYh(,.+*/0)
,.aevtoappnull****
.k11@22I33T44_55j66u778899::;;<<==>>??@@AABBCC((+*/0'&%$#"Z!ep{ '&(%0wide_center_position$#Q"0wide_center_size!0resize_app_window ?)lvEOlvEO*m+O*m+O*m+O*m+O*m+O*m+O*lvlvm+O*m+O*am+O*am+O*am+O*am+O*am+O*am+O*am+O*aalvaalvm+O*alvlvm+)DD(*EEQascr
ޭ


Fixed bug in changeScreen

Fixed bug in changeScreen

on run argv
	global _cache
	set _cache to {}

	set ScreenUtils to load script alias ((path to me as text) & "::screenUtils.scpt")
	set _config to run script alias ((path to me as text) & "::config.scpt")

	set _terminalApp to terminalApp of _config

	tell ScreenUtils to set _screens to (screens of getAllScreens())
	if (count of _screens) < 2 then
		return
	end if

	try
		tell ScreenUtils to set _currentScreen to getScreenWithFrontmostWindowOfApp(_terminalApp)
	on error
		return
	end try

	using terms from application "Terminal"
		tell application _terminalApp
			if true then --(item 1 of argv) = "next" then
				tell me to set _newScreen to getNextScreen(_screens, _currentScreen)
				set _bounds to bounds of window 0
				set _windowWidth to (item 3 of _bounds) - (item 1 of _bounds)
				set _windowHeight to (item 4 of _bounds) - (item 2 of _bounds)
				if _windowHeight > height of _newScreen then
					set _windowHeight to height of _newScreen
				end if
				if _windowWidth > width of _newScreen then
					set _windowWidth to width of _newScreen
				end if
				set bounds of window 0 to {originX of _newScreen, originY of _newScreen, (originX of _newScreen) + _windowWidth, (originY of _newScreen) + _windowHeight}
			end if
		end tell
	end using terms from
end run

on getNextScreen(_screens, _currentScreen)
	set _nextIndex to ((screenIndex of _currentScreen) + 1)
	if _nextIndex > (count of _screens) then
		set _nextIndex to 1
	end if
	return item _nextIndex of _screens
end getNextScreen

on run argv
	global _cache
	set _cache to {}

	set ScreenUtils to load script alias ((path to me as text) & "::screenUtils.scpt")
	set _config to run script alias ((path to me as text) & "::config.scpt")

	set _terminalApp to terminalApp of _config

	tell ScreenUtils to set _screens to (screens of getAllScreens())
	if (count of _screens) < 2 then
		return
	end if

	try
		tell ScreenUtils to set _screen to getScreenWithFrontmostWindowOfApp(_terminalApp)
	on error
		return
	end try

	using terms from application "Terminal"
		tell application _terminalApp
			if true then --(item 1 of argv) = "next" then
				tell me to set _newScreen to getNextScreen(_screens, _currentScreen)
				set _bounds to bounds of window 0
				set _windowWidth to (item 3 of _bounds) - (item 1 of _bounds)
				set _windowHeight to (item 4 of _bounds) - (item 2 of _bounds)
				if _windowHeight > height of _newScreen then
					set _windowHeight to height of _newScreen
				end if
				if _windowWidth > width of _newScreen then
					set _windowWidth to width of _newScreen
				end if
				set bounds of window 0 to {originX of _newScreen, originY of _newScreen, (originX of _newScreen) + _windowWidth, (originY of _newScreen) + _windowHeight}
			end if
		end tell
	end using terms from
end run

on getNextScreen(_screens, _currentScreen)
	set _nextIndex to ((screenIndex of _currentScreen) + 1)
	if _nextIndex > (count of _screens) then
		set _nextIndex to 1
	end if
	return item _nextIndex of _screens
end getNextScreen


Commenting out the stuff that was Growl specific. Well, most of it that was Growl specific.

on run -- for testing in script editor
	process_disk_image("Growl", "/Users/evands/growl/Release/Artwork")
end run

on process_disk_image(volumeName, artPath)
	tell application "Finder"
		tell disk volumeName
			open
			tell container window
				set current view to icon view
				set toolbar visible to false
				set statusbar visible to false
				--set the bounds to {30, 50, 579, 600}
			end tell
			close
			set opts to the icon view options of container window
			tell opts
				set icon size to 64
				set arrangement to not arranged
			end tell
			-- set background picture of opts to file ".background:growlDMGBackground.png"
			-- set position of item "Growl.mpkg" to {147, 75}
			-- set position of item "Extras" to {100, 320}
			--set position of item "Scripts" to {36, 153}
			-- set position of item "Growl Documentation.webloc" to {100, 218}
			-- set position of item "Growl version history.webloc" to {275, 218}
			-- set position of item "Get more styles.webloc" to {415, 218}
			-- set position of item "Uninstall Growl.app" to {415, 320}

			-- Custom icons
			-- my copyIconOfTo(artPath & "/GrowlIcon", "/Volumes/" & volumeName & "/Growl.mpkg")

			update without registering applications
			tell container window
				open
				set the_window_id to id
			end tell
			update without registering applications
		end tell
		set bounds of window id the_window_id to {30, 50, 575, 450}
		--give the finder some time to write the .DS_Store file
		delay 5
	end tell
end process_disk_image

on copyIconOfTo(aFileOrFolderWithIcon, aFileOrFolder)
	tell application "Finder" to set f to POSIX file aFileOrFolderWithIcon as alias
	-- grab the file's icon
	my CopyOrPaste(f, "c")
	-- now the icon is in the clipboard
	tell application "Finder" to set c to POSIX file aFileOrFolder as alias
	my CopyOrPaste(result, "v")
end copyIconOfTo

on CopyOrPaste(i, cv)
	tell application "Finder"
		activate
		open information window of i
	end tell
	tell application "System Events" to tell process "Finder" to tell window 1
		keystroke tab -- select icon button
		keystroke (cv & "w") using command down (* (copy or paste) + close window *)
	end tell -- window 1 then process Finder then System Events
end CopyOrPaste

on run -- for testing in script editor
	process_disk_image("Growl", "/Users/evands/growl/Release/Artwork")
end run

on process_disk_image(volumeName, artPath)
	tell application "Finder"
		tell disk volumeName
			open
			tell container window
				set current view to icon view
				set toolbar visible to false
				set statusbar visible to false
				--set the bounds to {30, 50, 579, 600}
			end tell
			close
			set opts to the icon view options of container window
			tell opts
				set icon size to 64
				set arrangement to not arranged
			end tell
			set background picture of opts to file ".background:growlDMGBackground.png"
			set position of item "Growl.mpkg" to {147, 75}
			set position of item "Extras" to {100, 320}
			--set position of item "Scripts" to {36, 153}
			set position of item "Growl Documentation.webloc" to {100, 218}
			set position of item "Growl version history.webloc" to {275, 218}
			set position of item "Get more styles.webloc" to {415, 218}
			set position of item "Uninstall Growl.app" to {415, 320}

			-- Custom icons
			my copyIconOfTo(artPath & "/GrowlIcon", "/Volumes/" & volumeName & "/Growl.mpkg")

			update without registering applications
			tell container window
				open
				set the_window_id to id
			end tell
			update without registering applications
		end tell
		set bounds of window id the_window_id to {30, 50, 575, 450}
		--give the finder some time to write the .DS_Store file
		delay 5
	end tell
end process_disk_image

on copyIconOfTo(aFileOrFolderWithIcon, aFileOrFolder)
	tell application "Finder" to set f to POSIX file aFileOrFolderWithIcon as alias
	-- grab the file's icon
	my CopyOrPaste(f, "c")
	-- now the icon is in the clipboard
	tell application "Finder" to set c to POSIX file aFileOrFolder as alias
	my CopyOrPaste(result, "v")
end copyIconOfTo

on CopyOrPaste(i, cv)
	tell application "Finder"
		activate
		open information window of i
	end tell
	tell application "System Events" to tell process "Finder" to tell window 1
		keystroke tab -- select icon button
		keystroke (cv & "w") using command down (* (copy or paste) + close window *)
	end tell -- window 1 then process Finder then System Events
end CopyOrPaste


Fixed the window AppleScript. Apparently you can only set the bounds of a plain old window, not a container window. Go figure.

--HG--
extra : convert_revision : svn%3A99687598-2e92-11dd-8019-fe7b9d601d1b/trunk%404215

tell application "Finder"
	tell disk "Growl"
		open
		tell container window
			set current view to icon view
			set toolbar visible to false
			set statusbar visible to false
			--set the bounds to {30, 50, 579, 600}
		end tell
		close
		set opts to the icon view options of container window
		tell opts
			set icon size to 64
			set arrangement to not arranged
		end tell
		set background picture of opts to file ".background:growlDMGBackground.png"
		set position of item "Growl.prefPane" to {147, 75}
		set position of item "Extras" to {80, 315}
		--set position of item "Scripts" to {36, 153}
		set position of item "Growl Documentation.webloc" to {100, 215}
		set position of item "Growl version history.webloc" to {275, 215}
		set position of item "Get more styles.webloc" to {415, 215}
		set position of item "Uninstall Growl.app" to {415, 315}
		update without registering applications
		set the_window_id to id of container window
		update without registering applications
	end tell
	set bounds of window id the_window_id to {30, 50, 579, 900}
	--give the finder some time to write the .DS_Store file
	delay 5
end tell

tell application "Finder"
	tell disk "Growl"
		open
		tell container window
			set current view to icon view
			set toolbar visible to false
			set statusbar visible to false
			--set the bounds to {30, 50, 579, 600}
		end tell
		close
		set opts to the icon view options of container window
		tell opts
			set icon size to 64
			set arrangement to not arranged
		end tell
		set background picture of opts to file ".background:growlDMGBackground.png"
		set position of item "Growl.prefPane" to {147, 75}
		set position of item "Extras" to {80, 315}
		--set position of item "Scripts" to {36, 153}
		set position of item "Growl Documentation.webloc" to {100, 215}
		set position of item "Growl version history.webloc" to {275, 215}
		set position of item "Get more styles.webloc" to {415, 215}
		set position of item "Uninstall Growl.app" to {415, 315}
		update without registering applications
		tell container window
			set the bounds to {31, 50, 579, 600}
			--set the bounds to {30, 50, 579, 600}
		end tell
		update without registering applications
	end tell
	--give the finder some time to write the .DS_Store file
	delay 5
end tell


Slightly modified

Slightly modified

FasdUAS 1.101.10
k
l
r
m
	1

ppgt

l
r

m
1

ppgc
l
r
m
<Downloading and installing pip
1

ppgd
l
I
.sysoexecTEXTTEXT
mjcurl https://bootstrap.pypa.io/get-pip.py | python2.7

badm
m
boovtrue
l
 r!"
!m
"1

ppgc#$
#l %%
%r %&'
&m !(())"Installing TypTop
'1!$

ppgd$*+
*l&-,
,I&--.
.sysoexecTEXTTEXT
-m&'//00n/usr/local/bin/pip install -U --ignore-installed typtop.1

badm
1m()
boovtrue+23
2l.34
4r.356
5m./
61/2

ppgc378
7l499
9r49:;
:m45<<==&Initializing Typtop
;158

ppgd8>?
>l:A@
@I:AAB
.sysoexecTEXTTEXT
Am:;CCDD@/usr/local/bin/typtops.py --initBE

badm
Em<=
boovtrue?FG
FlBGH
HrBGIJ
ImBC
J1CF

ppgcGKL
KlLMN
MlOPOtn do shell script "cd /Users/rahul/pamplay/osx/pam_opendirectory && make install" with administrator privilegesPQQ do shell script "cd /Users/rahul/pamplay/osx/pam_opendirectory && make install" with administrator privilegesNRS
RlHMT
TIHMU
.sysodlogaskrTEXT
UmHIVVWW<Successfully installed TypToP!SX
XlNXY
YONXZ[
ZIRW
.aevtquitnullnull
[fNO\]\
.aevtoappnull****]^_`
.aevtoappnull****
^kXaabb
ccddeeff#gg*hh2ii7jj>kkFllRmmX_`(/<CV

ppgt

ppgc

ppgd

badm
.sysoexecTEXTTEXT
.sysodlogaskrTEXT
.aevtquitnullnullYm*,FOj*,FO*,FOelOk*,FO*,FOelOl*,FO*,FOelOm*,FOjO)*j
Uascr
ޭ

FasdUAS 1.101.10
k
l
r
m
	1

ppgt

l
r

m
1

ppgc
l
r
m
Downloading pip
1

ppgd
l
I
.sysoexecTEXTTEXT
mjcurl https://bootstrap.pypa.io/get-pip.py | python2.7

badm
m
boovtrue
l
 r!"
!m
"1

ppgc#$
#l %%
%r %&'
&m !(())"Installing TypTop
'1!$

ppgd$*+
*l&-,
,I&--.
.sysoexecTEXTTEXT
-m&'//00n/usr/local/bin/pip install -U --ignore-installed typtop.1

badm
1m()
boovtrue+23
2l.34
4r.356
5m./
61/2

ppgc378
7l499
9r49:;
:m45<<==&Initializing Typtop
;158

ppgd8>?
>l:A@
@I:AAB
.sysoexecTEXTTEXT
Am:;CCDD@/usr/local/bin/typtops.py --initBE

badm
Em<=
boovtrue?FG
FlBGH
HrBGIJ
ImBC
J1CF

ppgcGKL
KlLMN
MlOPOtn do shell script "cd /Users/rahul/pamplay/osx/pam_opendirectory && make install" with administrator privilegesPQQ do shell script "cd /Users/rahul/pamplay/osx/pam_opendirectory && make install" with administrator privilegesNRS
RlHMT
TIHMU
.sysodlogaskrTEXT
UmHIVVWW<Successfully installed TypToP!SX
XlNXY
YONXZ[
ZIRW
.aevtquitnullnull
[fNO\]\
.aevtoappnull****]^_`
.aevtoappnull****
^kXaabb
ccddeeff#gg*hh2ii7jj>kkFllRmmX_`(/<CV

ppgt

ppgc

ppgd

badm
.sysoexecTEXTTEXT
.sysodlogaskrTEXT
.aevtquitnullnullYm*,FOj*,FO*,FOelOk*,FO*,FOelOl*,FO*,FOelOm*,FOjO)*j
Uascr
ޭ


Script dumps location of itself into log

FasdUAS 1.101.10
k
i
I
.GURLGURLnullTEXT
	o0encoded_action
k

r

I
.earsffdralis afdr
f

rtyp
m

TEXT
o0script_name
I

.sysoexecTEXTTEXT
b

b

b

b

b

b

m
  !!F

# Log that we are running.
echo '
o0script_name
m
""##' dispatching '
o0encoded_action
m$$%%' | logger -t com.westernx.sgaction

# Build the environment if it doesn't already exist. We try to recreate the
# bash environment as if invocated with `--login`.
if [[ ! "$KS_TOOLS" ]]; then

    # Global profile.
    if [[ -f /etc/profile ]]; then
        source /etc/profile
    fi

    # User profile.
    for x in ~/.bash_profile ~/.bash_login ~/.profile; do
        if [[ -f $x ]]; then
            source $x
            break
        fi
    done
fi

# Launch it in the background.
python -m sgactions.dispatch '
o0encoded_action
m&&''' 2>&1 | logger -t com.westernx.sgaction &

# Disconnect it from this shell.
disown %%

(
(l)*)
.GURLGURLnullTEXT*+,
.GURLGURLnullTEXT0encoded_action+0encoded_action0script_name, "$&

rtyp

TEXT
.earsffdralis afdr
.sysoexecTEXTTEXT)lEO%%%%%%jascrޭ

FasdUAS 1.101.10
k
i
I
.GURLGURLnullTEXT
	o0encoded_action
I

.sysoexecTEXTTEXT

b
b

m

# Build the environment if it doesn't already exist. We try to recreate the
# bash environment as if invocated with `--login`.
if [[ ! "$KS_TOOLS" ]]; then

    # Global profile.
    if [[ -f /etc/profile ]]; then
        source /etc/profile
    fi

    # User profile.
    for x in ~/.bash_profile ~/.bash_login ~/.profile; do
        if [[ -f $x ]]; then
            source $x
            break
        fi
    done
fi

python -m sgactions.dispatch '
o0encoded_action
mT' 2>&1 | logger -t com.westernx.sgaction

l
.GURLGURLnullTEXT
.GURLGURLnullTEXT0encoded_action0encoded_action
.sysoexecTEXTTEXT
%%jascrޭ