tweak due date

tweak due date

This seemed to help sync badge counts in the past, but now unsure of its
need. Leaving in commmented for future reference

property pTitle : "OmniFocus: Quick Stats"
property pVersion : "2.07.brett"

property pstrDBPath : "$HOME/Library/Containers/com.omnigroup.OmniFocus2/Data/Library/Caches/com.omnigroup.OmniFocus/OmniFocusDatabase2"
property pstrMinOSX : "10.9"

property pTimeOut : 30

-- Original version: https://github.com/RobTrew/tree-tools/blob/master/OmniFocus%20scripts/Statistics/QuickStats.applescript

-- Copyright  2012, 2013, 2014 Robin Trew
--
-- Permission is hereby granted, free of charge,
-- to any person obtaining a copy of this software
-- and associated documentation files (the "Software"),
-- to deal in the Software without restriction,
-- including without limitation the rights to use, copy,
-- modify, merge, publish, distribute, sublicense,
-- and/or sell copies of the Software, and to permit persons
-- to whom the Software is furnished to do so,
-- subject to the following conditions:
--
-- *******
-- The above copyright notice and this permission notice
-- shall be included in ALL copies
-- or substantial portions of the Software.
-- *******
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
-- OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
-- IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-- DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
-- TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
-- OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

-- Ver 0.8 adds clipboard option to dialogue
-- Ver 0.9 gives an error message if the cache schema has changed, leading to an SQL error in the script
-- Ver 1.0 slight simplification of the code
-- Ver 1.1 added count of Pending projects
-- Ver 1.2 added a count of available actions
-- Ver 1.3 added a break-down of unavailable actions
-- Ver 1.4 added count of Current projects to complement Pending projects
-- ver 1.5 replaced Applescript time function with SQL time expression
-- Ver 1.7 Reorganizes menu, and attempts to enable access for .macappstore installations of OF
--Ver 1.8 Adjusts handling of variant bundle identifiers generally
-- Ver 2.00 Redraft of task breakdown, with progressive narrowing of criteria ...

property pToClipboard : "Copy list to clipboard"

if not FileExists(pstrDBPath) then set pstrDBPath to GetCachePath()

tell application "Finder"
	if (version < pstrMinOSX) then
		display dialog "This script requires OSX " & pstrMinOSX & " or higher" buttons {"OK"} default button 1 with title pTitle & "Ver. " & pVersion
		return
	end if

	set screen_resolution to bounds of window of desktop
	set height to item 4 of screen_resolution
	if height < 1024 then
		set brief to true
	else
		set brief to false
	end if
end tell

if pstrDBPath  "" then
	set inbox_cmd to "
	select 'INBOX GROUPS & ACTIONS', count(*) from task where (inInbox=1);
	select '    Inbox action groups', count(*) from task where (inInbox=1) and (childrenCount>0);
	select '    Inbox actions', count(*) from task where (inInbox=1) and (childrenCount=0);
	select null;
	"
	set folders_cmd to "
	select 'FOLDERS'	, count(*) from folder;
	select '    Active folders', count(*) from folder where effectiveActive=1;
	select '    Dropped folders', count(*) from folder where effectiveActive=0;
	select null;
	"
	set projects_cmd to "
	select 'PROJECTS', count(*) from projectInfo where containsSingletonActions=0;
	select '    Active projects', count(*) from projectInfo where (containsSingletonActions=0) and (status='active');
	select '            Current projects', count(*) from projectInfo p join task t on t.projectinfo=p.pk where (p.containsSingletonActions=0) and (p.folderEffectiveActive=1) and (p.status='active') and (t.dateToStart is null or t.dateToStart < (strftime('%s','now') - strftime('%s','2001-01-01')));
	select '            Pending projects', count(*) from projectInfo p join task t on t.projectinfo=p.pk where (p.containsSingletonActions=0) and (p.folderEffectiveActive=1) and (p.status='active') and (t.dateToStart > (strftime('%s','now') - strftime('%s','2001-01-01')));
	select '    On-hold projects', count(*) from projectInfo where (containsSingletonActions=0) and (status='inactive');
	select '    Completed projects', count(*) from projectInfo where (containsSingletonActions=0) and (status='done');
	select '    Dropped projects', count(*) from projectInfo where (containsSingletonActions=0) and (( status='dropped') or (folderEffectiveActive=0));
	select null;
	"
	set lists_cmd to "
	select 'SINGLE ACTION LISTS', count(*) from projectInfo where containsSingletonActions=1;
	select '    Active single action lists', count(*) from projectInfo where (containsSingletonActions=1) and (status='active');
	select '    On-hold single action lists', count(*) from projectInfo where (containsSingletonActions=1) and (status='inactive');
	select '    Completed single action lists', count(*) from projectInfo where (containsSingletonActions=1) and (status='done');
	select '    Dropped single action lists', count(*) from projectInfo where (containsSingletonActions=1) and (( status='dropped') or (folderEffectiveActive=0));
	select null;
	"
	set contexts_cmd to "
	select 'CONTEXTS', count(*) from context;
	select '    Active contexts', count(*) from context where (effectiveActive=1) and (allowsNextAction=1);
	select '    On-hold contexts', count(*) from context where (effectiveActive=1) and allowsNextAction=0;
	select '    Dropped contexts', count(*) from context where effectiveActive=0;
	select null;
	"
	set groups_cmd to "
	select 'ACTION GROUPS', count(*) from task where (projectinfo is null) and (childrenCount>0);
	select '    Remaining action groups', count(*) from task where (projectinfo is null) and (dateCompleted is null) and (childrenCount>0);
	select '    Completed action groups', count(dateCompleted) from task where (projectinfo is null) and (childrenCount>0);
	select null;
	"
	set tasks_cmd to "
	select 'ALL TASKS', count(*) from task;
	select null;
	"
	set actions_cmd to "
	select 'ACTIONS', count(*) from task where (projectinfo is null) and (childrenCount=0);
	select '    Completed actions', count(dateCompleted) from task where (projectinfo is null) and (childrenCount=0);
	select '    Dropped project actions', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp where (projectinfo is null) and (childrenCount=0)  and (dateCompleted is null)
				and (tp.containingProjectinfo is not null and (tp.status='dropped' or tp.folderEffectiveActive=0));
	select '    Dropped context actions', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (projectinfo is null) and (tp.childrenCount=0)  and (dateCompleted is null)
				and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1))
				and c.effectiveActive= 0;
	select '    Remaining actions', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (projectinfo is null) and (tp.childrenCount=0)  and (dateCompleted is null)
				and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1))
				and (tp.context is null or c.effectiveActive= 1);
	select '        Actions in Projects on hold', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (projectinfo is null) and (tp.childrenCount=0)  and (dateCompleted is null)
				and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1))
				and (tp.context is null or c.effectiveActive= 1)
				and (tp.containingProjectInfo is not null and tp.status='inactive');
	select '        Actions in Contexts on hold', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (projectinfo is null) and (tp.childrenCount=0)  and (dateCompleted is null)
				and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1))
				and (tp.context is null or c.effectiveActive= 1)
				and (tp.containingProjectInfo is null or tp.status!='inactive')
				and (tp.context is not null and c.allowsNextAction=0);
	select '        Blocked actions', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (projectinfo is null) and (tp.childrenCount=0)  and (dateCompleted is null)
				and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1))
				and (tp.context is null or c.effectiveActive= 1)
				and (tp.containingProjectInfo is null or tp.status!='inactive')
				and (tp.context is null or c.allowsNextAction=1)
				and tp.blocked=1;
	select '        	Blocked by future start date', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (projectinfo is null) and (tp.childrenCount=0)  and (dateCompleted is null)
				and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1))
				and (tp.context is null or c.effectiveActive= 1)
				and (tp.containingProjectInfo is null or tp.status!='inactive')
				and (tp.context is null or c.allowsNextAction=1)
				and tp.blocked=1
				and tp.blockedByFutureStartDate=1;
	select '        	Sequentially blocked', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (projectinfo is null) and (tp.childrenCount=0)  and (dateCompleted is null)
				and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1))
				and (tp.context is null or c.effectiveActive= 1)
				and (tp.containingProjectInfo is null or tp.status!='inactive')
				and (tp.context is null or c.allowsNextAction=1)
				and tp.blocked=1
				and tp.blockedByFutureStartDate=0;
	select '        Available actions', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (projectinfo is null) and (tp.childrenCount=0)  and (dateCompleted is null)
				and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1))
				and (tp.context is null or c.effectiveActive= 1)
				and (tp.containingProjectInfo is null or tp.status!='inactive')
				and (tp.context is null or c.allowsNextAction=1)
				and tp.blocked=0;
	select null;
	"
	set summary_cmd to "
	select 'SUMMARY';
	select '    Inbox available actions', count(*) from task where (inInbox=1) and (dateCompleted is null);
	select '    Due in next week', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (projectinfo is null) and (tp.childrenCount=0)  and (dateCompleted is null)
				and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1))
				and (tp.context is null or c.effectiveActive= 1)
				and (tp.containingProjectInfo is null or tp.status!='inactive')
				/* and (tp.context is null or c.allowsNextAction=1) */
				and tp.blockedByFutureStartDate=0
				and effectiveDateDue <= strftime('%s','now','+7 days') - strftime('%s','2001-01-01');
				/* and dateDue < strftime('%s','now','+7 days') - strftime('%s','2001-01-01'); */
	select '    Flagged projects and actions', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (((projectinfo is null) and (tp.childrenCount=0))  or containsSingletonActions=0) and (dateCompleted is null)
				and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1))
				and (tp.context is null or c.effectiveActive= 1)
				and (tp.containingProjectInfo is null or tp.status!='inactive')
				/* and (tp.context is null or c.allowsNextAction=1) */
				and tp.blockedByFutureStartDate=0
				and tp.effectiveFlagged;
	select '    Due or Flagged', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (((projectinfo is null) and (tp.childrenCount=0))  or containsSingletonActions=0) and (dateCompleted is null)
				and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1))
				and (tp.context is null or c.effectiveActive= 1)
				and (tp.containingProjectInfo is null or tp.status!='inactive')
				/* and (tp.context is null or c.allowsNextAction=1) */
				and tp.blockedByFutureStartDate=0
				and (tp.effectiveFlagged or (effectiveDateDue <= strftime('%s','now','+7 days') - strftime('%s','2001-01-01')));
	select null;
	"
	if brief then
		set commands to summary_cmd & actions_cmd & projects_cmd & contexts_cmd
	else
		set commands to summary_cmd & actions_cmd & inbox_cmd & folders_cmd & projects_cmd & lists_cmd & contexts_cmd & groups_cmd & tasks_cmd
	end if
	set strCmd to "sqlite3 -separator ': ' \"" & pstrDBPath & "\" " & quoted form of (commands)

	-- 		try
	set strList to do shell script strCmd
	-- 		on error
	-- 			display dialog "The SQL schema for the OmniFocus cache may have changed in a recent update of OF." & return & return &
	-- 				"Look on the OmniFocus user forums for an updated version of this script." buttons {"OK"} with title pTitle & "Ver. " & pVersion
	-- 			return
	-- 		end try
	tell application id "sevs"
		activate
		if button returned of (display dialog strList buttons {pToClipboard, "OK"} default button "OK" giving up after pTimeOut with title pTitle & " Ver. " & pVersion)
			is pToClipboard then tell application id "com.apple.finder" to set the clipboard to strList
	end tell
