Skip to content

Commit

Permalink
custom_iterm_script.applescript: Improve method to detect open windows
Browse files Browse the repository at this point in the history
  • Loading branch information
vitorgalvao committed Jun 25, 2022
1 parent bd18cf6 commit c082d89
Showing 1 changed file with 40 additions and 31 deletions.
71 changes: 40 additions & 31 deletions custom_iterm_script.applescript
Expand Up @@ -9,56 +9,65 @@ property open_in_new_tab : true

-- Handlers
on new_window()
tell application "iTerm" to create window with default profile
tell application "iTerm" to create window with default profile
end new_window

on new_tab()
tell application "iTerm" to tell the first window to create tab with default profile
tell application "iTerm" to tell the first window to create tab with default profile
end new_tab

on call_forward()
tell application "iTerm" to activate
tell application "iTerm" to activate
end call_forward

on is_running()
application "iTerm" is running
application "iTerm" is running
end is_running

on has_windows()
if not is_running() then return false
if windows of application "iTerm" is {} then return false
true
if not is_running() then return false

tell application "iTerm"
if windows is {} then return false
if tabs of current window is {} then return false
if sessions of current tab of current window is {} then return false

set session_text to contents of current session of current tab of current window
if words of session_text is {} then return false
end tell

true
end has_windows

on send_text(custom_text)
tell application "iTerm" to tell the first window to tell current session to write text custom_text
tell application "iTerm" to tell the first window to tell current session to write text custom_text
end send_text

-- Main
on alfred_script(query)
if has_windows() then
if open_in_new_window then
new_window()
else if open_in_new_tab then
new_tab()
else
-- Reuse current tab
end if
else
-- If iTerm is not running and we tell it to create a new window, we get two
-- One from opening the application, and the other from the command
if is_running() then
new_window()
else
call_forward()
end if
end if
if has_windows() then
if open_in_new_window then
new_window()
else if open_in_new_tab then
new_tab()
else
-- Reuse current tab
end if
else
-- If iTerm is not running and we tell it to create a new window, we get two
-- One from opening the application, and the other from the command
if is_running() then
new_window()
else
call_forward()
end if
end if

-- Make sure a window exists before we continue, or the write may fail
repeat until has_windows()
delay 0.01
end repeat
-- Make sure a window exists before we continue, or the write may fail
repeat until has_windows()
delay 0.01
end repeat

send_text(query)
call_forward()
send_text(query)
call_forward()
end alfred_script

0 comments on commit c082d89

Please sign in to comment.