updated fmGUI_ScriptDebugger_Close to handle MBS Copy Script Text feature

-- fmGUI_ScriptDebugger_Close()
-- Daniel A. Shockley, NYHTC
-- Closes FileMaker's Script Debugger window

(*
HISTORY:
	2020-03-04 ( dshockley ): First created.

REQUIRES:
	fmGUI_AppFrontMost
*)

on run
	fmGUI_ScriptDebugger_Close()
end run

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

on fmGUI_ScriptDebugger_Close()
	-- version 2020-03-04

	fmGUI_AppFrontMost()
	tell application "System Events"
		tell process "FileMaker Pro Advanced"

			try
				(*
				If the MBS Plugin is installed and the "Copy Script Text" feature is enabled,
				that is the 1st button, so get the first one after that. If it does not exist, this still works.
				*)
				click (first button of (first window whose name is "Script Debugger") whose name is not "Copy Script Text")
			end try
			return true

		end tell
	end tell
end fmGUI_ScriptDebugger_Close

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

on fmGUI_AppFrontMost()
	tell application "htcLib" to fmGUI_AppFrontMost()
end fmGUI_AppFrontMost

-- fmGUI_ScriptDebugger_Close()
-- Daniel A. Shockley, NYHTC
-- Closes FileMaker's Script Debugger window

(*
HISTORY:
	2020-03-04 ( dshockley ): First created.

REQUIRES:
	fmGUI_AppFrontMost
*)

on run
	fmGUI_ScriptDebugger_Close()
end run

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

on fmGUI_ScriptDebugger_Close()
	-- version 2020-03-04

	fmGUI_AppFrontMost()
	tell application "System Events"
		tell process "FileMaker Pro Advanced"
			try
				click button 1 of (first window whose name is "Script Debugger")
			end try
			return true
		end tell
	end tell
end fmGUI_ScriptDebugger_Close

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

on fmGUI_AppFrontMost()
	tell application "htcLib" to fmGUI_AppFrontMost()
end fmGUI_AppFrontMost


minor fix

minor fix

-- fmGUI_ManageLayouts_Layout_CreateOrUpdate({layoutName:null})
-- Daniel A. Shockley, NYHTC
-- Create/Update a layout.

(*
HISTORY:
	2020-03-03 ( dshockley, hdu ): Updated as standalone function for fm-scripts git repository. Use clickObjectByCoords instead of clickObjFromHtcLib.
	-- 1.4 - 2017-06-14 ( eshagdar ): narrowed scope
	-- 1.3 - 2017-05-18 ( eshagdar ): updated for FM15.
	-- 1.2 - 2016-08-24 ( eshagdar ): wait until 'Layout Setup' window comes up.
	-- 1.1 - 2013-11-22 ( dshockley ): If oldLayoutName is specified, will look for and change layout name, even if otherwise doNotChangeExisting.

	-- TODO: NOT HANDLING SCRIPT TRIGGERS YET!!! 2013-11-20-dshockley

REQUIRES:
	clickObjectByCoords
	logConsole
	fmGUI_CheckboxSet
	fmGUI_DataViewer_Close
	fmGUI_ManageLayouts_LayoutFolderSelect
	fmGUI_ManageLayouts_Open
	fmGUI_ManageLayouts_PopupNewItemOfType
	fmGUI_ManageLayouts_Select
	fmGUI_PopupSet
	windowWaitUntil_FrontIS
*)

on run
	fmGUI_ManageLayouts_Layout_CreateOrUpdate({layoutName:"Directory"})
end run

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

on fmGUI_ManageLayouts_Layout_CreateOrUpdate(layoutOptions)
	-- version 1.4

	set defaultPrefs to {layoutName:null, oldLayoutName:null, doNotChangeExisting:false, baseTableName:null, layoutParentFolder:"", includeInLayoutMenus:0, menuSet:null, formViewEnabled:1, listViewEnabled:1, tableViewEnabled:1, defaultView:"Form View", scriptTriggers:{}}

	set layoutOptions to layoutOptions & defaultPrefs

	set layoutName to layoutName of layoutOptions
	set oldLayoutName to oldLayoutName of layoutOptions

	-- Select a Layout and Edit it, or create it if it didn't exist yet.
	try
		fmGUI_DataViewer_Close()
		fmGUI_ManageLayouts_Open({})

		-- INIT:
		set foundThisLayout to false
		set foundOldLayout to false
		set layoutSelected to false

		set foundThisLayout to fmGUI_ManageLayouts_Select({layoutName:layoutName})
		set layoutSelected to foundThisLayout

		if oldLayoutName is not null then
			set foundOldLayout to fmGUI_ManageLayouts_Select({layoutName:oldLayoutName})
			if foundThisLayout and foundOldLayout then
				error "Couldn't fmGUI_ManageLayouts_Layout_CreateOrUpdate: Both the old '" & oldLayoutName & "' and the 'new' layout name '" & layoutName & "' already exist - PROBLEM!"
			else if foundOldLayout then
				set layoutSelected to true
			end if

		end if

		tell application "System Events"
			tell application process "FileMaker Pro Advanced"
				set manageLayoutsWindow to window 1
			end tell
		end tell

		if layoutSelected then
			if doNotChangeExisting of layoutOptions and not foundOldLayout then
				-- do NOT change if it already exists with the correct name.
			else
				-- exists and was selected, so click Edit:

				tell application "System Events"
					tell application process "FileMaker Pro Advanced"
						set buttonRef to first button of manageLayoutsWindow whose title is "Edit"
					end tell
				end tell

				clickObjectByCoords(buttonRef)
				windowWaitUntil_FrontIS({windowName:"Layout Setup"})

				tell application "System Events"
					tell application process "FileMaker Pro Advanced"
						set layoutSetupDialog to window 1
						set interfaceParent to tab group 1 of layoutSetupDialog

						if foundOldLayout then
							-- need to rename this layout:
							set value of text field "Layout Name" of interfaceParent to layoutName
						end if
					end tell
				end tell

				if doNotChangeExisting of layoutOptions then

				else -- ALLOWED to CHANGE the other properties of the layout:
					tell application "System Events"
						tell application process "FileMaker Pro Advanced"
							click (first radio button of interfaceParent whose name is "General")
							set showRecordsButton to pop up button "Show records from:" of interfaceParent
							set inludeInMenuButton to checkbox "Include in layout menus" of interfaceParent
							set menuSetButton to pop up button "Menu Set:" of interfaceParent
						end tell
					end tell

					if baseTableName of layoutOptions is not null then fmGUI_PopupSet({objRef:my coerceToString(showRecordsButton), objValue:baseTableName of layoutOptions})
					if includeInLayoutMenus of layoutOptions is not null then fmGUI_CheckboxSet(inludeInMenuButton, includeInLayoutMenus of layoutOptions)
					if menuSet of layoutOptions is not null then fmGUI_PopupSet({objRef:my coerceToString(menuSetButton), objValue:menuSet of layoutOptions})

					tell application "System Events"
						tell application process "FileMaker Pro Advanced"
							click (first radio button of interfaceParent whose name is "Views")
							set formCheckbox to checkbox "Form View" of interfaceParent
							set listCheckbox to checkbox "List View" of interfaceParent
							set tableCheckbox to checkbox "Table View" of interfaceParent
							set defaultButton to pop up button "Default view:" of interfaceParent
						end tell
					end tell

					if formViewEnabled of layoutOptions is not null then fmGUI_CheckboxSet(formCheckbox, formViewEnabled of layoutOptions)
					if listViewEnabled of layoutOptions is not null then fmGUI_CheckboxSet(listCheckbox, listViewEnabled of layoutOptions)
					if tableViewEnabled of layoutOptions is not null then fmGUI_CheckboxSet(tableCheckbox, tableViewEnabled of layoutOptions)
					if defaultView of layoutOptions is not null then fmGUI_PopupSet({objRef:my coerceToString(defaultButton), objValue:defaultView of layoutOptions})

				end if

				tell application "System Events"
					tell application process "FileMaker Pro Advanced"
						click button "OK" of layoutSetupDialog
					end tell
				end tell
			end if

			-- END IF: existing to edit.

		else
			-- BEGIN: does not exist - need to create it:

			if length of (layoutParentFolder of layoutOptions) is greater than 0 then
				-- create it IN a layout folder:
				-- Select the folder, or create it if it doesn't exist yet:
				if not fmGUI_ManageLayouts_LayoutFolderSelect(layoutParentFolder of layoutOptions) then
					fmGUI_ManageLayouts_PopupNewItemOfType("Folder")
					tell application "System Events"
						tell application process "FileMaker Pro Advanced"
							set value of text field "Folder Name:" of window 1 to layoutParentFolder of layoutOptions
							click button "OK" of window 1
							set newFolderRow to first row of (outline 1 of scroll area 1 of manageLayoutsWindow) whose value of text field 1 of group 1 is layoutParentFolder of layoutOptions
							set checkboxRef to checkbox 1 of newFolderRow
						end tell
					end tell
					fmGUI_CheckboxSet(checkboxRef, 1)

				end if
			end if

			-- Create the layout:
			if debugMode then tell application "htcLib" to logConsole(ScriptName, "creating layout: " & (layoutName of layoutOptions))
			tell application "System Events"
				tell application process "FileMaker Pro Advanced"
					set buttonRef to first button of manageLayoutsWindow whose title is "New"
				end tell
			end tell

			-- BEGIN: NEW WINDOW CODE
			clickObjFromHtcLib(buttonRef)
			tell application "htcLib" to windowWaitUntil_FrontIS({windowName:"New Layout/Report"})

			tell application "System Events"
				tell application process "FileMaker Pro Advanced"
					set newLayoutDialog to window 1
					set value of text field 1 of newLayoutDialog to layoutName of layoutOptions
					set buttonRef to pop up button 1 of newLayoutDialog
				end tell
			end tell
			tell application "htcLib" to fmGUI_PopupSet({objRef:my coerceToString(buttonRef), objValue:baseTableName of layoutOptions})
			tell application "System Events"
				tell application process "FileMaker Pro Advanced"
					click button 4 of newLayoutDialog -- select 'Computer'
					click button 6 of newLayoutDialog -- select 'Form'

					-- we don't care which mode to view in, so Finish:
					click button "Finish" of newLayoutDialog
				end tell
			end tell

			delay 1

			-- Now, believe it or not, need to call ITSELF since not all options available during Create:
			fmGUI_ManageLayouts_Layout_CreateOrUpdate(layoutOptions)

			-- END IF: does not exist - need to create it.
		end if

		return true
	on error errMsg number errNum
		error "unable to fmGUI_ManageLayouts_Layout_CreateOrUpdate '" & layoutName of layoutOptions & "' - " & errMsg number errNum
	end try