else
	tell application id "sevs"
		activate
		display dialog "OmniFocus cache not found ..." buttons {"OK"} default button 1 with title pTitle & " Ver. " & pVersion
	end tell
end if

on FileExists(strPath)
	(do shell script "test -e " & strPath & " ; echo $?") = "0"
end FileExists

on GetCachePath()
	try
		tell application "Finder" to tell (application file id "OFOC") to "$HOME/Library/Containers/com.omnigroup.OmniFocus2/Data/Library/Caches/" & its id & "/OmniFocusDatabase2"
	on error
		error "OmniFocus not installed ..."
	end try
end GetCachePath

property pTitle : "OmniFocus: Quick Stats"
property pVersion : "2.07.brett"

property pstrDBPath : "$HOME/Library/Containers/com.omnigroup.OmniFocus2/Data/Library/Caches/com.omnigroup.OmniFocus/OmniFocusDatabase2"
property pstrMinOSX : "10.9"

property pTimeOut : 30

-- Original version: https://github.com/RobTrew/tree-tools/blob/master/OmniFocus%20scripts/Statistics/QuickStats.applescript

-- Copyright  2012, 2013, 2014 Robin Trew
--
-- Permission is hereby granted, free of charge,
-- to any person obtaining a copy of this software
-- and associated documentation files (the "Software"),
-- to deal in the Software without restriction,
-- including without limitation the rights to use, copy,
-- modify, merge, publish, distribute, sublicense,
-- and/or sell copies of the Software, and to permit persons
-- to whom the Software is furnished to do so,
-- subject to the following conditions:
--
-- *******
-- The above copyright notice and this permission notice
-- shall be included in ALL copies
-- or substantial portions of the Software.
-- *******
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
-- OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
-- IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-- DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
-- TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
-- OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

-- Ver 0.8 adds clipboard option to dialogue
-- Ver 0.9 gives an error message if the cache schema has changed, leading to an SQL error in the script
-- Ver 1.0 slight simplification of the code
-- Ver 1.1 added count of Pending projects
-- Ver 1.2 added a count of available actions
-- Ver 1.3 added a break-down of unavailable actions
-- Ver 1.4 added count of Current projects to complement Pending projects
-- ver 1.5 replaced Applescript time function with SQL time expression
-- Ver 1.7 Reorganizes menu, and attempts to enable access for .macappstore installations of OF
--Ver 1.8 Adjusts handling of variant bundle identifiers generally
-- Ver 2.00 Redraft of task breakdown, with progressive narrowing of criteria ...

property pToClipboard : "Copy list to clipboard"

if not FileExists(pstrDBPath) then set pstrDBPath to GetCachePath()

tell application "Finder"
	if (version < pstrMinOSX) then
		display dialog "This script requires OSX " & pstrMinOSX & " or higher" buttons {"OK"} default button 1 with title pTitle & "Ver. " & pVersion
		return
	end if

	set screen_resolution to bounds of window of desktop
	set height to item 4 of screen_resolution
	if height < 1024 then
		set brief to true
	else
		set brief to false
	end if
end tell

