comparison 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
comparison
equal deleted inserted replaced
1:3924ba5f3621 2:c28ae8f664ba
8 import urllib 8 import urllib
9 import threading 9 import threading
10 import logging 10 import logging
11 from StringIO import StringIO 11 from StringIO import StringIO
12 12
13 def cmd_menu(ensoapi):
14 import AppKit
15 import Foundation
16
17 app = AppKit.NSApplication.sharedApplication()
18
19 mainMenu = AppKit.NSMenu.alloc().initWithTitle_("Main")
20 ensoMenu = AppKit.NSMenu.alloc().initWithTitle_("Boogy")
21
22 item = AppKit.NSMenuItem.alloc().init()
23 item.setTitle_("Boogy")
24 item.setSubmenu_(ensoMenu)
25 mainMenu.insertItem_atIndex_(item, 0)
26
27 app.setMainMenu_(mainMenu)
28 app.setServicesMenu_(ensoMenu)
29
30 app.registerServicesMenuSendTypes_returnTypes_(
31 [AppKit.NSStringPboardType],
32 []
33 )
34
35 ensoapi.display_message(str(app.mainMenu()))
36
37 def cmd_define(ensoapi): 13 def cmd_define(ensoapi):
38 import AppKit 14 import AppKit
39 15
40 serviceName = "Look Up in Dictionary" 16 serviceName = "Look Up in Dictionary"
41 17
42 text = ensoapi.get_selection().get("text", "") 18 text = ensoapi.get_selection().get("text", "").strip()
19
20 if not text:
21 ensoapi.display_message("No text selection!")
22 return
43 23
44 pb = AppKit.NSPasteboard.pasteboardWithName_("EnsoServiceContent") 24 pb = AppKit.NSPasteboard.pasteboardWithName_("EnsoServiceContent")
45 25
46 pb.declareTypes_owner_( [AppKit.NSStringPboardType], None ) 26 pb.declareTypes_owner_( [AppKit.NSStringPboardType], None )
47 27
51 31
52 if not AppKit.NSPerformService( serviceName, pb ): 32 if not AppKit.NSPerformService( serviceName, pb ):
53 raise Exception( "Failed to perform service." ) 33 raise Exception( "Failed to perform service." )
54 finally: 34 finally:
55 pass 35 pass
56
57 def cmd_impersonate(ensoapi):
58 from xpcom import components
59
60 class MyEventHandler:
61 _com_interfaces_ = components.interfaces.nsIDOMEventListener
62
63 def __init__(self, corpus, author):
64 from nltk.probability import ConditionalFreqDist
65
66 cfd = ConditionalFreqDist()
67 prev_word = None
68 for word in corpus.words():
69 cfd[prev_word].inc(word)
70 prev_word = word
71
72 self._cfd = cfd
73 self._author = author
74 self._last_word = None
75
76 def handleEvent(self, event):
77 text = event.target.value[:event.target.selectionStart]
78 words = text.split()
79 if words and text[-1] == " ":
80 last_word = words[-1]
81 if last_word == self._last_word:
82 return
83 self._last_word = last_word
84
85 #sorted = self._cfd[last_word].sorted()
86 suggestions = self._cfd[last_word].samples()
87 suggestions.sort(key=len, reverse=True)
88 suggestions = [sugg for sugg in suggestions
89 if len(sugg) > 3]
90
91 # if suggestions:
92 # import random
93 # suggestion = random.choice(suggestions)
94 # cursor = event.target.selectionStart
95 # event.target.value = event.target.value[:cursor] + suggestion + " " + event.target.value[cursor:]
96 # cursor += len(suggestion) + 1
97 # event.target.setSelectionRange(cursor, cursor)
98
99 # suggestions = None
100 if suggestions:
101 cc = components.classes
102 asvc = cc["@mozilla.org/alerts-service;1"].getService(
103 components.interfaces.nsIAlertsService
104 )
105 asvc.showAlertNotification(
106 "http://www.mozilla.com/favicon.ico",
107 "%s would say..." % self._author,
108 ", ".join(suggestions[:10]),
109 False,
110 None,
111 None,
112 None,
113 )
114
115 element = ensoapi.get_selection()["dom.element"]
116
117 #from nltk.corpus import gutenberg
118
119 #corpus, author = (gutenberg, "Project Gutenberg")
120 from nltk.corpus.reader.plaintext import PlaintextCorpusReader
121
122 corpus = PlaintextCorpusReader(
123 os.getenv("HOME"),
124 ["argon.txt"]
125 )
126 author = "Jim Theis"
127
128 element.addEventListener(
129 "keyup",
130 MyEventHandler(corpus, author),
131 False
132 )
133
134 def cmd_extemporize(ensoapi):
135 element = ensoapi.get_selection().get("dom.element")
136
137 text = ""
138 if element:
139 text = element.value
140 words = text.split()
141 if words:
142 from nltk.corpus.reader.plaintext import PlaintextCorpusReader
143
144 corpus = PlaintextCorpusReader(
145 os.getenv("HOME"),
146 ["argon.txt"]
147 )
148
149 from nltk.probability import ConditionalFreqDist
150 import random
151
152 cfd = ConditionalFreqDist()
153 prev_word = None
154 for word in corpus.words():
155 cfd[prev_word].inc(word)
156 prev_word = word
157
158 last_word = words[-1]
159 new_words = []
160 for i in range(10):
161 potentials = cfd[last_word].samples()
162 if potentials:
163 next_word = random.choice(potentials)
164 else:
165 next_word = "Grignr"
166 new_words.append(next_word)
167 last_word = next_word
168 string = ""
169 for word in new_words:
170 if len(word) == 1 and not word.isalpha():
171 string += "%s" % word
172 else:
173 string += " %s" % word
174
175 element.value = text + string
176
177 def getFuelApplication():
178 from xpcom import components
179 fuel_cls = components.classes["@mozilla.org/fuel/application;1"]
180 fuel_abs = fuel_cls.createInstance()
181 fuel_if = components.interfaces.fuelIApplication
182 return fuel_abs.queryInterface(fuel_if)
183
184 def getXpcomObjInfo(thing):
185 thing._build_all_supported_interfaces_()
186 lines = []
187 for iname in thing._interface_names_:
188 methods = []
189 properties = []
190 for mname in thing._interface_names_[iname]._method_infos_:
191 if mname != "QueryInterface":
192 methods.append( "%s()" % mname )
193 for pname in thing._interface_names_[iname]._property_getters_:
194 properties.append( "%s" % pname )
195 lines.append("%s:" % iname)
196 if methods:
197 lines.extend([" METHODS: %s" % ", ".join(methods)])
198 if properties:
199 lines.extend([" PROPERTIES: %s" % ", ".join(properties)])
200 return "\n\n".join(lines)
201
202 def cmd_info(ensoapi):
203 thing = getFuelApplication()
204 ensoapi.set_selection( {"text" : getXpcomObjInfo(thing)} )
205
206 def cmd_highlight(ensoapi):
207 """
208 Highlights your current selection.
209 """
210
211 window = ensoapi.get_selection()["dom.window"]
212 document = window.document
213 sel = window.getSelection()
214 if sel.rangeCount >= 1:
215 range = sel.getRangeAt(0)
216 newNode = document.createElement("span")
217 newNode.style.background = "yellow"
218 range.surroundContents(newNode)
219 36
220 def cmd_count_lines(ensoapi): 37 def cmd_count_lines(ensoapi):
221 seldict = ensoapi.get_selection() 38 seldict = ensoapi.get_selection()
222 ensoapi.display_message( "Selection is %s lines." % 39 ensoapi.display_message( "Selection is %s lines." %
223 len(seldict.get("text","").splitlines()) ) 40 len(seldict.get("text","").splitlines()) )
385 else: 202 else:
386 ensoapi.set_selection( 203 ensoapi.set_selection(
387 {"html":normal_template % text, 204 {"html":normal_template % text,
388 "text":text} ) 205 "text":text} )
389 206
390 def cmd_paste_html(ensoapi):
391 ensoapi.set_selection(
392 {"text":"u do not support html.",
393 "html":"<p>hai2u, <i>u support html</i>!</p>"}
394 )
395
396 def cmd_get_pb_info(ensoapi):
397 import AppKit
398
399 pb = AppKit.NSPasteboard.generalPasteboard()
400
401 pbtypes = pb.types()
402 for string in pbtypes:
403 print "type: %s" % string
404
405 def make_get_url_func(url): 207 def make_get_url_func(url):
406 def get_url(): 208 def get_url():
407 import urllib2 209 import urllib2
408 210
409 f = urllib2.urlopen(url) 211 f = urllib2.urlopen(url)
965 767
966 webbrowser.open( KIRITSU_VIEW_TEMPLATE % (KIRITSU_DIR, viewname) ) 768 webbrowser.open( KIRITSU_VIEW_TEMPLATE % (KIRITSU_DIR, viewname) )
967 769
968 cmd_view.valid_args = KIRITSU_VIEWS 770 cmd_view.valid_args = KIRITSU_VIEWS
969 771
970 def cmd_rest(ensoapi):
971 import sys
972
973 ensoapi.display_message( "please wait..." )
974 popen = subprocess.Popen(
975 [ sys.executable,
976 "-c", "import time;time.sleep(2.0)" ]
977 )
978 while popen.poll() is None:
979 yield
980 if popen.returncode == 0:
981 msg = "done!"
982 else:
983 msg = "an error occurred."
984 ensoapi.display_message( msg )
985
986 def cmd_html_template(ensoapi): 772 def cmd_html_template(ensoapi):
987 ensoapi.set_selection({"text" : HTML_TEMPLATE}) 773 ensoapi.set_selection({"text" : HTML_TEMPLATE})
988 774
989 HTML_TEMPLATE = """\ 775 HTML_TEMPLATE = """\
990 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 776 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"