end fmGUI_ManageLayouts_Layout_CreateOrUpdate

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

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

on fmGUI_CheckboxSet(prefs)
	set objRefStr to coerceToString(objRef of prefs)
	tell application "htcLib" to fmGUI_CheckboxSet({objRef:objRefStr} & prefs)
end fmGUI_CheckboxSet

on fmGUI_DataViewer_Close()
	tell application "htcLib" to fmGUI_DataViewer_Close()
end fmGUI_DataViewer_Close

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

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

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

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

on fmGUI_PopupSet(prefs)
	set objRefStr to coerceToString(objRef of prefs)
	tell application "htcLib" to fmGUI_PopupSet({objRef:objRefStr} & prefs)
end fmGUI_PopupSet

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

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

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

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

-- fmGUI_ManageLayouts_Layout_CreateOrUpdate({layoutName:null})
-- Daniel A. Shockley, NYHTC
-- Create/Update a layout.

(*
HISTORY:
	2020-03-03 ( dshockley, hdu ): Updated as standalone function for fm-scripts git repository. Use clickObjectByCoords instead of clickObjFromHtcLib.
	-- 1.4 - 2017-06-14 ( eshagdar ): narrowed scope
	-- 1.3 - 2017-05-18 ( eshagdar ): updated for FM15.
	-- 1.2 - 2016-08-24 ( eshagdar ): wait until 'Layout Setup' window comes up.
	-- 1.1 - 2013-11-22 ( dshockley ): If oldLayoutName is specified, will look for and change layout name, even if otherwise doNotChangeExisting.

	-- TODO: NOT HANDLING SCRIPT TRIGGERS YET!!! 2013-11-20-dshockley

REQUIRES:
	clickObjectByCoords
	logConsole
	fmGUI_CheckboxSet
	fmGUI_DataViewer_Close
	fmGUI_ManageLayouts_LayoutFolderSelect
	fmGUI_ManageLayouts_Open
	fmGUI_ManageLayouts_PopupNewItemOfType
	fmGUI_ManageLayouts_Select
	fmGUI_PopupSet
	windowWaitUntil_FrontIS
*)

on run
	fmGUI_ManageLayouts_Layout_CreateOrUpdate({layoutName:"Directory"})
end run

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

on fmGUI_ManageLayouts_Layout_CreateOrUpdate(layoutOptions)
	-- version 1.4

	set defaultPrefs to {layoutName:null, oldLayoutName:null, doNotChangeExisting:false, baseTableName:null, layoutParentFolder:"", includeInLayoutMenus:0, menuSet:null, formViewEnabled:1, listViewEnabled:1, tableViewEnabled:1, defaultView:"Form View", scriptTriggers:{}}

	set layoutOptions to layoutOptions & defaultPrefs

	set layoutName to layoutName of layoutOptions
	set oldLayoutName to oldLayoutName of layoutOptions

	-- Select a Layout and Edit it, or create it if it didn't exist yet.
	try
		fmGUI_DataViewer_Close()
		fmGUI_ManageLayouts_Open({})

		-- INIT:
		set foundThisLayout to false
		set foundOldLayout to false
		set layoutSelected to false

		set foundThisLayout to fmGUI_ManageLayouts_Select({layoutName:layoutName})
		set layoutSelected to foundThisLayout

		if oldLayoutName is not null then
			set foundOldLayout to fmGUI_ManageLayouts_Select({layoutName:oldLayoutName})
			if foundThisLayout and foundOldLayout then
				error "Couldn't fmGUI_ManageLayouts_Layout_CreateOrUpdate: Both the old '" & oldLayoutName & "' and the 'new' layout name '" & layoutName & "' already exist - PROBLEM!"
			else if foundOldLayout then
				set layoutSelected to true
			end if

		end if

		tell application "System Events"
			tell application process "FileMaker Pro Advanced"
				set manageLayoutsWindow to window 1
			end tell
		end tell

		if layoutSelected then
			if doNotChangeExisting of layoutOptions and not foundOldLayout then
				-- do NOT change if it already exists with the correct name.
			else
				-- exists and was selected, so click Edit:

				tell application "System Events"
					tell application process "FileMaker Pro Advanced"
						set buttonRef to first button of manageLayoutsWindow whose title is "Edit"
					end tell
				end tell

				clickObjectByCoords(buttonRef)
				windowWaitUntil_FrontIS({windowName:"Layout Setup"})

				tell application "System Events"
					tell application process "FileMaker Pro Advanced"
						set layoutSetupDialog to window 1
						set interfaceParent to tab group 1 of layoutSetupDialog

						if foundOldLayout then
							-- need to rename this layout:
							set value of text field "Layout Name" of interfaceParent to layoutName
						end if
					end tell
				end tell

				if doNotChangeExisting of layoutOptions then

				else -- ALLOWED to CHANGE the other properties of the layout:
					tell application "System Events"
						tell application process "FileMaker Pro Advanced"
							click (first radio button of interfaceParent whose name is "General")
							set showRecordsButton to pop up button "Show records from:" of interfaceParent
							set inludeInMenuButton to checkbox "Include in layout menus" of interfaceParent
							set menuSetButton to pop up button "Menu Set:" of interfaceParent
						end tell
					end tell

					if baseTableName of layoutOptions is not null then fmGUI_PopupSet({objRef:my coerceToString(showRecordsButton), objValue:baseTableName of layoutOptions})
					if includeInLayoutMenus of layoutOptions is not null then fmGUI_CheckboxSet(inludeInMenuButton, includeInLayoutMenus of layoutOptions)
					if menuSet of layoutOptions is not null then fmGUI_PopupSet({objRef:my coerceToString(menuSetButton), objValue:menuSet of layoutOptions})

					tell application "System Events"
						tell application process "FileMaker Pro Advanced"
							click (first radio button of interfaceParent whose name is "Views")
							set formCheckbox to checkbox "Form View" of interfaceParent
							set listCheckbox to checkbox "List View" of interfaceParent
							set tableCheckbox to checkbox "Table View" of interfaceParent
							set defaultButton to pop up button "Default view:" of interfaceParent
						end tell
					end tell

					if formViewEnabled of layoutOptions is not null then fmGUI_CheckboxSet(formCheckbox, formViewEnabled of layoutOptions)
					if listViewEnabled of layoutOptions is not null then fmGUI_CheckboxSet(listCheckbox, listViewEnabled of layoutOptions)
					if tableViewEnabled of layoutOptions is not null then fmGUI_CheckboxSet(tableCheckbox, tableViewEnabled of layoutOptions)
					if defaultView of layoutOptions is not null then fmGUI_PopupSet({objRef:my coerceToString(defaultButton), objValue:defaultView of layoutOptions})

				end if

				tell application "System Events"
					tell application process "FileMaker Pro Advanced"
						click button "OK" of layoutSetupDialog
					end tell
				end tell
			end if

			-- END IF: existing to edit.

		else
			-- BEGIN: does not exist - need to create it:

			if length of (layoutParentFolder of layoutOptions) is greater than 0 then
				-- create it IN a layout folder:
				-- Select the folder, or create it if it doesn't exist yet:
				if not fmGUI_ManageLayouts_LayoutFolderSelect(layoutParentFolder of layoutOptions) then
					fmGUI_ManageLayouts_PopupNewItemOfType("Folder")
					tell application "System Events"
						tell application process "FileMaker Pro Advanced"
							set value of text field "Folder Name:" of window 1 to layoutParentFolder of layoutOptions
							click button "OK" of window 1
							set newFolderRow to first row of (outline 1 of scroll area 1 of manageLayoutsWindow) whose value of text field 1 of group 1 is layoutParentFolder of layoutOptions
							set checkboxRef to checkbox 1 of newFolderRow
						end tell
					end tell
					fmGUI_CheckboxSet(checkboxRef, 1)

				end if
			end if

			-- Create the layout:
			if debugMode then tell application "htcLib" to logConsole(ScriptName, "creating layout: " & (layoutName of layoutOptions))
			tell application "System Events"
				tell application process "FileMaker Pro Advanced"
					set buttonRef to first button of manageLayoutsWindow whose title is "New"
				end tell
			end tell

			-- BEGIN: NEW WINDOW CODE
			clickObjFromHtcLib(buttonRef)
			tell application "htcLib" to windowWaitUntil_FrontIS({windowName:"New Layout/Report"})

			tell application "System Events"
				tell application process "FileMaker Pro Advanced"
					set newLayoutDialog to window 1
					set value of text field 1 of newLayoutDialog to layoutName of layoutOptions
					set buttonRef to pop up button 1 of newLayoutDialog
				end tell
			end tell
			tell application "htcLib" to fmGUI_PopupSet({objRef:my coerceToString(buttonRef), objValue:baseTableName of layoutOptions})
			tell application "System Events"
				tell application process "FileMaker Pro Advanced"
					click button 4 of newLayoutDialog -- select 'Computer'
					click button 6 of newLayoutDialog -- select 'Form'

					-- we don't care which mode to view in, so Finish:
					click button "Finish" of newLayoutDialog
				end tell
			end tell

			delay 1

			-- Now, believe it or not, need to call ITSELF since not all options available during Create:
			fmGUI_ManageLayouts_Layout_CreateOrUpdate(layoutOptions)

			-- END IF: does not exist - need to create it.
		end if

		return true
	on error errMsg number errNum
		error "unable to fmGUI_ManageLayouts_Layout_CreateOrUpdate '" & layoutName of layoutOptions & "' - " & errMsg number errNum
	end try

