|
2 | 2 | import subprocess |
3 | 3 | from subprocess import PIPE |
4 | 4 | from typing import Dict |
5 | | - |
| 5 | +from Foundation import NSAppleScript |
6 | 6 |
|
7 | 7 | # the applescript version of the macos strategy is kept here until the jxa |
8 | 8 | # approach is proven out in production environments |
9 | 9 | # https://github.com/ActivityWatch/aw-watcher-window/pull/52 |
10 | 10 |
|
| 11 | +source = """ |
| 12 | +global frontApp, frontAppName, windowTitle |
| 13 | +
|
| 14 | +set windowTitle to "" |
| 15 | +tell application "System Events" |
| 16 | + set frontApp to first application process whose frontmost is true |
| 17 | + set frontAppName to name of frontApp |
| 18 | + tell process frontAppName |
| 19 | + try |
| 20 | + tell (1st window whose value of attribute "AXMain" is true) |
| 21 | + set windowTitle to value of attribute "AXTitle" |
| 22 | + end tell |
| 23 | + end try |
| 24 | + end tell |
| 25 | +end tell |
| 26 | +
|
| 27 | +return frontAppName & " |
| 28 | +" & windowTitle |
| 29 | +""" |
| 30 | + |
| 31 | +script = None |
| 32 | + |
11 | 33 |
|
12 | 34 | def getInfo() -> Dict[str, str]: |
13 | | - cmd = [ |
14 | | - "osascript", |
15 | | - os.path.join(os.path.dirname(os.path.realpath(__file__)), "printAppTitle.scpt"), |
16 | | - ] |
17 | | - p = subprocess.run(cmd, stdout=PIPE) |
18 | | - info = str(p.stdout, "utf8").strip() |
| 35 | + # Cache compiled script |
| 36 | + global script |
| 37 | + if script is None: |
| 38 | + script = NSAppleScript.alloc().initWithSource_(source) |
19 | 39 |
|
20 | | - app = getApp(info) |
21 | | - title = getTitle(info) |
| 40 | + # Call script |
| 41 | + result, errorinfo = script.executeAndReturnError_(None) |
| 42 | + if errorinfo: |
| 43 | + raise Exception(errorinfo) |
| 44 | + output = result.stringValue() |
| 45 | + |
| 46 | + # Ensure there's no extra newlines in the output |
| 47 | + assert len(output.split("\n")) == 2 |
| 48 | + |
| 49 | + app = getApp(output) |
| 50 | + title = getTitle(output) |
22 | 51 |
|
23 | 52 | return {"app": app, "title": title} |
24 | 53 |
|
25 | 54 |
|
26 | 55 | def getApp(info: str) -> str: |
27 | | - return info.split('","')[0][1:] |
| 56 | + return info.split('\n')[0] |
28 | 57 |
|
29 | 58 |
|
30 | 59 | def getTitle(info: str) -> str: |
31 | | - return info.split('","')[1][:-1] |
| 60 | + return info.split('\n')[1] |
| 61 | + |
| 62 | + |
| 63 | +if __name__ == "__main__": |
| 64 | + info = getInfo() |
| 65 | + print(info) |
0 commit comments