forked from adeelahmad/MacPilot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdirect_applescript.py
More file actions
203 lines (158 loc) · 8.11 KB
/
Copy pathdirect_applescript.py
File metadata and controls
203 lines (158 loc) · 8.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
#!/usr/bin/env python3
"""
Direct AppleScript Command Interface
Execute AppleScript commands directly and see the actual results.
"""
import sys
import asyncio
from pathlib import Path
import json
# Add automation framework to path
sys.path.insert(0, str(Path(__file__).parent / "automation_framework"))
from rich.console import Console
from rich.panel import Panel
from rich.syntax import Syntax
from rich.table import Table
console = Console()
async def execute_applescript_command(command: str):
"""Execute AppleScript commands directly and show results"""
console.print(f"[cyan]🍎 Direct AppleScript Command:[/cyan] {command}")
console.print("-" * 60)
try:
from actors.generic.mouse_keyboard import GenericActorStack
actor = GenericActorStack()
# Map commands to actions
if command.lower() in ["get_current_window", "get current window", "current window", "window info"]:
console.print("[yellow]📋 Getting current window information...[/yellow]")
result = await actor.execute_action("get_current_window")
if result:
console.print("[green]✅ Window Information Retrieved:[/green]")
# Show as table
table = Table(title="Current Window")
table.add_column("Property", style="cyan")
table.add_column("Value", style="green")
table.add_row("Application", result.get('application', 'Unknown'))
table.add_row("Window", result.get('window', 'Unknown'))
table.add_row("Raw Output", result.get('raw', 'Unknown'))
console.print(table)
# Show as JSON
console.print("\n[cyan]📄 JSON Format:[/cyan]")
json_str = json.dumps(result, indent=2, ensure_ascii=False)
syntax = Syntax(json_str, "json", theme="monokai", line_numbers=True)
console.print(syntax)
else:
console.print("[red]❌ Could not get window information[/red]")
elif command.lower() in ["screenshot", "take screenshot", "screen capture"]:
console.print("[yellow]📸 Taking screenshot...[/yellow]")
result = await actor.execute_action("screenshot", filename="macpilot_screenshot.png")
if result:
console.print("[green]✅ Screenshot saved to: macpilot_screenshot.png[/green]")
else:
console.print("[red]❌ Screenshot failed[/red]")
elif command.lower().startswith("applescript:"):
# Custom AppleScript
script = command[12:].strip() # Remove "applescript:" prefix
console.print(f"[yellow]🍎 Running custom AppleScript...[/yellow]")
console.print(Panel(script, title="AppleScript Code"))
result = await actor.execute_action("run_applescript", script=script)
console.print(f"[green]✅ AppleScript Result:[/green]")
console.print(Panel(str(result), title="Output"))
elif command.lower() in ["list windows", "windows", "open windows"]:
# List all windows
script = '''
tell application "System Events"
set windowList to {}
repeat with proc in (every application process whose visible is true)
set procName to name of proc
try
repeat with win in (every window of proc)
set end of windowList to procName & " | " & (name of win)
end repeat
end try
end repeat
return my listToString(windowList, "\\n")
end tell
on listToString(lst, delim)
set oldDelims to AppleScript's text item delimiters
set AppleScript's text item delimiters to delim
set str to lst as string
set AppleScript's text item delimiters to oldDelims
return str
end listToString
'''
console.print("[yellow]📋 Getting all open windows...[/yellow]")
result = await actor.execute_action("run_applescript", script=script)
if result:
windows = result.split('\n') if result else []
table = Table(title="Open Windows")
table.add_column("Application", style="cyan")
table.add_column("Window", style="green")
for window in windows:
if " | " in window:
app, win = window.split(" | ", 1)
table.add_row(app, win)
console.print(table)
else:
console.print("[red]❌ Could not get window list[/red]")
elif command.lower() in ["list apps", "applications", "running apps"]:
# List running applications
script = '''
tell application "System Events"
set appList to name of every application process whose visible is true
return my listToString(appList, "\\n")
end tell
on listToString(lst, delim)
set oldDelims to AppleScript's text item delimiters
set AppleScript's text item delimiters to delim
set str to lst as string
set AppleScript's text item delimiters to oldDelims
return str
end listToString
'''
console.print("[yellow]📋 Getting running applications...[/yellow]")
result = await actor.execute_action("run_applescript", script=script)
if result:
apps = result.split('\n') if result else []
table = Table(title="Running Applications")
table.add_column("#", style="dim")
table.add_column("Application", style="cyan")
for i, app in enumerate(apps, 1):
table.add_row(str(i), app)
console.print(table)
else:
console.print("[red]❌ Could not get application list[/red]")
else:
console.print("[red]❌ Unknown command. Available commands:[/red]")
console.print(" • get current window")
console.print(" • screenshot")
console.print(" • list windows")
console.print(" • list apps")
console.print(" • applescript: <your script>")
await actor.cleanup()
return True
except Exception as e:
console.print(f"[red]❌ Command failed: {e}[/red]")
import traceback
traceback.print_exc()
return False
def main():
"""Main entry point"""
if len(sys.argv) < 2:
console.print("[red]Usage: python direct_applescript.py \"command\"[/red]")
console.print("\nAvailable commands:")
console.print(" • [cyan]get current window[/cyan] - Get active window info")
console.print(" • [cyan]screenshot[/cyan] - Take a screenshot")
console.print(" • [cyan]list windows[/cyan] - List all open windows")
console.print(" • [cyan]list apps[/cyan] - List running applications")
console.print(" • [cyan]applescript: <script>[/cyan] - Run custom AppleScript")
console.print("\nExamples:")
console.print(" python direct_applescript.py \"get current window\"")
console.print(" python direct_applescript.py \"list windows\"")
console.print(" python direct_applescript.py \"applescript: tell app \\\"Finder\\\" to get name of front window\"")
sys.exit(1)
command = " ".join(sys.argv[1:])
# Run the command
success = asyncio.run(execute_applescript_command(command))
sys.exit(0 if success else 1)
if __name__ == "__main__":
main()