Much more robust check for dependencies. Fixes #4

--
--  DASAppDelegate.applescript
--  itunes-concatenator
--
--  Created by David Schlachter on 2014-08-26.
--  Copyright (c) 2014 Red Eft Software. All rights reserved.
--

-- via http://macscripter.net/viewtopic.php?pid=173787 ; apparently needed for using arrays

script DASAppDelegate
	property parent : class "NSObject"

    global these_files, these_times, these_titles, the_index, the_pipes, theCounter, cmdPrefix

	-- IBOutlets
	property window : missing value
    property trackTable : missing value
    property catName : missing value
    property catArtist : missing value
    property catAlbum : missing value
    property catComposer : missing value
    property catGenre : missing value
    property catTrack : missing value
    property catTracks : missing value
    property catDisc : missing value
    property catDiscs : missing value
    property catAlbumArtist : missing value
    property catYear : missing value

    -- Again, per macscripter, we'll set up bindings for the options
    property pcatName : ""
    property pcatArtist : ""
    property pcatAlbum : ""
    property pcatComposer : ""
    property pcatGenre : ""
    property pcatTrack : ""
    property pcatTracks : ""
    property pcatDisc : ""
    property pcatDiscs : ""
    property pcatAlbumArtist : ""
    property pcatYear : ""
    property missingPackages : ""

    -- Empty strings for each file name and location
    property pEachName : ""
    property pEachLocation : ""

    property these_titles : {}
    property these_files : {}
    property these_times: {}
    property the_index: {}
    property the_pipes: {}

    property theCounter : ""
    property cmdPrefix : "if [[ -r /etc/profile ]];then . /etc/profile;fi;if [[ -r ~/.bashrc ]];then . ~/.bashrc;fi;if [[ -r ~/.bash_profile ]];then . ~/.bash_profile;fi;"

    on awakeFromNib()
        -- Check for FFMPEG in the path
        try
            do shell script cmdPrefix & " if [ -x \"`/usr/bin/which ffmpeg`\" ];then exit 0;else exit 1;fi"
            on error number error_number
            set missingPackages to "FFMPEG "
        end try

        -- Check for MP4v2 in the path
        try
            do shell script cmdPrefix & " if [ -x \"`/usr/bin/which mp4chaps`\" ];then exit 0;else exit 1;fi"
            on error number error_number
            if missingPackages is "FFMPEG" then
                set the end of missingPackages to "MP4v2 "
                else
                set missingPackages to "MP4v2 "
            end if

        end try

        if missingPackages is not "" then
            display dialog "You must install the following programs to continue: \n\t" & missingPackages & " \n\nYou may have to install Xcode Command Line Tools and Homebrew first. If you continue, we'll attempt to install them for you if they are not already present. \n\nIf you have already installed FFMPEG and MP4v2, ensure that they are in your bash path." buttons {"Quit","Install"} default button 2
            if result = {button returned:"Install"} then
                tell application "Terminal"
                    set newTab to do script cmdPrefix & "if [[ -x `which brew` ]];then brew install ffmpeg mp4v2 && exit 0;else /usr/bin/ruby -e \"$(/usr/bin/curl -fsSL https://raw.github.com/Homebrew/homebrew/go/install)\"; brew install ffmpeg mp4v2 && exit 0;fi"
                    delay 1
                    activate
                    -- Check for when the Terminal is done
                    try
                        repeat
                            delay 0.2
                            if not busy of newTab then exit repeat
                        end repeat
                    end try
                end tell
                -- Check if installation was successful
                try
                    do shell script cmdPrefix & " if [ -x \"`/usr/bin/which ffmpeg`\" -a -x \"`/usr/bin/which mp4chaps`\" ];then exit 0;else exit 1;fi"
                    tell application "Terminal" to quit
                    activate
                    display dialog "Installation was successful!" buttons {"OK"} default button "OK"
                    on error error_number
                    activate
                    display dialog "Homebrew, FFMPEG and/or MP4v2 could not be installed."
                end try
                else if result = {button returned:"Quit"} then
                tell me to quit
            end if
        end if
    end awakeFromNib

    on btnGetTracks_(sender)
        -- Code to add iTunes tracks to our list
        -- via http://dougscripts.com/itunes/itinfo/info02.php and http://www.randomsequence.com/articles/applescript-to-send-selected-itunes-tracks-using-mail/
        tell application "iTunes"
            set these_titles to {}
            set these_times to {}
            set these_files to {}
            set the_index to {}
            if selection is not {} then -- there ARE tracks selected...
                set mySelection to selection
                set i to 1
                repeat with aTrack in mySelection
                    if class of aTrack is file track then
                        set end of these_titles to ((name of aTrack) as string)
                        set end of these_times to ((time of aTrack) as string)
                        set end of these_files to (posix path of (get location of aTrack))
                        set end of the_index to (count of these_titles)
                        -- Get metadata from the first track
                        if i is 1 then
                            set pcatArtist to ((artist of aTrack) as string)
                            set pcatAlbum to ((album of aTrack) as string)
                            set pcatComposer to ((composer of aTrack) as string)
                            set pcatGenre to ((genre of aTrack) as string)
                            set pcatDisc to ((disc number of aTrack) as string)
                            set pcatDiscs to ((disc count of aTrack) as string)
                            set pcatAlbumArtist to ((album artist of aTrack) as string)
                            set pcatYear to ((year of aTrack) as string)
                        end if
                        set i to (i + 1)
                    end if
                end repeat
            end if
        end tell
        -- Display the songs to be concatenated
        -- via http://stackoverflow.com/questions/25537750/setstringvalue-with-applescript-list
        set olddelimeters to AppleScript's text item delimiters
        set AppleScript's text item delimiters to "\n"
        set disp_titles to these_titles as string
        trackTable's setStringValue_(disp_titles)
        set AppleScript's text item delimiters to olddelimeters
        -- Update the default metadata
        catArtist's setStringValue_(pcatArtist)
        catAlbum's setStringValue_(pcatAlbum)
        catComposer's setStringValue_(pcatComposer)
        catGenre's setStringValue_(pcatGenre)
        catDisc's setStringValue_(pcatDisc)
        catDiscs's setStringValue_(pcatDiscs)
        catAlbumArtist's setStringValue_(pcatAlbumArtist)
        catYear's setStringValue_(pcatYear)
        -- Reset the name and track fields
        catName's setStringValue_("")
        catTrack's setStringValue_("")
        catTracks's setStringValue_("")
    end btnGetTracks_

    on btnConcatenate_(sender)
        -- Update the metadata variables with the user's input
        set pcatName to catName's stringValue()
        set pcatArtist to catArtist's stringValue()
        set pcatAlbum to catAlbum's stringValue()
        set pcatComposer to catComposer's stringValue()
        set pcatGenre to catGenre's stringValue()
        set pcatTrack to catTrack's stringValue()
        set pcatTracks to catTracks's stringValue()
        set pcatDisc to catDisc's stringValue()
        set pcatDiscs to catDiscs's stringValue()
        set pcatAlbumArtist to catAlbumArtist's stringValue()
        set pcatYear to catYear's stringValue()
        set the_pipes to {}
        repeat with theIndex in the_index
            -- TODO: Needs error checking!
            -- TODO: We need to check what kind of audio files we have, then adjust accordingly
            do shell script (cmdPrefix & "ffmpeg -i \"" & (item theIndex of these_files as text) & "\" -c copy -bsf:v h264_mp4toannexb -f mpegts /private/tmp/concat" & theIndex & ".ts 2> /dev/null" as text)
            log ("Processed file number" & theIndex) as text
            set end of the_pipes to ("/private/tmp/concat" & theIndex & ".ts" as text)
        end repeat
        -- Run the actual concatenation command in ffmpeg (for mp4/AAC files only!)
        -- via https://trac.ffmpeg.org/wiki/How%20to%20concatenate%20(join,%20merge)%20media%20files
        set olddelimeters to AppleScript's text item delimiters
        set AppleScript's text item delimiters to "|"
        set disp_thepipes to the_pipes as string
        do shell script (cmdPrefix & "ffmpeg -f mpegts -i \"concat:" & (disp_thepipes as text) & "\" -c copy -bsf:a aac_adtstoasc /private/tmp/cat.mp4")
        set AppleScript's text item delimiters to olddelimeters
        -- Now let's create the chapter file
        repeat with theIndex in the_index
            if theIndex < 2 then
                do shell script ("/bin/echo \"00:00:00.000 " & (item theIndex of these_titles as text) & "\" > /private/tmp/cat.chapters.txt" as text)
                set theCounter to (do shell script (cmdPrefix & "ffprobe -loglevel panic -show_streams /private/tmp/concat" & (theIndex as text) & ".ts | egrep -m 1 'duration=[0-9]+\\.' | sed 's/duration=\\([0-9]*[0-9]\\.[0-9]*\\)/\\1/'" as text) as string)
                set theCounter to (do shell script ("/bin/echo $(/usr/bin/printf %.$2f $(/bin/echo \"`/usr/bin/printf %.3f " & theCounter & "` * 1000\" | /usr/bin/bc))") as string)
            else
                set theDateStamp to do shell script (cmdPrefix & "t="& (theCounter as text) & ";((msec=t%1000, t/=1000, sec=t%60, t/=60, min=t%60, hrs=t/60));timestamp=$(printf \"%02d:%02d:%02d.%03d\" $hrs $min $sec $msec);/bin/echo $timestamp" as text)
                do shell script ("/bin/echo \"" & (theDateStamp as text) & " " & (item theIndex of these_titles as text) & "\" >> /private/tmp/cat.chapters.txt" as text)
                set theNewCounter to do shell script ((cmdPrefix & "ffprobe -loglevel panic -show_streams /private/tmp/concat" & (theIndex as text) & ".ts | egrep -m 1 'duration=[0-9]+\\.' | sed 's/duration=\\([0-9]*[0-9]\\.[0-9]*\\)/\\1/'" as text) as string)
                set theNewCounter to do shell script ("/bin/echo $(/usr/bin/printf %.$2f $(/bin/echo \"`/usr/bin/printf %.3f " & theNewCounter & "` * 1000\" | /usr/bin/bc))") as string
                log "theNewCounter is " & theNewCounter
                set theCounter to (theCounter + theNewCounter)
                log ("Post-addition, theCounter is " & theCounter) as text
            end if
        end repeat
        -- Chapterize cat.mp4
        do shell script (cmdPrefix & "mp4chaps -i /private/tmp/cat.mp4" as text)
        -- Add tags
        do shell script (cmdPrefix & "mp4tags -song \"" & pcatName & "\" -album \"" &  pcatAlbum & "\" -artist \"" &  pcatArtist & "\" -writer \"" &  pcatComposer & "\" -genre \"" &  pcatGenre & "\" -track \"" &  pcatTrack & "\" -tracks \"" &  pcatTracks & "\" -disk \"" &  pcatDisc & "\" -disks \"" &  pcatDiscs & "\" -albumartist \"" & pcatAlbumArtist & "\" -year \"" & pcatYear & "\" /private/tmp/cat.mp4" as text)
        -- Add the finished track to iTunes
        do shell script "/bin/mv /private/tmp/cat.mp4 /private/tmp/cat.m4a"
        tell application "iTunes"
                add file ":private:tmp:cat.m4a"
        end tell
        -- Clean up
        do shell script "/bin/rm /private/tmp/concat* /private/tmp/cat.chapters.txt /private/tmp/cat.m4a"
        set theCounter to ""
    end btnConcatenate_

	on applicationWillFinishLaunching_(aNotification)
        -- Insert code here to initialize your application before any files are opened
	end applicationWillFinishLaunching_

	on applicationShouldTerminate_(sender)
		-- Insert code here to do any housekeeping before your application quits
		return current application's NSTerminateNow
	end applicationShouldTerminate_