if pstrDBPath  "" then
	set inbox_cmd to "
	select 'INBOX GROUPS & ACTIONS', count(*) from task where (inInbox=1);
	select '    Inbox action groups', count(*) from task where (inInbox=1) and (childrenCount>0);
	select '    Inbox actions', count(*) from task where (inInbox=1) and (childrenCount=0);
	select null;
	"
	set folders_cmd to "
	select 'FOLDERS'	, count(*) from folder;
	select '    Active folders', count(*) from folder where effectiveActive=1;
	select '    Dropped folders', count(*) from folder where effectiveActive=0;
	select null;
	"
	set projects_cmd to "
	select 'PROJECTS', count(*) from projectInfo where containsSingletonActions=0;
	select '    Active projects', count(*) from projectInfo where (containsSingletonActions=0) and (status='active');
	select '            Current projects', count(*) from projectInfo p join task t on t.projectinfo=p.pk where (p.containsSingletonActions=0) and (p.folderEffectiveActive=1) and (p.status='active') and (t.dateToStart is null or t.dateToStart < (strftime('%s','now') - strftime('%s','2001-01-01')));
	select '            Pending projects', count(*) from projectInfo p join task t on t.projectinfo=p.pk where (p.containsSingletonActions=0) and (p.folderEffectiveActive=1) and (p.status='active') and (t.dateToStart > (strftime('%s','now') - strftime('%s','2001-01-01')));
	select '    On-hold projects', count(*) from projectInfo where (containsSingletonActions=0) and (status='inactive');
	select '    Completed projects', count(*) from projectInfo where (containsSingletonActions=0) and (status='done');
	select '    Dropped projects', count(*) from projectInfo where (containsSingletonActions=0) and (( status='dropped') or (folderEffectiveActive=0));
	select null;
	"
	set lists_cmd to "
	select 'SINGLE ACTION LISTS', count(*) from projectInfo where containsSingletonActions=1;
	select '    Active single action lists', count(*) from projectInfo where (containsSingletonActions=1) and (status='active');
	select '    On-hold single action lists', count(*) from projectInfo where (containsSingletonActions=1) and (status='inactive');
	select '    Completed single action lists', count(*) from projectInfo where (containsSingletonActions=1) and (status='done');
	select '    Dropped single action lists', count(*) from projectInfo where (containsSingletonActions=1) and (( status='dropped') or (folderEffectiveActive=0));
	select null;
	"
	set contexts_cmd to "
	select 'CONTEXTS', count(*) from context;
	select '    Active contexts', count(*) from context where (effectiveActive=1) and (allowsNextAction=1);
	select '    On-hold contexts', count(*) from context where (effectiveActive=1) and allowsNextAction=0;
	select '    Dropped contexts', count(*) from context where effectiveActive=0;
	select null;
	"
	set groups_cmd to "
	select 'ACTION GROUPS', count(*) from task where (projectinfo is null) and (childrenCount>0);
	select '    Remaining action groups', count(*) from task where (projectinfo is null) and (dateCompleted is null) and (childrenCount>0);
	select '    Completed action groups', count(dateCompleted) from task where (projectinfo is null) and (childrenCount>0);
	select null;
	"
	set tasks_cmd to "
	select 'ALL TASKS', count(*) from task;
	select null;
	"
	set actions_cmd to "
	select 'ACTIONS', count(*) from task where (projectinfo is null) and (childrenCount=0);
	select '    Completed actions', count(dateCompleted) from task where (projectinfo is null) and (childrenCount=0);
	select '    Dropped project actions', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp where (projectinfo is null) and (childrenCount=0)  and (dateCompleted is null)
				and (tp.containingProjectinfo is not null and (tp.status='dropped' or tp.folderEffectiveActive=0));
	select '    Dropped context actions', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (projectinfo is null) and (tp.childrenCount=0)  and (dateCompleted is null)
				and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1))
				and c.effectiveActive= 0;
	select '    Remaining actions', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (projectinfo is null) and (tp.childrenCount=0)  and (dateCompleted is null)
				and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1))
				and (tp.context is null or c.effectiveActive= 1);
	select '        Actions in Projects on hold', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (projectinfo is null) and (tp.childrenCount=0)  and (dateCompleted is null)
				and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1))
				and (tp.context is null or c.effectiveActive= 1)
				and (tp.containingProjectInfo is not null and tp.status='inactive');
	select '        Actions in Contexts on hold', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (projectinfo is null) and (tp.childrenCount=0)  and (dateCompleted is null)
				and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1))
				and (tp.context is null or c.effectiveActive= 1)
				and (tp.containingProjectInfo is null or tp.status!='inactive')
				and (tp.context is not null and c.allowsNextAction=0);
	select '        Blocked actions', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (projectinfo is null) and (tp.childrenCount=0)  and (dateCompleted is null)
				and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1))
				and (tp.context is null or c.effectiveActive= 1)
				and (tp.containingProjectInfo is null or tp.status!='inactive')
				and (tp.context is null or c.allowsNextAction=1)
				and tp.blocked=1;
	select '        	Blocked by future start date', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (projectinfo is null) and (tp.childrenCount=0)  and (dateCompleted is null)
				and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1))
				and (tp.context is null or c.effectiveActive= 1)
				and (tp.containingProjectInfo is null or tp.status!='inactive')
				and (tp.context is null or c.allowsNextAction=1)
				and tp.blocked=1
				and tp.blockedByFutureStartDate=1;
	select '        	Sequentially blocked', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (projectinfo is null) and (tp.childrenCount=0)  and (dateCompleted is null)
				and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1))
				and (tp.context is null or c.effectiveActive= 1)
				and (tp.containingProjectInfo is null or tp.status!='inactive')
				and (tp.context is null or c.allowsNextAction=1)
				and tp.blocked=1
				and tp.blockedByFutureStartDate=0;
	select '        Available actions', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (projectinfo is null) and (tp.childrenCount=0)  and (dateCompleted is null)
				and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1))
				and (tp.context is null or c.effectiveActive= 1)
				and (tp.containingProjectInfo is null or tp.status!='inactive')
				and (tp.context is null or c.allowsNextAction=1)
				and tp.blocked=0;
	select null;
	"
	set summary_cmd to "
	select 'SUMMARY';
	select '    Inbox available actions', count(*) from task where (inInbox=1) and (dateCompleted is null);
	select '    Due in next week', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (projectinfo is null) and (tp.childrenCount=0)  and (dateCompleted is null)
				and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1))
				and (tp.context is null or c.effectiveActive= 1)
				and (tp.containingProjectInfo is null or tp.status!='inactive')
				/* and (tp.context is null or c.allowsNextAction=1) */
				and tp.blockedByFutureStartDate=0
				and effectiveDateDue <= strftime('%s','now','+7 days') - strftime('%s','2001-01-01');
	select '    Flagged projects and actions', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (((projectinfo is null) and (tp.childrenCount=0))  or containsSingletonActions=0) and (dateCompleted is null)
				and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1))
				and (tp.context is null or c.effectiveActive= 1)
				and (tp.containingProjectInfo is null or tp.status!='inactive')
				/* and (tp.context is null or c.allowsNextAction=1) */
				and tp.blockedByFutureStartDate=0
				and tp.effectiveFlagged;
	select '    Due or Flagged', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (((projectinfo is null) and (tp.childrenCount=0))  or containsSingletonActions=0) and (dateCompleted is null)
				and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1))
				and (tp.context is null or c.effectiveActive= 1)
				and (tp.containingProjectInfo is null or tp.status!='inactive')
				/* and (tp.context is null or c.allowsNextAction=1) */
				and tp.blockedByFutureStartDate=0
				and (tp.effectiveFlagged or (effectiveDateDue <= strftime('%s','now','+7 days') - strftime('%s','2001-01-01')));
	select null;
	"
	if brief then
		set commands to summary_cmd & actions_cmd & projects_cmd & contexts_cmd
	else
		set commands to summary_cmd & actions_cmd & inbox_cmd & folders_cmd & projects_cmd & lists_cmd & contexts_cmd & groups_cmd & tasks_cmd
	end if
	set strCmd to "sqlite3 -separator ': ' \"" & pstrDBPath & "\" " & quoted form of (commands)

	-- 		try
	set strList to do shell script strCmd
	-- 		on error
	-- 			display dialog "The SQL schema for the OmniFocus cache may have changed in a recent update of OF." & return & return &
	-- 				"Look on the OmniFocus user forums for an updated version of this script." buttons {"OK"} with title pTitle & "Ver. " & pVersion
	-- 			return
	-- 		end try
	tell application id "sevs"
		activate
		if button returned of (display dialog strList buttons {pToClipboard, "OK"} default button "OK" giving up after pTimeOut with title pTitle & " Ver. " & pVersion)
			is pToClipboard then tell application id "com.apple.finder" to set the clipboard to strList
	end tell
else
	tell application id "sevs"
		activate
		display dialog "OmniFocus cache not found ..." buttons {"OK"} default button 1 with title pTitle & " Ver. " & pVersion
	end tell
end if

on FileExists(strPath)
	(do shell script "test -e " & strPath & " ; echo $?") = "0"
end FileExists

on GetCachePath()
	try
		tell application "Finder" to tell (application file id "OFOC") to "$HOME/Library/Containers/com.omnigroup.OmniFocus2/Data/Library/Caches/" & its id & "/OmniFocusDatabase2"
	on error
		error "OmniFocus not installed ..."
	end try
end GetCachePath


Delete TestAllSettings.applescript

Delete TestAllSettings.applescript

MC = Application("Menubar Countdown")

MC.activate()

MC.showStartDialog()

MC.hours = 99
MC.minutes = 59
MC.seconds = 59

MC.blink = false
MC.playAlertSound = false
MC.repeatAlertSound = false
MC.showAlertWindow = false
MC.showNotification = false
MC.playNotificationSound = false
MC.speakAnnouncement = false

MC.announcementText = "The checkboxes should all be off now."

MC.displaySeconds = false
MC.showStartDialogOnLaunch = false

delay(2)

MC.hours = 0
MC.minutes = 25
MC.seconds = 0

MC.blink = true
MC.playAlertSound = true
MC.repeatAlertSound = true
MC.showAlertWindow = true
MC.showNotification = true
MC.playNotificationSound = true
MC.speakAnnouncement = true

MC.announcementText = "The checkboxes should all be on now."

MC.displaySeconds = true
MC.showStartDialogOnLaunch = true


Setting this back to the value it had before accidentally changing it.

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

tell application "Finder"
	tell disk "Growl"
		open
		tell container window
			set current view to icon view
			set toolbar visible to false
			set statusbar visible to false
			set the bounds to {30, 50, 480, 350}
		end tell
		close
		set opts to the icon view options of container window
		tell opts
			set icon size to 56
			set arrangement to not arranged
		end tell
		set background picture of opts to file ".background:growlDMGBackground.png"
		set position of item "Growl.prefPane" to {45, 41}
		set position of item "Extras" to {162, 33}
		--set position of item "Scripts" to {36, 153}
		set position of item "Growl Documentation.webloc" to {128, 123}
		set position of item "Growl version history.webloc" to {265, 41}
		set position of item "Get more styles.webloc" to {383, 41}
		set position of item "Uninstall Growl.app" to {383, 123}
		update without registering applications
		tell container window
			set the bounds to {31, 50, 579, 350}
			set the bounds to {30, 50, 579, 350}
		end tell
		update without registering applications
	end tell
	--give the finder some time to write the .DS_Store file
	delay 5
end tell

tell application "Finder"
	tell disk "Growl"
		open
		tell container window
			set current view to icon view
			set toolbar visible to false
			set statusbar visible to false
			set the bounds to {30, 50, 480, 350}
		end tell
		close
		set opts to the icon view options of container window
		tell opts
			set icon size to 56
			set arrangement to not arranged
		end tell
		set background picture of opts to file ".background:growlDMGBackground.png"
		set position of item "Growl.prefPane" to {45, 41}
		set position of item "Extras" to {162, 33}
		--set position of item "Scripts" to {36, 153}
		set position of item "Growl Documentation.webloc" to {128, 123}
		set position of item "Growl version history.webloc" to {265, 41}
		set position of item "Get more styles.webloc" to {383, 41}
		set position of item "Uninstall Growl.app" to {383, 123}
		update without registering applications
		tell container window
			set the bounds to {31, 50, 579, 4000}
			set the bounds to {30, 50, 579, 4000}
		end tell
		update without registering applications
	end tell
	--give the finder some time to write the .DS_Store file
	delay 5
