fix filename in comment

fix filename in comment

--
--  slideshow -- Observe and Control Slideshow Applications
--  Copyright (c) 2014-2015 Ralf S. Engelschall <http://engelschall.com>
--
--  This Source Code Form is subject to the terms of the Mozilla Public
--  License (MPL), version 2.0. If a copy of the MPL was not distributed
--  with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
--
--  File:     connector-osx-kn6.scpt
--  Purpose:  connector engine for Apple Keynote 6 under Mac OS X
--  Language: AppleScript
--

--  utility function
on filterText(this_text, allowed_chars)
   set new_text to ""
   repeat with this_char in this_text
       set x to the offset of this_char in allowed_chars
       if x is not 0 then
           set new_text to (new_text & this_char) as string
       end if
   end repeat
   return new_text
end filterText

--  utility function
on replaceText(this_text, search_string, replacement_string)
   set AppleScript's text item delimiters to the search_string
   set the item_list to every text item of this_text
   set AppleScript's text item delimiters to the replacement_string
   set this_text to the item_list as string
   set AppleScript's text item delimiters to ""
   return this_text
end replace_chars

--  utility function
on asciiCharset()
    set charset to " \"'!#$%()*+,-./:;<=>?@[\\]^_{|}~"
    set charset to (charset & "0123456789")
    set charset to (charset & "ABCDEFGHIJKLMNOPQRSTUVWXYZ")
    set charset to (charset & "abcdefghijklmnopqrstuvwxyz")
    return charset
end asciiCharset

--  get application state
on knGetState()
    set state to "closed"
    tell application "System Events"
        set is_running to (exists (some process whose name is "Keynote"))
    end tell
    if is_running then
       try
            set state to "running"
            tell application "Keynote"
                if false then -- FIXME: how to detect play mode?
                    set state to "viewing"
                else if (get count of slides of front document) > 0 then
                    set state to "editing"
                end if
            end tell
        on error errMsg
        end try
    end if
    return state
end knGetState

--  get Apple Keynote current slide
on knGetCurSlide()
    try
        tell application "Keynote"
            if false then -- FIXME: how to detect play mode?
                return (get slide number of current slide of front document) -- FIXME: wrong!
            else
                return (get slide number of current slide of front document)
            end if
        end tell
    on error errMsg
        return 0
    end try
end knGetCurSlide

--  get Apple Keynote maximum slide
on knGetMaxSlide()
    try
        tell application "Keynote"
            return (get count of slides of front document)
        end tell
    on error errMsg
        return 0
    end try
end knGetMaxSlide

--  the STATE command
on cmdSTATE()
    set state to knGetState()
    if state is "closed" then
        set position to 0
        set slides to 0
    else
        set position to knGetCurSlide()
        set slides to knGetMaxSlide()
    end if
    return ("{ \"response\": { " & ¬
        "\"state\": \"" & state & "\", " & ¬
        "\"position\": " & position & ", " & ¬
        "\"slides\": " & slides & " " & ¬
    "} }")
end cmdSTATE

--  the INFO command
on cmdINFO()
    set output to ""
    if knGetMaxSlide() is 0 then
        error "still no active presentation"
    end if
    tell application "Keynote"
        set thePresentation to front document
        set theTitles to ""
        set theNotes to ""
        set slideCount to (get count of slides of thePresentation)
        repeat with slideNum from 1 to slideCount
            set theSlide to slide slideNum of thePresentation

            set theTitle to (get object text of default title item of theSlide) as string
            if theTitles is not "" then
                set theTitles to (theTitles & ", ")
            end if
            set theTitles to (theTitles & "\"" & (my replaceText(theTitle, "\"", "\\\"")) & "\"")

            set theNote to (presenter notes of theSlide) as string
            set theNote to (my filterText(theNote, my asciiCharset()))
            if theNotes is not "" then
                set theNotes to (theNotes & ", ")
            end if
            set theNotes to (theNotes & "\"" & (my replaceText(theNote, "\"", "\\\"")) & "\"")

        end repeat
        set theTitles to ("[ " & theTitles & " ]")
        set theNotes to ("[ " & theNotes & " ]")
        set output to ("{ \"response\": { \"titles\": " & theTitles & ", \"notes\": " & theNotes & " } }")
    end tell
    return output
end cmdINFO

--  the control commands
on cmdCTRL(command, arg)
    set state to knGetState()
    if command is "BOOT" then
        if state is not "closed" then
            error "application already running"
        end if
        tell application "Keynote"
            activate
        end tell
    else if command is "QUIT" then
        if state is "closed" then
            error "application already closed"
        end if
        tell application "Keynote"
            quit
        end tell
    else if command is "OPEN" then
        if state is "editing" or state is "viewing" then
            error "active presentation already existing"
        end if
        tell application "Keynote"
            tell application "Finder" to set thePath to ¬
                POSIX file (POSIX path of (container of (path to me) as string) & (arg)) as alias
            open thePath
        end tell
    else if command is "CLOSE" then
        if state is "closed" or state is "running" then
            error "still no active presentation"
        end if
        tell application "Keynote"
            close front document
        end tell
    else if command is "START" then
        if state is "closed" or state is "running" then
            error "still no active presentation"
        end if
        if state is "viewing" then
            error "active presentation already viewing"
        end if
        tell application "Keynote"
            start front document from (slide 1 of front document)
        end tell
    else if command is "STOP" then
        if state is not "viewing" then
            error "no active slideshow"
        end if
        tell application "Keynote"
            stop front document
        end tell
    else if command is "PAUSE" then
        if state is not "viewing" then
            error "no active slideshow"
        end if
        tell application "Keynote"
            activate
            tell application "System Events" to keystroke "b"
        end tell
    else if command is "RESUME" then
        if state is not "viewing" then
            error "no active slideshow"
        end if
        tell application "Keynote"
            activate
            tell application "System Events" to keystroke "b"
        end tell
    else if command is "FIRST" then
        if state is not "viewing" then
            error "no active slideshow"
        end if
        tell application "Keynote"
            repeat with i from 1 to (my knGetMaxSlide())
                try
                    show previous
                on error errMsg
                    exit repeat
                end try
                delay 0.02
            end repeat
        end tell
    else if command is "LAST" then
        if state is not "viewing" then
            error "no active slideshow"
        end if
        tell application "Keynote"
            repeat with i from 1 to ((my knGetMaxSlide()) - 1)
                try
                    show next
                on error errMsg
                    exit repeat
                end try
                delay 0.02
            end repeat
        end tell
    else if command is "GOTO" then
        if state is not "viewing" then
            error "no active slideshow"
        end if
        tell application "Keynote"
            repeat with i from 1 to (my knGetMaxSlide())
                try
                    show previous
                on error errMsg
                    exit repeat
                end try
                delay 0.02
            end repeat
            repeat with i from 1 to ((arg as integer) - 1)
                try
                    show next
                end try
                delay 0.02
            end repeat
        end tell
    else if command is "PREV" then
        if state is not "viewing" then
            error "no active slideshow"
        end if
        tell application "Keynote"
            show previous
        end tell
    else if command is "NEXT" then
        if state is not "viewing" then
            error "no active slideshow"
        end if
        tell application "Keynote"
            show next
        end tell
    end if
    return "{ \"response\": \"OK\" }"
