Skip to content

Commit

Permalink
window_action: use appscript to close all windows (#55)
Browse files Browse the repository at this point in the history
I noticed that stuff like "window close all" in applications like Finder
was really slow and flaky, and would often result in several windows
being left open if you had a lot open (probably because they technically
treat tabs as windows).

I was poking around with AppleScript and noticed that it's actually much
faster and more reliable to just close all of the windows that way, ie
with:

```
tell application "Finder"
	close every window
end tell
```

It fixes the Finder issue, and even in applications previously behaved
well, there is an improvement (all windows close immediately, rather
than a cascade of closures as it iterates through them). So let's use
that!

I didn't do much to improve the "current window" and "other windows" use
cases, although it probably not much work. I just wanted to knock this
out quickly.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
  • Loading branch information
phillco and pre-commit-ci[bot] authored Jun 24, 2023
1 parent 7da1ffa commit 95296d7
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions window_action.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import logging

from talon import Context, Module, actions, app, ui

if app.platform == "mac":
Expand All @@ -20,6 +22,29 @@
}


def close_windows_via_appscript(app: App) -> bool:
"""Closes all windows for the given application using appscript.
This is faster/more reliable than accessibility for applications that support scripting.
Returns whether successful."""
try:
windows = app.appscript().windows
except AttributeError:
# Application doesn't expose a scripting interface, or `windows`.
return False

try:
# TODO(pcohen): investigate this for "current" and "others" as well,
# as well as other window actions.
windows.close(timeout=0.3)
return True
except Exception as e:
logging.debug(
f"Error closing windows for app {app.name} using appscript: {type(e)} {e}; falling back to accessibility"
)
return False


@mod.action_class
class Actions:
# TODO(pcohen): this could use a better name
Expand Down Expand Up @@ -48,6 +73,11 @@ def action_windows_app(
`on_current`: whether to affect the current window
`on_others`: whether to affect the non-current window
"""
# Using appscript is faster than accessibility and more reliable for applications that support it.
if on_current and on_others and action == "close":
if close_windows_via_appscript(app):
return

for window in app.windows():
if window == app.active_window and not on_current:
continue
Expand Down

0 comments on commit 95296d7

Please sign in to comment.