end tell


Fixed \r in changeScreen

Fixed \r in changeScreen

on run argv
	global _cache
	set _cache to {}

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

	set _terminalApp to terminalApp of _config

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

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

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

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


Update the text fields when tracks are loaded

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

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

script DASAppDelegate
	property parent : class "NSObject"

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

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

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

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

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

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

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

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

    on btnConcatenate_(sender)
        set the_pipes to {}
        repeat with theIndex in the_index
            -- TODO: Needs error checking!
            -- TODO: We need to check what kind of audio files we have, then adjust accordingly
            do shell script (cmdPrefix & "ffmpeg -i \"" & (item theIndex of these_files as text) & "\" -c copy -bsf:v h264_mp4toannexb -f mpegts /private/tmp/concat" & theIndex & ".ts 2> /dev/null" as text)
            log ("Processed file number" & theIndex) as text
            set end of the_pipes to ("/private/tmp/concat" & theIndex & ".ts" as text)
        end repeat
        -- Run the actual concatenation command in ffmpeg (for mp4/AAC files only!)
        -- via https://trac.ffmpeg.org/wiki/How%20to%20concatenate%20(join,%20merge)%20media%20files
        set olddelimeters to AppleScript's text item delimiters
        set AppleScript's text item delimiters to "|"
        set disp_thepipes to the_pipes as string
        do shell script (cmdPrefix & "ffmpeg -f mpegts -i \"concat:" & (disp_thepipes as text) & "\" -c copy -bsf:a aac_adtstoasc /private/tmp/cat.mp4")
        set AppleScript's text item delimiters to olddelimeters
        -- Log some debugging information
        log (pcatArtist as string)
        log (pcatAlbum as string)
        log (pcatComposer as string)
        log (pcatGenre as string)
        log (pcatDisc as string)
        log (pcatDiscs as string)
        -- Now let's create the chapter file
        repeat with theIndex in the_index
            if theIndex < 2 then
                do shell script ("/bin/echo \"00:00:00.000 " & (item theIndex of these_titles as text) & "\" > /private/tmp/cat.chapters.txt" as text)
                set theCounter to (do shell script (cmdPrefix & "ffprobe -loglevel panic -show_streams /private/tmp/concat" & (theIndex as text) & ".ts | egrep -m 1 'duration=[0-9]+\\.' | sed 's/duration=\\([0-9]*[0-9]\\)\\.[0-9]*/\\1/'" as text) as string)
            else
                set theDateStamp to do shell script (cmdPrefix & "t="& (theCounter as text) & ";((sec=t%60, t/=60, min=t%60, hrs=t/60));timestamp=$(printf \"%02d:%02d:%02d\" $hrs $min $sec);/bin/echo $timestamp" as text)
                do shell script ("/bin/echo \"" & (theDateStamp as text) & ".000 " & (item theIndex of these_titles as text) & "\" >> /private/tmp/cat.chapters.txt" as text)
                log ("Before the addition, theCounter is " & theCounter) as text
                set theCounter to do shell script (cmdPrefix & "t=" & theCounter & ";t=`echo $t\"+\\`ffprobe -loglevel panic -show_streams /private/tmp/concat" & (theIndex as text) & ".ts | egrep -m 1 'duration=[0-9]+\\.' | sed 's/duration=\\([0-9]*[0-9]\\)\\.[0-9]*/\\1/'\\`\" | bc`;echo $t" as text)
                log ("After the addition, theCounter is " & theCounter) as text
            end if
        end repeat
        -- Chapterize cat.mp4
        do shell script (cmdPrefix & "mp4chaps -i /private/tmp/cat.mp4" as text)
        -- Clean up
        do shell script "/bin/rm /private/tmp/concat* /private/tmp/cat.chapters.txt /private/tmp/cat.mp4"
        set theCounter to ""
    end btnConcatenate_

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

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

end script

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

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

script DASAppDelegate
	property parent : class "NSObject"

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

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

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

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

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

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

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

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

    on btnConcatenate_(sender)
        set the_pipes to {}
        repeat with theIndex in the_index
            -- TODO: Needs error checking!
            -- TODO: We need to check what kind of audio files we have, then adjust accordingly
            do shell script (cmdPrefix & "ffmpeg -i \"" & (item theIndex of these_files as text) & "\" -c copy -bsf:v h264_mp4toannexb -f mpegts /private/tmp/concat" & theIndex & ".ts 2> /dev/null" as text)
            log ("Processed file number" & theIndex) as text
            set end of the_pipes to ("/private/tmp/concat" & theIndex & ".ts" as text)
        end repeat
        -- Run the actual concatenation command in ffmpeg (for mp4/AAC files only!)
        -- via https://trac.ffmpeg.org/wiki/How%20to%20concatenate%20(join,%20merge)%20media%20files
        set olddelimeters to AppleScript's text item delimiters
        set AppleScript's text item delimiters to "|"
        set disp_thepipes to the_pipes as string
        do shell script (cmdPrefix & "ffmpeg -f mpegts -i \"concat:" & (disp_thepipes as text) & "\" -c copy -bsf:a aac_adtstoasc /private/tmp/cat.mp4")
        set AppleScript's text item delimiters to olddelimeters
        -- Log some debugging information
        log (pcatArtist as string)
        log (pcatAlbum as string)
        log (pcatComposer as string)
        log (pcatGenre as string)
        log (pcatDisc as string)
        log (pcatDiscs as string)
        -- Now let's create the chapter file
        repeat with theIndex in the_index
            if theIndex < 2 then
                do shell script ("/bin/echo \"00:00:00.000 " & (item theIndex of these_titles as text) & "\" > /private/tmp/cat.chapters.txt" as text)
                set theCounter to (do shell script (cmdPrefix & "ffprobe -loglevel panic -show_streams /private/tmp/concat" & (theIndex as text) & ".ts | egrep -m 1 'duration=[0-9]+\\.' | sed 's/duration=\\([0-9]*[0-9]\\)\\.[0-9]*/\\1/'" as text) as string)
            else
                set theDateStamp to do shell script (cmdPrefix & "t="& (theCounter as text) & ";((sec=t%60, t/=60, min=t%60, hrs=t/60));timestamp=$(printf \"%02d:%02d:%02d\" $hrs $min $sec);/bin/echo $timestamp" as text)
                do shell script ("/bin/echo \"" & (theDateStamp as text) & ".000 " & (item theIndex of these_titles as text) & "\" >> /private/tmp/cat.chapters.txt" as text)
                log ("Before the addition, theCounter is " & theCounter) as text
                set theCounter to do shell script (cmdPrefix & "t=" & theCounter & ";t=`echo $t\"+\\`ffprobe -loglevel panic -show_streams /private/tmp/concat" & (theIndex as text) & ".ts | egrep -m 1 'duration=[0-9]+\\.' | sed 's/duration=\\([0-9]*[0-9]\\)\\.[0-9]*/\\1/'\\`\" | bc`;echo $t" as text)
                log ("After the addition, theCounter is " & theCounter) as text
            end if
        end repeat
        -- Chapterize cat.mp4
        do shell script (cmdPrefix & "mp4chaps -i /private/tmp/cat.mp4" as text)
        -- Clean up
        do shell script "/bin/rm /private/tmp/concat* /private/tmp/cat.chapters.txt /private/tmp/cat.mp4"
        set theCounter to ""
    end btnConcatenate_

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

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

end script


fix apple script

fix apple script

(* commented out printer section for now
tell application "iPhone Simulator" to activate

tell application "System Events"
    tell process "iPhone Simulator"
        tell menu bar 1
            tell menu bar item "File"
                tell menu "File"
                    click menu item "Open Printer Simulator"
                end tell
            end tell
        end tell
    end tell
end tell
*)

tell application "iOS Simulator" to launch

set inTime to current date
repeat
    tell application "System Events"
        if "iOS Simulator" is in (get name of processes) then exit repeat
    end tell
    if (current date) - inTime is greater than 10 then exit repeat
    delay 0.2
end repeat

tell application "iOS Simulator" to activate

set inTime to current date
repeat
    tell application "System Events"
        if visible of process "iOS Simulator" is true then exit repeat
    end tell
    if (current date) - inTime is greater than 10 then exit repeat
    delay 0.2
end repeat

tell application "System Events"
    tell process "iOS Simulator"
        tell menu bar 1
            tell menu bar item "iOS Simulator"
                tell menu "iOS Simulator"
                    click menu item "Reset Content and Settings…"
                end tell
            end tell
        end tell

        tell window 1
            click button "Reset"
        end tell
    end tell
end tell

tell application "iOS Simulator" to quit

set inTime to current date
repeat
    tell application "System Events"
        if "iOS Simulator" is not in (get name of processes) then exit repeat
    end tell
    if (current date) - inTime is greater than 10 then exit repeat
    delay 0.2