end cmdCTRL

--  main procedure
on run argv
    set cmd to item 1 of argv
    set arg to ""
    if count of argv is 2 then
        set arg to item 2 of argv
    end if
    try
        if cmd is "STAT" then
            set output to cmdSTATE()
        else if cmd is "INFO" then
            set output to cmdINFO()
        else if cmd is "BOOT" ¬
            or cmd is "QUIT" ¬
            or cmd is "OPEN" ¬
            or cmd is "CLOSE" ¬
            or cmd is "START" ¬
            or cmd is "STOP" ¬
            or cmd is "PAUSE" ¬
            or cmd is "RESUME" ¬
            or cmd is "FIRST" ¬
            or cmd is "LAST" ¬
            or cmd is "GOTO" ¬
            or cmd is "PREV" ¬
            or cmd is "NEXT" then
            set output to cmdCTRL(cmd, arg)
        else
            set output to "{ \"error\": \"invalid command\" }"
        end if
    on error errMsg
        set output to ("{ \"error\": \"" & errMsg & "\" }")
    end try
    copy output to stdout
end run

--
--  slideshow -- Observe and Control Slideshow Applications
--  Copyright (c) 2014-2015 Ralf S. Engelschall <http://engelschall.com>
--
--  This Source Code Form is subject to the terms of the Mozilla Public
--  License (MPL), version 2.0. If a copy of the MPL was not distributed
--  with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
--
--  File:     connector-osx-kn6.js
--  Purpose:  connector engine for Apple Keynote 6 under Mac OS X
--  Language: AppleScript
--

--  utility function
on filterText(this_text, allowed_chars)
   set new_text to ""
   repeat with this_char in this_text
       set x to the offset of this_char in allowed_chars
       if x is not 0 then
           set new_text to (new_text & this_char) as string
       end if
   end repeat
   return new_text
end filterText

--  utility function
on replaceText(this_text, search_string, replacement_string)
   set AppleScript's text item delimiters to the search_string
   set the item_list to every text item of this_text
   set AppleScript's text item delimiters to the replacement_string
   set this_text to the item_list as string
   set AppleScript's text item delimiters to ""
   return this_text
end replace_chars

--  utility function
on asciiCharset()
    set charset to " \"'!#$%()*+,-./:;<=>?@[\\]^_{|}~"
    set charset to (charset & "0123456789")
    set charset to (charset & "ABCDEFGHIJKLMNOPQRSTUVWXYZ")
    set charset to (charset & "abcdefghijklmnopqrstuvwxyz")
    return charset
end asciiCharset

--  get application state
on knGetState()
    set state to "closed"
    tell application "System Events"
        set is_running to (exists (some process whose name is "Keynote"))
    end tell
    if is_running then
       try
            set state to "running"
            tell application "Keynote"
                if false then -- FIXME: how to detect play mode?
                    set state to "viewing"
                else if (get count of slides of front document) > 0 then
                    set state to "editing"
                end if
            end tell
        on error errMsg
        end try
    end if
    return state
end knGetState

--  get Apple Keynote current slide
on knGetCurSlide()
    try
        tell application "Keynote"
            if false then -- FIXME: how to detect play mode?
                return (get slide number of current slide of front document) -- FIXME: wrong!
            else
                return (get slide number of current slide of front document)
            end if
        end tell
    on error errMsg
        return 0
    end try
end knGetCurSlide

--  get Apple Keynote maximum slide
on knGetMaxSlide()
    try
        tell application "Keynote"
            return (get count of slides of front document)
        end tell
    on error errMsg
        return 0
    end try
end knGetMaxSlide

--  the STATE command
on cmdSTATE()
    set state to knGetState()
    if state is "closed" then
        set position to 0
        set slides to 0
    else
        set position to knGetCurSlide()
        set slides to knGetMaxSlide()
    end if
    return ("{ \"response\": { " & ¬
        "\"state\": \"" & state & "\", " & ¬
        "\"position\": " & position & ", " & ¬
        "\"slides\": " & slides & " " & ¬
    "} }")
end cmdSTATE

--  the INFO command
on cmdINFO()
    set output to ""
    if knGetMaxSlide() is 0 then
        error "still no active presentation"
    end if
    tell application "Keynote"
        set thePresentation to front document
        set theTitles to ""
        set theNotes to ""
        set slideCount to (get count of slides of thePresentation)
        repeat with slideNum from 1 to slideCount
            set theSlide to slide slideNum of thePresentation

            set theTitle to (get object text of default title item of theSlide) as string
            if theTitles is not "" then
                set theTitles to (theTitles & ", ")
            end if
            set theTitles to (theTitles & "\"" & (my replaceText(theTitle, "\"", "\\\"")) & "\"")

            set theNote to (presenter notes of theSlide) as string
            set theNote to (my filterText(theNote, my asciiCharset()))
            if theNotes is not "" then
                set theNotes to (theNotes & ", ")
            end if
            set theNotes to (theNotes & "\"" & (my replaceText(theNote, "\"", "\\\"")) & "\"")

        end repeat
        set theTitles to ("[ " & theTitles & " ]")
        set theNotes to ("[ " & theNotes & " ]")
        set output to ("{ \"response\": { \"titles\": " & theTitles & ", \"notes\": " & theNotes & " } }")
    end tell
    return output
end cmdINFO

--  the control commands
on cmdCTRL(command, arg)
    set state to knGetState()
    if command is "BOOT" then
        if state is not "closed" then
            error "application already running"
        end if
        tell application "Keynote"
            activate
        end tell
    else if command is "QUIT" then
        if state is "closed" then
            error "application already closed"
        end if
        tell application "Keynote"
            quit
        end tell
    else if command is "OPEN" then
        if state is "editing" or state is "viewing" then
            error "active presentation already existing"
        end if
        tell application "Keynote"
            tell application "Finder" to set thePath to ¬
                POSIX file (POSIX path of (container of (path to me) as string) & (arg)) as alias
            open thePath
        end tell
    else if command is "CLOSE" then
        if state is "closed" or state is "running" then
            error "still no active presentation"
        end if
        tell application "Keynote"
            close front document
        end tell
    else if command is "START" then
        if state is "closed" or state is "running" then
            error "still no active presentation"
        end if
        if state is "viewing" then
            error "active presentation already viewing"
        end if
        tell application "Keynote"
            start front document from (slide 1 of front document)
        end tell
    else if command is "STOP" then
        if state is not "viewing" then
            error "no active slideshow"
        end if
        tell application "Keynote"
            stop front document
        end tell
    else if command is "PAUSE" then
        if state is not "viewing" then
            error "no active slideshow"
        end if
        tell application "Keynote"
            activate
            tell application "System Events" to keystroke "b"
        end tell
    else if command is "RESUME" then
        if state is not "viewing" then
            error "no active slideshow"
        end if
        tell application "Keynote"
            activate
            tell application "System Events" to keystroke "b"
        end tell
    else if command is "FIRST" then
        if state is not "viewing" then
            error "no active slideshow"
        end if
        tell application "Keynote"
            repeat with i from 1 to (my knGetMaxSlide())
                try
                    show previous
                on error errMsg
                    exit repeat
                end try
                delay 0.02
            end repeat
        end tell
    else if command is "LAST" then
        if state is not "viewing" then
            error "no active slideshow"
        end if
        tell application "Keynote"
            repeat with i from 1 to ((my knGetMaxSlide()) - 1)
                try
                    show next
                on error errMsg
                    exit repeat
                end try
                delay 0.02
            end repeat
        end tell
    else if command is "GOTO" then
        if state is not "viewing" then
            error "no active slideshow"
        end if
        tell application "Keynote"
            repeat with i from 1 to (my knGetMaxSlide())
                try
                    show previous
                on error errMsg
                    exit repeat
                end try
                delay 0.02
            end repeat
            repeat with i from 1 to ((arg as integer) - 1)
                try
                    show next
                end try
                delay 0.02
            end repeat
        end tell
    else if command is "PREV" then
        if state is not "viewing" then
            error "no active slideshow"
        end if
        tell application "Keynote"
            show previous
        end tell
    else if command is "NEXT" then
        if state is not "viewing" then
            error "no active slideshow"
        end if
        tell application "Keynote"
            show next
        end tell
    end if
    return "{ \"response\": \"OK\" }"