end fmGUI_ManageLayouts_Layout_CreateOrUpdate

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

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

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

on fmGUI_DataViewer_Close()
	tell application "htcLib" to fmGUI_DataViewer_Close()
end fmGUI_DataViewer_Close

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

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

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

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

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

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

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


Fixed many errors, changed delay, and added more feedback

--Location of this script and its work files:
set workFolder to "/Users/[your user]/[path to ZotDevon]"
--The name of the group in DevonThink where you wish to create folders/notes:
set groupName to "/Sources/"
--Name of file containing new entries to add:
set newFile to "new.txt"
--set the formate you want to have for the title
-- 1. Author - Title
-- 2. Title - Author
set formatOrder to 1

--if you are debugging or have run the findnew.rb script already, set skipscript to one
--to jump directly to the DevonThink import process. Leave as 0 otherwise.
set skipScript to 0

on split(someText, delimiter)
	set AppleScript's text item delimiters to delimiter
	set someText to someText's text items
	set AppleScript's text item delimiters to {""} --> restore delimiters to default value
	return someText
end split

on readFile(filePath)
	set progressFile to ((POSIX file filePath) as string)
	try
		set fileContents to read file progressFile as class utf8
	on error error_message number error_number
		if the error_number is not -128 then
			if error_number is -39 then
				--I think this happens when they are writing and reading at same timetry again
				delay 2
				set fileContents to read file progressFile as class utf8
			end if
		end if
	end try
	return fileContents
end readFile

on existsFile(filePath)
	tell application "Finder" to set fileExists to exists my POSIX file filePath
	return fileExists
end existsFile

on formatTitle(dataArray, type)
	set titleData to item 3 of dataArray
	if titleData is "" then
		set titleData to "Untitled" & item 2 of dataArray
	end if
	set authorData to item 4 of dataArray
	if type is 1 then
		set returnData to titleData
		if authorData is not "" then
			set returnData to authorData & " - " & titleData
		end if
		return cleanTitle(returnData)
	else
		set returnData to titleData
		if authorData is not "" then
			set returnData to titleData & " - " & authorData
		end if
		return cleanTitle(returnData)
	end if
end formatTitle