end repeat

-- tell application "System Events" to tell process "Printer Simulator" to set visible to false

(* commented out printer section for now
tell application "iPhone Simulator" to activate

tell application "System Events"
    tell process "iPhone Simulator"
        tell menu bar 1
            tell menu bar item "File"
                tell menu "File"
                    click menu item "Open Printer Simulator"
                end tell
            end tell
        end tell
    end tell
end tell
*)

tell application "iPhone Simulator" to launch

set inTime to current date
repeat
    tell application "System Events"
        if "iPhone Simulator" is in (get name of processes) then exit repeat
    end tell
    if (current date) - inTime is greater than 10 then exit repeat
    delay 0.2
end repeat

tell application "iPhone Simulator" to activate

set inTime to current date
repeat
    tell application "System Events"
        if visible of process "iPhone Simulator" is true then exit repeat
    end tell
    if (current date) - inTime is greater than 10 then exit repeat
    delay 0.2
end repeat

tell application "System Events"
    tell process "iPhone Simulator"
        tell menu bar 1
            tell menu bar item "iOS Simulator"
                tell menu "iOS Simulator"
                    click menu item "Reset Content and Settings…"
                end tell
            end tell
        end tell

        tell window 1
            click button "Reset"
        end tell
    end tell
end tell

tell application "iPhone Simulator" to quit

set inTime to current date
repeat
    tell application "System Events"
        if "iPhone Simulator" is not in (get name of processes) then exit repeat
    end tell
    if (current date) - inTime is greater than 10 then exit repeat
    delay 0.2
end repeat

-- tell application "System Events" to tell process "Printer Simulator" to set visible to false


beta? what beta? you didn't see this

beta? what beta? you didn't see this

#!/usr/bin/osascript

on run argv
    set idx to item 1 of argv
    if application "Deckset" is running
        tell application "Deckset"
            tell first item of documents
                set slideIndex to idx
            end tell
        end tell
    end if
end run

#!/usr/bin/osascript

on run argv
    set idx to item 1 of argv
    if application "Deckset private beta" is running
        tell application "Deckset private beta"
            tell first item of documents
                set slideIndex to idx
            end tell
        end tell
    end if
end run


Fixing error log path

Fixing error log path

Thanks to @steveswinsburg for the report.
Fixes issue #15

property debug : false
property currentVolume : null

if (isTheFirstRun() and not isInLoginItems()) then
    set userAnswer to the button returned of (display dialog "Hi, thanks for installing Spotifree!" & ¬
        return & "Just so you know, Spotifree has no interface yet, and will work silently in the background." & return & return ¬
        & "BTW, do you want it to run automatically on startup?" with title ¬
        "You are awesome!" with icon 1 buttons {"No, thanks", "OK"} default button 2)
    if (userAnswer = "OK") then
        try
            my addToLoginItems()
        end try
    end if
    try
        -- Save in the preferences that Spotifree has already ran.
        do shell script "defaults write com.ArtemGordinsky.Spotifree 'hasRanBefore' 'true'"
    end try
end if

repeat
    try
        -- Adding a 5 seconds timeout instead of default 2 min. Prevents long unresponsiveness of the app.
        with timeout of (5) seconds
            if (isRunning() and isPlaying() and isAnAd()) then
                try
                    mute()
                end try
                repeat
                    delay 0.3
                    try
                        if (isRunning() and not isAnAd()) then
                            -- Have to delay a little bit, because Spotify may tell us about the next track too early,
                            -- and a user may to hear the last half-second of an ad.
                            delay 0.8
                            unmute()
                            exit repeat
                        end if
                    end try
                end repeat
            else
                -- Delaying, to get less of the crashing "connection is invalid" errors.
                delay 1
            end if
        end timeout
    on error errorMessage number errorNumber
        my log_error(errorNumber, errorMessage, "Somewhere in the outer loop.")
    end try
    -- This is how fast we are polling Spotify.
    -- The only speed at which you will hear almost no sounds passing through.
    -- Fortunately, even combined with the added load on Spotify, the CPU usage is rather miniscule.
    delay 0.3
end repeat

on mute()
    try
        tell application "Spotify"
            set currentVolume to sound volume
            -- This is the only way possible to mute Spotify during an advertisement.
            -- Otherwise it pauses when you mute the sound.
            pause
            set sound volume to 0
            play
        end tell
    on error errorMessage number errorNumber
        my log_error(errorNumber, errorMessage, "mute()")
    end try
    return
end mute

on unmute()
    try
        tell application "Spotify"
            -- Restore the volume to the level supplied to the parameter.
            set sound volume to currentVolume
        end tell
    on error errorMessage number errorNumber
        my log_error(errorNumber, errorMessage, "unmute()")
    end try
    return
end unmute

on isAnAd()
    local currentTrackPopularity, currentTrackDuration
    set currentTrackPopularity to null
    set currentTrackDuration to null
    # Nesting "try" blocks is the only way to handle multiple errors in AppleScript
    try
        try
            try
                tell application "Spotify"
                    set currentTrackPopularity to popularity of current track
                    set currentTrackDuration to duration of current track
                end tell
            on error number -1728
                # Ignoring "can't get current track" error
            end try
        on error number -609
            # Ignoring the "invalid connection errors"
        end try
    on error errorMessage number errorNumber
        my log_error(errorNumber, errorMessage, "isAnAd()")
        return false
    end try
    if ((currentTrackPopularity ≠ null and currentTrackDuration ≠ null) and (currentTrackPopularity = 0 and currentTrackDuration ≤ 40)) then
        return true
    else
        return false
    end if
end isAnAd

on isPlaying()
    local playerState
    set playerState to null
    # Nesting "try" blocks is the only way to handle multiple errors in AppleScript
    try
        try
            tell application "Spotify"
                set playerState to player state
            end tell
        on error -609
            # Ignoring the "invalid connection" errors
        end try
    on error errorMessage number errorNumber
        my log_error(errorNumber, errorMessage, "isRunning()")
        return false
    end try
    if (playerState ≠ null and playerState = «constant ****kPSP») then
        return true
    else
        return false
    end if
end isPlaying

on isRunning()
    local spotifyProcesses
    # Nesting "try" blocks is the only way to handle multiple errors in AppleScript
    try
        try
            tell application "System Events"
                set spotifyProcesses to (count of (every process whose name is "Spotify"))
            end tell
        on error number -609
            # Ignoring the "invalid connection" errors
        end try
    on error errorMessage number errorNumber
        my log_error(errorNumber, errorMessage, "isRunning()")
        return false
    end try
    if spotifyProcesses is 1 then
        return true
    else
        return false
    end if
end isRunning

on addToLoginItems()
    try
        tell application "System Events"
            -- Add Spotifree to the Login Items.
            make login item at end with properties {name:"Spotifree", path:"/Applications/Spotifree.app", hidden:true}
        end tell
    on error errorMessage number errorNumber
        my log_error(errorNumber, errorMessage, "addToLoginItems()")
        return
    end try
end addToLoginItems

on isTheFirstRun()
    local isPrefFileExists, prefFilePath
    set prefFilePath to "~/Library/Preferences/com.ArtemGordinsky.Spotifree"
    try
        tell application "System Events"
            if exists file prefFilePath then
                set isPrefFileExists to true
            else
                set isPrefFileExists to false
            end if
        end tell
    on error errorMessage number errorNumber
        my log_error(errorNumber, errorMessage, "isTheFirstRun()")
        return true
    end try
    # "not" works like a bang sign here
    return not isPrefFileExists
end isTheFirstRun

on isInLoginItems()
    try
        tell application "System Events"
            if login item "Spotifree" exists then
                return true
            else
                return false
            end if
        end tell
    on error errorMessage number errorNumber
        my log_error(errorNumber, errorMessage, "isInLoginItems()")
        return false
    end try
end isInLoginItems

on log_error(error_number, error_message, diag_message)
    local content
    if (debug = true) then
        set content to (return & "" & ¬
            return & my dateAndTime() & return & "Error number: " & error_number ¬
            & return & "Error message: " & error_message & return & ¬
            "Diagnostic message: " & diag_message & return ¬
            & "" & return)
        set log_file to (((path to desktop folder) as text) & "Spotifree_log.txt")
        my write_to_file(content, log_file, true)
    end if
end log_error

on write_to_file(this_data, target_file, append_data) -- (string, file path as string, boolean)
    try
        set the target_file to the target_file as text
        set the open_target_file to ¬
            open for access file target_file with write permission
        if append_data is false then ¬
            set eof of the open_target_file to 0
        write this_data to the open_target_file starting at eof
        close access the open_target_file
        return true
    on error
        try
            close access file target_file
        end try
    end try
end write_to_file

on dateAndTime()
    set currentDateAndTime to (current date) as string
    return currentDateAndTime
end dateAndTime

property debug : false
property currentVolume : null