end cmdCTRL

--  main procedure
on run argv
    set cmd to item 1 of argv
    set arg to ""
    if count of argv is 2 then
        set arg to item 2 of argv
    end if
    try
        if cmd is "STAT" then
            set output to cmdSTATE()
        else if cmd is "INFO" then
            set output to cmdINFO()
        else if cmd is "BOOT" ¬
            or cmd is "QUIT" ¬
            or cmd is "OPEN" ¬
            or cmd is "CLOSE" ¬
            or cmd is "START" ¬
            or cmd is "STOP" ¬
            or cmd is "PAUSE" ¬
            or cmd is "RESUME" ¬
            or cmd is "FIRST" ¬
            or cmd is "LAST" ¬
            or cmd is "GOTO" ¬
            or cmd is "PREV" ¬
            or cmd is "NEXT" then
            set output to cmdCTRL(cmd, arg)
        else
            set output to "{ \"error\": \"invalid command\" }"
        end if
    on error errMsg
        set output to ("{ \"error\": \"" & errMsg & "\" }")
    end try
    copy output to stdout
end run


Remove FIXME: comments

Remove FIXME: comments

on newPresentation(themeName)
	tell application "Keynote"
		activate
		-- FIXME: Make this selectable?
		set targetWidth to 1024 -- 1440 <-- higher resolution
		set targetHeight to 768 -- 1080 <-- higher resolution

		set props to {document theme:theme (themeName as string), width:targetWidth, height:targetHeight}

		set thisDocument to make new document with properties props
		return id of thisDocument
	end tell
end newPresentation

on openPresentation(posixPath)
	tell application "Keynote"
		open posixPath
	end tell
end openPresentation

on savePresentation(docId, posixPath)
	tell application "Keynote"
		activate
        set theDocument to document id docId
		save theDocument in POSIX file posixPath
        delete theDocument
        open posixPath
	end tell
end savePresentation

on closePresentation(docId)
	tell application "Keynote"
		activate
        set theDocument to document id docId
		close theDocument
	end tell
end savePresentation

on createSlide(docId, masterSlideName)
	tell application "Keynote"
		tell document id docId
			set thisSlide to make new slide with properties {base slide:master slide masterSlideName}
		end tell
	end tell
end createSlide

on deleteAllSlides(docId)
	tell application "Keynote"
		tell document id docId to delete every slide
	end tell
end deleteAllSlides

on finalize(docId)
	tell application "Keynote"
		tell document id docId to delete slide 1
	end tell
end finalize

on themeMasters(docId)
	--	  tell application "Keynote" to get the name of every master slide of thisDocument
	tell application "Keynote"
		set names to the name of every master slide of document id docId
		return names
	end tell
end themeMasters

on addImage(docId, slideIndex, n, filepath)
  tell application "Keynote"
	tell slide slideIndex of document id docId
		-- TO REPLACE A PLACEHOLDER OR EXISTING IMAGE:
		set thisPlaceholderImageItem to image n
		-- change the value of the “file name” property of the image to be an HFS file reference to the replacement image file
	    set macPath to POSIX file filepath as Unicode text
		set file name of thisPlaceholderImageItem to ¬
			alias macPath
	end tell
  end tell
end addImage

on addTitle(docId, slideIndex, thisSlideTitle)
	tell application "Keynote"
    	tell slide slideIndex of document id docId
			set the object text of the default title item to thisSlideTitle
		end tell
	end tell
end addTitle

on addBody(docId, slideIndex, thisSlideBody)
	tell application "Keynote"
    	tell slide slideIndex of document id docId
            set the object text of the default body item to thisSlideBody
		end tell
	end tell
end addTitle

on addPresenterNotes(docId, slideIndex, theNotes)
	tell application "Keynote"
    	tell slide slideIndex of document id docId
			set presenter notes to theNotes
		end tell
	end tell
end addPresenterNotes

on addText(docId, slideIndex, n, theText)
  tell application "Keynote"
  	tell slide slideIndex of document id docId
		set thisPlaceholderItem to text item n
		set object text of thisPlaceholderItem to theText
	end tell
  end tell
end addText

on newPresentation(themeName)
	tell application "Keynote"
		activate
		-- FIXME: Make this selectable?
		set targetWidth to 1024 -- 1440 <-- higher resolution
		set targetHeight to 768 -- 1080 <-- higher resolution

		set props to {document theme:theme (themeName as string), width:targetWidth, height:targetHeight}

		set thisDocument to make new document with properties props
		return id of thisDocument
	end tell
end newPresentation

on openPresentation(posixPath)
	tell application "Keynote"
		open posixPath
	end tell
end openPresentation

on savePresentation(docId, posixPath)
	tell application "Keynote"
		activate
        set theDocument to document id docId
		save theDocument in POSIX file posixPath
        delete theDocument
        open posixPath
	end tell
end savePresentation

on closePresentation(docId)
	tell application "Keynote"
		activate
        set theDocument to document id docId
		close theDocument
	end tell
end savePresentation

on createSlide(docId, masterSlideName)
	tell application "Keynote"
		tell document id docId
			set thisSlide to make new slide with properties {base slide:master slide masterSlideName}
		end tell
	end tell
end createSlide

on deleteAllSlides(docId)
	tell application "Keynote"
		tell document id docId to delete every slide
	end tell
end deleteAllSlides

on finalize(docId)
	tell application "Keynote"
		tell document id docId to delete slide 1
	end tell
end finalize

on themeMasters(docId)
	--	  tell application "Keynote" to get the name of every master slide of thisDocument
	tell application "Keynote"
		set names to the name of every master slide of document id docId
		return names
	end tell
end themeMasters

on addImage(docId, slideIndex, n, filepath)
  (*
	FIXME: Use slide ID to adress slide instead of "current slide"
  *)
  tell application "Keynote"
	tell slide slideIndex of document id docId
		-- TO REPLACE A PLACEHOLDER OR EXISTING IMAGE:
		set thisPlaceholderImageItem to image n
		-- change the value of the “file name” property of the image to be an HFS file reference to the replacement image file
	    set macPath to POSIX file filepath as Unicode text
		set file name of thisPlaceholderImageItem to ¬
			alias macPath
	end tell
  end tell