on replace_chars(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

on cleanTitle(theTitle)
	log "Pre: " & theTitle
	set returnData to replace_chars(theTitle, "/", "-")
	log "After: " & returnData
	return returnData
end cleanTitle

if skipScript is not 1 then
	--check to see if there is a key and udpate file if there isn't then make an empty one
	if existsFile(workFolder & "keys.txt") is false then
		set a to do shell script "touch '" & workFolder & "keys.txt'"
	end if
	if existsFile(workFolder & "lastupdate.txt") is false then
		set a to do shell script "touch '" & workFolder & "lastupdate.txt'"
	end if

	--check to see if there are leftover backup files and use them if there are
	if existsFile(workFolder & "keys_backup.txt") or existsFile(workFolder & "new.txt") then
		set myanswer to display dialog "The last sync did not complete. Do you wish to cancel, look for a backup of pre-import list of entries and ignore any downloaded entries, or first just import already downloaded items and cleanup (You can sync again afterwards)." buttons {"Cancel", "Look for Backup", "Import Downloaded Entries"} default button 3 cancel button 1
		if the button returned of myanswer is "Look for Backup" then
			if existsFile(workFolder & "keys_backup.txt") then
				set a to do shell script "mv '" & workFolder & "keys_backup.txt' '" & workFolder & "keys.txt'"
			end if
			if existsFile(workFolder & "lastupdate.txt") then
				set b to do shell script "mv '" & workFolder & "lastupdate_backup.txt' '" & workFolder & "lastupdate.txt'"
			end if
		else if the button returned of myanswer is "Import Downloaded Entries" then
			if existsFile(workFolder & "keys_backup.txt") then
				set a to do shell script "rm '" & workFolder & "keys_backup.txt'"
			end if
			if existsFile(workFolder & "lastupdate_backup.txt") then
				set a to do shell script "rm '" & workFolder & "lastupdate_backup.txt'"
			end if
			set skipScript to 1
		end if
	end if
end if

if skipScript is not 1 then
	--make a copy of our list of database keys in case something goes wrong during sync
	set y to do shell script "cp '" & workFolder & "keys.txt' '" & workFolder & "keys_backup.txt'"
	set z to do shell script "cp '" & workFolder & "lastupdate.txt' '" & workFolder & "lastupdate_backup.txt'"

	--run ruby script to determine what IDs are missing
	set x to do shell script "'" & workFolder & "findnew.rb' &> /dev/null 2>&1 &"
	set startstat to split(readFile(workFolder & "info.txt"), "/")
	set totalitems to item 2 of startstat
	set abortmission to false

	tell application "ASObjC Runner"
		-- set up dialog and show it
		reset progress
		set properties of progress window to {button title:"Cancel", button visible:true, message:"Checking for new items.", detail:"Looking for Zotero items not yet imported.", indeterminate:false, max value:10, current value:0}
		activate
		show progress
	end tell

	set isdone to false

	--with timeout of 60 seconds
	repeat while isdone is false
		set mystats to split(readFile(workFolder & "info.txt"), "/")
		log mystats
		tell application "ASObjC Runner"
			set currentitem to item 1 of mystats
			set totalitems to item 2 of mystats
			--reduce chance of annoying error as read/write happens at same time during large library import
			if totalitems < 200 then
				delay 2
			else if totalitems < 500 then
				delay 3
			else
				delay 6
			end if
			if currentitem = "Done" then
				exit repeat
			end if
			if totalitems > 0 then
				set properties of progress window to {detail:"Getting Data: " & currentitem & " of " & totalitems & ".", current value:currentitem, max value:totalitems}
			end if
			if button was pressed of progress window then
				set abortmission to true
				exit repeat
			end if
		end tell
	end repeat
	--end timeout
	--set progressMade to readProgress(workFolder)

	tell application "ASObjC Runner"
		activate
		if abortmission is true then
			set properties of progress window to {detail:"Operation cancelled. DevonThink database not modified."}
			delay 1
			tell application "ASObjC Runner" to hide progress
			error number -128
		else
			set properties of progress window to {detail:"Found " & totalitems & " new items including attachments and notes."}
		end if
	end tell

end if

--read the file with new entries to be added
set filetoread to workFolder & "new.txt"

if existsFile(filetoread) of me is false then
	--The "new.txt" file could not be found, so nothing to import
	display dialog "Could not find any downloaded entries. Nothing to import"
	error number -128
end if

set newEntries to readFile(filetoread) of me
--split it into separate lines
set entryList to split(newEntries, "
") of me

if the number of items in entryList < 1 then
	--There must be at least one entry to import
	display dialog "Could not find any downloaded entries. Nothing to import"
	error number -128
end if

--add all the attachments and notes last, extract them and add them to end
set normalList to {}
set endList to {}
log the number of items in entryList
tell application "ASObjC Runner"
	-- set up dialog and show it
	reset progress
	set properties of progress window to {button title:"Cancel", button visible:true, message:"Extracting attachments.", detail:"Putting attachments and notes after all other items before importing into DEVONthink.", indeterminate:true}
	activate
	show progress
end tell
repeat with newEntry in entryList
	if newEntry is not "" and the number of words in newEntry > 1 then
		log newEntry
		if word 1 of newEntry is "attachment" or word 1 of newEntry is "note" then
			set endList to endList & {newEntry}
		else
			set normalList to normalList & {newEntry}
		end if
	end if
end repeat
set sortedList to normalList & endList

tell application id "com.devon-technologies.thinkpro2" to activate
--cycle through each new entry and add it to DevonThink
tell application "ASObjC Runner"
	-- set up dialog and show it
	reset progress
	set properties of progress window to {button title:"Cancel", button visible:true, message:"Importing downloaded items into DEVONthink.", detail:"Looking for Zotero items not yet imported.", indeterminate:true}
	activate
	show progress
end tell
set mycount to 0
repeat with newEntry in sortedList
	set mycount to mycount + 1
	set entryData to split(newEntry, "	") of me
	log entryData
	set finalTitle to formatTitle(entryData, formatOrder) of me
	set entryType to item 1 of entryData
	set entryKey to item 2 of entryData
	set entryParent to item 5 of entryData
	set entryAtType to item 6 of entryData
	set entryURL to item 7 of entryData
	tell application "ASObjC Runner"
		set properties of progress window to {detail:"Adding item: " & mycount & " of " & the number of items in sortedList & ".", indeterminate:false, current value:mycount, max value:the number of items in sortedList}
		if button was pressed of progress window then
			set abortmission to true
			exit repeat
		end if
	end tell
	log finalTitle
	tell application id "com.devon-technologies.thinkpro2"
		try
			set theDatabase to current database
			if ((entryType is not "attachment") and (entryType is not "note")) then

				if not (exists record at groupName & finalTitle) then
					set theGroup to create location groupName & finalTitle in theDatabase
					set the comment of theGroup to entryKey
					if entryURL is not "" then
						set the URL of theGroup to entryURL
					end if
					set newRecord to create record with {name:finalTitle, type:rtf, rich text:finalTitle, URL:"zotero://select/item/0_" & entryKey} in theGroup
					try
						if entryType is "book" then
							set entryIcon to "treeitem-book.png"
						else if entryType is "thesis" then
							set entryIcon to "treeitem-thesis.png"
						else if entryType is "journalArticle" then
							set entryIcon to "treeitem-journalArticle.png"
						else if entryType is "newspaperArticle" then
							set entryIcon to "treeitem-newspaperArticle.png"
						else if entryType is "manuscript" then
							set entryIcon to "treeitem-manuscript.png"
						else if entryType is "case" then
							set entryIcon to "treeitem-case.png"
						else if entryType is "bookSection" then
							set entryIcon to "treeitem-bookSection.png"
						else if entryType is "document" then
							set entryIcon to "treeitem-attachment-file.png"
						else if entryType is "webpage" then
							set entryIcon to "treeitem-webpage.png"
						end if

						set iconPath to workFolder & "icons/" & entryIcon
						set thumbnail of theGroup to iconPath
					end try
				end if
			else
				--We should have passed all normal entries now so we can find them by the Key in the comment
				set parentRecordList to lookup records with comment entryParent in theDatabase
				--If one record with the parent key is found then let us add children to it
				if the number of items in parentRecordList is 1 then
					set parentRecord to item 1 of parentRecordList
					if not (exists record at path of parentRecord & "/" & finalTitle) then
						if entryAtType is not "text/html" then
							set myurl to "zotero://select/item/0_" & entryKey
						else
							set myurl to entryURL
						end if
						set newRecord to create record with {name:finalTitle, type:rtf, rich text:finalTitle, URL:myurl} in parentRecord

						try
							if entryAtType is "text/html" then
								set entryIcon to "treeitem-attachment-web-link.png"
							else if entryAtType is "application/pdf" then
								set entryIcon to "treeitem-attachment-pdf.png"
							end if
							if entryType is "note" then
								set entryIcon to "treeitem-note.png"
							end if

							set iconPath to workFolder & "icons/" & entryIcon
							set thumbnail of newRecord to iconPath
						end try

					end if
				end if
			end if
		on error error_message number error_number
			tell application "ASObjC Runner" to hide progress
			if the error_number is not -128 then display alert "DEVONthink Pro" message error_message as warning
		end try
	end tell
end repeat

tell application "ASObjC Runner"
	set properties of progress window to {detail:"Import complete. " & mycount & " entries or attachments added."}
	delay 2
	hide progress
end tell

--Now that import is complete, delete the "new.txt" file
if existsFile(workFolder & "new.txt") then
	set y to do shell script "mv '" & workFolder & "new.txt' '" & workFolder & "lastimport.txt'"
end if
--Delete the backup files too
if existsFile(workFolder & "keys_backup.txt") then
	set y to do shell script "rm '" & workFolder & "keys_backup.txt'"
end if
if existsFile(workFolder & "lastupdate_backup.txt") then
	set z to do shell script "rm '" & workFolder & "lastupdate_backup.txt'"
end if

--Location of this script and its work files:
set workFolder to "/Users/[your user]/[path to ZotDevon]"
--The name of the group in DevonThink where you wish to create folders/notes:
set groupName to "/Sources/"
--Name of file containing new entries to add:
set newFile to "new.txt"
--set the formate you want to have for the title
-- 1. Author - Title
-- 2. Title - Author
set formatOrder to 1

--if you are debugging or have run the findnew.rb script already, set skipscript to one
--to jump directly to the DevonThink import process. Leave as 0 otherwise.
set skipScript to 0

on split(someText, delimiter)
	set AppleScript's text item delimiters to delimiter
	set someText to someText's text items
	set AppleScript's text item delimiters to {""} --> restore delimiters to default value
	return someText
end split

on readFile(filePath)
	set progressFile to ((POSIX file filePath) as string)
	try
		set fileContents to read file progressFile as class utf8
	on error error_message number error_number
		if the error_number is not -128 then
			if error_number is -39 then
				--I think this happens when they are writing and reading at same timetry again
				delay 2
				set fileContents to read file progressFile as class utf8
			end if
		end if
	end try
	return fileContents
end readFile

on existsFile(filePath)
	tell application "Finder" to set fileExists to exists my POSIX file filePath
	return fileExists
end existsFile

on formatTitle(dataArray, type)
	set titleData to item 3 of dataArray
	if titleData is "" then
		set titleData to "Untitled" & item 2 of dataArray
	end if
	set authorData to item 4 of dataArray
	if type is 1 then
		set returnData to titleData
		if authorData is not "" then
			set returnData to authorData & " - " & titleData
		end if
		return cleanTitle(returnData)
	else
		set returnData to titleData
		if authorData is not "" then
			set returnData to titleData & " - " & authorData
		end if
		return cleanTitle(returnData)
	end if
end formatTitle

on replace_chars(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

on cleanTitle(theTitle)
	log "Pre: " & theTitle
	set returnData to replace_chars(theTitle, "/", "-")
	log "After: " & returnData
	return returnData
end cleanTitle

if skipScript is not 1 then
	--check to see if there is a key and udpate file if there isn't then make an empty one
	if existsFile(workFolder & "keys.txt") is false then
		set a to do shell script "touch '" & workFolder & "keys.txt'"
	end if
	if existsFile(workFolder & "lastupdate.txt") is false then
		set a to do shell script "touch '" & workFolder & "lastupdate.txt'"
	end if

	--check to see if there are leftover backup files and use them if there are
	if existsFile(workFolder & "keys_backup.txt") then
		set myanswer to display dialog "The last sync was aborted. The script will proceed with the pre-sync backup list of items."
		if the button returned of myanswer is "OK" then
			set a to do shell script "mv '" & workFolder & "keys_backup.txt' '" & workFolder & "keys.txt'"
			if existsFile(workFolder & "lastupdate.txt") then
				set b to do shell script "mv '" & workFolder & "lastupdate_backup.txt' '" & workFolder & "lastupdate.txt'"
			end if
		end if
	end if

	--make a copy of our list of database keys in case something goes wrong during sync
	set y to do shell script "cp '" & workFolder & "keys.txt' '" & workFolder & "keys_backup.txt'"
	set z to do shell script "cp '" & workFolder & "lastupdate.txt' '" & workFolder & "lastupdate_backup.txt'"

	--run ruby script to determine what IDs are missing
	set x to do shell script "'" & workFolder & "findnew.rb' &> /dev/null 2>&1 &"
	set startstat to split(readFile(workFolder & "info.txt"), "/")
	set totalitems to item 2 of startstat
	set abortmission to false

	tell application "ASObjC Runner"
		-- set up dialog and show it
		reset progress
		set properties of progress window to {button title:"Cancel", button visible:true, message:"Checking for new items.", detail:"Looking for Zotero items not yet imported.", indeterminate:false, max value:10, current value:0}
		activate
		show progress
	end tell

	set isdone to false

	--with timeout of 60 seconds
	repeat while isdone is false
		set mystats to split(readFile(workFolder & "info.txt"), "/")
		log mystats
		tell application "ASObjC Runner"
			set currentitem to item 1 of mystats
			set totalitems to item 2 of mystats
			--reduce chance of annoying error as read/write happens at same time during large library import
			if totalitems < 200 then
				delay 1
			else if totalitems < 500 then
				delay 4
			else
				delay 10
			end if
			if currentitem = "Done" then
				exit repeat
			end if
			if totalitems > 0 then
				set properties of progress window to {detail:"Getting Data: " & currentitem & " of " & totalitems & ".", current value:currentitem, max value:totalitems}
			end if
			if button was pressed of progress window then
				set abortmission to true
				exit repeat
			end if
		end tell
	end repeat
	--end timeout
	--set progressMade to readProgress(workFolder)

	tell application "ASObjC Runner"
		activate
		if abortmission is true then
			set properties of progress window to {detail:"Operation cancelled. DevonThink database not modified."}
			delay 1
			tell application "ASObjC Runner" to hide progress
			error number -128
		else
			set properties of progress window to {detail:"Found " & totalitems & " new items including attachments and notes."}
		end if
	end tell

end if

tell application id "com.devon-technologies.thinkpro2"
	activate
	try
		--read the file with new entries to be added
		set filetoread to workFolder & "new.txt"
		set newEntries to readFile(filetoread) of me
		--split it into separate lines
		set entryList to split(newEntries, "
") of me

		--add all the attachments and notes last, extract them and add them to end
		set normalList to {}
		set endList to {}
		repeat with newEntry in entryList
			if word 1 of newEntry is "attachment" or word 1 of newEntry is "note" then
				set endList to endList & {newEntry}
			else
				set normalList to normalList & {newEntry}
			end if
		end repeat
		set sortedList to normalList & endList

		--cycle through each new entry and add it to DevonThink
		repeat with newEntry in sortedList
			set entryData to split(newEntry, "	") of me
			log entryData
			set finalTitle to formatTitle(entryData, formatOrder) of me
			set entryType to item 1 of entryData
			set entryKey to item 2 of entryData
			set entryParent to item 5 of entryData
			set entryAtType to item 6 of entryData
			set entryURL to item 7 of entryData
			set theDatabase to current database
			log finalTitle
			if ((entryType is not "attachment") and (entryType is not "note")) then

				if not (exists record at groupName & finalTitle) then
					set theGroup to create location groupName & finalTitle in theDatabase
					set the comment of theGroup to entryKey
					if entryURL is not "" then
						set the URL of theGroup to entryURL
					end if
					set newRecord to create record with {name:finalTitle, type:rtf, rich text:finalTitle, URL:"zotero://select/item/0_" & entryKey} in theGroup
					try
						if entryType is "book" then
							set entryIcon to "treeitem-book.png"
						else if entryType is "thesis" then
							set entryIcon to "treeitem-thesis.png"
						else if entryType is "journalArticle" then
							set entryIcon to "treeitem-journalArticle.png"
						else if entryType is "newspaperArticle" then
							set entryIcon to "treeitem-newspaperArticle.png"
						else if entryType is "manuscript" then
							set entryIcon to "treeitem-manuscript.png"
						else if entryType is "case" then
							set entryIcon to "treeitem-case.png"
						else if entryType is "bookSection" then
							set entryIcon to "treeitem-bookSection.png"
						else if entryType is "document" then
							set entryIcon to "treeitem-attachment-file.png"
						else if entryType is "webpage" then
							set entryIcon to "treeitem-webpage.png"
						end if

						set iconPath to workFolder & "icons/" & entryIcon
						set thumbnail of theGroup to iconPath
					end try
				end if
			else
				--We should have passed all normal entries now so we can find them by the Key in the comment
				set parentRecordList to lookup records with comment entryParent in theDatabase
				--If one record with the parent key is found then let us add children to it
				if the number of items in parentRecordList is 1 then
					set parentRecord to item 1 of parentRecordList
					if not (exists record at path of parentRecord & "/" & finalTitle) then
						if entryAtType is not "text/html" then
							set myurl to "zotero://select/item/0_" & entryKey
						else
							set myurl to entryURL
						end if
						set newRecord to create record with {name:finalTitle, type:rtf, rich text:finalTitle, URL:myurl} in parentRecord

						try
							if entryAtType is "text/html" then
								set entryIcon to "treeitem-attachment-web-link.png"
							else if entryAtType is "application/pdf" then
								set entryIcon to "treeitem-attachment-pdf.png"
							end if
							if entryType is "note" then
								set entryIcon to "treeitem-note.png"
							end if

							set iconPath to workFolder & "icons/" & entryIcon
							set thumbnail of newRecord to iconPath
						end try

					end if
				end if
			end if

			--TODO:
			--ADD LINK TO HEADER TEXT
			--Allow people to sync only a particular collection

		end repeat
	on error error_message number error_number
		if the error_number is not -128 then display alert "DEVONthink Pro" message error_message as warning
	end try
end tell

if skipScript is not 1 then
	delay 2
	tell application "ASObjC Runner" to hide progress
	set y to do shell script "rm '" & workFolder & "keys_backup.txt'"
	set z to do shell script "rm '" & workFolder & "lastupdate_backup.txt'"
end if


log only if debugMode

log only if debugMode

Scripts/fmClip - Replace String in FM Objects.applescript


fmGUI_2empowerFM_Toolbox_Close comment update

-- fmGUI_2empowerFM_Toolbox_Close()
-- Daniel A. Shockley, NYHTC
-- Closes floating 2empowerFM Toolbox utility window.

(*
HISTORY:
	2020-03-04 ( dshockley ): first created

REQUIRES:
	fmGUI_AppFrontMost
*)

on run
	fmGUI_2empowerFM_Toolbox_Close()
end run

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

on fmGUI_2empowerFM_Toolbox_Close()
	-- version 2020-03-04

	fmGUI_AppFrontMost()
	tell application "System Events"
		tell process "FileMaker Pro Advanced"
			try
				click button 1 of (first window whose name is "2empowerFM Toolbox")
				-- gets an error even if button exists, but still works.
			end try
			return true
		end tell
	end tell
end fmGUI_2empowerFM_Toolbox_Close

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

on fmGUI_AppFrontMost()
	tell application "htcLib" to fmGUI_AppFrontMost()
end fmGUI_AppFrontMost

-- fmGUI_2empowerFM_Toolbox_Close()
-- Daniel A. Shockley, NYHTC
-- Closes floating 2empowerFM Toolbox utility window.

(*
HISTORY:
	2020-03-04 ( dshockley ): first created

REQUIRES:
	fmGUI_AppFrontMost
*)

on run
	fmGUI_2empowerFM_Toolbox_Close()
end run

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

on fmGUI_2empowerFM_Toolbox_Close()
	-- version 2020-03-04

	fmGUI_AppFrontMost()
	tell application "System Events"
		tell process "FileMaker Pro Advanced"
			try
				click button 1 of (first window whose name is "2empowerFM Toolbox")
			end try
			return true
		end tell
	end tell
end fmGUI_2empowerFM_Toolbox_Close

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

on fmGUI_AppFrontMost()
	tell application "htcLib" to fmGUI_AppFrontMost()
end fmGUI_AppFrontMost


Make Mac disk image packager set application icon location more reliably.

-- This Applescript changes all of the icon labels on the disk image to
--  a different color.
-- Usage: osascript set-labels.applescript <volume-name>
-- where <volume-name> is the volume name of the disk image.

on run argv
	tell application "Finder"
		set diskname to item 1 of argv
		tell disk diskname
			set file_list to every file
			repeat with i in file_list
				if the name of i is "Applications" then
					set the position of i to {368, 135}
				else if the name of i ends with ".app" then
					set the position of i to {134, 135}
				end if
			-- The magic happens here: This will set the label color of
			--  the file icon. Change the 7 to change the color: 0 is no
			--  label, then red, orange, yellow, green, blue, purple, or gray.
				set the label index of i to 7
			end repeat
			update without registering applications
			delay 4
		end tell
	end tell
end run

-- This Applescript changes all of the icon labels on the disk image to
--  a different color.
-- Usage: osascript set-labels.applescript <volume-name>
-- where <volume-name> is the volume name of the disk image.

on run argv
	tell application "Finder"
		set diskname to item 1 of argv
		set file_list to every file in disk diskname
		repeat with i in file_list
			if the name of i is "Applications" then
				set the position of i to {368, 135}
			else if the name of i ends with ".app" then
				set the position of i to {134, 135}
			end if
		-- The magic happens here: This will set the label color of
		--  the file icon. Change the 7 to change the color: 0 is no
		--  label, then red, orange, yellow, green, blue, purple, or gray.
			set the label index of i to 7
		end repeat
	end tell
end run


updated fmGUI_MangeDB_TO_Add

updated fmGUI_MangeDB_TO_Add

-- fmGUI_ManageDb_TO_Add({tocName:null, dbName:null, doNotChangeExisting:false, baseTableName:null})
-- Daniel Shockley, NYHTC
-- add table occurence to the current database

(*
HISTORY:
	1.4 - 2016-08-23 ( eshagdar ): declare all params. fixed error message.
	1.3 - 2015-04-24 ( eshagdar ): creates a data source if needed
	1.2 -
	1.1 -
	1.0 - created

REQUIRES:
	fmGUI_AppFrontMost
	fmGUI_ManageDataSources_EnsureExists
	fmGUI_ManageDataSources_Save
	fmGUI_ManageDb_GoToTab_Relationships
	fmGUI_ObjectClick_AffectsWindow
	fmGUI_PopupSet
*)

property helper : ""

on run
	set pathHelper to do shell script "dirname " & quoted form of POSIX path of ((path to me) as string)
	set pathHelper to do shell script "dirname " & quoted form of POSIX path of pathHelper
	set pathHelper to do shell script "dirname " & quoted form of POSIX path of pathHelper
	set pathHelper to POSIX file (pathHelper & "/main.scpt") as string
	set helper to load script file pathHelper

	fmGUI_ManageDb_TO_Add({tocName:"bob", dbName:"a01_PERSON", baseTableName:"A_PERSON"})
end run

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

on fmGUI_ManageDb_TO_Add(prefs)
	-- version 1.4

	set defaultPrefs to {TOName:null, dbName:null, doNotChangeExisting:false, baseTableName:null}

	set prefs to prefs & defaultPrefs
	set dbName to dbName of prefs
	set baseTableName to baseTableName of prefs
	set TOName to TOName of prefs

	try
		fmGUI_ManageDb_GoToTab_Relationships({})
		tell application "System Events"
			tell application process "FileMaker Pro Advanced"
				my fmGUI_AppFrontMost()
				set addTocButton to first button of tab group 1 of window 1 whose description contains "Add a table"
				my fmGUI_ObjectClick_AffectsWindow(addTocButton)
				delay 1
				set dataSourcePopUpButton to pop up button "Data Source:" of window 1
				try
					my fmGUI_PopupSet(dataSourcePopUpButton, dbName)
					select (first row of table 1 of scroll area 1 of window 1 whose value of static text 1 is baseTableName)
				on error
					--Not an existing data source, so create it
					key code 53 -- Hit 'Esc'
					my fmGUI_PopupSet(dataSourcePopUpButton, "Manage Data Sources")
					my fmGUI_ManageDataSources_EnsureExists({dataSourceName:dbName})
					my fmGUI_ManageDataSources_Save({})
					delay 1

					-- now that we've added the data source, try again
					my fmGUI_PopupSet(dataSourcePopUpButton, dbName)
					select (first row of table 1 of scroll area 1 of window 1 whose value of static text 1 is baseTableName)
				end try
				--if debugMode then my logLEVEL(5, "Add TO 003")
				--if debugMode then my logLEVEL(5, "About to edit name")
				set value of text field "Name" of window 1 to TOName
				if debugMode then my logLEVEL(5, "TO added: '" & TOName & "'")

				my fmGUI_ObjectClick_AffectsWindow(button "OK" of window 1)

				return true
			end tell
		end tell
	on error errMsg number errNum
		error "fmGUI_ManageDb_TO_Add - " & errMsg number errNum
	end try

end fmGUI_ManageDb_TO_Add

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

on fmGUI_AppFrontMost()
	tell helper to fmGUI_AppFrontMost()
end fmGUI_AppFrontMost

on fmGUI_ManageDataSources_EnsureExists(prefs)
	tell helper to fmGUI_ManageDataSources_EnsureExists(prefs)
end fmGUI_ManageDataSources_EnsureExists

on fmGUI_ManageDataSources_Save(prefs)
	tell helper to fmGUI_ManageDataSources_Save(prefs)
end fmGUI_ManageDataSources_Save

on fmGUI_ManageDb_GoToTab_Relationships(prefs)
	tell helper to fmGUI_ManageDb_GoToTab_Relationships(prefs)
end fmGUI_ManageDb_GoToTab_Relationships

on fmGUI_ObjectClick_AffectsWindow(prefs)
	tell helper to fmGUI_ObjectClick_AffectsWindow(prefs)
end fmGUI_ObjectClick_AffectsWindow

on fmGUI_PopupSet(popupObject, popupChoice)
	tell helper to fmGUI_PopupSet(popupObject, popupChoice)
end fmGUI_PopupSet

-- fmGUI_ManageDb_TO_Add({tocName:null, dbName:null, doNotChangeExisting:false, baseTableName:null})
-- Daniel Shockley, NYHTC
-- add table occurence to the current database

(*
HISTORY:
	1.3 - 2015-04-24 ( eshagdar ): creates a data source if needed
	1.2 -
	1.1 -
	1.0 - created

REQUIRES:
	fmGUI_AppFrontMost
	fmGUI_ManageDataSources_EnsureExists
	fmGUI_ManageDataSources_Save
	fmGUI_ManageDb_GoToTab_Relationships
	fmGUI_ObjectClick_AffectsWindow
	fmGUI_PopupSet
*)

property helper : ""

on run
	set pathHelper to do shell script "dirname " & quoted form of POSIX path of ((path to me) as string)
	set pathHelper to do shell script "dirname " & quoted form of POSIX path of pathHelper
	set pathHelper to do shell script "dirname " & quoted form of POSIX path of pathHelper
	set pathHelper to POSIX file (pathHelper & "/main.scpt") as string
	set helper to load script file pathHelper

	fmGUI_ManageDb_TO_Add({tocName:"bob", dbName:"a01_PERSON", baseTableName:"A_PERSON"})
end run

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

on fmGUI_ManageDb_TO_Add(prefs)
	-- version 1.3

	set defaultPrefs to {tocName:null, dbName:null, doNotChangeExisting:false, baseTableName:null}

	set prefs to prefs & defaultPrefs

	try
		fmGUI_ManageDb_GoToTab_Relationships({})
		tell application "System Events"
			tell application process "FileMaker Pro Advanced"
				my fmGUI_AppFrontMost()
				set addTocButton to first button of tab group 1 of window 1 whose description contains "Add a table"
				my fmGUI_ObjectClick_AffectsWindow(addTocButton)
				delay 1
				try
					my fmGUI_PopupSet(pop up button "Data Source:" of window 1, dbName of prefs)
					select (first row of table 1 of scroll area 1 of window 1 whose value of static text 1 is baseTableName of prefs)
				on error
					--Not an existing data source, so create it
					key code 53 -- Hit 'Esc' to close pop up.

					-- add data source from within adding a new TO window
					my fmGUI_PopupSet(pop up button "Data Source:" of window 1, "Manage Data Sources")
					my fmGUI_ManageDataSources_EnsureExists({dataSourceName:dbName of prefs})
					my fmGUI_ManageDataSources_Save({})
					delay 1

					-- now that we've added the data source, try again...
					my fmGUI_PopupSet(pop up button "Data Source:" of window 1, dbName of prefs)
					select (first row of table 1 of scroll area 1 of window 1 whose value of static text 1 is baseTableName of prefs)
				end try

				set value of text field "Name" of window 1 to tocName of prefs
				my fmGUI_ObjectClick_AffectsWindow(button "OK" of window 1)

				return true
			end tell
		end tell
	on error errMsg number errNum
		error "Couldn't add TO in Manage DB - " & errMsg number errNum
	end try

end fmGUI_ManageDb_TO_Add

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

on fmGUI_AppFrontMost()
	tell helper to fmGUI_AppFrontMost()
end fmGUI_AppFrontMost

on fmGUI_ManageDataSources_EnsureExists(prefs)
	tell helper to fmGUI_ManageDataSources_EnsureExists(prefs)
end fmGUI_ManageDataSources_EnsureExists

on fmGUI_ManageDataSources_Save(prefs)
	tell helper to fmGUI_ManageDataSources_Save(prefs)
end fmGUI_ManageDataSources_Save

on fmGUI_ManageDb_GoToTab_Relationships(prefs)
	tell helper to fmGUI_ManageDb_GoToTab_Relationships(prefs)
end fmGUI_ManageDb_GoToTab_Relationships

on fmGUI_ObjectClick_AffectsWindow(prefs)
	tell helper to fmGUI_ObjectClick_AffectsWindow(prefs)
end fmGUI_ObjectClick_AffectsWindow

on fmGUI_PopupSet(popupObject, popupChoice)
	tell helper to fmGUI_PopupSet(popupObject, popupChoice)
end fmGUI_PopupSet


Cleanup dispatch path debug message

Cleanup dispatch path debug message

FasdUAS 1.101.10
k
i
I
.GURLGURLnullTEXT
	o0encoded_action
k

r

I
.earsffdralis afdr
f

rtyp
m

TEXT
o0script_name
I

.sysoexecTEXTTEXT
b

b

b

b

b

b

m
  !!8

# Log that we are running; rewrite AppleScript path with colons to use slashes.
# E.g. 'path:to:script.app:' -> '/path/to/script.app'
script_name=$(echo '
o0script_name
m
""##' | sed -E 's,([^:]+):,/\1,g')
echo "$script_name" dispatching '
o0encoded_action
m$$%%' | logger -t com.westernx.sgaction

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

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

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

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

# Disconnect it from this shell.
disown %%

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

rtyp

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

FasdUAS 1.101.10
k
i
I
.GURLGURLnullTEXT
	o0encoded_action
k

r

I
.earsffdralis afdr
f

rtyp
m

TEXT
o0script_name
I

.sysoexecTEXTTEXT
b

b

b

b

b

b

m
  !!F

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

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

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

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

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

# Disconnect it from this shell.
disown %%

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

rtyp

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


Fix open_shortcuts

Fix open_shortcuts

-- vim-anywhere - use Vim whenever, wherever
-- Author: Chris Knadler
-- Homepage: https://www.github.com/cknadler/vim-anywhere
--
-- Open the "Services" keyboard shortcuts tab of keyboard system preferences

tell application "System Preferences"
  activate
  reveal anchor "shortcutsTab" of pane id "com.apple.preference.keyboard"
  keystroke tab
  repeat 3 times
    key code 125
  end repeat
end tell

-- vim-anywhere - use Vim whenever, wherever
-- Author: Chris Knadler
-- Homepage: https://www.github.com/cknadler/vim-anywhere
--
-- Open the keyboard shortcuts tab of keyboard system preferences

tell application "System Preferences"
  activate
  reveal anchor "shortcutsTab" of pane id "com.apple.preference.keyboard"
  keystroke tab
  keystroke key code 125
  keystroke key code 125
  keystroke key code 125
end tell


RawVideoRec update

RawVideoRec update

Working version of the applescript for raw video recording with the
livetrack+VTOP setup

FasdUAS 1.101.10
k
l[U This script records video via the ezcap VideoCapture software. To launch the script:		 This script records video via the ezcap VideoCapture software. To launch the script:

l

l[U from terminal  osascript /path/to/script/RawVideoRec.scpt savePath vidName recLength from terminal  osascript /path/to/script/RawVideoRec.scpt savePath vidName recLength

l
l from matlab  system(sprintf('osascript /path/to/script/RawVideoRec.scpt %s %s %s', savePath, vidName1, num2str(recTime+postBufferTime))); from matlab  system(sprintf('osascript /path/to/script/RawVideoRec.scpt %s %s %s', savePath, vidName1, num2str(recTime+postBufferTime)));
l
i
I
.aevtoappnull****
o0argv
k !
 r"#
"I$
.sysoexecTEXTTEXT
$m%%&&6/usr/local/bin/gdate +%s.%N
#o0
beforetell
BeforeTell!'(
'OG)*
)kF++,-
,I.
.aevtodocnullalis
.4/

cwin
/m0011$ezcap VideoGrabber-23
2r45
4I6
.sysoexecTEXTTEXT
6m77886/usr/local/bin/gdate +%s.%N
5o0beforestartBeforeStart39:
9I:;
.efxcStarnullnull;<=

kWch
<m >>??$ezcap VideoGrabber=@A

kFil
@4!/B

psxf
Bl#.C
Cb#.DE
Db#,FG
Fn#'HI
H4$'J

cobj
Jm%&
Io#$0argv
Gn'+KL
K4(+M

cobj
Mm)*
Lo'(0argv
Em,-NNOO.movAP

kDur
Pn04QR
Q414S

cobj
Sm23
Ro010argv:T
Tr;FUV
UI;BW
.sysoexecTEXTTEXT
Wm;>XXYY6/usr/local/bin/gdate +%s.%N
Vo0
afterstart
AfterStart
*m	ZZ@alisMacintosh HD	LHH+ezcap VideoCapture.app	 ezcap VideoGrabber	JZHEMacintosh HD:Applications:ezcap VideoGrabber:ezcap VideoCapture.app.ezcap VideoCapture.appMacintosh HD6Applications/ezcap VideoGrabber/ezcap VideoCapture.app/([\
[rHS]^
]IHO_
.sysoexecTEXTTEXT
_mHK``aa6/usr/local/bin/gdate +%s.%N
^o0	aftertell	AfterTell\bc
brTdde
dJT`ffgh
goTU0
beforetell
BeforeTellhij
ioUV0beforestartBeforeStartjkl
koVY0
afterstart
AfterStartlm
moY\0	aftertell	AfterTell
eo0mylistmyListcno
nreppq
pcelrs
rmehttuu
smhk

ctxt
qo0mystringmyStringovw
vXqxy
xrz{
zb|}
|b~
~o0mystringmyString
o0myitemmyItem
}1

lnfd
{o0mystringmyString0myitemmyItem
yotw0mylistmyListw
L
o0mystringmyString
l
l

.aevtoappnull****0
beforetell
BeforeTell0beforestartBeforeStart0
afterstart
AfterStart0	aftertell	AfterTell0mylistmyList0mystringmyString
.aevtoappnull****0argv0argv0myitemmyItem%Z07>NX`t
.sysoexecTEXTTEXT0
beforetell
BeforeTell

cwin
.aevtodocnullalis0beforestartBeforeStart

kWch

kFil

psxf

cobj

kDur
.efxcStarnullnull0
afterstart
AfterStart0	aftertell	AfterTell0mylistmyList

ctxt0mystringmyString

kocl
.corecnte********

lnfdjEO<*/jOjEO**k/l/%%/m/aOajE`UOajE`O__avE`Oaa&E`O%_[alkh_%_%E`[OYO_(1517410650.728043000(1517410650.740879000(1517410650.782892000(1517410650.7902590001517410650.728043000
1517410650.740879000
1517410650.782892000
1517410650.790259000
ascr
ޭ

FasdUAS 1.101.10
k
l[U This script records video via the ezcap VideoCapture software. To launch the script:		 This script records video via the ezcap VideoCapture software. To launch the script:

l

l[U from terminal  osascript /path/to/script/RawVideoRec.scpt savePath vidName recLength from terminal  osascript /path/to/script/RawVideoRec.scpt savePath vidName recLength

l
l from matlab  system(sprintf('osascript /path/to/script/RawVideoRec.scpt %s %s %s', savePath, vidName1, num2str(recTime+postBufferTime))); from matlab  system(sprintf('osascript /path/to/script/RawVideoRec.scpt %s %s %s', savePath, vidName1, num2str(recTime+postBufferTime)));
l
i
I
.aevtoappnull****
o0argv
k !
 r"#
"I$
.sysoexecTEXTTEXT
$m%%&&6/usr/local/bin/gdate +%s.%N
#o0
beforetell
BeforeTell!'(
'OG)*
)kF++,-
,I.
.aevtodocnullalis
.4/

cwin
/m0011$ezcap VideoGrabber-23
2r45
4I6
.sysoexecTEXTTEXT
6m77886/usr/local/bin/gdate +%s.%N
5o0beforestartBeforeStart39:
9I:;
.efxcStarnullnull;<=

kWch
<m >>??$ezcap VideoGrabber=@A

kFil
@4!/B

psxf
Bl#.C
Cb#.DE
Db#,FG
Fn#'HI
H4$'J

cobj
Jm%&
Io#$0argv
Gn'+KL
K4(+M

cobj
Mm)*
Lo'(0argv
Em,-NNOO.movAP

kDur
Pn04QR
Q414S

cobj
Sm23
Ro010argv:T
Tr;FUV
UI;BW
.sysoexecTEXTTEXT
Wm;>XXYY6/usr/local/bin/gdate +%s.%N
Vo0
afterstart
AfterStart
*m	ZZ@alisMacintosh HDA'H+}Qezcap VideoCapture.app}R	 ezcap VideoGrabberAmJZ}QIEMacintosh HD:Applications:ezcap VideoGrabber:ezcap VideoCapture.app.ezcap VideoCapture.appMacintosh HD6Applications/ezcap VideoGrabber/ezcap VideoCapture.app/([\
[rHS]^
]IHO_
.sysoexecTEXTTEXT
_mHK``aa6/usr/local/bin/gdate +%s.%N
^o0	aftertell	AfterTell\bc
brTdde
dJT`ffgh
goTU0
beforetell
BeforeTellhij
ioUV0beforestartBeforeStartjkl
koVY0
afterstart
AfterStartlm
moY\0	aftertell	AfterTell
eo0mylistmyListcno
nreppq
pcelrs
rmehttuu
smhk

ctxt
qo0mystringmyStringovw
vXqxy
xrz{
zb|}
|b~
~o0mystringmyString
o0myitemmyItem
}1

lnfd
{o0mystringmyString0myitemmyItem
yotw0mylistmyListw
L
o0mystringmyString
l
l

.aevtoappnull****0
beforetell
BeforeTell0beforestartBeforeStart0
afterstart
AfterStart0	aftertell	AfterTell0mylistmyList0mystringmyString
.aevtoappnull****0argv0argv0myitemmyItem%Z07>NX`t
.sysoexecTEXTTEXT0
beforetell
BeforeTell

cwin
.aevtodocnullalis0beforestartBeforeStart

kWch

kFil

psxf

cobj

kDur
.efxcStarnullnull0
afterstart
AfterStart0	aftertell	AfterTell0mylistmyList

ctxt0mystringmyString

kocl
.corecnte********

lnfdjEO<*/jOjEO**k/l/%%/m/aOajE`UOajE`O__avE`Oaa&E`O%_[alkh_%_%E`[OYO_(1475503738.525951000(1475503738.535010000(1475503738.567056000(1475503738.5731240001475503738.525951000
1475503738.535010000
1475503738.567056000
1475503738.573124000
ascr
ޭ


Alfred checkin

Alfred checkin

FasdUAS 1.101.10
l
i
I
.aevtoappnull****
o0argv
r
I

.sysodsct****scpt

l
b

b
mL
	tell application "System Events"
		set _app to item 1 of (every process whose frontmost is true)
	end tell

	tell application "System Events"
		tell _app
			tell
n
4

cobj
m
o0argv

m
				if (it exists) then perform action "AXPress"
			end tell
		end tell
	end tell
	o0scpt
.aevtoappnull****0scpt
.aevtoappnull****0argv0argv

cobj
.sysodsct****scpt0scptk/%%jE !"!#$#%&%'('))*
misccura

pcap*++iTerm2

mbar

mbri(,,Edit

menE&--Edit

menI$..*Marks and Annotations

menE"//*Marks and Annotations

menI 00Previous Mark

actT11AXPressascrޭ

FasdUAS 1.101.10
l
i
I
.aevtoappnull****
o0argv
r
I

.sysodsct****scpt

l
b

b
mL
	tell application "System Events"
		set _app to item 1 of (every process whose frontmost is true)
	end tell

	tell application "System Events"
		tell _app
			tell
n
4

cobj
m
o0argv

m
				if (it exists) then perform action "AXPress"
			end tell
		end tell
	end tell
	o0scpt
.aevtoappnull****0scpt
.aevtoappnull****0argv0argv

cobj
.sysodsct****scpt0scptk/%%jE !"!#$#%%&
misccura

pcap&''Script Editor

mbar

mbri$((File

menE"))File

menI ** Open Dictionary &

actT++AXPressascrޭ


Delete trailing whitespace

Delete trailing whitespace

tell application "iTunes"
  set specified_tracks to (every track whose #{conditions})

	set json to "["

	repeat with specified_track in specified_tracks
    set props to {}

    set end of props to "{"
    set end of props to ("\"persistent_id\":\"" & persistent ID of specified_track & "\",")
    set end of props to ("\"name\":\"" & my escape_quote(name of specified_track) & "\",")
    set end of props to ("\"album\":\"" & my escape_quote(album of specified_track) & "\",")
    set end of props to ("\"artist\":\"" & my escape_quote(artist of specified_track) & "\",")
    set end of props to ("\"track_count\":\"" & track count of specified_track & "\",")
    set end of props to ("\"track_number\":\"" & track number of specified_track & "\"")
    set end of props to "}"

    set json to json & props as string & ","
  end repeat

  set json to json & "null]"
  return json

end tell

on escape_quote(someText)
 return replaceText(someText, "\"", "\\\"")
end escape_quote

(*
   https://discussions.apple.com/thread/4588230?start=0&tstart=0
*)
on replaceText(someText, oldItem, newItem)
     set {tempTID, AppleScript's text item delimiters} to {AppleScript's text item delimiters, oldItem}
     try
          set {itemList, AppleScript's text item delimiters} to {text items of someText, newItem}
          set {someText, AppleScript's text item delimiters} to {itemList as text, tempTID}
     on error errorMessage number errorNumber -- oops
          set AppleScript's text item delimiters to tempTID
          error errorMessage number errorNumber -- pass it on
     end try

     return someText
end replaceText


added dialogs to smart paste functions.

added dialogs to smart paste functions.

Scripts/fmClip - Smart Paste Functions.applescript