if (isTheFirstRun() and not isInLoginItems()) then
    set userAnswer to the button returned of (display dialog "Hi, thanks for installing Spotifree!" & ¬
        return & "Just so you know, Spotifree has no interface yet, and will work silently in the background." & return & return ¬
        & "BTW, do you want it to run automatically on startup?" with title ¬
        "You are awesome!" with icon 1 buttons {"No, thanks", "OK"} default button 2)
    if (userAnswer = "OK") then
        try
            my addToLoginItems()
        end try
    end if
    try
        -- Save in the preferences that Spotifree has already ran.
        do shell script "defaults write com.ArtemGordinsky.Spotifree 'hasRanBefore' 'true'"
    end try
end if

repeat
    try
        -- Adding a 5 seconds timeout instead of default 2 min. Prevents long unresponsiveness of the app.
        with timeout of (5) seconds
            if (isRunning() and isPlaying() and isAnAd()) then
                try
                    mute()
                end try
                repeat
                    delay 0.3
                    try
                        if (isRunning() and not isAnAd()) then
                            -- Have to delay a little bit, because Spotify may tell us about the next track too early,
                            -- and a user may to hear the last half-second of an ad.
                            delay 0.8
                            unmute()
                            exit repeat
                        end if
                    end try
                end repeat
            else
                -- Delaying, to get less of the crashing "connection is invalid" errors.
                delay 1
            end if
        end timeout
    on error errorMessage number errorNumber
        my log_error(errorNumber, errorMessage, "Somewhere in the outer loop.")
    end try
    -- This is how fast we are polling Spotify.
    -- The only speed at which you will hear almost no sounds passing through.
    -- Fortunately, even combined with the added load on Spotify, the CPU usage is rather miniscule.
    delay 0.3
end repeat

on mute()
    try
        tell application "Spotify"
            set currentVolume to sound volume
            -- This is the only way possible to mute Spotify during an advertisement.
            -- Otherwise it pauses when you mute the sound.
            pause
            set sound volume to 0
            play
        end tell
    on error errorMessage number errorNumber
        my log_error(errorNumber, errorMessage, "mute()")
    end try
    return
end mute

on unmute()
    try
        tell application "Spotify"
            -- Restore the volume to the level supplied to the parameter.
            set sound volume to currentVolume
        end tell
    on error errorMessage number errorNumber
        my log_error(errorNumber, errorMessage, "unmute()")
    end try
    return
end unmute

on isAnAd()
    local currentTrackPopularity, currentTrackDuration
    set currentTrackPopularity to null
    set currentTrackDuration to null
    # Nesting "try" blocks is the only way to handle multiple errors in AppleScript
    try
        try
            try
                tell application "Spotify"
                    set currentTrackPopularity to popularity of current track
                    set currentTrackDuration to duration of current track
                end tell
            on error number -1728
                # Ignoring "can't get current track" error
            end try
        on error number -609
            # Ignoring the "invalid connection errors"
        end try
    on error errorMessage number errorNumber
        my log_error(errorNumber, errorMessage, "isAnAd()")
        return false
    end try
    if ((currentTrackPopularity ≠ null and currentTrackDuration ≠ null) and (currentTrackPopularity = 0 and currentTrackDuration ≤ 40)) then
        return true
    else
        return false
    end if
end isAnAd

on isPlaying()
    local playerState
    set playerState to null
    # Nesting "try" blocks is the only way to handle multiple errors in AppleScript
    try
        try
            tell application "Spotify"
                set playerState to player state
            end tell
        on error -609
            # Ignoring the "invalid connection" errors
        end try
    on error errorMessage number errorNumber
        my log_error(errorNumber, errorMessage, "isRunning()")
        return false
    end try
    if (playerState ≠ null and playerState = «constant ****kPSP») then
        return true
    else
        return false
    end if
end isPlaying

on isRunning()
    local spotifyProcesses
    # Nesting "try" blocks is the only way to handle multiple errors in AppleScript
    try
        try
            tell application "System Events"
                set spotifyProcesses to (count of (every process whose name is "Spotify"))
            end tell
        on error number -609
            # Ignoring the "invalid connection" errors
        end try
    on error errorMessage number errorNumber
        my log_error(errorNumber, errorMessage, "isRunning()")
        return false
    end try
    if spotifyProcesses is 1 then
        return true
    else
        return false
    end if
end isRunning

on addToLoginItems()
    try
        tell application "System Events"
            -- Add Spotifree to the Login Items.
            make login item at end with properties {name:"Spotifree", path:"/Applications/Spotifree.app", hidden:true}
        end tell
    on error errorMessage number errorNumber
        my log_error(errorNumber, errorMessage, "addToLoginItems()")
        return
    end try
end addToLoginItems

on isTheFirstRun()
    local isPrefFileExists, prefFilePath
    set prefFilePath to "~/Library/Preferences/com.ArtemGordinsky.Spotifree"
    try
        tell application "System Events"
            if exists file prefFilePath then
                set isPrefFileExists to true
            else
                set isPrefFileExists to false
            end if
        end tell
    on error errorMessage number errorNumber
        my log_error(errorNumber, errorMessage, "isTheFirstRun()")
        return true
    end try
    # "not" works like a bang sign here
    return not isPrefFileExists
end isTheFirstRun

on isInLoginItems()
    try
        tell application "System Events"
            if login item "Spotifree" exists then
                return true
            else
                return false
            end if
        end tell
    on error errorMessage number errorNumber
        my log_error(errorNumber, errorMessage, "isInLoginItems()")
        return false
    end try
end isInLoginItems

on log_message(message)
    local content
    set content to (return & ¬
        "-----------------------------------------------------------" & ¬
        return & my dateAndTime() & return & message & return ¬
        & "-----------------------------------------------------------" & return)
    set log_file to ("Mountain Lion:Users:Mephistopelus:Developer:The Stuff:AppleScript:SpotiFree:Spotifree_log.txt")
    my write_to_file(content, log_file, true)
end log_message

on log_error(error_number, error_message, _where)
    local content
    if (debug) then
        set content to (return & "-----------------------------------------------------------" & ¬
            return & my dateAndTime() & return & "Error number: " & error_number ¬
            & return & "Error message: " & error_message & return & ¬
            "Where: " & _where & return ¬
            & "-----------------------------------------------------------" & return)
        set log_file to ("Mountain Lion:Users:Mephistopelus:Developer:The Stuff:AppleScript:SpotiFree:Spotifree_log.txt")
        my write_to_file(content, log_file, true)
    end if
end log_error

on write_to_file(this_data, target_file, append_data) -- (string, file path as string, boolean)
    try
        set the target_file to the target_file as text
        set the open_target_file to ¬
            open for access file target_file with write permission
        if append_data is false then ¬
            set eof of the open_target_file to 0
        write this_data to the open_target_file starting at eof
        close access the open_target_file
        return true
    on error
        try
            close access file target_file
        end try
    end try
end write_to_file

on dateAndTime()
    set currentDateAndTime to (current date) as string
    return currentDateAndTime
end dateAndTime


Commented the script

Commented the script

FasdUAS 1.101.10
l
R
.ascrerr ********
mtThis script contains uncompiled changes and cannot be run.
.aevtoappnull****

.aevtoappnull****

k

)jascrޭ

FasdUAS 1.101.10
l
T
k
Q

	k~

O8
k7
r
1

pVol
o0cur_vol
r
n
1

pTrN
1

pTrk
o
0trackk
r!
n !
 1

pnam
!1

pTrk
o	0namme"#
"r")$%
$n"'&'
&1%'

spPo
'1"%

pTrk
%o0pop#()
(r*1*+
*n*/,-
,1-/

pDur
-1*-

pTrk
+o0dur).
.r27/0
/125

pPos
0o0pos
m	11sptyalisT
Mountain LioncYH+tSpotify.app	6̜	 Applicationsc)̜t'Mountain Lion:Applications:Spotify.appSpotify.app
Mountain LionApplications/Spotify.app/23
2l99345
4Z9|678
6F9D9:
9=9<;<
;o9:0pop
<m:;
:A?B=>
=o?@0dur
>m@A(
7kGr??@A
@OG]BC
BkK\DDEF
EIKP
.spfyPausnullnullFGH
GrQVIJ
ImQR
J1RU