end addImage

on addTitle(docId, slideIndex, thisSlideTitle)
  (*
	FIXME: Use slide ID to adress slide instead of "current slide"
  *)
	tell application "Keynote"
    	tell slide slideIndex of document id docId
			set the object text of the default title item to thisSlideTitle
		end tell
	end tell
end addTitle

on addBody(docId, slideIndex, thisSlideBody)
  (*
	FIXME: Use slide ID to adress slide instead of "current slide"
  *)
	tell application "Keynote"
    	tell slide slideIndex of document id docId
            set the object text of the default body item to thisSlideBody
		end tell
	end tell
end addTitle

    (*
  	FIXME: Use slide ID to adress slide instead of "current slide"
    *)
on addPresenterNotes(docId, slideIndex, theNotes)
	tell application "Keynote"
    	tell slide slideIndex of document id docId
			set presenter notes to theNotes
		end tell
	end tell
end addPresenterNotes

on addText(docId, slideIndex, n, theText)
  (*
	FIXME: Use slide ID to adress slide instead of "current slide"
  *)
  tell application "Keynote"
  	tell slide slideIndex of document id docId
		set thisPlaceholderItem to text item n
		set object text of thisPlaceholderItem to theText
	end tell
  end tell
end addText


added option to prepend canvas number for iPad export

-- export all layers to image files
-- Copyright (c) 2011, Charles-Axel Dein

-- Settings
property exportFileExtension : "png"
property CANVAS_ORIGIN = {200, 220}
property CANVAS_SIZE = {1024, 748} -- this is landscape orientation
property ADD_CANVAS_NUMBER : true
-- End of Settings

on file_exists(FileOrFolderToCheckString)
   try
       alias FileOrFolderToCheckString
       return true
   on error
       return false
   end try
end file_exists

