Mercurial > my-enso-commands
annotate my-enso-commands.py @ 2:c28ae8f664ba
Removed a bunch of diagnostic or highly experimental commands. Also removed the PyXPCOM commands b/c I'm not running Enso on top of Firefox right now, but they're still stored in the repository for future use.
author | Atul Varma <varmaa@toolness.com> |
---|---|
date | Sun, 18 May 2008 00:31:26 -0700 |
parents | 3924ba5f3621 |
children | 9767abfe290b |
rev | line source |
---|---|
0 | 1 # -*-Mode:python-*- |
2 | |
3 import os | |
4 import tempfile | |
5 import sys | |
6 import subprocess | |
7 import webbrowser | |
8 import urllib | |
9 import threading | |
1
3924ba5f3621
Added a bunch of commands, many of which are experimental. Some require PyXPCOM, meaning that Enso must be running atop Firefox or something similar.
Atul Varma <varmaa@toolness.com>
parents:
0
diff
changeset
|
10 import logging |
0 | 11 from StringIO import StringIO |
12 | |
1
3924ba5f3621
Added a bunch of commands, many of which are experimental. Some require PyXPCOM, meaning that Enso must be running atop Firefox or something similar.
Atul Varma <varmaa@toolness.com>
parents:
0
diff
changeset
|
13 def cmd_define(ensoapi): |
3924ba5f3621
Added a bunch of commands, many of which are experimental. Some require PyXPCOM, meaning that Enso must be running atop Firefox or something similar.
Atul Varma <varmaa@toolness.com>
parents:
0
diff
changeset
|
14 import AppKit |
3924ba5f3621
Added a bunch of commands, many of which are experimental. Some require PyXPCOM, meaning that Enso must be running atop Firefox or something similar.
Atul Varma <varmaa@toolness.com>
parents:
0
diff
changeset
|
15 |
3924ba5f3621
Added a bunch of commands, many of which are experimental. Some require PyXPCOM, meaning that Enso must be running atop Firefox or something similar.
Atul Varma <varmaa@toolness.com>
parents:
0
diff
changeset
|
16 serviceName = "Look Up in Dictionary" |
3924ba5f3621
Added a bunch of commands, many of which are experimental. Some require PyXPCOM, meaning that Enso must be running atop Firefox or something similar.
Atul Varma <varmaa@toolness.com>
parents:
0
diff
changeset
|
17 |
2
c28ae8f664ba
Removed a bunch of diagnostic or highly experimental commands. Also removed the PyXPCOM commands b/c I'm not running Enso on top of Firefox right now, but they're still stored in the repository for future use.
Atul Varma <varmaa@toolness.com>
parents:
1
diff
changeset
|
18 text = ensoapi.get_selection().get("text", "").strip() |
c28ae8f664ba
Removed a bunch of diagnostic or highly experimental commands. Also removed the PyXPCOM commands b/c I'm not running Enso on top of Firefox right now, but they're still stored in the repository for future use.
Atul Varma <varmaa@toolness.com>
parents:
1
diff
changeset
|
19 |
c28ae8f664ba
Removed a bunch of diagnostic or highly experimental commands. Also removed the PyXPCOM commands b/c I'm not running Enso on top of Firefox right now, but they're still stored in the repository for future use.
Atul Varma <varmaa@toolness.com>
parents:
1
diff
changeset
|
20 if not text: |
c28ae8f664ba
Removed a bunch of diagnostic or highly experimental commands. Also removed the PyXPCOM commands b/c I'm not running Enso on top of Firefox right now, but they're still stored in the repository for future use.
Atul Varma <varmaa@toolness.com>
parents:
1
diff
changeset
|
21 ensoapi.display_message("No text selection!") |
c28ae8f664ba
Removed a bunch of diagnostic or highly experimental commands. Also removed the PyXPCOM commands b/c I'm not running Enso on top of Firefox right now, but they're still stored in the repository for future use.
Atul Varma <varmaa@toolness.com>
parents:
1
diff
changeset
|
22 return |
1
3924ba5f3621
Added a bunch of commands, many of which are experimental. Some require PyXPCOM, meaning that Enso must be running atop Firefox or something similar.
Atul Varma <varmaa@toolness.com>
parents:
0
diff
changeset
|
23 |
3924ba5f3621
Added a bunch of commands, many of which are experimental. Some require PyXPCOM, meaning that Enso must be running atop Firefox or something similar.
Atul Varma <varmaa@toolness.com>
parents:
0
diff
changeset
|
24 pb = AppKit.NSPasteboard.pasteboardWithName_("EnsoServiceContent") |
3924ba5f3621
Added a bunch of commands, many of which are experimental. Some require PyXPCOM, meaning that Enso must be running atop Firefox or something similar.
Atul Varma <varmaa@toolness.com>
parents:
0
diff
changeset
|
25 |
3924ba5f3621
Added a bunch of commands, many of which are experimental. Some require PyXPCOM, meaning that Enso must be running atop Firefox or something similar.
Atul Varma <varmaa@toolness.com>
parents:
0
diff
changeset
|
26 pb.declareTypes_owner_( [AppKit.NSStringPboardType], None ) |
3924ba5f3621
Added a bunch of commands, many of which are experimental. Some require PyXPCOM, meaning that Enso must be running atop Firefox or something similar.
Atul Varma <varmaa@toolness.com>
parents:
0
diff
changeset
|
27 |
3924ba5f3621
Added a bunch of commands, many of which are experimental. Some require PyXPCOM, meaning that Enso must be running atop Firefox or something similar.
Atul Varma <varmaa@toolness.com>
parents:
0
diff
changeset
|
28 try: |
3924ba5f3621
Added a bunch of commands, many of which are experimental. Some require PyXPCOM, meaning that Enso must be running atop Firefox or something similar.
Atul Varma <varmaa@toolness.com>
parents:
0
diff
changeset
|
29 if not pb.setString_forType_( text, AppKit.NSStringPboardType ): |
3924ba5f3621
Added a bunch of commands, many of which are experimental. Some require PyXPCOM, meaning that Enso must be running atop Firefox or something similar.
Atul Varma <varmaa@toolness.com>
parents:
0
diff
changeset
|
30 raise Exception( "Failed to set pasteboard data." ) |
3924ba5f3621
Added a bunch of commands, many of which are experimental. Some require PyXPCOM, meaning that Enso must be running atop Firefox or something similar.
Atul Varma <varmaa@toolness.com>
parents:
0
diff
changeset
|
31 |
3924ba5f3621
Added a bunch of commands, many of which are experimental. Some require PyXPCOM, meaning that Enso must be running atop Firefox or something similar.
Atul Varma <varmaa@toolness.com>
parents:
0
diff
changeset
|
32 if not AppKit.NSPerformService( serviceName, pb ): |
3924ba5f3621
Added a bunch of commands, many of which are experimental. Some require PyXPCOM, meaning that Enso must be running atop Firefox or something similar.
Atul Varma <varmaa@toolness.com>
parents:
0
diff
changeset
|
33 raise Exception( "Failed to perform service." ) |
3924ba5f3621
Added a bunch of commands, many of which are experimental. Some require PyXPCOM, meaning that Enso must be running atop Firefox or something similar.
Atul Varma <varmaa@toolness.com>
parents:
0
diff
changeset
|
34 finally: |
3924ba5f3621
Added a bunch of commands, many of which are experimental. Some require PyXPCOM, meaning that Enso must be running atop Firefox or something similar.
Atul Varma <varmaa@toolness.com>
parents:
0
diff
changeset
|
35 pass |
3924ba5f3621
Added a bunch of commands, many of which are experimental. Some require PyXPCOM, meaning that Enso must be running atop Firefox or something similar.
Atul Varma <varmaa@toolness.com>
parents:
0
diff
changeset
|
36 |
0 | 37 def cmd_count_lines(ensoapi): |
38 seldict = ensoapi.get_selection() | |
39 ensoapi.display_message( "Selection is %s lines." % | |
40 len(seldict.get("text","").splitlines()) ) | |
41 | |
42 def _get_filelike_timestamp(): | |
43 import time | |
44 | |
45 return time.strftime("%Y%m%d%H%M%S") | |
46 | |
47 def _get_clipboard_img_datafile(): | |
48 import AppKit | |
49 | |
50 pb = AppKit.NSPasteboard.generalPasteboard() | |
51 if pb.availableTypeFromArray_([AppKit.NSTIFFPboardType]): | |
52 bytes = pb.dataForType_(AppKit.NSTIFFPboardType).bytes() | |
53 datafile = StringIO(str(bytes)) | |
54 return datafile | |
55 else: | |
56 return None | |
57 | |
58 def image_command(func): | |
59 def wrapper(ensoapi): | |
60 import Image | |
61 | |
62 datafile = _get_clipboard_img_datafile() | |
63 if datafile: | |
64 img = Image.open(datafile) | |
65 return func(ensoapi, img) | |
66 else: | |
67 files = ensoapi.get_selection().get("files", []) | |
68 if files: | |
69 if len(files) == 1: | |
70 filename = files[0] | |
71 img = None | |
72 try: | |
73 img = Image.open(filename) | |
74 except IOError, e: | |
75 ensoapi.display_message("An error occurred: %s." % e) | |
76 if img: | |
77 return func(ensoapi, img) | |
78 else: | |
79 ensoapi.display_message("More than one file selected.") | |
80 else: | |
81 ensoapi.display_message("No image in clipboard, and no " | |
82 "file selected.") | |
83 return wrapper | |
84 | |
85 @image_command | |
86 def cmd_get_image_size(ensoapi, img): | |
87 outputfile = StringIO() | |
88 img.save(outputfile, "PNG") | |
89 png_size = outputfile.tell() | |
90 outputfile = StringIO() | |
91 img.save(outputfile, "JPEG", quality=90) | |
92 jpg_size = outputfile.tell() | |
93 ensoapi.display_message("png size: %d bytes. jpg-90 size: %d bytes." % | |
94 (png_size, jpg_size)) | |
95 | |
96 def cmd_unupload_image(ensoapi): | |
97 url = ensoapi.get_selection().get("text", "") | |
98 if url: | |
99 if url.startswith(REMOTE_UPLOAD_URL): | |
100 filename = url[len(REMOTE_UPLOAD_URL):] | |
101 localfile = os.path.join(LOCAL_UPLOAD_DIR, filename) | |
102 # It's just easier to upload a truncated file than it is | |
103 # to remove the file remotely. | |
104 open(localfile, "w").close() | |
105 popen = subprocess.Popen( | |
106 ["scp", | |
107 localfile, | |
108 "%s%s" % (REMOTE_UPLOAD_DIR, filename)] | |
109 ) | |
110 while popen.poll() is None: | |
111 yield | |
112 if popen.returncode == 0: | |
113 os.remove(localfile) | |
114 ensoapi.display_message("Image removed.") | |
115 else: | |
116 ensoapi.display_message("An error occurred.") | |
117 else: | |
118 ensoapi.display_message("URL is not an upload URL.") | |
119 else: | |
120 ensoapi.display_message("No selection!") | |
121 | |
122 LOCAL_UPLOAD_DIR = "/Users/varmaa/Archive/toolness-images/" | |
123 REMOTE_UPLOAD_DIR = "toolness.com:/home/varmaa/toolness.com/images/" | |
124 REMOTE_UPLOAD_URL = "http://www.toolness.com/images/" | |
125 | |
126 @image_command | |
127 def cmd_upload_image(ensoapi, img): | |
128 filename = "%s.jpg" % _get_filelike_timestamp() | |
129 localfile = os.path.join(LOCAL_UPLOAD_DIR, filename) | |
130 img.save(localfile, quality=90) | |
131 | |
132 ensoapi.display_message("Uploading image...") | |
133 | |
134 popen = subprocess.Popen( | |
135 ["scp", | |
136 localfile, | |
137 "%s%s" % (REMOTE_UPLOAD_DIR, filename)] | |
138 ) | |
139 while popen.poll() is None: | |
140 yield | |
141 if popen.returncode == 0: | |
142 webbrowser.open("%s%s" % (REMOTE_UPLOAD_URL, filename)) | |
143 else: | |
144 ensoapi.display_message("An error occurred.") | |
145 | |
146 class ThreadedFunc(threading.Thread): | |
147 def __init__(self, target): | |
148 self.__target = target | |
149 threading.Thread.__init__(self) | |
150 self.__success = False | |
151 self.__retval = None | |
152 self.start() | |
153 | |
154 def run(self): | |
155 self.__retval = self.__target() | |
156 self.__success = True | |
157 | |
158 def wasSuccessful(self): | |
159 if self.isAlive(): | |
160 raise Exception( "Thread not finished" ) | |
161 return self.__success | |
162 | |
163 def getRetval(self): | |
164 if self.isAlive(): | |
165 raise Exception( "Thread not finished" ) | |
166 return self.__retval | |
167 | |
168 def htmlifier(func): | |
169 def wrapper(ensoapi): | |
170 seldict = ensoapi.get_selection() | |
171 text = seldict.get("text", "") | |
172 html = seldict.get("html", text) | |
173 if not text: | |
174 ensoapi.display_message("No selection!") | |
175 else: | |
176 result = func(ensoapi, html) | |
177 ensoapi.set_selection( | |
178 {"html":result, | |
179 "text":result} | |
180 ) | |
181 | |
182 return wrapper | |
183 | |
184 @htmlifier | |
185 def cmd_bold(ensoapi, text): | |
186 return "<b>%s</b>" % text | |
187 | |
188 @htmlifier | |
189 def cmd_italics(ensoapi, text): | |
190 return "<i>%s</i>" % text | |
191 | |
192 @htmlifier | |
193 def cmd_monospace(ensoapi, text): | |
194 return "<pre>%s</pre>" % text | |
195 | |
196 def cmd_normalize(ensoapi): | |
197 normal_template = "<span style=\"font-weight: normal;\">%s</span>" | |
198 seldict = ensoapi.get_selection() | |
199 text = seldict.get("text", "") | |
200 if not text: | |
201 ensoapi.display_message("No selection!") | |
202 else: | |
203 ensoapi.set_selection( | |
204 {"html":normal_template % text, | |
205 "text":text} ) | |
206 | |
207 def make_get_url_func(url): | |
208 def get_url(): | |
209 import urllib2 | |
210 | |
211 f = urllib2.urlopen(url) | |
212 return f.read() | |
213 return get_url | |
214 | |
215 def get_weather(xml_data): | |
216 """ | |
217 Shows the weather for the given place. | |
218 """ | |
219 | |
220 import elementtree.ElementTree as ET | |
221 | |
222 page = ET.fromstring(xml_data) | |
223 | |
224 weather = page.find( "weather/current_conditions" ) | |
225 | |
226 return { | |
227 'f' : weather.find( "temp_f" ).get( "data" ), | |
228 'c' : weather.find( "temp_c" ).get( "data" ), | |
229 'humidity' : weather.find( "humidity" ).get( "data" ), | |
230 'wind' : weather.find( "wind_condition" ).get( "data" ) | |
231 } | |
232 | |
233 def test_get_weather(): | |
234 xml_data = """<?xml version="1.0"?><xml_api_reply version="1"><weather module_id="0" tab_id="0"><forecast_information><city data="Chicago, IL"/><postal_code data="60657"/><latitude_e6 data=""/><longitude_e6 data=""/><forecast_date data="2008-04-07"/><current_date_time data="2008-04-07 06:38:00 +0000"/><unit_system data="US"/></forecast_information><current_conditions><condition data="Cloudy"/><temp_f data="57"/><temp_c data="14"/><humidity data="Humidity: 47%"/><icon data="/images/weather/cloudy.gif"/><wind_condition data="Wind: N at 0 mph"/></current_conditions><forecast_conditions><day_of_week data="Today"/><low data="40"/><high data="56"/><icon data="/images/weather/cloudy.gif"/><condition data="Cloudy"/></forecast_conditions><forecast_conditions><day_of_week data="Tue"/><low data="45"/><high data="54"/><icon data="/images/weather/thunderstorm.gif"/><condition data="Thunderstorm"/></forecast_conditions><forecast_conditions><day_of_week data="Wed"/><low data="40"/><high data="54"/><icon data="/images/weather/mostly_sunny.gif"/><condition data="Partly Sunny"/></forecast_conditions><forecast_conditions><day_of_week data="Thu"/><low data="38"/><high data="49"/><icon data="/images/weather/chance_of_rain.gif"/><condition data="Chance of Showers"/></forecast_conditions></weather></xml_api_reply>""" | |
235 | |
236 assert get_weather(xml_data) == {'c': '14', 'humidity': 'Humidity: 47%', 'wind': 'Wind: N at 0 mph', 'f': '57'} | |
237 | |
238 def cmd_weather(ensoapi, place="san francisco"): | |
239 zipcode = cmd_weather.places[place] | |
240 url = "http://www.google.com/ig/api?weather=%s" % zipcode | |
241 thread = ThreadedFunc(make_get_url_func(url)) | |
242 while thread.isAlive(): | |
243 yield | |
244 weather_xml = thread.getRetval() | |
245 if not weather_xml: | |
246 ensoapi.display_message("An error occurred when getting the weather.") | |
247 else: | |
248 wdict = get_weather(weather_xml) | |
249 wdict["place"] = place | |
250 ensoapi.display_message(u"In %(place)s it is " | |
251 u"%(f)s\u00b0F/%(c)s\u00b0C, " | |
252 u"%(humidity)s, %(wind)s." % wdict) | |
253 | |
254 cmd_weather.places = { "san francisco" : "94115", | |
255 "chicago" : "60640", | |
256 "mountain view" : "94043" } | |
257 | |
258 cmd_weather.valid_args = cmd_weather.places.keys() | |
259 | |
260 def cmd_what_is_my_ip(ensoapi): | |
261 thread = ThreadedFunc(make_get_url_func("http://www.toolness.com/ip/")) | |
262 while thread.isAlive(): | |
263 yield | |
264 ensoapi.display_message("%s." % thread.getRetval()) | |
265 | |
266 def cmd_character_count(ensoapi): | |
267 text = ensoapi.get_selection().get("text", "").strip() | |
268 if not text: | |
269 ensoapi.display_message( "No selection." ) | |
270 ensoapi.display_message( "%d characters." % len(text) ) | |
271 | |
272 def cmd_email_to_me(ensoapi): | |
273 text = ensoapi.get_selection().get("text", "").strip() | |
274 if not text: | |
275 ensoapi.display_message( "No selection." ) | |
276 else: | |
277 server = "mail.toolness.com" | |
278 port = 587 | |
279 username = "no-reply@toolness.com" | |
280 password = "4p5o3j45ot%$" | |
281 | |
282 mailfrom = "varmaa@gmail.com" | |
283 rcpttos = ["varmaa@gmail.com"] | |
284 | |
285 text = text.encode("ascii", "xmlcharrefreplace") | |
286 subject = text.splitlines()[0] | |
287 text = ("This message was sent by Enso's " | |
288 "'email to' command.\n\n" + text) | |
289 data = "From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n%s" % \ | |
290 (mailfrom, ", ".join(rcpttos), subject, text) | |
291 | |
292 def sendmail(): | |
293 import smtplib | |
294 | |
295 try: | |
296 svr = smtplib.SMTP( server, port ) | |
297 svr.login( username, password ) | |
298 svr.sendmail( mailfrom, rcpttos, data ) | |
299 svr.quit() | |
300 except: | |
301 success[0] = False | |
302 raise | |
303 | |
304 thread = ThreadedFunc(sendmail) | |
305 ensoapi.display_message( "Sending message..." ) | |
306 while thread.isAlive(): | |
307 yield | |
308 if thread.wasSuccessful(): | |
309 ensoapi.display_message( "Message sent." ) | |
310 else: | |
311 ensoapi.display_message( | |
312 "An error occurred when sending the message." | |
313 ) | |
314 | |
315 def cmd_date(ensoapi): | |
316 import time | |
317 | |
318 ensoapi.display_message( "%s" % time.asctime() ) | |
319 | |
320 def cmd_insert_date(ensoapi): | |
321 import time | |
322 | |
323 ensoapi.set_selection( time.asctime() ) | |
324 | |
325 class WebSearchCmd(object): | |
326 def __init__(self, url_template): | |
327 self._url_template = url_template | |
328 | |
329 def __call__(self, ensoapi, query=None): | |
330 if not query: | |
331 query = ensoapi.get_selection().get("text", u"") | |
332 query = query.strip() | |
333 | |
334 if not query: | |
335 ensoapi.display_message( "No query." ) | |
336 return | |
337 | |
338 query = urllib.quote( query.encode("utf-8") ) | |
339 | |
340 webbrowser.open( self._url_template % {"query" : query} ) | |
341 | |
342 cmd_wiki = WebSearchCmd("http://en.wikipedia.org/wiki/%(query)s") | |
343 cmd_wowhead = WebSearchCmd("http://www.wowhead.com/?search=%(query)s") | |
344 cmd_amaz = WebSearchCmd("http://www.amazon.com/exec/obidos/search-handle-url/index%%3Dblended%%26field-keywords%%3D%(query)s%%26store-name%%3Dall-product-search") | |
345 cmd_yp = WebSearchCmd("http://local.google.com/local?sc=1&q=%(query)s&near=2418+washington+94115&btnG=Google+Search") | |
346 cmd_imdb = WebSearchCmd("http://www.imdb.com/find?s=all&q=%(query)s&x=0&y=0") | |
347 cmd_mdc = WebSearchCmd("http://www.google.com/search?hl=en&q=%(query)s+site%%3Adeveloper.mozilla.org&btnG=Google+Search") | |
348 cmd_mxr = WebSearchCmd("http://mxr.mozilla.org/mozilla/search?string=%(query)s") | |
349 cmd_phonebook = WebSearchCmd("https://ldap.mozilla.org/phonebook/search.php?search=%(query)s") | |
350 | |
351 # For help on this one see http://www.squarefree.com/bugzilla/quicksearch-help.html | |
352 cmd_bugzilla = WebSearchCmd("https://bugzilla.mozilla.org/buglist.cgi?quicksearch=%(query)s") | |
353 | |
354 def cmd_farewell(ensoapi): | |
355 import AppKit | |
356 | |
357 app = AppKit.NSApplication.sharedApplication() | |
358 app.terminate_(None) | |
359 | |
360 class Launcher(object): | |
361 def __init__(self): | |
362 import Foundation | |
363 import AppKit | |
364 | |
365 self._targets = {} | |
366 | |
367 query = Foundation.NSMetadataQuery.alloc().init() | |
368 queryString = ( "((kMDItemKind == \"Application\") " | |
369 " and (kMDItemSupportFileType != \"MDSystemFile\"))" ) | |
370 queryString += " or (kMDItemKind == \"Mac OS X Preference Pane\")" | |
371 predicate = Foundation.NSPredicate.predicateWithFormat_( | |
372 queryString | |
373 ) | |
374 query.setPredicate_( predicate ) | |
375 if query.startQuery() != True: | |
376 raise Exception( "startQuery() failed." ) | |
377 self._query = query | |
378 self._workspace = AppKit.NSWorkspace.sharedWorkspace() | |
379 self._targets = {} | |
380 | |
381 def get_namespace(self): | |
382 return self._targets.keys() | |
383 | |
384 def get_target(self, name): | |
385 return self._targets[name] | |
386 | |
387 def update(self): | |
388 query = self._query | |
389 | |
390 while query.isGathering(): | |
391 yield | |
392 | |
393 # TODO: Modify this so we just get notified whenever the query | |
394 # results change instead of constantly "polling" every time | |
395 # the quasimode starts. | |
396 | |
397 resultList = [] | |
398 targets = {} | |
399 | |
400 query.disableUpdates() | |
401 numresults = query.resultCount() | |
402 | |
403 BATCH_SIZE = 10 | |
404 | |
405 for i in range( numresults ): | |
406 result = query.resultAtIndex_( i ) | |
407 fsname = result.valueForAttribute_("kMDItemFSName") | |
408 name = result.valueForAttribute_("kMDItemDisplayName") | |
409 kind = result.valueForAttribute_("kMDItemKind") | |
410 if name: | |
411 name = name.lower() | |
412 itempath = result.valueForAttribute_("kMDItemPath") | |
413 if kind == "Mac OS X Preference Pane": | |
414 name += " preferences" | |
415 target = ShellOpenLaunchableTarget(itempath) | |
416 else: | |
417 target = AppLaunchableTarget(self._workspace, itempath) | |
418 resultList.append(name) | |
419 targets[name] = target | |
420 if i / BATCH_SIZE == i / float(BATCH_SIZE): | |
421 yield | |
422 #print "total results: %s" % numresults | |
423 query.enableUpdates() | |
424 targets["computer"] = ShellOpenLaunchableTarget("/") | |
425 self._targets = targets | |
426 | |
427 class AppLaunchableTarget(object): | |
428 def __init__(self, workspace, path): | |
429 self._workspace = workspace | |
430 self._path = path | |
431 | |
432 def launch(self, with_files=None): | |
433 if with_files: | |
434 for filename in with_files: | |
435 self._workspace.openFile_withApplication_( | |
436 filename, | |
437 self._path | |
438 ) | |
439 else: | |
440 self._workspace.launchApplication_( self._path ) | |
441 | |
442 def can_launch_with(self): | |
443 return True | |
444 | |
445 class ShellOpenLaunchableTarget(object): | |
446 def __init__(self, path): | |
447 self._path = path | |
448 | |
449 def launch(self): | |
450 subprocess.Popen( ["open", self._path] ) | |
451 | |
452 def can_launch_with(self): | |
453 return False | |
454 | |
455 class OpenCommand(object): | |
456 """ | |
457 Opens an application, folder, or URL. | |
458 """ | |
459 | |
460 def __init__(self, launcher): | |
461 self.launcher = launcher | |
462 self._isFetchingArgs = False | |
463 | |
464 def on_quasimode_start(self): | |
465 if self._isFetchingArgs: | |
466 return | |
467 | |
468 self._isFetchingArgs = True | |
469 | |
470 for _ in self.launcher.update(): | |
471 yield | |
472 | |
473 self.valid_args = self.launcher.get_namespace() | |
474 | |
475 self._isFetchingArgs = False | |
476 | |
477 valid_args = [] | |
478 | |
479 def __call__(self, ensoapi, target=None): | |
480 if not target: | |
481 seldict = ensoapi.get_selection() | |
482 if seldict.get("files"): | |
483 for file in seldict["files"]: | |
484 subprocess.Popen( ["open", file] ) | |
485 elif seldict.get("text"): | |
486 filename = seldict["text"].strip() | |
487 if os.path.isabs(filename): | |
488 subprocess.Popen( ["open", filename] ) | |
489 else: | |
490 webbrowser.open(filename) | |
491 else: | |
492 self.launcher.get_target(target).launch() | |
493 | |
494 class OpenWithCommand(object): | |
495 """ | |
496 Opens the selected file(s) with a particular application. | |
497 """ | |
498 | |
499 def __init__(self, launcher): | |
500 self.launcher = launcher | |
501 | |
502 def _get_valid_args(self): | |
503 return self.launcher.get_namespace() | |
504 | |
505 valid_args = property(_get_valid_args) | |
506 | |
507 def __call__(self, ensoapi, target): | |
508 files = ensoapi.get_selection().get("files", []) | |
509 targ = self.launcher.get_target(target) | |
510 if not files: | |
511 ensoapi.display_message("No files selected!") | |
512 elif not targ.can_launch_with(): | |
513 ensoapi.display_message("Can't open files with %s." % target) | |
514 else: | |
515 targ.launch(files) | |
516 | |
517 cmd_go = OpenCommand(Launcher()) | |
518 cmd_open = cmd_go | |
519 cmd_bust_with = OpenWithCommand(cmd_open.launcher) | |
520 | |
521 def cmd_run_python(ensoapi): | |
522 """ | |
523 runs the selected text as python code. | |
524 """ | |
525 | |
526 text = ensoapi.get_selection().get("text","") | |
527 | |
528 if not text: | |
529 ensoapi.display_message("No text selection!") | |
530 return | |
531 | |
532 output_fd, output_name = tempfile.mkstemp() | |
533 | |
534 # TODO: This is for OSX only; will have to figure out what to do | |
535 # for other platforms. | |
536 cmd = text.replace( "\r", "\n" ) | |
537 | |
538 try: | |
539 compile( cmd, "<selected text>", "eval" ) | |
540 is_eval = True | |
541 except: | |
542 is_eval = False | |
543 | |
544 if is_eval: | |
545 cmd = "print %s," % cmd | |
546 | |
547 cmd = ("try:\n" | |
548 " from autoimp import *\n" | |
549 "except ImportError:\n" | |
550 " pass\n\n" + cmd ) | |
551 | |
552 popen = subprocess.Popen( | |
553 [ sys.executable, | |
554 "-c", cmd ], | |
555 stdout = output_fd, | |
556 stderr = subprocess.STDOUT, | |
557 ) | |
558 | |
559 while popen.poll() is None: | |
560 yield | |
561 | |
562 os.close(output_fd) | |
563 | |
564 output_text = open(output_name, "r").read().strip() | |
565 if output_text: | |
566 seldict = {"text" : "\n".join([text, output_text])} | |
567 ensoapi.set_selection(seldict) | |
568 else: | |
569 if popen.returncode == 0: | |
570 ensoapi.display_message("Code run successfully.") | |
571 else: | |
572 ensoapi.display_message("An error occurred.") | |
573 | |
574 os.remove(output_name) | |
575 | |
576 def cmd_doctest(ensoapi): | |
577 """ | |
578 python doctests the selected section of plain text. | |
579 """ | |
580 | |
581 text = ensoapi.get_selection().get("text","") | |
582 | |
583 if not text: | |
584 ensoapi.display_message("No text selection!") | |
585 return | |
586 | |
587 # TODO: This is for OSX only; will have to figure out what to do | |
588 # for other platforms. | |
589 new_text = text.replace( "\r", "\n" ) | |
590 | |
591 fd, source_name = tempfile.mkstemp() | |
592 os.close(fd) | |
593 open(source_name, "wb").write(new_text) | |
594 | |
595 output_fd, output_name = tempfile.mkstemp() | |
596 | |
597 cmd = ("import doctest; doctest.testfile(%s, " | |
598 "module_relative=False)" % repr(source_name)) | |
599 | |
600 popen = subprocess.Popen( | |
601 [ sys.executable, | |
602 "-c", cmd ], | |
603 stdout = output_fd, | |
604 stderr = subprocess.STDOUT, | |
605 ) | |
606 | |
607 while popen.poll() is None: | |
608 yield | |
609 | |
610 os.close(output_fd) | |
611 | |
612 if popen.returncode == 0: | |
613 output_text = open(output_name, "r").read() | |
614 if output_text: | |
615 seldict = {"text":text + output_text} | |
616 ensoapi.set_selection(seldict) | |
617 else: | |
618 ensoapi.display_message("All doctests successful!") | |
619 else: | |
620 ensoapi.display_message("An error occurred.") | |
621 | |
622 os.remove(source_name) | |
623 os.remove(output_name) | |
624 | |
625 def cmd_nosetest(ensoapi): | |
626 """ | |
627 runs nosetests on the selected region of python code. | |
628 """ | |
629 | |
630 text = ensoapi.get_selection().get("text","") | |
631 | |
632 if not text: | |
633 ensoapi.display_message("No text selection!") | |
634 return | |
635 | |
636 # TODO: This is for OSX only; will have to figure out what to do | |
637 # for other platforms. | |
638 new_text = text.replace( "\r", "\n" ) | |
639 | |
640 fd, source_name = tempfile.mkstemp(suffix=".py") | |
641 os.close(fd) | |
642 open(source_name, "wb").write(new_text) | |
643 | |
644 output_fd, output_name = tempfile.mkstemp() | |
645 | |
646 popen = subprocess.Popen( | |
647 [ "nosetests", | |
648 source_name, | |
649 "--with-doctest" ], | |
650 stdout = output_fd, | |
651 stderr = subprocess.STDOUT, | |
652 ) | |
653 | |
654 while popen.poll() is None: | |
655 yield | |
656 | |
657 os.close(output_fd) | |
658 | |
659 output_text = open(output_name, "r").read() | |
660 if output_text: | |
661 if popen.returncode == 0: | |
662 lines = output_text.splitlines() | |
663 ensoapi.display_message(lines[2]) | |
664 else: | |
665 seldict = {"text":text + output_text} | |
666 ensoapi.set_selection(seldict) | |
667 else: | |
668 raise AssertionError( "nosetests didn't return anything!" ) | |
669 | |
670 os.remove(source_name) | |
671 os.remove(output_name) | |
672 | |
673 def cmd_insert_html(ensoapi): | |
674 ensoapi.set_selection( {"html":"<b>hi</b> <p>there</p>"} ) | |
675 | |
676 def _runAppleScript( script ): | |
677 params = [ "osascript", "-e", script ] | |
678 popen = subprocess.Popen( params ) | |
679 | |
680 def cmd_screen_saver(ensoapi): | |
681 """ | |
682 Starts your screen saver. | |
683 """ | |
684 | |
685 _runAppleScript( | |
686 "tell application id \"com.apple.ScreenSaver.Engine\" " | |
687 "to launch" | |
688 ) | |
689 | |
690 def cmd_sleep(ensoapi): | |
691 """ | |
692 Puts your computer to sleep. | |
693 """ | |
694 | |
695 _runAppleScript( | |
696 "tell application \"Finder\" to sleep" | |
697 ) | |
698 | |
699 def cmd_play(ensoapi): | |
700 """ | |
701 Plays the current iTunes song. | |
702 """ | |
703 | |
704 _runAppleScript( | |
705 "tell application \"iTunes\" to play" | |
706 ) | |
707 | |
708 def cmd_pause(ensoapi): | |
709 """ | |
710 Pauses the current iTunes song. | |
711 """ | |
712 | |
713 _runAppleScript( | |
714 "tell application \"iTunes\" to pause" | |
715 ) | |
716 | |
717 | |
718 def cmd_next_track(ensoapi): | |
719 """ | |
720 Goes to the next track on iTunes. | |
721 """ | |
722 | |
723 _runAppleScript( | |
724 "tell application \"iTunes\" to next track" | |
725 ) | |
726 | |
727 def cmd_previous_track(ensoapi): | |
728 """ | |
729 Goes to the previous track on iTunes. | |
730 """ | |
731 | |
732 _runAppleScript( | |
733 "tell application \"iTunes\" to back track" | |
734 ) | |
735 | |
736 KIRITSU_DIR = "/Users/varmaa/Documents/kiritsu" | |
737 KIRITSU_MAKE_SCRIPT = "%s/MakeEverything.py" % KIRITSU_DIR | |
738 KIRITSU_VIEW_TEMPLATE = "file://%s/%s.html" | |
739 KIRITSU_VIEWS = ["work", "play", "chores"] | |
740 | |
741 def cmd_refresh_kiritsu(ensoapi): | |
742 """ | |
743 Refreshes all kiritsu feeds. | |
744 """ | |
745 | |
746 popen = subprocess.Popen( | |
747 [sys.executable, | |
748 KIRITSU_MAKE_SCRIPT], | |
749 cwd = KIRITSU_DIR | |
750 ) | |
751 | |
752 ensoapi.display_message( "Please wait while kiritsu retrieves " | |
753 "new feeds." ) | |
754 | |
755 while popen.poll() is None: | |
756 yield | |
757 | |
758 if popen.returncode != 0: | |
759 ensoapi.display_message( "An error occurred in Kiritsu." ) | |
760 else: | |
761 ensoapi.display_message( "Kiritsu is done." ) | |
762 | |
763 def cmd_view( ensoapi, viewname ): | |
764 """ | |
765 Opens the given kiritsu view. | |
766 """ | |
767 | |
768 webbrowser.open( KIRITSU_VIEW_TEMPLATE % (KIRITSU_DIR, viewname) ) | |
769 | |
770 cmd_view.valid_args = KIRITSU_VIEWS | |
771 | |
1
3924ba5f3621
Added a bunch of commands, many of which are experimental. Some require PyXPCOM, meaning that Enso must be running atop Firefox or something similar.
Atul Varma <varmaa@toolness.com>
parents:
0
diff
changeset
|
772 def cmd_html_template(ensoapi): |
3924ba5f3621
Added a bunch of commands, many of which are experimental. Some require PyXPCOM, meaning that Enso must be running atop Firefox or something similar.
Atul Varma <varmaa@toolness.com>
parents:
0
diff
changeset
|
773 ensoapi.set_selection({"text" : HTML_TEMPLATE}) |
3924ba5f3621
Added a bunch of commands, many of which are experimental. Some require PyXPCOM, meaning that Enso must be running atop Firefox or something similar.
Atul Varma <varmaa@toolness.com>
parents:
0
diff
changeset
|
774 |
3924ba5f3621
Added a bunch of commands, many of which are experimental. Some require PyXPCOM, meaning that Enso must be running atop Firefox or something similar.
Atul Varma <varmaa@toolness.com>
parents:
0
diff
changeset
|
775 HTML_TEMPLATE = """\ |
3924ba5f3621
Added a bunch of commands, many of which are experimental. Some require PyXPCOM, meaning that Enso must be running atop Firefox or something similar.
Atul Varma <varmaa@toolness.com>
parents:
0
diff
changeset
|
776 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" |
3924ba5f3621
Added a bunch of commands, many of which are experimental. Some require PyXPCOM, meaning that Enso must be running atop Firefox or something similar.
Atul Varma <varmaa@toolness.com>
parents:
0
diff
changeset
|
777 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> |
3924ba5f3621
Added a bunch of commands, many of which are experimental. Some require PyXPCOM, meaning that Enso must be running atop Firefox or something similar.
Atul Varma <varmaa@toolness.com>
parents:
0
diff
changeset
|
778 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> |
3924ba5f3621
Added a bunch of commands, many of which are experimental. Some require PyXPCOM, meaning that Enso must be running atop Firefox or something similar.
Atul Varma <varmaa@toolness.com>
parents:
0
diff
changeset
|
779 <head> |
3924ba5f3621
Added a bunch of commands, many of which are experimental. Some require PyXPCOM, meaning that Enso must be running atop Firefox or something similar.
Atul Varma <varmaa@toolness.com>
parents:
0
diff
changeset
|
780 <meta http-equiv="Content-type" content="text/html; charset=utf-8" /> |
3924ba5f3621
Added a bunch of commands, many of which are experimental. Some require PyXPCOM, meaning that Enso must be running atop Firefox or something similar.
Atul Varma <varmaa@toolness.com>
parents:
0
diff
changeset
|
781 <link rel="stylesheet" type="text/css" media="all" |
3924ba5f3621
Added a bunch of commands, many of which are experimental. Some require PyXPCOM, meaning that Enso must be running atop Firefox or something similar.
Atul Varma <varmaa@toolness.com>
parents:
0
diff
changeset
|
782 href="" /> |
3924ba5f3621
Added a bunch of commands, many of which are experimental. Some require PyXPCOM, meaning that Enso must be running atop Firefox or something similar.
Atul Varma <varmaa@toolness.com>
parents:
0
diff
changeset
|
783 <title></title> |
3924ba5f3621
Added a bunch of commands, many of which are experimental. Some require PyXPCOM, meaning that Enso must be running atop Firefox or something similar.
Atul Varma <varmaa@toolness.com>
parents:
0
diff
changeset
|
784 </head> |
3924ba5f3621
Added a bunch of commands, many of which are experimental. Some require PyXPCOM, meaning that Enso must be running atop Firefox or something similar.
Atul Varma <varmaa@toolness.com>
parents:
0
diff
changeset
|
785 <body> |
3924ba5f3621
Added a bunch of commands, many of which are experimental. Some require PyXPCOM, meaning that Enso must be running atop Firefox or something similar.
Atul Varma <varmaa@toolness.com>
parents:
0
diff
changeset
|
786 |
3924ba5f3621
Added a bunch of commands, many of which are experimental. Some require PyXPCOM, meaning that Enso must be running atop Firefox or something similar.
Atul Varma <varmaa@toolness.com>
parents:
0
diff
changeset
|
787 </body> |
3924ba5f3621
Added a bunch of commands, many of which are experimental. Some require PyXPCOM, meaning that Enso must be running atop Firefox or something similar.
Atul Varma <varmaa@toolness.com>
parents:
0
diff
changeset
|
788 <script type="text/javascript" src=""></script> |
3924ba5f3621
Added a bunch of commands, many of which are experimental. Some require PyXPCOM, meaning that Enso must be running atop Firefox or something similar.
Atul Varma <varmaa@toolness.com>
parents:
0
diff
changeset
|
789 </html> |
3924ba5f3621
Added a bunch of commands, many of which are experimental. Some require PyXPCOM, meaning that Enso must be running atop Firefox or something similar.
Atul Varma <varmaa@toolness.com>
parents:
0
diff
changeset
|
790 """ |