pVolHK
KIW\
.spfyPlaynullnull
CmGHLLsptyalisT
Mountain LioncYH+tSpotify.app	6̜	 Applicationsc)̜t'Mountain Lion:Applications:Spotify.appSpotify.app
Mountain LionApplications/Spotify.app/AMN
MI^gO
.sysodelanullnmbr
O[^cPQ
P\^aRS
Ro^_0dur
So_`0pos
QmabNT
TOhrUV
UrlqWX
Wolm0cur_vol
X1mp

pVol
VmhiYYsptyalisT
Mountain LioncYH+tSpotify.app	6̜	 Applicationsc)̜t'Mountain Lion:Applications:Spotify.appSpotify.app
Mountain LionApplications/Spotify.app/
8Iu|Z
.sysodelanullnmbr
Zmux[[?5\
\l}}

R]
.ascrerr ********
]o0errormessageerrorMessage
I^
.sysodelanullnmbr
^m__?`
`l
abcda
.aevtoappnull****0cur_vol
0trackk	0namme0pop0dur0posbefg
.aevtoappnull****
ekhhf0errormessageerrorMessageg1[

pVol0cur_vol

pTrk

pTrN
0trackk

pnam	0namme

spPo0pop

pDur0dur

pPos0pos(

bool
.spfyPausnullnull
.spfyPlaynullnull
.sysodelanullnmbr0errormessageerrorMessagehZ{-*,EO*,,EO*,,EO*,,EO*,,EO*,EUOj	&0*jOj*,FO*jUOkjO*,FUY	ajOPWXajOP[OYrdciiOtacon"d@u ascr
ޭ


tweaking the now playing scrip to return a more parsable value

on run
  set info to ""
  tell application "System Events"
    set num to count (every process whose name is "Spotify")
  end tell
  if num > 0 then
    tell application "Spotify"
      if player state is playing then
        set who to artist of current track
        set what to name of current track
        set onwhat to album of current track
        set info to  what & "::" & who & "::" & onwhat
      end if
    end tell
  end if
  return info
end run

on run
  set info to ""
  tell application "System Events"
    set num to count (every process whose name is "Spotify")
  end tell
  if num > 0 then
    tell application "Spotify"
      if player state is playing then
        set who to artist of current track
        set what to name of current track
        set onwhat to album of current track
        set info to "“" & what & "”" & " by " & who & " " & "from " & onwhat
      end if
    end tell
  end if
  return info
end run


Changed interface to decide if new window or tab is required.

#!/usr/bin/osascript

on run argv
  if count of argv < 3
    set myName to (POSIX path of (path to me) as string)
    return "Usage: osascript " & myName & " <profile-name> <session-name> <command-parameter> [<attach-session-name>]"
  end if

  set profileName to item 1 of argv
  set sessionName to item 2 of argv
  set commandParam to item 3 of argv

  try
    set attachSessionName to item 4 of argv
  on error
    set attachSessionName to ""
  end try

  set myHome to (path to current user folder as string)
  set launcherPath to (myHome & "bin:iterm-launcher")
  set launcher to POSIX path of launcherPath
  set launcherCommand to "exec " & quoted form of launcher ¬
  	& " " & quoted form of sessionName & " " & quoted form of commandParam

  tell application "iTerm"
    activate

    set procRunning to false
    set myTermCount to count of terminal
    set attachTerm to 0

    if myTermCount is 0 then
      -- No iTerm windows open
      set newTerm to (make new terminal)
      tell newTerm
        launch session profileName
        tell current session
          write text launcherCommand
          set name to sessionName
        end tell
        set procRunning to true
      end tell

    else
      -- iTerm windows open
      repeat with i from 1 to myTermCount by 1
        set myTerm to (terminal i)
        tell myTerm
          set myTabCount to count of session
          repeat with j from 1 to myTabCount by 1
            set mySession to (session j)
            tell mySession
              set mySessionName to name of mySession
              if mySessionName is sessionName then
                select myTerm
                select mySession
                set procRunning to true
              else if mySessionName is attachSessionName then
                -- Found terminal window with session <attach-session-name>
                -- Attach to this window if required to create a new tab
                set attachTerm to i
              end if
            end tell -- mySession
          end repeat -- myTabCount
        end tell -- myTerm
      end repeat -- myTermCount
    end if -- myTermCount is 0

    if procRunning is false then
      -- Terminal windows open, but process not running
      if attachTerm > 0
        set myTerm to (terminal attachTerm)
      else
        set myTerm to (make new terminal)
      end if

      tell myTerm
        launch session profileName
        tell current session
          write text launcherCommand
          set name to sessionName
        end tell
        set procRunning to true
      end tell -- myTerm
    end if -- procRunning is false
  end tell -- "iTerm"
end run

#!/usr/bin/osascript

on run argv
  if count of argv < 3
    set myName to (POSIX path of (path to me) as string)
    return "Usage: osascript " & myName & " <profile-name> <session-name>
    <command-parameter> [<force-new-window>]"
  end if

  set profileName to item 1 of argv
  set sessionName to item 2 of argv
  set commandParam to item 3 of argv

  try
    set forceNewWindow to item 4 of argv
    set forceNewWindow to forceNewWindow as number
  on error errStr number errorNumber
    if errorNumber is -1728 then
      -- Fourth parameter not set
      set forceNewWindow to 0
    else if errorNumber is -1700 then
      -- Fourth parameter not a number; count it as set
      set forceNewWindow to 1
    else
      error errStr number errorNumber
    end if
  end try

  set myHome to (path to current user folder as string)
  set launcherPath to (myHome & "bin:iterm-launcher")
  set launcher to POSIX path of launcherPath
  set launcherCommand to "exec " & quoted form of launcher ¬
  	& " " & quoted form of sessionName & " " & quoted form of commandParam

  tell application "iTerm"
    activate

    set procRunning to false
    set myTermCount to count of terminal
    if myTermCount is 0 then
      -- No iTerm windows open
      set newTerm to (make new terminal)
      tell newTerm
        launch session profileName
        tell current session
          write text launcherCommand
          set name to sessionName
        end tell
        set procRunning to true
      end tell

    else
      -- iTerm windows open
      repeat with i from 1 to myTermCount by 1
        set myTerm to (terminal i)
        tell myTerm
          set myTabCount to count of session
          repeat with j from 1 to myTabCount by 1
            set mySession to (session j)
            tell mySession
              if name of mySession is sessionName then
                select myTerm
                select mySession
                set procRunning to true
              end if
            end tell -- mySession
          end repeat -- myTabCount
        end tell -- myTerm
      end repeat -- myTermCount
    end if -- myTermCount is 0

    if procRunning is false then
      -- Terminal windows open, but process not running

      -- If there is only one terminal window open, add a new tab
      -- Else, launch a new terminal window
      if myTermCount > 1 or forceNewWindow > 0 then
        set myTerm to (make new terminal)
      else
        set myTerm to (terminal 1)
      end if

      tell myTerm
        launch session profileName
        tell current session
          write text launcherCommand
          set name to sessionName
        end tell
        set procRunning to true
      end tell -- myTerm
    end if -- procRunning is false
  end tell -- "iTerm"
end run


(fix) safari debugger find simulator

(fix) safari debugger find simulator

on run argv

	if (count argv) = 0 then
		#log "No arguments given, opening any index.html"
		set StringPart to "index.html"
	else
		#log "Opening " & item 1 of argv
		set StringPart to item 1 of argv
	end if

	# Make sure Safari is running.
	# Note that we don't *activate* it yet, so that if something goes wrong the Terminal window stays active and the user gets to see error messages.
	# (This also avoids a bug affecting both OSX 10.8 and 10.9 where, if Safari isn't running, `tell application "Safari" to activate` *launches, but doesn't activate* Safari.)
	tell application "Safari" to launch

	tell application "System Events"

		tell process "Safari"

			# Try to obtain a reference to the `Developer > {iPhone|iPad} Simulator`submenu items; give up after a while.
			set simSubMenu to missing value
			repeat with i from 1 to 20
				# Note that we reference the Developer menu by *index*, as its name may be localized.
				# Furthermore, we search for the relevant menu item by the tokens "iPhone" or "iPad" only, since the "Simulator" part could be localized, too.
				# Note that the menu-item name reflects whether the simulator currently simulates the iPhone or the iPad.
				tell (first menu item of menu -3 of menu bar 1 whose name contains "iPhone" or name contains "iPad" or name contains "Simulator" )
					if exists then # Menu item found?
						# Simulate a click on the menu item so as to get it to populate its submenu with the currently debuggable pages.
						click it
						# Loop over submenu items and find the desired page.
						set pageUrl to missing value
						repeat with itm in menu items of menu of it
							set props to properties of itm # !! Bizarrely, this intermediate step is needed - directly accessing `help of itm` leads to strange behavior on OSX 10.8.
							set pageUrl to help of props # Page URL is in `help` property.
							if pageUrl is not missing value and pageUrl contains StringPart then
								# Only now that we've found a matching page do we activate Safari.
								tell application "Safari" to activate
								# Finally, click on the item to show the Web Inspector for the matching page.
								click itm
								return
							end if
						end repeat
						# Report error, if no matching page found.
						error "No currently debuggable page matching '" & StringPart & "' found."
					end if
				end tell
				delay 0.2 # Menu item not (yet) available; try again.
			end repeat

			# Getting here means that the simulator menu item wasn't found within the timeout period.
			# Abort with an error.
			error "Cannot determine debuggable pages: iOS Simulator-related menu items not found in Safari.
Make sure that the `Developer` menu is activated in the advanced preferences and that the iOS simulator is running a UIWebView-based app."

		end tell

	end tell

end run

FasdUAS 1.101.10
k
i
I
.aevtoappnull****
	o0argv
k

l

Z
=
l
I
.corecnte********
o0argv
m
k

l

60log "No arguments given, opening any index.html"`log "No arguments given, opening any index.html"
r

m
  index.html
o0
stringpart
StringPart
k!!"#
"l$%$%log "Opening " & item 1 of argv%&&>log "Opening " & item 1 of argv#'
'r()
(n*+
*4,

cobj
,m
+o0argv
)o0
stringpart
StringPart-.
-l./0
/l121# Make sure Safari is running.233: Make sure Safari is running.045
4l676 Note that we don't *activate* it yet, so that if something goes wrong the Terminal window stays active and the user gets to see error messages.788  Note that we don't *activate* it yet, so that if something goes wrong the Terminal window stays active and the user gets to see error messages.59:
9l;<; (This also avoids a bug affecting both OSX 10.8 and 10.9 where, if Safari isn't running, `tell application "Safari" to activate` *launches, but doesn't activate* Safari.)<==V (This also avoids a bug affecting both OSX 10.8 and 10.9 where, if Safari isn't running, `tell application "Safari" to activate` *launches, but doesn't activate* Safari.):>?
>O!@A
@I
.ascrnoop********
AmBBsfrialis6IroniV1H+k
Safari.applR	 Applicationsi,6kIron:Applications:Safari.app
Safari.app
IronApplications/Safari.app/?CD
Cl""DEF
EO"GH
Gk&IIJK
Jl&&KLM
LO&NO
Nk-PPQR
Ql--RST
Sl--UVUuo Try to obtain a reference to the `Developer > {iPhone|iPad} Simulator`submenu items; give up after a while.			VWW Try to obtain a reference to the `Developer > {iPhone|iPad} Simulator`submenu items; give up after a while.			TXY
Xr-0Z[
Zm-.

msng
[o0
simsubmenu
simSubMenuY\]
\Y1^_`
^k;aabc
bl;;dedZT Note that we reference the Developer menu by *index*, as its name may be localized.eff Note that we reference the Developer menu by *index*, as its name may be localized.cgh
gl;;iji Furthermore, we search for the relevant menu item by the tokens "iPhone" or "iPad" only, since the "Simulator" part could be localized, too.jkk Furthermore, we search for the relevant menu item by the tokens "iPhone" or "iPad" only, since the "Simulator" part could be localized, too.hlm
ll;;nonnh Note that the menu-item name reflects whether the simulator currently simulates the iPhone or the iPad.opp Note that the menu-item name reflects whether the simulator currently simulates the iPhone or the iPad.mqr
qO;st
sZeuv
uIej
.coredoexboolobj
vlmwxy
wkmzz{|
{lmm}~}uo Simulate a click on the menu item so as to get it to populate its submenu with the currently debuggable pages.~ Simulate a click on the menu item so as to get it to populate its submenu with the currently debuggable pages.|
Imr
.prcsclicuieluiel
gmn
lss93 Loop over submenu items and find the desired page.f Loop over submenu items and find the desired page.
rsx
mst

msng
o0pageurlpageUrl
Xy
k
l
r
n
1

pALL
o0itm
o	0propsy !! Bizarrely, this intermediate step is needed - directly accessing `help of itm` leads to strange behavior on OSX 10.8. !! Bizarrely, this intermediate step is needed - directly accessing `help of itm` leads to strange behavior on OSX 10.8.
l
r
n
1

help
o	0props
o0pageurlpageUrl&  Page URL is in `help` property.@ Page URL is in `help` property.
Z
F
>
o0pageurlpageUrl
m

msng
E
o0pageurlpageUrl
o0
stringpart
StringPart
k
lGA Only now that we've found a matching page do we activate Safari. Only now that we've found a matching page do we activate Safari.
O
I
.miscactvnullnull
msfrialis6IroniV1H+k
Safari.applR	 Applicationsi,6kIron:Applications:Safari.app
Safari.app
IronApplications/Safari.app/
lRL Finally, click on the item to show the Web Inspector for the matching page. Finally, click on the item to show the Web Inspector for the matching page.
I
.prcsclicuieluiel
o0itm
L0itm
n|
2

menI
n|
m}

menE
g|}
l/) Report error, if no matching page found.R Report error, if no matching page found.
R
.ascrerr ********
b
b
mNNo currently debuggable page matching '
o0
stringpart
StringPart
m' found.x Menu item found?y" Menu item found?
tl;b
6;b
n;E
4BE

menI
mCD
n;B
4?B

menE
m@A
4;?

mbar
m=>
GHa
EIT
1JN

pnam
mOSiPhone
EU`
1VZ

pnam
m[_iPadr
l
I
.sysodelanullnmbr
m?ə0* Menu item not (yet) available; try again.T Menu item not (yet) available; try again.0i
_m45
`m56]
l
l^X Getting here means that the simulator menu item wasn't found within the timeout period. Getting here means that the simulator menu item wasn't found within the timeout period.
l Abort with an error.* Abort with an error.
R
.ascrerr ********
mCannot determine debuggable pages: iOS Simulator-related menu items not found in Safari.
Make sure that the `Developer` menu is activated in the advanced preferences and that the iOS simulator is running a UIWebView-based app.
l
l
O4&*

prcs
m()SafariM
l
Hm"#		sevsaliszIroniV1H+NSystem Events.app0(	 CoreServicesi,NHG5Iron:System:Library:CoreServices:System Events.app$System Events.app
Iron-System/Library/CoreServices/System Events.app/F

l~
l}|{}|{~
z
yxwvzutsrqpon
u.aevtoappnull****t0
stringpart
StringParts0
simsubmenu
simSubMenur0pageurlpageUrlq	0propspon
mlkj
m.aevtoappnull****l0argvkihgi0argvh0ig0itm"fedBc	ba`_^]\[ZYXWVUTSRQP
f.corecnte********e0
stringpart
StringPart
d
cobj
c.ascrnoop********
b
prcs
a
msng`0
simsubmenu
simSubMenu_
^
mbar
]
menE\
[
menI
Z
pnam
Y.coredoexboolobj
X.prcsclicuieluielW0pageurlpageUrl
V
kocl
U
pALLT	0props
S
help
R
bool
Q.miscactvnullnull
P.sysodelanullnmbrjjjEYk/EO*jUO*/EOkkh*k//k/a[[a,\Za@\[a,\Za@B1*jz*jOE`O[*,-[alkha,E`O_a,E`O_	_a&*jUOjOhYh[OYO)ja%a%YhUOaj [OYFO)ja!OPUOPUOPtab
y
msng4http://localhost/tab1.htmlO
O
descmenu itemNM
N
orie
M
msngL
L
posnKKJIJILHG
H
pcls
G
menIF
F
rold  menu itemED!
E
axds
D
msng!CB"
C
focu
B
msng"A#$
A
titl#%%*localhost   tab1.html$@&'
@
ptsz&?(?(>=>='<;)
<
valL
;
msng):*
:
help*98+
9
enaB
8boovtrue+76,
7
maxV
6
msng,5-.
5
role-//AXMenuItem.401
4
ects032321213
2
sbrl
1
msng30/4
0
selE
/boovfals4.56
.
pnam577*localhost   tab1.html6-,+
-
minW
,
msng+xwvascr
ޭ


Delete jLinuxInstaller.scpt

Delete jLinuxInstaller.scpt

--jLinuxInstaller.scpt DOES NOT work fully yet
--Due to the fact that .app files are actually folders, getting them with cURL does not work
--This will be fixed later but isn't a high priority right now
--
-- (c) 2016 Brendan Manning
-- MIT Liscense
display dialog "jLinux Quick Installer..." with title "Install jLinux" buttons {"Install", "Quit"} default button 1
if button returned of result = "Install" then
	display alert "Downloading files from the Internet...If you do not have Internet access, you may be required to install manually" giving up after 2
	tell application "Terminal"
		quit
		delay 5
		activate
		do script "mkdir /Applications/jLinux/"
		delay 1
		do script "curl -f http://thecyberbay.com/cdn/jLinux/latest/latest.jar -o /Applications/jLinux/latest.jar"
		delay 10
		do script "rm /Applications/jLinux/jLinux.jar"
		do script "mv /Applications/jLinux/latest.jar /Applications/jLinux/jLinux.jar"
		--commented code that doesn't work yet
		--delay 1
		--do script "curl -f http://thecyberbay.com/cdn/jLinux/latest/jLinuxLauncher.app -o /Applications/jLinux/jLinuxLauncher.app"
		--delay 10
		--do script "curl -f http://thecyberbay.com/cdn/jLinux/latest/jLinuxUpdater.app -o /Applications/jLinux/jLinuxUpdater.app"
		quit
		delay 5
		activate
		do script "java -jar /Applications/jLinux/jLinux.jar"
		display alert "jLinux Installed!" buttons {"Great", "ALRIGHT!", "Rock on man!"} default button 3
	end tell
else
	display alert "You have aborted jLinux installation. If you would like to return, simply reopen this app!" buttons {"Acknowledged", "Affirmative", "10-4"} default button 2
end if