tell application "OmniGraffle Professional 5"
	set theWindow to front window
	set theDocument to document of theWindow
	set theFilename to name of theDocument
	-- remove .graffle
	set theFilename to texts 1 thru ((offset of "." in theFilename) - 1) of theFilename

	set export_folder to (choose folder with prompt "Pick the destination folder") as string
	set export_folder to export_folder & theFilename & ":"

	-- create folder
	if file_exists(export_folder) of me then
		try
			display alert "The file already exists. Do you want to replace it?" buttons {"Cancel", "Erase"} cancel button 1
		on error errText number errNum
			if (errNum is equal to -128) then
				return
			end if
		end try

		-- deletes the folder (necessary because some layers may have been renamed
		do shell script "rm -rf " & quoted form of POSIX path of export_folder

	else
		-- creates the folder
		do shell script "mkdir -p " & quoted form of POSIX path of export_folder
	end if

	set canvasCount to count of canvases of theDocument

	set i to 0
	repeat with canvasNumber from 1 to canvasCount
		set theCanvas to canvas canvasNumber of theDocument
		set canvas_name to name of theCanvas
		set canvas of theWindow to theCanvas
		set layerCount to count of layers of theCanvas

		-- hide all layers, except those beginning with "*"
		-- also check if there is only one layer to be exported
		repeat with layerNumber from 1 to layerCount
			set theLayer to layer layerNumber of theCanvas
			set number_of_layer_to_be_exported to 0

			if theLayer is prints and class of theLayer is not shared layer then
				set layer_name to name of theLayer as string
				if character 1 of layer_name is not "*" then
					set visible of theLayer to false
					set number_of_layer_to_be_exported to number_of_layer_to_be_exported + 1
				else
					set visible of theLayer to true
				end if
			end if

		end repeat

		set area type of current export settings to manual region
		set draws background of current export settings to false
		set include border of current export settings to false
		set origin of current export settings to CANVAS_ORIGIN
		set size of current export settings to CANVAS_SIZE

		set canvas_filename to ""
		if ADD_CANVAS_NUMBER then
			set canvas_filename to canvasNumber & "- "
		end if
		set canvas_filename to canvas_filename & canvas_name

		repeat with layerNumber from 1 to layerCount
			set theLayer to layer layerNumber of theCanvas

			if (theLayer is prints) and (class of theLayer is not shared layer) then
				set layer_name to name of theLayer as string
				set filename to canvas_filename & " - " & layer_name & "." & exportFileExtension
				set export_filename to export_folder & filename

				-- show the layer, export, then hide the layer
				if character 1 of layer_name is not "*" then
					set visible of theLayer to true
					save theDocument in export_filename
					set visible of theLayer to false
				end if

			end if

		end repeat

	end repeat
end tell

-- export all layers to image files
-- Copyright (c) 2011, Charles-Axel Dein

-- Settings
property exportFileExtension : "png"
property CANVAS_ORIGIN = {200, 220}
property CANVAS_SIZE = {1024, 748} -- this is landscape orientation
-- End of Settings

tell application "OmniGraffle Professional 5"
	set theWindow to front window
	set theDocument to document of theWindow
	set theFilename to name of theDocument
	-- remove .graffle
	set theFilename to texts 1 thru ((offset of "." in theFilename) - 1) of theFilename

	set export_folder to (choose folder with prompt "Pick the destination folder") as string
	set export_folder to export_folder & theFilename & ":"

	-- create folder
	do shell script "mkdir -p " & quoted form of POSIX path of export_folder

	set canvasCount to count of canvases of theDocument

	set i to 0
	repeat with canvasNumber from 1 to canvasCount
		set theCanvas to canvas canvasNumber of theDocument
		set canvas_name to name of theCanvas
		set canvas of theWindow to theCanvas
		set layerCount to count of layers of theCanvas

		-- hide all layers, except those beginning with "*"
		-- also check if there is only one layer to be exported
		repeat with layerNumber from 1 to layerCount
			set theLayer to layer layerNumber of theCanvas
			set number_of_layer_to_be_exported to 0

			if theLayer is prints and class of theLayer is not shared layer then
				set layer_name to name of theLayer as string
				if character 1 of layer_name is not "*" then
					set visible of theLayer to false
					set number_of_layer_to_be_exported to number_of_layer_to_be_exported + 1
				else
					set visible of theLayer to true
				end if
			end if

		end repeat

		set area type of current export settings to manual region
		set draws background of current export settings to false
		set include border of current export settings to false
		set origin of current export settings to CANVAS_ORIGIN
		set size of current export settings to CANVAS_SIZE

		repeat with layerNumber from 1 to layerCount
			set theLayer to layer layerNumber of theCanvas

			if (theLayer is prints) and (class of theLayer is not shared layer) then
				set layer_name to name of theLayer as string
				set filename to canvas_name & " - " & layer_name & "." & exportFileExtension
				set export_filename to export_folder & filename

				-- show the layer, export, then hide the layer
				if character 1 of layer_name is not "*" then
					set visible of theLayer to true
					save theDocument in export_filename
					set visible of theLayer to false
				end if

			end if

		end repeat

	end repeat
end tell


mod helper to write temp file using write instead of shell echo

-- main_helper
-- Erik Shagdar, NYHTC
-- Helper script that compiles all .applescript files into a main.scpt.

(* HISTORY:
	2017-12-18 ( eshagdar ): skip files whose name begins wtih 'WIP_' ( work in progress ).
	2017-11-14 ( dshockley ): open system preference pane even from command line.
	2017-10-20 ( eshagdar ): allow running with params. If ran with 'False', dialogs ( and re-enabling assistve devices ) is suppressed.
	2017-10-18 ( eshagdar ): debugMode is a property. htcLib scriptName is 'htcLib', not 'main.scpt'.
	2017-10-06 ( eshagdar ): added library folder to skip when generating htcLib. renamed variables for clarity.
	2017-09-12 ( eshagdar ): attempt to de-select and re-select the htcLib checkbox.
	2017-06-29 ( eshagdar ): check to see if htcLib exists.
	2017-06-26 ( eshagdar ): quit the app before deleting it.
	2017-06-14 ( eshagdar ): also make an app.
	2016-04-21 ( eshagdar ): Updated clickCommandPosix path.
	2016-03-17 ( eshagdar ): Added DebugMode and clickCommandPosix properties.
	2016-03-15 ( eshagdar ): added documentation to main script. Separated individual functions into library directories and updated run code to loop over files in sub-directories.
	2016-03-14 ( eshagdar ): first created.
*)

property debugMode : true

property LF : ASCII character 10
property tempFileName : "temp.applescript"
property mainFileName : "main.scpt"
property appName : "htcLib"
property appExtension : ".app"
property securityPrefPanePosix : "/System/Library/PreferencePanes/Security.prefPane"

on run prefs
	set defaultPrefs to {true}
	if class of prefs is script or prefs is equal to {} then set prefs to defaultPrefs
	set showDialogs to ((item 1 of prefs) as boolean)

	set folderName_library to "library:"
	set folderName_toSkip to "standalone"
	set fileNamePrefix_toSkip to "WIP_"

	set tempCode to ""
	set commentBreaker to "--------------------"
	set codeStart to commentBreaker & LF & "-- START OF CODE" & LF & commentBreaker
	set codeEnd to commentBreaker & LF & "-- END OF CODE" & LF & commentBreaker

	tell application "Finder"
		set pathRoot to (folder of (path to me)) as string
		set thisFileName to name of (path to me)
	end tell

	set pathTempCode to pathRoot & tempFileName
	set pathMain to pathRoot & mainFileName
	set pathApp to pathRoot & appName & appExtension
	set pathLibrary to pathRoot & folderName_library
	set libraryNames to list folder (pathLibrary) without invisibles

	-- loop over each sub-directory, appending code from each file
	repeat with dirCount from 1 to count of libraryNames
		set oneLibraryName to item dirCount of libraryNames
		set pathOneLibrary to pathLibrary & oneLibraryName
		if oneLibraryName is equal to folderName_toSkip then
			-- skip this folder because it contains standalone handlers
		else
			-- get all files in the the folder
			set fileNamesInOneLibrary to list folder (pathOneLibrary) without invisibles

			-- append all libraries into a single file
			repeat with fileCount from 1 to count of fileNamesInOneLibrary

				-- read one file and get everything above the helper methods
				set oneFileName to item fileCount of fileNamesInOneLibrary
				if oneFileName does not start with fileNamePrefix_toSkip then
					set pathOneFileinOneLibrary to pathOneLibrary & ":" & oneFileName
					set oneFileRawCode to read file pathOneFileinOneLibrary
					if oneFileRawCode contains codeStart and oneFileRawCode contains codeEnd then
						set oneHandlerCode to getTextBetween({oneFileRawCode, codeStart, codeEnd})
					else
						set oneHandlerCode to oneFileRawCode
					end if
					set oneHandlerCode to trimWhitespace(oneHandlerCode)

					-- now append
					if (length of tempCode) is greater than 0 then set tempCode to tempCode & return & return & return
					set tempCode to tempCode & oneHandlerCode
				end if
			end repeat
		end if
	end repeat

	-- prepend code with documentation
	set docCode to "-- main script"
	set docCode to docCode & LF & "-- Erik Shagdar, NYHTC"
	set docCode to docCode & LF
	set docCode to docCode & LF & "-- Generated: " & (do shell script "date '+%Y-%m-%d %T'")
	set docCode to docCode & LF & "-- Run " & quoted form of thisFileName & " to after making changes in any .applescript file and after each git pull."
	set docCode to docCode & LF & "-- Assumes file is located at '~/Code/applescript-fm-helper/'. If it is not, make sure to update clickCommandPosix property and 'vendor.sh' script."
	set docCode to docCode & LF
	set docCode to docCode & LF & "property DebugMode : " & debugMode
	set docCode to docCode & LF & "property ScriptName : \"" & appName & "\""
	set docCode to docCode & LF & "property clickCommandPosix : POSIX path of (((path to home folder) as string)) & \"Code/applescript-fm-helper/vendor/cliclick/cliclick\""

	set tempCode to docCode & LF & LF & LF & tempCode

	-- create a temp file of all libaries, then create a compiled version of it.
	--	do shell script "echo " & quoted form of tempCode & " > " & quoted form of POSIX path of pathTempCode

	try
		close access fileRef
	end try
	set fileRef to (open for access file pathTempCode with write permission)
	set eof of fileRef to 0 --> empty file contents if needed
	--> now write the flag
	--	write ((ASCII character 239) & (ASCII character 187) & (ASCII character 191)) to fileRef --> not as class utf8
	--> now write the data
	write tempCode to fileRef
	close access fileRef

	do shell script "osacompile -o " & quoted form of POSIX path of pathMain & " " & quoted form of POSIX path of pathTempCode
	do shell script "pwd"
	do shell script "sh " & quoted form of (POSIX path of (pathRoot & "vendor.sh"))
	if result does not contain "SUCCESS" then return "Error: unable to run vendor.sh"

	set appExists to false
	tell application "Finder"
		if exists pathApp then set appExists to true
	end tell

	--quit the pre-existing app
	if appExists then
		tell application appName to quit
	end if

	-- remove pre-existing app file
	tell application "Finder"
		if appExists then delete file pathApp
	end tell

	-- now make it into an app
	do shell script "osacompile -s -o " & quoted form of POSIX path of pathApp & " " & quoted form of POSIX path of pathTempCode

	-- remove the temp file
	tell application "Finder"
		if exists pathTempCode then delete file pathTempCode
	end tell

	if showDialogs then
		tell it to activate
		set AsstAccessDlg to display dialog "You must enable assistive access for " & appName & "." with title appName buttons {"Open", "OK"} default button "OK"

		-- navigate to security preference pane
		if button returned of AsstAccessDlg is equal to "Open" then

			tell application "System Preferences" to activate
			do shell script "open " & quoted form of securityPrefPanePosix

			tell application "System Events"
				tell process "System Preferences"
					click radio button "Privacy" of tab group 1 of window 1

					-- get htcLib checkbox
					set htcLibRow to (first row of table 1 of scroll area 1 of group 1 of tab group 1 of window 1 whose value of static text 1 of UI element 1 contains "htcLib")
					set htcLibCheckbox to checkbox 1 of UI element 1 of htcLibRow
					select htcLibRow

					-- unlock if needed
					set canMakeChanges to enabled of htcLibCheckbox
					if canMakeChanges is false then
						click button 1 of window 1
						display dialog "You must deselect, then reselect the HtcLib checkbox" buttons "OK" default button "OK"
						return true
					end if

					-- uncheck, then recheck to re-allow control of htcLib
					click htcLibCheckbox
					delay 0.5
					click htcLibCheckbox
					delay 0.5
					set visible to false
				end tell
			end tell

			tell me to activate
			display dialog "HtcLib is ready" buttons "OK" default button "OK"
		end if
		return true
	else

		tell application "System Preferences" to activate
		do shell script "open " & quoted form of securityPrefPanePosix

		return "you must re-allow assistive devices to '" & appName & "'."

	end if

end run

--------------------
-- HELPER FUNCTIONS
--------------------

on parentFolderOfPath(incomingPath)
	--version 1.1, Daniel A. Shockley

	set incomingPath to incomingPath as string
	if incomingPath is "" then
		error "Cannot find a parent folder for a path that is blank." number -1027
	end if

	if last character of incomingPath is ":" then
		-- if it ends with ":" (a folder), leave that off for the code below
		set incomingPath to (text 1 through -2 of incomingPath) as string
	end if

	set {od, AppleScript's text item delimiters} to {AppleScript's text item delimiters, ":"}
	if (count of text items of incomingPath) is 1 then
		-- the item in question is a disk, so CANNOT return a parent folder
		set AppleScript's text item delimiters to od
		error "Cannot find a parent folder of a DISK: " & incomingPath & "." number -1027
	else
		set enclosingFolder to (text items 1 through -2 of incomingPath as string)
	end if

	set AppleScript's text item delimiters to od
	return enclosingFolder & ":"

end parentFolderOfPath

on getTextBetween(prefs)
	-- version 1.6, Daniel A. Shockley <http://www.danshockley.com>

	set defaultPrefs to {textItemNum:2, includeMarkers:false}

	if (class of prefs is not list) and ((class of prefs) as string is not "record") then
		error "getTextBetween FAILED: parameter should be a record or list. If it is multiple items, just make it into a list to upgrade to this handler." number 1024
	end if
	if class of prefs is list then
		if (count of prefs) is 4 then
			set textItemNum of defaultPrefs to item 4 of prefs
		end if
		set prefs to {sourceTEXT:item 1 of prefs, beforeText:item 2 of prefs, afterText:item 3 of prefs}
	end if
	set prefs to prefs & defaultPrefs -- add on default preferences, if needed
	set sourceTEXT to sourceTEXT of prefs
	set beforeText to beforeText of prefs
	set afterText to afterText of prefs
	set textItemNum to textItemNum of prefs
	set includeMarkers to includeMarkers of prefs

	try
		set {oldDelims, AppleScript's text item delimiters} to {AppleScript's text item delimiters, beforeText}
		set the prefixRemoved to text item textItemNum of sourceTEXT
		set AppleScript's text item delimiters to afterText
		set the finalResult to text item 1 of prefixRemoved
		set AppleScript's text item delimiters to oldDelims

		if includeMarkers then set finalResult to beforeText & finalResult & afterText

	on error errMsg number errNum
		set AppleScript's text item delimiters to oldDelims
		-- 	tell me to log "Error in getTextBetween() : " & errMsg
		set the finalResult to "" -- return nothing if the surrounding text is not found
	end try

	return finalResult

end getTextBetween

on trimWhitespace(inputString)
	-- version 1.2:

	set whiteSpaceAsciiNumbers to {13, 10, 32, 9} -- characters that count as whitespace.

	set textLength to length of inputString
	if textLength is 0 then return ""
	set endSpot to -textLength -- if only whitespace is found, will chop whole string

	-- chop from end
	set i to -1
	repeat while -i is less than or equal to textLength
		set testChar to text i thru i of inputString
		if whiteSpaceAsciiNumbers does not contain (ASCII number testChar) then
			set endSpot to i
			exit repeat
		end if
		set i to i - 1
	end repeat

	if -endSpot is equal to textLength then
		if whiteSpaceAsciiNumbers contains (ASCII number testChar) then return ""
	end if

	set inputString to text 1 thru endSpot of inputString
	set textLength to length of inputString
	set newStart to 1

	-- chop from beginning
	set i to 1
	repeat while i is less than or equal to textLength
		set testChar to text i thru i of inputString
		if whiteSpaceAsciiNumbers does not contain (ASCII number testChar) then
			set newStart to i
			exit repeat
		end if
		set i to i + 1
	end repeat

	set inputString to text newStart thru textLength of inputString

	return inputString

end trimWhitespace

-- main_helper
-- Erik Shagdar, NYHTC
-- Helper script that compiles all .applescript files into a main.scpt.

(* HISTORY:
	2017-12-18 ( eshagdar ): skip files whose name begins wtih 'WIP_' ( work in progress ).
	2017-11-14 ( dshockley ): open system preference pane even from command line.
	2017-10-20 ( eshagdar ): allow running with params. If ran with 'False', dialogs ( and re-enabling assistve devices ) is suppressed.
	2017-10-18 ( eshagdar ): debugMode is a property. htcLib scriptName is 'htcLib', not 'main.scpt'.
	2017-10-06 ( eshagdar ): added library folder to skip when generating htcLib. renamed variables for clarity.
	2017-09-12 ( eshagdar ): attempt to de-select and re-select the htcLib checkbox.
	2017-06-29 ( eshagdar ): check to see if htcLib exists.
	2017-06-26 ( eshagdar ): quit the app before deleting it.
	2017-06-14 ( eshagdar ): also make an app.
	2016-04-21 ( eshagdar ): Updated clickCommandPosix path.
	2016-03-17 ( eshagdar ): Added DebugMode and clickCommandPosix properties.
	2016-03-15 ( eshagdar ): added documentation to main script. Separated individual functions into library directories and updated run code to loop over files in sub-directories.
	2016-03-14 ( eshagdar ): first created.
*)

property debugMode : true

property LF : ASCII character 10
property tempFileName : "temp.applescript"
property mainFileName : "main.scpt"
property appName : "htcLib"
property appExtension : ".app"
property securityPrefPanePosix : "/System/Library/PreferencePanes/Security.prefPane"

on run prefs
	set defaultPrefs to {true}
	if class of prefs is script or prefs is equal to {} then set prefs to defaultPrefs
	set showDialogs to ((item 1 of prefs) as boolean)

	set folderName_library to "library:"
	set folderName_toSkip to "standalone"
	set fileNamePrefix_toSkip to "WIP_"

	set tempCode to ""
	set commentBreaker to "--------------------"
	set codeStart to commentBreaker & LF & "-- START OF CODE" & LF & commentBreaker
	set codeEnd to commentBreaker & LF & "-- END OF CODE" & LF & commentBreaker

	tell application "Finder"
		set pathRoot to (folder of (path to me)) as string
		set thisFileName to name of (path to me)
	end tell

	set pathTempCode to pathRoot & tempFileName
	set pathMain to pathRoot & mainFileName
	set pathApp to pathRoot & appName & appExtension
	set pathLibrary to pathRoot & folderName_library
	set libraryNames to list folder (pathLibrary) without invisibles

	-- loop over each sub-directory, appending code from each file
	repeat with dirCount from 1 to count of libraryNames
		set oneLibraryName to item dirCount of libraryNames
		set pathOneLibrary to pathLibrary & oneLibraryName
		if oneLibraryName is equal to folderName_toSkip then
			-- skip this folder because it contains standalone handlers
		else
			-- get all files in the the folder
			set fileNamesInOneLibrary to list folder (pathOneLibrary) without invisibles

			-- append all libraries into a single file
			repeat with fileCount from 1 to count of fileNamesInOneLibrary

				-- read one file and get everything above the helper methods
				set oneFileName to item fileCount of fileNamesInOneLibrary
				if oneFileName does not start with fileNamePrefix_toSkip then
					set pathOneFileinOneLibrary to pathOneLibrary & ":" & oneFileName
					set oneFileRawCode to read file pathOneFileinOneLibrary
					if oneFileRawCode contains codeStart and oneFileRawCode contains codeEnd then
						set oneHandlerCode to getTextBetween({oneFileRawCode, codeStart, codeEnd})
					else
						set oneHandlerCode to oneFileRawCode
					end if
					set oneHandlerCode to trimWhitespace(oneHandlerCode)

					-- now append
					if (length of tempCode) is greater than 0 then set tempCode to tempCode & return & return & return
					set tempCode to tempCode & oneHandlerCode
				end if
			end repeat
		end if
	end repeat

	-- prepend code with documentation
	set docCode to "-- main script"
	set docCode to docCode & LF & "-- Erik Shagdar, NYHTC"
	set docCode to docCode & LF
	set docCode to docCode & LF & "-- Generated: " & (do shell script "date '+%Y-%m-%d %T'")
	set docCode to docCode & LF & "-- Run " & quoted form of thisFileName & " to after making changes in any .applescript file and after each git pull."
	set docCode to docCode & LF & "-- Assumes file is located at '~/Code/applescript-fm-helper/'. If it is not, make sure to update clickCommandPosix property and 'vendor.sh' script."
	set docCode to docCode & LF
	set docCode to docCode & LF & "property DebugMode : " & debugMode
	set docCode to docCode & LF & "property ScriptName : \"" & appName & "\""
	set docCode to docCode & LF & "property clickCommandPosix : POSIX path of (((path to home folder) as string)) & \"Code/applescript-fm-helper/vendor/cliclick/cliclick\""

	set tempCode to docCode & LF & LF & LF & tempCode

	-- create a temp file of all libaries, then create a compiled version of it.
	do shell script "echo " & quoted form of tempCode & " > " & quoted form of POSIX path of pathTempCode
	do shell script "osacompile -o " & quoted form of POSIX path of pathMain & " " & quoted form of POSIX path of pathTempCode
	do shell script "pwd"
	do shell script "sh " & quoted form of (POSIX path of (pathRoot & "vendor.sh"))
	if result does not contain "SUCCESS" then return "Error: unable to run vendor.sh"

	set appExists to false
	tell application "Finder"
		if exists pathApp then set appExists to true
	end tell

	--quit the pre-existing app
	if appExists then
		tell application appName to quit
	end if

	-- remove pre-existing app file
	tell application "Finder"
		if appExists then delete file pathApp
	end tell

	-- now make it into an app
	do shell script "osacompile -s -o " & quoted form of POSIX path of pathApp & " " & quoted form of POSIX path of pathTempCode

	-- remove the temp file
	tell application "Finder"
		if exists pathTempCode then delete file pathTempCode
	end tell

	if showDialogs then
		tell it to activate
		set AsstAccessDlg to display dialog "You must enable assistive access for " & appName & "." with title appName buttons {"Open", "OK"} default button "OK"

		-- navigate to security preference pane
		if button returned of AsstAccessDlg is equal to "Open" then

			tell application "System Preferences" to activate
			do shell script "open " & quoted form of securityPrefPanePosix

			tell application "System Events"
				tell process "System Preferences"
					click radio button "Privacy" of tab group 1 of window 1

					-- get htcLib checkbox
					set htcLibRow to (first row of table 1 of scroll area 1 of group 1 of tab group 1 of window 1 whose value of static text 1 of UI element 1 contains "htcLib")
					set htcLibCheckbox to checkbox 1 of UI element 1 of htcLibRow
					select htcLibRow

					-- unlock if needed
					set canMakeChanges to enabled of htcLibCheckbox
					if canMakeChanges is false then
						click button 1 of window 1
						display dialog "You must deselect, then reselect the HtcLib checkbox" buttons "OK" default button "OK"
						return true
					end if

					-- uncheck, then recheck to re-allow control of htcLib
					click htcLibCheckbox
					delay 0.5
					click htcLibCheckbox
					delay 0.5
					set visible to false
				end tell
			end tell

			tell me to activate
			display dialog "HtcLib is ready" buttons "OK" default button "OK"
		end if
		return true
	else

		tell application "System Preferences" to activate
		do shell script "open " & quoted form of securityPrefPanePosix

		return "you must re-allow assistive devices to '" & appName & "'."

	end if

end run

--------------------
-- HELPER FUNCTIONS
--------------------

on parentFolderOfPath(incomingPath)
	--version 1.1, Daniel A. Shockley

	set incomingPath to incomingPath as string
	if incomingPath is "" then
		error "Cannot find a parent folder for a path that is blank." number -1027
	end if

	if last character of incomingPath is ":" then
		-- if it ends with ":" (a folder), leave that off for the code below
		set incomingPath to (text 1 through -2 of incomingPath) as string
	end if

	set {od, AppleScript's text item delimiters} to {AppleScript's text item delimiters, ":"}
	if (count of text items of incomingPath) is 1 then
		-- the item in question is a disk, so CANNOT return a parent folder
		set AppleScript's text item delimiters to od
		error "Cannot find a parent folder of a DISK: " & incomingPath & "." number -1027
	else
		set enclosingFolder to (text items 1 through -2 of incomingPath as string)
	end if

	set AppleScript's text item delimiters to od
	return enclosingFolder & ":"

end parentFolderOfPath

on getTextBetween(prefs)
	-- version 1.6, Daniel A. Shockley <http://www.danshockley.com>

	set defaultPrefs to {textItemNum:2, includeMarkers:false}

	if (class of prefs is not list) and ((class of prefs) as string is not "record") then
		error "getTextBetween FAILED: parameter should be a record or list. If it is multiple items, just make it into a list to upgrade to this handler." number 1024
	end if
	if class of prefs is list then
		if (count of prefs) is 4 then
			set textItemNum of defaultPrefs to item 4 of prefs
		end if
		set prefs to {sourceTEXT:item 1 of prefs, beforeText:item 2 of prefs, afterText:item 3 of prefs}
	end if
	set prefs to prefs & defaultPrefs -- add on default preferences, if needed
	set sourceTEXT to sourceTEXT of prefs
	set beforeText to beforeText of prefs
	set afterText to afterText of prefs
	set textItemNum to textItemNum of prefs
	set includeMarkers to includeMarkers of prefs

	try
		set {oldDelims, AppleScript's text item delimiters} to {AppleScript's text item delimiters, beforeText}
		set the prefixRemoved to text item textItemNum of sourceTEXT
		set AppleScript's text item delimiters to afterText
		set the finalResult to text item 1 of prefixRemoved
		set AppleScript's text item delimiters to oldDelims

		if includeMarkers then set finalResult to beforeText & finalResult & afterText

	on error errMsg number errNum
		set AppleScript's text item delimiters to oldDelims
		-- 	tell me to log "Error in getTextBetween() : " & errMsg
		set the finalResult to "" -- return nothing if the surrounding text is not found
	end try

	return finalResult

end getTextBetween

on trimWhitespace(inputString)
	-- version 1.2:

	set whiteSpaceAsciiNumbers to {13, 10, 32, 9} -- characters that count as whitespace.

	set textLength to length of inputString
	if textLength is 0 then return ""
	set endSpot to -textLength -- if only whitespace is found, will chop whole string

	-- chop from end
	set i to -1
	repeat while -i is less than or equal to textLength
		set testChar to text i thru i of inputString
		if whiteSpaceAsciiNumbers does not contain (ASCII number testChar) then
			set endSpot to i
			exit repeat
		end if
		set i to i - 1
	end repeat

	if -endSpot is equal to textLength then
		if whiteSpaceAsciiNumbers contains (ASCII number testChar) then return ""
	end if

	set inputString to text 1 thru endSpot of inputString
	set textLength to length of inputString
	set newStart to 1

	-- chop from beginning
	set i to 1
	repeat while i is less than or equal to textLength
		set testChar to text i thru i of inputString
		if whiteSpaceAsciiNumbers does not contain (ASCII number testChar) then
			set newStart to i
			exit repeat
		end if
		set i to i + 1
	end repeat

	set inputString to text newStart thru textLength of inputString

	return inputString

end trimWhitespace


Split start and next actions

Split start and next actions

FasdUAS 1.101.10
lB
ZB
=
n

1

prun
mkeynalis2OS$NH+=b0Keynote.app	 Applications$.i=b0OS:Applications:Keynote.appKeynote.appOSApplications/Keynote.app/
	m
boovtrue
O=

Z<
=
1

Plng
m
boovtrue
k
I
.KntcsteFnullnull
L
m
boovtrue
k<
I$
.miscactvnullnull
Q%<
k(3 !
 I(0"
.KnstplaYnulldocu
"l(,#
#4(,$

docu
$m*+!%
%L13&
&m12
boovtrue
R
.ascrerr ********
m	''keynalis2OS$NH+=b0Keynote.app	 Applications$.i=b0OS:Applications:Keynote.appKeynote.appOSApplications/Keynote.app/
L@B(
(m@A
boovfals)*)
.aevtoappnull*****+,-
.aevtoappnull****
+kB..,-

prun

Plng
.KntcsteFnullnull
.miscactvnullnull

docu
.KnstplaYnulldocuC,e:2*,e
*jOeY*jO*k/jOeWXhUYfascrޭ


[#2]: Fix broken javascript calls

[#2]: Fix broken javascript calls

At some point, using $() seems to have broken in Chrome. Replaced those
calls with equivalent DOM calls in vanilla Javascript.

on alfred_script(q)

    set AppleScript's text item delimiters to {" "}

    tell application "Google Chrome"

        if q is "" or q is "p" or q is "pp" or q is "play" or q is "pause" then
            set execCode to "document.getElementsByClassName('play')[0].click()"
        else if q is "next" or q is "skip" or q is "n" then
            set execCode to "document.getElementsByClassName('next')[0].click()"
        else
            set argList to every text item of q
            if item 1 of argList is "genre" then
                set execCode to "document.querySelectorAll('li.genre a')[" & item 2 of argList & "].click();"
            end if
        end if

        set seenPlayerTab to 0

        set thisWindowIndex to 1
        repeat with thisWindow in windows

            set thisTabIndex to 1
            repeat with thisTab in tabs of thisWindow

                if URL of thisTab starts with "https://www.focusatwill.com/" then
                    set seenPlayerTab to 1
                    exit repeat
                end if

                set thisTabIndex to thisTabIndex + 1

            end repeat

            if seenPlayerTab is greater than 0 then
                tell tab thisTabIndex of window thisWindowIndex
                    execute javascript execCode
                end tell
                exit repeat
            end if

            set thisWindowIndex to thisWindowIndex + 1

        end repeat

        if seenPlayerTab is 0 then
            set newTab to make new tab at end of tabs of window 1
            set URL of newTab to "https://www.focusatwill.com/music/#player"
            delay 5
            tell newTab
                execute javascript execCode
            end tell
        end if

    end tell
end alfred_script

on alfred_script(q)

    set AppleScript's text item delimiters to {" "}

    tell application "Google Chrome"

        if q is "" or q is "p" or q is "pp" or q is "play" or q is "pause" then
            set buttonClass to "play"
            set execCode to "$('." & buttonClass & "').first().click()"
        else if q is "next" or q is "skip" or q is "n" then
            set buttonClass to "next"
            set execCode to "$('." & buttonClass & "').first().click()"
        else
            set argList to every text item of q
            if item 1 of argList is "genre" then
                set execCode to "$('li.genre a')[" & item 2 of argList & "].click();"
            end if
        end if

        set seenPlayerTab to 0

        set thisWindowIndex to 1
        repeat with thisWindow in windows

            set thisTabIndex to 1
            repeat with thisTab in tabs of thisWindow

                if URL of thisTab starts with "https://www.focusatwill.com/" then
                    set seenPlayerTab to 1
                    exit repeat
                end if

                set thisTabIndex to thisTabIndex + 1

            end repeat

            if seenPlayerTab is greater than 0 then
                tell tab thisTabIndex of window thisWindowIndex
                    execute javascript execCode
                end tell
                exit repeat
            end if

            set thisWindowIndex to thisWindowIndex + 1

        end repeat

        if seenPlayerTab is 0 then
            set newTab to make new tab at end of tabs of window 1
            set URL of newTab to "https://www.focusatwill.com/music/#player"
            delay 5
            tell newTab
                execute javascript execCode
            end tell
        end if

    end tell
end alfred_script


removing BeatSecurityAgent script

removing BeatSecurityAgent script

This is no longer needed because we no longer fill out the security
prompts using applescript ui automation

-- Examples:
-- $ osascript BeatSecurityAgent.applescript jason s3cr3t

on run argv
    set the_username to item 1 of argv
    set the_password to item 2 of argv

    repeat
        try
            set procs to ""
            tell application "System Events"
                set procs to name of every process
            end tell
            if procs contains "SecurityAgent" then
                tell application "System Events"
                    tell process "SecurityAgent" to set value of text field 1 of scroll area 1 of group 1 of window 1 to the_username
                    tell process "SecurityAgent" to set value of text field 2 of scroll area 1 of group 1 of window 1 to the_password
                    click button 2 of group 2 of window 1 of application process "SecurityAgent"
                    log ("Dismissed Security Dialog")
                end tell
            end if
        end try
        delay 1
    end repeat
end run


removed unused code in fmClip - Button Info from Clipboard

Scripts/fmClip - Button Info from Clipboard.applescript