end script

--
--  DASAppDelegate.applescript
--  itunes-concatenator
--
--  Created by David Schlachter on 2014-08-26.
--  Copyright (c) 2014 Red Eft Software. All rights reserved.
--

-- via http://macscripter.net/viewtopic.php?pid=173787 ; apparently needed for using arrays

script DASAppDelegate
	property parent : class "NSObject"

    global these_files, these_times, these_titles, the_index, the_pipes, theCounter, cmdPrefix

	-- IBOutlets
	property window : missing value
    property trackTable : missing value
    property catName : missing value
    property catArtist : missing value
    property catAlbum : missing value
    property catComposer : missing value
    property catGenre : missing value
    property catTrack : missing value
    property catTracks : missing value
    property catDisc : missing value
    property catDiscs : missing value
    property catAlbumArtist : missing value
    property catYear : missing value

    -- Again, per macscripter, we'll set up bindings for the options
    property pcatName : ""
    property pcatArtist : ""
    property pcatAlbum : ""
    property pcatComposer : ""
    property pcatGenre : ""
    property pcatTrack : ""
    property pcatTracks : ""
    property pcatDisc : ""
    property pcatDiscs : ""
    property pcatAlbumArtist : ""
    property pcatYear : ""

    -- Empty strings for each file name and location
    property pEachName : ""
    property pEachLocation : ""

    property these_titles : {}
    property these_files : {}
    property these_times: {}
    property the_index: {}
    property the_pipes: {}

    property theCounter : ""
    property cmdPrefix : "if [[ -r /etc/profile ]];then . /etc/profile;fi;if [[ -r ~/.bashrc ]];then . ~/.bashrc;fi;if [[ -r ~/.bash_profile ]];then . ~/.bash_profile;fi;"

    on awakeFromNib()
        --
        -- Check for FFMPEG and MP4v2
        --
        -- (This works, but it's ugly!)
        --
        --
        try
            do shell script cmdPrefix & " if [ -x \"`/usr/bin/which ffmpeg`\" ];then exit 0;else exit 1;fi"
        on error number error_number
            display dialog "You must install FFMPEG and MP4v2 to continue. \n\nYou may have to install Xcode Command Line Tools and Homebrew first. If you continue, we'll attempt to install them for you if they are not already present. \n\nIf you have already installed FFMPEG and MP4v2, ensure that they are in your bash path." buttons {"Quit","Install"} default button 2
            If button returned of result is "Install" then
                try
                    tell application "Terminal"
                        -- TODO: This should be cleaner -- Terminal in front, only one window, focus back to the cat'er afterwards
                        set newTab to do script cmdPrefix & "if [[ -x `which brew` ]];then brew install ffmpeg;else /usr/bin/ruby -e \"$(/usr/bin/curl -fsSL https://raw.github.com/Homebrew/homebrew/go/install)\";brew install ffmpeg mp4v2;fi"
                        delay 4
                        repeat
                            delay 0.1
                            if not busy of newTab then exit repeat
                        end repeat
                    end tell
                     -- TODO: This needs a better test, i.e., check if ffmpeg is actually accessible on the path
                    display dialog "FFMPEG was successfully installed"
                    -- TODO: This should actually work! (Bring us back to the foreground)
                    activate current application
                on error number error_number
                    display dialog "FFMPEG did not successfully install"
                end try
            end If
            If button returned of result is "Quit" then
                -- Fix!
                current application's NSApp's terminate()
            end If
        end try
    end awakeFromNib

    on btnGetTracks_(sender)
        -- Code to add iTunes tracks to our list
        -- via http://dougscripts.com/itunes/itinfo/info02.php and http://www.randomsequence.com/articles/applescript-to-send-selected-itunes-tracks-using-mail/
        tell application "iTunes"
            set these_titles to {}
            set these_times to {}
            set these_files to {}
            set the_index to {}
            if selection is not {} then -- there ARE tracks selected...
                set mySelection to selection
                set i to 1
                repeat with aTrack in mySelection
                    if class of aTrack is file track then
                        set end of these_titles to ((name of aTrack) as string)
                        set end of these_times to ((time of aTrack) as string)
                        set end of these_files to (posix path of (get location of aTrack))
                        set end of the_index to (count of these_titles)
                        -- Get metadata from the first track
                        if i is 1 then
                            set pcatArtist to ((artist of aTrack) as string)
                            set pcatAlbum to ((album of aTrack) as string)
                            set pcatComposer to ((composer of aTrack) as string)
                            set pcatGenre to ((genre of aTrack) as string)
                            set pcatDisc to ((disc number of aTrack) as string)
                            set pcatDiscs to ((disc count of aTrack) as string)
                            set pcatAlbumArtist to ((album artist of aTrack) as string)
                            set pcatYear to ((year of aTrack) as string)
                        end if
                        set i to (i + 1)
                    end if
                end repeat
            end if
        end tell
        -- Display the songs to be concatenated
        -- via http://stackoverflow.com/questions/25537750/setstringvalue-with-applescript-list
        set olddelimeters to AppleScript's text item delimiters
        set AppleScript's text item delimiters to "\n"
        set disp_titles to these_titles as string
        trackTable's setStringValue_(disp_titles)
        set AppleScript's text item delimiters to olddelimeters
        -- Update the default metadata
        catArtist's setStringValue_(pcatArtist)
        catAlbum's setStringValue_(pcatAlbum)
        catComposer's setStringValue_(pcatComposer)
        catGenre's setStringValue_(pcatGenre)
        catDisc's setStringValue_(pcatDisc)
        catDiscs's setStringValue_(pcatDiscs)
        catAlbumArtist's setStringValue_(pcatAlbumArtist)
        catYear's setStringValue_(pcatYear)
        -- Reset the name and track fields
        catName's setStringValue_("")
        catTrack's setStringValue_("")
        catTracks's setStringValue_("")
    end btnGetTracks_

    on btnConcatenate_(sender)
        -- Update the metadata variables with the user's input
        set pcatName to catName's stringValue()
        set pcatArtist to catArtist's stringValue()
        set pcatAlbum to catAlbum's stringValue()
        set pcatComposer to catComposer's stringValue()
        set pcatGenre to catGenre's stringValue()
        set pcatTrack to catTrack's stringValue()
        set pcatTracks to catTracks's stringValue()
        set pcatDisc to catDisc's stringValue()
        set pcatDiscs to catDiscs's stringValue()
        set pcatAlbumArtist to catAlbumArtist's stringValue()
        set pcatYear to catYear's stringValue()
        set the_pipes to {}
        repeat with theIndex in the_index
            -- TODO: Needs error checking!
            -- TODO: We need to check what kind of audio files we have, then adjust accordingly
            do shell script (cmdPrefix & "ffmpeg -i \"" & (item theIndex of these_files as text) & "\" -c copy -bsf:v h264_mp4toannexb -f mpegts /private/tmp/concat" & theIndex & ".ts 2> /dev/null" as text)
            log ("Processed file number" & theIndex) as text
            set end of the_pipes to ("/private/tmp/concat" & theIndex & ".ts" as text)
        end repeat
        -- Run the actual concatenation command in ffmpeg (for mp4/AAC files only!)
        -- via https://trac.ffmpeg.org/wiki/How%20to%20concatenate%20(join,%20merge)%20media%20files
        set olddelimeters to AppleScript's text item delimiters
        set AppleScript's text item delimiters to "|"
        set disp_thepipes to the_pipes as string
        do shell script (cmdPrefix & "ffmpeg -f mpegts -i \"concat:" & (disp_thepipes as text) & "\" -c copy -bsf:a aac_adtstoasc /private/tmp/cat.mp4")
        set AppleScript's text item delimiters to olddelimeters
        -- Now let's create the chapter file
        repeat with theIndex in the_index
            if theIndex < 2 then
                do shell script ("/bin/echo \"00:00:00.000 " & (item theIndex of these_titles as text) & "\" > /private/tmp/cat.chapters.txt" as text)
                set theCounter to (do shell script (cmdPrefix & "ffprobe -loglevel panic -show_streams /private/tmp/concat" & (theIndex as text) & ".ts | egrep -m 1 'duration=[0-9]+\\.' | sed 's/duration=\\([0-9]*[0-9]\\.[0-9]*\\)/\\1/'" as text) as string)
                set theCounter to (do shell script ("/bin/echo $(/usr/bin/printf %.$2f $(/bin/echo \"`/usr/bin/printf %.3f " & theCounter & "` * 1000\" | /usr/bin/bc))") as string)
            else
                set theDateStamp to do shell script (cmdPrefix & "t="& (theCounter as text) & ";((msec=t%1000, t/=1000, sec=t%60, t/=60, min=t%60, hrs=t/60));timestamp=$(printf \"%02d:%02d:%02d.%03d\" $hrs $min $sec $msec);/bin/echo $timestamp" as text)
                do shell script ("/bin/echo \"" & (theDateStamp as text) & " " & (item theIndex of these_titles as text) & "\" >> /private/tmp/cat.chapters.txt" as text)
                set theNewCounter to do shell script ((cmdPrefix & "ffprobe -loglevel panic -show_streams /private/tmp/concat" & (theIndex as text) & ".ts | egrep -m 1 'duration=[0-9]+\\.' | sed 's/duration=\\([0-9]*[0-9]\\.[0-9]*\\)/\\1/'" as text) as string)
                set theNewCounter to do shell script ("/bin/echo $(/usr/bin/printf %.$2f $(/bin/echo \"`/usr/bin/printf %.3f " & theNewCounter & "` * 1000\" | /usr/bin/bc))") as string
                log "theNewCounter is " & theNewCounter
                set theCounter to (theCounter + theNewCounter)
                log ("Post-addition, theCounter is " & theCounter) as text
            end if
        end repeat
        -- Chapterize cat.mp4
        do shell script (cmdPrefix & "mp4chaps -i /private/tmp/cat.mp4" as text)
        -- Add tags
        do shell script (cmdPrefix & "mp4tags -song \"" & pcatName & "\" -album \"" &  pcatAlbum & "\" -artist \"" &  pcatArtist & "\" -writer \"" &  pcatComposer & "\" -genre \"" &  pcatGenre & "\" -track \"" &  pcatTrack & "\" -tracks \"" &  pcatTracks & "\" -disk \"" &  pcatDisc & "\" -disks \"" &  pcatDiscs & "\" -albumartist \"" & pcatAlbumArtist & "\" -year \"" & pcatYear & "\" /private/tmp/cat.mp4" as text)
        -- Add the finished track to iTunes
        do shell script "/bin/mv /private/tmp/cat.mp4 /private/tmp/cat.m4a"
        tell application "iTunes"
                add file ":private:tmp:cat.m4a"
        end tell
        -- Clean up
        do shell script "/bin/rm /private/tmp/concat* /private/tmp/cat.chapters.txt /private/tmp/cat.m4a"
        set theCounter to ""
    end btnConcatenate_

	on applicationWillFinishLaunching_(aNotification)
		-- Insert code here to initialize your application before any files are opened
	end applicationWillFinishLaunching_

	on applicationShouldTerminate_(sender)
		-- Insert code here to do any housekeeping before your application quits
		return current application's NSTerminateNow
	end applicationShouldTerminate_

end script


Change script for rspec command only

Change script for rspec command only

-- execute_iterm.scpt
-- last change: 19 Jan 2013
---
-- this script require an argument that represent the command to execute

on run argv

    set command to (item 1 of argv)
    tell application "iTerm"
      repeat with _terminal in terminals
        repeat with _session in (every session of _terminal whose name contains "rspec")
          tell the _session
            write text command
          end tell
        end repeat
      end repeat
    end tell
end run

-- execute_iterm.scpt
-- last change: 19 Jan 2013
---
-- this script require an argument that represent the command to execute

on run argv

    set command to (item 1 of argv)

    tell application "iTerm"

        try
            set mysession to current session of current terminal
        on error
            set myterm to (make new terminal)
            tell myterm
                launch session "rspec"
                set mysession to current session
            end tell
        end try

        -- execute the command
        tell mysession
            write text command
        end tell

    end tell

end run


Offer an option to run under iTerm if it's installed

FasdUAS 1.101.10
k
l
r
m
boovfals
	o 0iterminstallediTermInstalled

l!
Q!

k
O
e
5

appf
m
*com.googlecode.iterm2
kfrmID
mMACSalistMacintosh HDH+0
Finder.app	\	 CoreServices\0*)6Macintosh HD:System:Library:CoreServices:Finder.app
Finder.appMacintosh HD&System/Library/CoreServices/Finder.app/
r
m
boovtrue
o 0iterminstallediTermInstalled
R
.ascrerr ********
r!
m
boovfals
o 0iterminstallediTermInstalled
l !"
!l"#
#Z"$%&
$o"# 0iterminstallediTermInstalled
%k&''()
(r&1*+
*b&/,-
,l&-.
.c&-/0
/l&+1
1I&+2
.earsffdralis afdr
2m&'
afdrcusr
0m+,

ctxt
-m-.3344:.boot2docker:preferences.scpt
+o"0preferencespathpreferencesPath)56
5h297&0preferencesscriptpreferencesScript
7j80terminalappterminalApp
8m99::Terminal6;<
;l::<=>
=Q:?@A
?k=MBBCD
Cc=@EF
Eo=>"0preferencespathpreferencesPath
Fm>?

alisDG
GrAMHI
HIAKJ
.sysoloadscptfile
J4AGK

file
KoEF"0preferencespathpreferencesPath
Io&0preferencesscriptpreferencesScript
@R
.ascrerr ********
AkULLMN
MrUwOP
OlUqQ
QnUqRS
R1mq

bhit
SlUmT
TIUmUV
.sysodlogaskrTEXT
UmUXWWXX0Launch Boot2Docker with &VYZ

btns
YJ[c[[\]
\m[^^^__Terminal]`
`m^aaabb
iTermZc

dflt
cmfg
Pnde
dorv0terminalappterminalApp
eoqr&0preferencesscriptpreferencesScriptNf
fIxgh
.sysostornullscpt
goxy&0preferencesscriptpreferencesScripthij

fpth
i4|k

file
ko"0preferencespathpreferencesPathjl

savo
lm
boovtrue>mn
mlnop
orqr
qls
sntu
to0terminalappterminalApp
uo&0preferencesscriptpreferencesScript
ro0terminalappterminalApppv
vrwx
wly
ymzz{{* To change your default terminal application, please delete ~/.boot2docker/preferences.scpt
xo 0terminalappmsgterminalAppMsg
&k||}~
}r
mTerminal
o0terminalappterminalApp~
r
l
m
o 0terminalappmsgterminalAppMsg"
l
l
Z
=
o0terminalappterminalApp
mTerminal
O
k
r
I
.coredoscnullctxt
o0	newwindow	newWindow
r
m&Boot2Docker for OSX
o0windowtitlewindowTitle
r
m
boovtrue
n
1

tdct
o0	newwindow	newWindow
r
m4/usr/local/bin/boot2docker
o0b2d
I
.coredoscnullctxt
mbash

kfil
o0	newwindow	newWindow
r
o0windowtitlewindowTitle
n
1

titl
o0	newwindow	newWindow
I
.miscactvnullnull
I
.coredoscnullctxt
m^unset DYLD_LIBRARY_PATH ; unset LD_LIBRARY_PATH

kfil
o0	newwindow	newWindow
I
.coredoscnullctxt
m.mkdir -p ~/.boot2docker

kfil
o0	newwindow	newWindow
I!.
.coredoscnullctxt
m!$if [ ! -f ~/.boot2docker/boot2docker.iso ]; then cp /usr/local/share/boot2docker/boot2docker.iso ~/.boot2docker/ ; fi

kfil
o'*0	newwindow	newWindow
I/@
.coredoscnullctxt
b/6
o/20b2d
m25 init ~}
~
kfil
o9<||0	newwindow	newWindow}
IAR{
{.coredoscnullctxt
bAH
oADzz0b2d
mDG up && export DOCKER_HOST=tcp://$(/usr/local/bin/boot2docker ip 2>/dev/null):2375yx
y
kfil
oKNww0	newwindow	newWindowx
IS`v
v.coredoscnullctxt
mSVdocker versionut
u
kfil
oY\ss0	newwindow	newWindowtr
Zaqp
?aj
nah
1dho
o
leng
oadnn 0terminalappmsgterminalAppMsg
mhimm
Iml
l.coredoscnullctxt
bm|
mmpecho -e
np{
1w{k
k
strq
lpwji
cpw
opshh 0terminalappmsgterminalAppMsg
msvg
g
TEXTjife
f
kfil
odd0	newwindow	newWindoweqpr
m@alislMacintosh HDH+NTerminal.app!/	 	UtilitiesNM2Macintosh HD:Applications:Utilities:Terminal.appTerminal.appMacintosh HD#Applications/Utilities/Terminal.app/
lcbacba`
l_^
Z]\
=
o[[0terminalappterminalApp
m
iTerm
O
k

IZYX
Z.miscactvnullnullYX

r
lWV
IUT
U.corecrel****nullTSR
S
kocl
mQ
Q
PtrmRWV
oPP0	newwindow	newWindowO
O
k
r
lNM
ILK
L.corecrel****nullKJ
J
kocl
mI
I
PssnH G
H
insh
 l!FE
!n"#
";
#2D
D
PssnFEGNM
oCC0
newsession
newSession$B
$O%&
%k''()
(r*+
*m,,--&Boot2Docker for OSX
+1A
A
pnam)./
.r01
0m2233/usr/local/bin/
1o@@0localbinlocalBin/45
4r67
6b89
8o??0localbinlocalBin
9m::;;boot2docker
7o>>0b2d5<=
<r>?
>b@A
@o==0localbinlocalBin
AmBBCCdocker
?o<<0d=DE
DI;:F
;.ITRMExecnullobj :F9G8
9
Cmnd
GmHHIIbash -l8EJK
JI76L
7.ITRMWrtenullobj 6L5M4
5
iTxt
MmNNOO^unset DYLD_LIBRARY_PATH ; unset LD_LIBRARY_PATH4KPQ
PI*32R
3.ITRMWrtenullobj 2R1S0
1
iTxt
Sm#&TTUU.mkdir -p ~/.boot2docker0QVW
VI+6/.X
/.ITRMWrtenullobj .X-Y,
-
iTxt
Ym/2ZZ[[if [ ! -f ~/.boot2docker/boot2docker.iso ]; then cp /usr/local/share/boot2docker/boot2docker.iso ~/.boot2docker/ ; fi,W\]
\I7F+*^
+.ITRMWrtenullobj *^)_(
)
iTxt
_b;B`a
`o;>''0b2d
am>Abbcc
 init(]de
dIG^&%f
&.ITRMWrtenullobj %f$g#
$
iTxt
gbKZhi
hbKVjk
jbKRlm
loKN""0b2d
mmNQnnooD up && export DOCKER_HOST=tcp://$(
koRU!!0b2d
imVYppqq* ip 2>/dev/null):2375#ers
rI_n t
 .ITRMWrtenullobj tu

iTxt
ubcjvw
vocf0d
wmfixxyy versionsz
zZo{|
{?ox}~
}nov
1rv

leng
oor 0terminalappmsgterminalAppMsg
~mvw
|I{
.ITRMWrtenullobj

iTxt
b
mecho -e
n
1

strq
l
c
o 0terminalappmsgterminalAppMsg
m

TEXT
&o0
newsession
newSessionB
o0	newwindow	newWindowO
	mITRMalisHMacintosh HDH+M	iTerm.appջ~	 ApplicationsnM$Macintosh HD:Applications:iTerm.app	iTerm.appMacintosh HDApplications/iTerm.app/]\_^`
	z2

.aevtoappnull**** 0iterminstallediTermInstalled"0preferencespathpreferencesPath0terminalappterminalApp 0terminalappmsgterminalAppMsg0	newwindow	newWindow0
newsession
newSession0localbinlocalBin0b2d0d
.aevtoappnull****
k
!&0preferencesscriptpreferencesScriptU37W^az,2:BHNTZbnpx 0iterminstallediTermInstalled

appf
kfrmID
afdrcusr
.earsffdralis afdr

ctxt"0preferencespathpreferencesPath&0preferencesscriptpreferencesScript
.ascrinit********
k70terminalappterminalApp90terminalappterminalApp

alis

file
.sysoloadscptfile

btns

dflt
.sysodlogaskrTEXT

bhit0terminalappterminalApp

fpth

savo
.sysostornullscpt 0terminalappmsgterminalAppMsg
.coredoscnullctxt0	newwindow	newWindow0windowtitlewindowTitle

tdct0b2d

kfil

titl
.miscactvnullnull

leng

TEXT

strq

kocl

Ptrm
.corecrel****null

Pssn

insh0
newsession
newSession

pnam0localbinlocalBin0d

Cmnd
.ITRMExecnullobj

iTxt
.ITRMWrtenullobj fEO*0EUOeEW
XfEO}j&%EOKSO&O*a/jEW>Xaaaalvakaa,a,FOa*a/aeaOa,E`OaE`Ya E`Oa!E`O_a"a#*j$E`%Oa&E`'Oe_%a(,FOa)E`*Oa+a,_%l$O_'_%a-,FO*j.Oa/a,_%l$Oa0a,_%l$Oa1a,_%l$O_*a2%a,_%l$O_*a3%a,_%l$Oa4a,_%l$O_a5,ja6_a7&a8,%a,_%l$YhUYhO_a9a:*j.O*a;a<l=E`%O_%*a;a>a?*a>-6a=E`@O_@aA*aB,FOaCE`DO_DaE%E`*O_DaF%E`GO*aHaIlJO*aKaLlMO*aKaNlMO*aKaOlMO*aK_*aP%lMO*aK_*aQ%_*%aR%lMO*aK_GaS%lMO_a5,j*aKaT_a7&a8,%lMYhUUUYh
	boovtruenMacintosh HD:Users:artiom:.boot2docker:preferences.scpt
iTerm

Ptrm

Ptrm

Pssn4/usr/local/bin/boot2docker*/usr/local/bin/dockerascr
ޭ

FasdUAS 1.101.10
lf
Of
ke
r

I
.coredoscnullctxt
o0	newwindow	newWindow

r
m
&Boot2Docker for OSX
o0windowtitlewindowTitle

r
m
boovtrue
n
1

tdct
o0	newwindow	newWindow
r
m4/usr/local/bin/boot2docker
o0b2d
I! !
.coredoscnullctxt
 m""##bash!$

kfil
$o0	newwindow	newWindow%&
%r"''(
'o"#0windowtitlewindowTitle
(n)*
)1$&

titl
*o#$0	newwindow	newWindow&+,
+I(-
.miscactvnullnull,-.
-I.5/0
.coredoscnullctxt
/m./1122^unset DYLD_LIBRARY_PATH ; unset LD_LIBRARY_PATH03

kfil
3o010	newwindow	newWindow.45
4I6=67
.coredoscnullctxt
6m678899.mkdir -p ~/.boot2docker7:

kfil
:o890	newwindow	newWindow5;<
;I>E=>
.coredoscnullctxt
=m>???@@if [ ! -f ~/.boot2docker/boot2docker.iso ]; then cp /usr/local/share/boot2docker/boot2docker.iso ~/.boot2docker/ ; fi>A

kfil
Ao@A0	newwindow	newWindow<BC
BIFODE
.coredoscnullctxt
DbFIFG
FoFG0b2d
GmGHHHII init EJ

kfil
JoJK0	newwindow	newWindowCKL
KIP[MN
.coredoscnullctxt
MbPUOP
OoPQ0b2d
PmQTQQRR up && export DOCKER_HOST=tcp://$(/usr/local/bin/boot2docker ip 2>/dev/null):2375NS

kfil
SoVW0	newwindow	newWindowLT
TI\eUV
.coredoscnullctxt
Um\_WWXXdocker versionVY

kfil
Yo`a0	newwindow	newWindow
mZZ@alisZOSX-OSyH+PTerminal.app(?u	 	Utilitiesy`?APO,OSX-OS:Applications:Utilities:Terminal.appTerminal.appOSX-OS#Applications/Utilities/Terminal.app/[\[
.aevtoappnull****\]^_
.aevtoappnull****
]kf``^_Z"18?HQW
.coredoscnullctxt0	newwindow	newWindow0windowtitlewindowTitle

tdct0b2d

kfil

titl
.miscactvnullnullgc*jEOEOe,FOEOlO,FO*jOlOlOlO%lOa%lOalUascr
ޭ


unset DYLD_LIBRARY_PATH settings, they seem to cause virtualbox to break (b2d-cli#148)

FasdUAS 1.101.10
lf
Of
ke
r

I
.coredoscnullctxt
o0	newwindow	newWindow

r
m
&Boot2Docker for OSX
o0windowtitlewindowTitle

r
m
boovtrue
n
1

tdct
o0	newwindow	newWindow
r
m4/usr/local/bin/boot2docker
o0b2d
I! !
.coredoscnullctxt
 m""##bash!$

kfil
$o0	newwindow	newWindow%&
%r"''(
'o"#0windowtitlewindowTitle
(n)*
)1$&

titl
*o#$0	newwindow	newWindow&+,
+I(-
.miscactvnullnull,-.
-I.5/0
.coredoscnullctxt
/m./1122^unset DYLD_LIBRARY_PATH ; unset LD_LIBRARY_PATH03

kfil
3o010	newwindow	newWindow.45
4I6=67
.coredoscnullctxt
6m678899.mkdir -p ~/.boot2docker7:

kfil
:o890	newwindow	newWindow5;<
;I>E=>
.coredoscnullctxt
=m>???@@if [ ! -f ~/.boot2docker/boot2docker.iso ]; then cp /usr/local/share/boot2docker/boot2docker.iso ~/.boot2docker/ ; fi>A

kfil
Ao@A0	newwindow	newWindow<BC
BIFODE
.coredoscnullctxt
DbFIFG
FoFG0b2d
GmGHHHII init EJ

kfil
JoJK0	newwindow	newWindowCKL
KIP[MN
.coredoscnullctxt
MbPUOP
OoPQ0b2d
PmQTQQRR up && export DOCKER_HOST=tcp://$(/usr/local/bin/boot2docker ip 2>/dev/null):2375NS

kfil
SoVW0	newwindow	newWindowLT
TI\eUV
.coredoscnullctxt
Um\_WWXXdocker versionVY

kfil
Yo`a0	newwindow	newWindow
mZZ@alisZOSX-OSyH+PTerminal.app(?u	 	Utilitiesy`?APO,OSX-OS:Applications:Utilities:Terminal.appTerminal.appOSX-OS#Applications/Utilities/Terminal.app/[\[
.aevtoappnull****\]^_
.aevtoappnull****
]kf``^_Z"18?HQW
.coredoscnullctxt0	newwindow	newWindow0windowtitlewindowTitle

tdct0b2d

kfil

titl
.miscactvnullnullgc*jEOEOe,FOEOlO,FO*jOlOlOlO%lOa%lOalUascr
ޭ

FasdUAS 1.101.10
l\
O\
k[
r

I
.coredoscnullctxt
o0	newwindow	newWindow

r
m
&Boot2Docker for OSX
o0windowtitlewindowTitle

r
m
boovtrue
n
1

tdct
o0	newwindow	newWindow
r
m4/usr/local/bin/boot2docker
o0b2d
I! !
.coredoscnullctxt
 m""##bash!$

kfil
$o0	newwindow	newWindow%&
%r"''(
'o"#0windowtitlewindowTitle
(n)*
)1$&

titl
*o#$0	newwindow	newWindow&+,
+I(-
.miscactvnullnull,-.
-I.5/0
.coredoscnullctxt
/m./1122.mkdir -p ~/.boot2docker03

kfil
3o010	newwindow	newWindow.45
4I6=67
.coredoscnullctxt
6m678899if [ ! -f ~/.boot2docker/boot2docker.iso ]; then cp /usr/local/share/boot2docker/boot2docker.iso ~/.boot2docker/ ; fi7:

kfil
:o890	newwindow	newWindow5;<
;I>G=>
.coredoscnullctxt
=b>A?@
?o>?0b2d
@m?@AABB init >C

kfil
CoBC0	newwindow	newWindow<DE
DIHQFG
.coredoscnullctxt
FbHKHI
HoHI0b2d
ImIJJJKK up && export DOCKER_HOST=tcp://$(/usr/local/bin/boot2docker ip 2>/dev/null):2375GL

kfil
LoLM0	newwindow	newWindowEM
MIR[NO
.coredoscnullctxt
NmRUPPQQdocker versionOR

kfil
RoVW0	newwindow	newWindow
mSS@alisZOSX-OSxH+PTerminal.app(>e	 	Utilitiesy`?APO,OSX-OS:Applications:Utilities:Terminal.appTerminal.appOSX-OS#Applications/Utilities/Terminal.app/TUT
.aevtoappnull****UVWX
.aevtoappnull****
Vk\YYWXS"18AJP
.coredoscnullctxt0	newwindow	newWindow0windowtitlewindowTitle

tdct0b2d

kfil

titl
.miscactvnullnull]Y*jEOEOe,FOEOlO,FO*jOlOlO%lO%lOalUascr
ޭ


Upd Chrome opening script

Upd Chrome opening script

(*
Copyright (c) 2015-present, Facebook, Inc.
All rights reserved.
This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree. An additional grant
of patent rights can be found in the PATENTS file in the same directory.
*)

property targetTab: null
property targetTabIndex: -1
property targetWindow: null

on run argv
  set theURL to item 1 of argv

  tell application "Chrome"

    if (count every window) = 0 then
      make new window
    end if

    -- 1: Looking for tab running debugger
    -- then, Reload debugging tab if found
    -- then return
    set found to my lookupTabWithUrl(theURL)
    if found then
      set targetWindow's active tab index to targetTabIndex
      tell targetTab to reload
      tell targetWindow to activate
      set index of targetWindow to 1
      return
    end if

    -- 2: Looking for Empty tab
    -- In case debugging tab was not found
    -- We try to find an empty tab instead
    set found to my lookupTabWithUrl("chrome://newtab/")
    if found then
      set targetWindow's active tab index to targetTabIndex
      set URL of targetTab to theURL
      tell targetWindow to activate
      return
    end if

    -- 3: Create new tab
    -- both debugging and empty tab were not found
    -- make a new tab with url
    tell window 1
      activate
      make new tab with properties {URL:theURL}
    end tell
  end tell
end run

-- Function:
-- Lookup tab with given url
-- if found, store tab, index, and window in properties
-- (properties were declared on top of file)
on lookupTabWithUrl(lookupUrl)
  tell application "Chrome"
    -- Find a tab with the given url
    set found to false
    set theTabIndex to -1
    repeat with theWindow in every window
      set theTabIndex to 0
      repeat with theTab in every tab of theWindow
        set theTabIndex to theTabIndex + 1
        if (theTab's URL as string) contains lookupUrl then
          -- assign tab, tab index, and window to properties
          set targetTab to theTab
          set targetTabIndex to theTabIndex
          set targetWindow to theWindow
          set found to true
          exit repeat
        end if
      end repeat

      if found then
        exit repeat
      end if
    end repeat
  end tell
  return found
end lookupTabWithUrl

(*
Copyright (c) 2015-present, Facebook, Inc.
All rights reserved.

This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree. An additional grant
of patent rights can be found in the PATENTS file in the same directory.
*)

on run argv
  set theURL to item 1 of argv

  tell application "Chrome"

    if (count every window) = 0 then
      make new window
    end if

    -- Find a tab currently running the debugger
    set found to false
    set theTabIndex to -1
    repeat with theWindow in every window
      set theTabIndex to 0
      repeat with theTab in every tab of theWindow
        set theTabIndex to theTabIndex + 1
        if theTab's URL is theURL then
          set found to true
          exit repeat
        end if
      end repeat

      if found then
        exit repeat
      end if
    end repeat

    if found then
      tell theTab to reload
      set index of theWindow to 1
      set theWindow's active tab index to theTabIndex
    else
      tell window 1
        activate
        make new tab with properties {URL:theURL}
      end tell
    end if
  end tell
end run


hard code spotlight button due to localization problems

tell application "System Events"
	tell process "SystemUIServer"
		try
			--			repeat with menuBarNum from (count of menu bars) to 0 by -1
			--				repeat with theItem in (menu bar items of (item menuBarNum of menu bars))
			set theItem to menu bar item 1 of menu bar 2
			if (description of theItem) contains "spotlight" then
				-- we found it
				if (selected of theItem) is false then
					click theItem
				end if
				keystroke "{popclip text}"
				error
			end if
			--				end repeat
			--			end repeat
		on error theError
		end try
	end tell
end tell

tell application "System Events"
	tell process "SystemUIServer"
		-- find the spotlight menu item. count backwards because it's usually in the second one.
		try
			repeat with menuBarNum from (count of menu bars) to 0 by -1
				repeat with theItem in (menu bar items of (item menuBarNum of menu bars))
					if (description of theItem) contains "spotlight" then
						-- we found it
						if (selected of theItem) is false then
							click theItem
						end if
						keystroke "{popclip text}"
						error
					end if
				end repeat
			end repeat
		on error theError
		end try
	end tell
end tell


Reference playlist object when finding first song

-- playplaylist filter --

on loadConfig()
	return (load script POSIX file (do shell script "./resources/compile-config.sh"))
end loadConfig

on getPlaylistResultListFeedback(query)

	global config

	set query to trimWhitespace(query) of config

	tell application "iTunes"

		-- retrieve list of playlists matching query (ordered by relevance)
		set thePlaylists to (get playlists whose name starts with query and name is not config's workflowPlaylistName and special kind is none and size is not 0)

		if length of thePlaylists < config's resultLimit then

			set thePlaylists to thePlaylists & (get playlists whose name contains (space & query) and name does not start with query and name is not config's workflowPlaylistName and special kind is none and size is not 0)

		end if

		if length of thePlaylists < config's resultLimit then

			set thePlaylists to thePlaylists & (get playlists whose name contains query and name does not start with query and name does not contain (space & query) and name is not config's workflowPlaylistName and special kind is none and size is not 0)

		end if

		if length of thePlaylists > config's resultLimit then

			set thePlaylists to items 1 thru (config's resultLimit) of thePlaylists

		end if

		repeat with thePlaylist in thePlaylists

			set playlistName to name of thePlaylist
			set playlistId to id of thePlaylist
			set songCount to number of tracks in thePlaylist
			set playlistDuration to time of thePlaylist

			try
				set theSong to (first track in thePlaylist whose kind contains (songDescriptor of config))
				set songArtworkPath to getSongArtworkPath(theSong) of config

				set itemSubtitle to (quantifyNumber(songCount, "track", "tracks") of config) & ", " & playlistDuration & " in length"

				addResult({uid:("playlist-" & playlistId) as text, valid:"yes", title:playlistName, subtitle:itemSubtitle, icon:songArtworkPath}) of config
			on error number -1728
			end try

		end repeat

		if config's resultListIsEmpty() then

			addNoResultsItem(query, "playlist") of config

		end if

	end tell

	return getResultListFeedback() of config

end getPlaylistResultListFeedback

on run query
	set config to loadConfig()
	getPlaylistResultListFeedback(query as text)
end run

-- playplaylist filter --

on loadConfig()
	return (load script POSIX file (do shell script "./resources/compile-config.sh"))
end loadConfig

on getPlaylistResultListFeedback(query)

	global config

	set query to trimWhitespace(query) of config

	tell application "iTunes"

		-- retrieve list of playlists matching query (ordered by relevance)
		set thePlaylists to (get playlists whose name starts with query and name is not config's workflowPlaylistName and special kind is none and size is not 0)

		if length of thePlaylists < config's resultLimit then

			set thePlaylists to thePlaylists & (get playlists whose name contains (space & query) and name does not start with query and name is not config's workflowPlaylistName and special kind is none and size is not 0)

		end if

		if length of thePlaylists < config's resultLimit then

			set thePlaylists to thePlaylists & (get playlists whose name contains query and name does not start with query and name does not contain (space & query) and name is not config's workflowPlaylistName and special kind is none and size is not 0)

		end if

		if length of thePlaylists > config's resultLimit then

			set thePlaylists to items 1 thru (config's resultLimit) of thePlaylists

		end if

		repeat with thePlaylist in thePlaylists

			set playlistName to name of thePlaylist
			set playlistId to id of thePlaylist
			set songCount to number of tracks in thePlaylist
			set playlistDuration to time of thePlaylist

			try
				set theSong to (first track in playlist playlistName whose kind contains (songDescriptor of config))
				set songArtworkPath to getSongArtworkPath(theSong) of config

				set itemSubtitle to (quantifyNumber(songCount, "track", "tracks") of config) & ", " & playlistDuration & " in length"

				addResult({uid:("playlist-" & playlistId) as text, valid:"yes", title:playlistName, subtitle:itemSubtitle, icon:songArtworkPath}) of config
			on error number -1728
			end try

		end repeat

		if config's resultListIsEmpty() then

			addNoResultsItem(query, "playlist") of config

		end if

	end tell

	return getResultListFeedback() of config

end getPlaylistResultListFeedback

on run query
	set config to loadConfig()
	getPlaylistResultListFeedback(query as text)
end run


Formatting tweak

Formatting tweak

--
--  DASAppDelegate.applescript
--  itunes-concatenator
--
--  Created by David Schlachter on 2014-08-26.
--  Copyright (c) 2014 Red Eft Software. All rights reserved.
--

-- via http://macscripter.net/viewtopic.php?pid=173787 ; apparently needed for using arrays

script DASAppDelegate
	property parent : class "NSObject"

    global these_files, these_times, these_titles, the_index, the_pipes, theCounter, cmdPrefix

	-- IBOutlets
	property window : missing value
    property trackTable : missing value
    property catName : missing value
    property catArtist : missing value
    property catAlbum : missing value
    property catComposer : missing value
    property catGenre : missing value
    property catTrack : missing value
    property catTracks : missing value
    property catDisc : missing value
    property catDiscs : missing value
    property catAlbumArtist : missing value
    property catYear : missing value

    -- Again, per macscripter, we'll set up bindings for the options
    property pcatName : ""
    property pcatArtist : ""
    property pcatAlbum : ""
    property pcatComposer : ""
    property pcatGenre : ""
    property pcatTrack : ""
    property pcatTracks : ""
    property pcatDisc : ""
    property pcatDiscs : ""
    property pcatAlbumArtist : ""
    property pcatYear : ""
    property missingPackages : ""

    -- Empty strings for each file name and location
    property pEachName : ""
    property pEachLocation : ""

    property these_titles : {}
    property these_files : {}
    property these_times: {}
    property the_index: {}
    property the_pipes: {}

    property theCounter : ""
    property cmdPrefix : "if [[ -r /etc/profile ]];then . /etc/profile;fi;if [[ -r ~/.bashrc ]];then . ~/.bashrc;fi;if [[ -r ~/.bash_profile ]];then . ~/.bash_profile;fi;"

    on awakeFromNib()
        -- Check for FFMPEG in the path
        try
            do shell script cmdPrefix & " if [ -x \"`/usr/bin/which ffmpeg`\" ];then exit 0;else exit 1;fi"
            on error number error_number
            set missingPackages to "FFMPEG "
        end try

        -- Check for MP4v2 in the path
        try
            do shell script cmdPrefix & " if [ -x \"`/usr/bin/which mp4chaps`\" ];then exit 0;else exit 1;fi"
            on error number error_number
            if missingPackages is "FFMPEG" then
                set the end of missingPackages to "MP4v2 "
            else
                set missingPackages to "MP4v2 "
            end if
        end try

        if missingPackages is not "" then
            display dialog "You must install the following programs to continue: \n\t" & missingPackages & " \n\nYou may have to install Xcode Command Line Tools and Homebrew first. If you continue, we'll attempt to install them for you if they are not already present. \n\nIf you have already installed FFMPEG and MP4v2, ensure that they are in your bash path." buttons {"Quit","Install"} default button 2
            if result = {button returned:"Install"} then
                tell application "Terminal"
                    set newTab to do script cmdPrefix & "if [[ -x `which brew` ]];then brew install ffmpeg mp4v2 && exit 0;else /usr/bin/ruby -e \"$(/usr/bin/curl -fsSL https://raw.github.com/Homebrew/homebrew/go/install)\"; brew install ffmpeg mp4v2 && exit 0;fi"
                    delay 1
                    activate
                    -- Check for when the Terminal is done
                    try
                        repeat
                            delay 0.2
                            if not busy of newTab then exit repeat
                        end repeat
                    end try
                end tell
                -- Check if installation was successful
                try
                    do shell script cmdPrefix & " if [ -x \"`/usr/bin/which ffmpeg`\" -a -x \"`/usr/bin/which mp4chaps`\" ];then exit 0;else exit 1;fi"
                    tell application "Terminal" to quit
                    activate
                    display dialog "Installation was successful!" buttons {"OK"} default button "OK"
                    on error error_number
                    activate
                    display dialog "Homebrew, FFMPEG and/or MP4v2 could not be installed."
                end try
                else if result = {button returned:"Quit"} then
                tell me to quit
            end if
        end if
    end awakeFromNib

    on btnGetTracks_(sender)
        -- Code to add iTunes tracks to our list
        -- via http://dougscripts.com/itunes/itinfo/info02.php and http://www.randomsequence.com/articles/applescript-to-send-selected-itunes-tracks-using-mail/
        tell application "iTunes"
            set these_titles to {}
            set these_times to {}
            set these_files to {}
            set the_index to {}
            if selection is not {} then -- there ARE tracks selected...
                set mySelection to selection
                set i to 1
                repeat with aTrack in mySelection
                    if class of aTrack is file track then
                        set end of these_titles to ((name of aTrack) as string)
                        set end of these_times to ((time of aTrack) as string)
                        set end of these_files to (posix path of (get location of aTrack))
                        set end of the_index to (count of these_titles)
                        -- Get metadata from the first track
                        if i is 1 then
                            set pcatArtist to ((artist of aTrack) as string)
                            set pcatAlbum to ((album of aTrack) as string)
                            set pcatComposer to ((composer of aTrack) as string)
                            set pcatGenre to ((genre of aTrack) as string)
                            set pcatDisc to ((disc number of aTrack) as string)
                            set pcatDiscs to ((disc count of aTrack) as string)
                            set pcatAlbumArtist to ((album artist of aTrack) as string)
                            set pcatYear to ((year of aTrack) as string)
                        end if
                        set i to (i + 1)
                    end if
                end repeat
            end if
        end tell
        -- Display the songs to be concatenated
        -- via http://stackoverflow.com/questions/25537750/setstringvalue-with-applescript-list
        set olddelimeters to AppleScript's text item delimiters
        set AppleScript's text item delimiters to "\n"
        set disp_titles to these_titles as string
        trackTable's setStringValue_(disp_titles)
        set AppleScript's text item delimiters to olddelimeters
        -- Update the default metadata
        catArtist's setStringValue_(pcatArtist)
        catAlbum's setStringValue_(pcatAlbum)
        catComposer's setStringValue_(pcatComposer)
        catGenre's setStringValue_(pcatGenre)
        catDisc's setStringValue_(pcatDisc)
        catDiscs's setStringValue_(pcatDiscs)
        catAlbumArtist's setStringValue_(pcatAlbumArtist)
        catYear's setStringValue_(pcatYear)
        -- Reset the name and track fields
        catName's setStringValue_("")
        catTrack's setStringValue_("")
        catTracks's setStringValue_("")
    end btnGetTracks_

    on btnConcatenate_(sender)
        -- Update the metadata variables with the user's input
        set pcatName to catName's stringValue()
        set pcatArtist to catArtist's stringValue()
        set pcatAlbum to catAlbum's stringValue()
        set pcatComposer to catComposer's stringValue()
        set pcatGenre to catGenre's stringValue()
        set pcatTrack to catTrack's stringValue()
        set pcatTracks to catTracks's stringValue()
        set pcatDisc to catDisc's stringValue()
        set pcatDiscs to catDiscs's stringValue()
        set pcatAlbumArtist to catAlbumArtist's stringValue()
        set pcatYear to catYear's stringValue()
        set the_pipes to {}
        try
            do shell script "/bin/rm -f /private/tmp/concat* /private/tmp/cat.chapters.txt /private/tmp/cat.m4a /private/tmp/cat.mp4"
        end try
        set errorHappened to false
        try
            repeat with theIndex in the_index
                do shell script (cmdPrefix & "ffmpeg -i \"" & (item theIndex of these_files as text) & "\" -c copy -bsf:v h264_mp4toannexb -f mpegts /private/tmp/concat" & theIndex & ".ts 2> /dev/null" as text)
                log ("Processed file number" & theIndex) as text
                set end of the_pipes to ("/private/tmp/concat" & theIndex & ".ts" as text)
            end repeat
        on error error_number
            set errorHappened to true
            do shell script "/bin/rm -f /private/tmp/concat*"
            display dialog "The tracks you selected could not be joined. Only mp4 files encoded as AAC can be joined presently."
        end try
        -- Run the actual concatenation command in ffmpeg (for mp4/AAC files only!)
        -- via https://trac.ffmpeg.org/wiki/How%20to%20concatenate%20(join,%20merge)%20media%20files
        if not errorHappened then
            try
                set olddelimeters to AppleScript's text item delimiters
                set AppleScript's text item delimiters to "|"
                set disp_thepipes to the_pipes as string
                do shell script (cmdPrefix & "ffmpeg -f mpegts -i \"concat:" & (disp_thepipes as text) & "\" -c copy -bsf:a aac_adtstoasc /private/tmp/cat.mp4")
                set AppleScript's text item delimiters to olddelimeters
            on error error_number
                set errorHappened to true
                do shell script "/bin/rm -f /private/tmp/concat* /private/tmp/cat.mp4"
                display dialog "The tracks could not be joined."
            end try
        end if
        -- Now let's create the chapter file
        if not errorHappened then
            try
                repeat with theIndex in the_index
                    if theIndex < 2 then
                        do shell script ("/bin/echo \"00:00:00.000 " & (item theIndex of these_titles as text) & "\" > /private/tmp/cat.chapters.txt" as text)
                        set theCounter to (do shell script (cmdPrefix & "ffprobe -loglevel panic -show_streams /private/tmp/concat" & (theIndex as text) & ".ts | egrep -m 1 'duration=[0-9]+\\.' | sed 's/duration=\\([0-9]*[0-9]\\.[0-9]*\\)/\\1/'" as text) as string)
                        set theCounter to (do shell script ("/bin/echo $(/usr/bin/printf %.$2f $(/bin/echo \"`/usr/bin/printf %.3f " & theCounter & "` * 1000\" | /usr/bin/bc))") as string)
                    else
                        set theDateStamp to do shell script (cmdPrefix & "t="& (theCounter as text) & ";((msec=t%1000, t/=1000, sec=t%60, t/=60, min=t%60, hrs=t/60));timestamp=$(printf \"%02d:%02d:%02d.%03d\" $hrs $min $sec $msec);/bin/echo $timestamp" as text)
                        do shell script ("/bin/echo \"" & (theDateStamp as text) & " " & (item theIndex of these_titles as text) & "\" >> /private/tmp/cat.chapters.txt" as text)
                        set theNewCounter to do shell script ((cmdPrefix & "ffprobe -loglevel panic -show_streams /private/tmp/concat" & (theIndex as text) & ".ts | egrep -m 1 'duration=[0-9]+\\.' | sed 's/duration=\\([0-9]*[0-9]\\.[0-9]*\\)/\\1/'" as text) as string)
                        set theNewCounter to do shell script ("/bin/echo $(/usr/bin/printf %.$2f $(/bin/echo \"`/usr/bin/printf %.3f " & theNewCounter & "` * 1000\" | /usr/bin/bc))") as string
                        set theCounter to (theCounter + theNewCounter)
                    end if
                end repeat
            on error error_number
                set errorHappened to true
                do shell script "/bin/rm -f /private/tmp/concat* /private/tmp/cat.mp4 /private/tmp/cat.chapters.txt"
                display dialog "The chapters could not be read from the tracks you had selected."
            end try
        end if
        -- Chapterize cat.mp4
        if not errorHappened then
            try
                do shell script (cmdPrefix & "mp4chaps -i /private/tmp/cat.mp4" as text)
            on error error_number
                set errorHappened to true
                do shell script "/bin/rm -f /private/tmp/concat* /private/tmp/cat.mp4 /private/tmp/cat.chapters.txt"
                display dialog "The chapters could not be added to concatenated file."
            end try
        end if
        -- Add tags
        if not errorHappened then
            try
                do shell script (cmdPrefix & "mp4tags -song \"" & pcatName & "\" -album \"" &  pcatAlbum & "\" -artist \"" &  pcatArtist & "\" -writer \"" &  pcatComposer & "\" -genre \"" &  pcatGenre & "\" -track \"" &  pcatTrack & "\" -tracks \"" &  pcatTracks & "\" -disk \"" &  pcatDisc & "\" -disks \"" &  pcatDiscs & "\" -albumartist \"" & pcatAlbumArtist & "\" -year \"" & pcatYear & "\" /private/tmp/cat.mp4" as text)
            on error error_number
                set errorHappened to true
                do shell script "/bin/rm -f /private/tmp/concat* /private/tmp/cat.mp4 /private/tmp/cat.chapters.txt"
                display dialog "The tags could not be added to the concatenated audio file."
            end try
        end if
        -- Add the finished track to iTunes
        if not errorHappened then
            try
                do shell script "/bin/mv /private/tmp/cat.mp4 /private/tmp/cat.m4a"
                tell application "iTunes"
                        add file ":private:tmp:cat.m4a"
                end tell
            on error error_number
                set errorHappened to true
                do shell script "/bin/rm -f /private/tmp/concat* /private/tmp/cat.mp4 /private/tmp/cat.chapters.txt /private/tmp/cat.m4a"
                display dialog "The concatenated file could not be added to iTunes."
            end try
        end if
        -- Clean up
        do shell script "/bin/rm -f /private/tmp/concat* /private/tmp/cat.chapters.txt /private/tmp/cat.m4a"
        set theCounter to ""
    end btnConcatenate_

	on applicationWillFinishLaunching_(aNotification)
        -- Insert code here to initialize your application before any files are opened
	end applicationWillFinishLaunching_

	on applicationShouldTerminate_(sender)
		-- Insert code here to do any housekeeping before your application quits
		return current application's NSTerminateNow
	end applicationShouldTerminate_

end script


Fix error when encountering non-music playlists

-- playplaylist filter --

on loadConfig()

	do shell script "./compile-config.sh"
	set config to load script alias ((path to library folder from user domain as text) & "Caches:com.runningwithcrayons.Alfred-3:Workflow Data:com.calebevans.playsong:config.scpt")
	return config

end loadConfig

on getPlaylistResultListFeedback(query)

	global config

	set query to trimWhitespace(query) of config

	tell application "iTunes"

		-- retrieve list of playlists matching query (ordered by relevance)
		set thePlaylists to (get user playlists whose name starts with query and name is not config's workflowPlaylistName and special kind is none and size is not 0)

		if length of thePlaylists < config's resultLimit then

			set thePlaylists to thePlaylists & (get user playlists whose name contains (space & query) and name does not start with query and name is not config's workflowPlaylistName and special kind is none and size is not 0)

		end if

		if length of thePlaylists < config's resultLimit then

			set thePlaylists to thePlaylists & (get user playlists whose name contains query and name does not start with query and name does not contain (space & query) and name is not config's workflowPlaylistName and special kind is none and size is not 0)

		end if

		if length of thePlaylists > config's resultLimit then

			set thePlaylists to items 1 thru (config's resultLimit) of thePlaylists

		end if

		repeat with thePlaylist in thePlaylists

			set playlistName to name of thePlaylist
			set playlistId to id of thePlaylist
			set songCount to number of tracks in thePlaylist
			set playlistDuration to time of thePlaylist

			try
				set theSong to (first track in user playlist playlistName whose kind contains (songDescriptor of config))
				set songArtworkPath to getSongArtworkPath(theSong) of config

				set itemSubtitle to (quantifyNumber(songCount, "track", "tracks") of config) & ", " & playlistDuration & " in length"

				addResult({uid:("playlist-" & playlistId) as text, valid:"yes", title:playlistName, subtitle:itemSubtitle, icon:songArtworkPath}) of config
			on error number -1728
			end try

		end repeat

		if config's resultListIsEmpty() then

			addNoResultsItem(query, "playlist") of config

		end if

	end tell

	return getResultListFeedback() of config

end getPlaylistResultListFeedback

set config to loadConfig()
getPlaylistResultListFeedback("{query}")

-- playplaylist filter --

on loadConfig()

	do shell script "./compile-config.sh"
	set config to load script alias ((path to library folder from user domain as text) & "Caches:com.runningwithcrayons.Alfred-3:Workflow Data:com.calebevans.playsong:config.scpt")
	return config

end loadConfig

on getPlaylistResultListFeedback(query)

	global config

	set query to trimWhitespace(query) of config

	tell application "iTunes"

		-- retrieve list of playlists matching query (ordered by relevance)
		set thePlaylists to (get user playlists whose name starts with query and name is not config's workflowPlaylistName and special kind is none and size is not 0)

		if length of thePlaylists < config's resultLimit then

			set thePlaylists to thePlaylists & (get user playlists whose name contains (space & query) and name does not start with query and name is not config's workflowPlaylistName and special kind is none and size is not 0)

		end if

		if length of thePlaylists < config's resultLimit then

			set thePlaylists to thePlaylists & (get user playlists whose name contains query and name does not start with query and name does not contain (space & query) and name is not config's workflowPlaylistName and special kind is none and size is not 0)

		end if

		if length of thePlaylists > config's resultLimit then

			set thePlaylists to items 1 thru (config's resultLimit) of thePlaylists

		end if

		repeat with thePlaylist in thePlaylists

			set playlistName to name of thePlaylist
			set playlistId to id of thePlaylist
			set songCount to number of tracks in thePlaylist
			set playlistDuration to time of thePlaylist

			set theSong to (first track in user playlist playlistName whose kind contains (songDescriptor of config))
			set songArtworkPath to getSongArtworkPath(theSong) of config

			set itemSubtitle to (quantifyNumber(songCount, "song", "songs") of config) & ", " & playlistDuration & " in length"

			addResult({uid:("playlist-" & playlistId) as text, valid:"yes", title:playlistName, subtitle:itemSubtitle, icon:songArtworkPath}) of config

		end repeat

		if config's resultListIsEmpty() then

			addNoResultsItem(query, "playlist") of config

		end if

	end tell

	return getResultListFeedback() of config

end getPlaylistResultListFeedback

set config to loadConfig()
getPlaylistResultListFeedback("{query}")


kext removed even when not loaded

kext removed even when not loaded

set kext to "/Library/Extensions/Soundflower.kext"
try
	tell application "System Events"
		if not (exists file kext) then
			error kext & " not found."
		end if
	end tell
	try
		do shell script "/sbin/kextunload " & kext with administrator privileges
	end try
	do shell script "/bin/rm -rf " & kext with administrator privileges
	display dialog "Successfully uninstalled."
on error errMsg number errNum
	display dialog errMsg
end try

set kext to "/Library/Extensions/Soundflower.kext"
try
	tell application "System Events"
		if not exists file kext then
			error kext & " not found."
		end if
	end tell
	do shell script "/sbin/kextunload " & kext with administrator privileges
	do shell script "/bin/rm -rf " & kext with administrator privileges
	display dialog "Successfully uninstalled."
on error errMsg number errNum
	display dialog errMsg
end try


Update iTerm script to fix time issue

Update iTerm script to fix time issue


corrected timings for changing dir in existing session

on run command
	set options to my split(command as string, "|")
	set iterm_running to (item 1 of options) as integer
	set session_name to item 2 of options
	set change_dir to (item 3 of options) as integer

	tell application "iTerm"
		activate
		set termCount to count of terminals

		if termCount is 0 then
			set _term to (make new terminal)
		else
			if iterm_running > 0 then
				set _term to the first terminal
				tell i term application "System Events" to keystroke "t" using command down
			end if
		end if

		try
			set _session to current session of current terminal
		on error
			tell _term
				launch session "Default"
				set _session to current session
			end tell
		end try

		tell _session
		    if session_name is not "" then
                write text "tmux attach -t \"" & session_name & "\""
				delay 1
		    end if
			if change_dir > 0 then
				tell i term application "Path Finder"
					set target_path to "\"" & (the POSIX path of the target of the front finder window) & "\""
					set change_dir_command to "cd " & target_path
				end tell
				write text change_dir_command
				write text "clear"
			end if
		end tell
	end tell
end run

on split(str, delimiter)
	set oldDelimiters to AppleScript's text item delimiters
	set AppleScript's text item delimiters to delimiter
	set theArray to every text item of str
	set AppleScript's text item delimiters to oldDelimiters
	return theArray
end split

on run command
	set options to my split(command as string, "|")
	set iterm_running to (item 1 of options) as integer
	set session_name to item 2 of options
	set change_dir to (item 3 of options) as integer

	tell application "iTerm"
		activate
		set termCount to count of terminals

		if termCount is 0 then
			set _term to (make new terminal)
		else
			if iterm_running > 0 then
				set _term to the first terminal
				tell i term application "System Events" to tell process "Terminal.app" to keystroke "t" using command down
			end if
		end if

		try
			set _session to current session of current terminal
		on error
			tell _term
				launch session "Default"
				set _session to current session
			end tell
		end try

		tell _session
		    if session_name is not "" then
                write text "tmux attach -t \"" & session_name & "\""
		    end if
			if change_dir > 0 then
				tell i term application "Path Finder"
					set target_path to "\"" & (the POSIX path of the target of the front finder window) & "\""
					set change_dir_command to "cd " & target_path
				end tell
				delay 0.1
				write text change_dir_command
				write text "clear"
			end if
		end tell
	end tell
end run

on split(str, delimiter)
	set oldDelimiters to AppleScript's text item delimiters
	set AppleScript's text item delimiters to delimiter
	set theArray to every text item of str
	set AppleScript's text item delimiters to oldDelimiters
	return theArray
end split