# HG changeset patch # User Atul Varma # Date 1211095503 25200 # Node ID 3924ba5f362162a8516e10eba411e6f045c4347a # Parent 429e04abae50d388390790ca2df3ce011e028b16 Added a bunch of commands, many of which are experimental. Some require PyXPCOM, meaning that Enso must be running atop Firefox or something similar. diff -r 429e04abae50 -r 3924ba5f3621 my-enso-commands.py --- a/my-enso-commands.py Thu May 08 11:34:42 2008 -0700 +++ b/my-enso-commands.py Sun May 18 00:25:03 2008 -0700 @@ -7,8 +7,173 @@ import webbrowser import urllib import threading +import logging from StringIO import StringIO +def cmd_menu(ensoapi): + import AppKit + import Foundation + + app = AppKit.NSApplication.sharedApplication() + + mainMenu = AppKit.NSMenu.alloc().initWithTitle_("Main") + ensoMenu = AppKit.NSMenu.alloc().initWithTitle_("Boogy") + + item = AppKit.NSMenuItem.alloc().init() + item.setTitle_("Boogy") + item.setSubmenu_(ensoMenu) + mainMenu.insertItem_atIndex_(item, 0) + + app.setMainMenu_(mainMenu) + app.setServicesMenu_(ensoMenu) + + app.registerServicesMenuSendTypes_returnTypes_( + [AppKit.NSStringPboardType], + [] + ) + + ensoapi.display_message(str(app.mainMenu())) + +def cmd_define(ensoapi): + import AppKit + + serviceName = "Look Up in Dictionary" + + text = ensoapi.get_selection().get("text", "") + + pb = AppKit.NSPasteboard.pasteboardWithName_("EnsoServiceContent") + + pb.declareTypes_owner_( [AppKit.NSStringPboardType], None ) + + try: + if not pb.setString_forType_( text, AppKit.NSStringPboardType ): + raise Exception( "Failed to set pasteboard data." ) + + if not AppKit.NSPerformService( serviceName, pb ): + raise Exception( "Failed to perform service." ) + finally: + pass + +def cmd_impersonate(ensoapi): + from xpcom import components + + class MyEventHandler: + _com_interfaces_ = components.interfaces.nsIDOMEventListener + + def __init__(self, corpus, author): + from nltk.probability import ConditionalFreqDist + + cfd = ConditionalFreqDist() + prev_word = None + for word in corpus.words(): + cfd[prev_word].inc(word) + prev_word = word + + self._cfd = cfd + self._author = author + self._last_word = None + + def handleEvent(self, event): + text = event.target.value[:event.target.selectionStart] + words = text.split() + if words and text[-1] == " ": + last_word = words[-1] + if last_word == self._last_word: + return + self._last_word = last_word + + #sorted = self._cfd[last_word].sorted() + suggestions = self._cfd[last_word].samples() + suggestions.sort(key=len, reverse=True) + suggestions = [sugg for sugg in suggestions + if len(sugg) > 3] + +# if suggestions: +# import random +# suggestion = random.choice(suggestions) +# cursor = event.target.selectionStart +# event.target.value = event.target.value[:cursor] + suggestion + " " + event.target.value[cursor:] +# cursor += len(suggestion) + 1 +# event.target.setSelectionRange(cursor, cursor) + +# suggestions = None + if suggestions: + cc = components.classes + asvc = cc["@mozilla.org/alerts-service;1"].getService( + components.interfaces.nsIAlertsService + ) + asvc.showAlertNotification( + "http://www.mozilla.com/favicon.ico", + "%s would say..." % self._author, + ", ".join(suggestions[:10]), + False, + None, + None, + None, + ) + + element = ensoapi.get_selection()["dom.element"] + + #from nltk.corpus import gutenberg + + #corpus, author = (gutenberg, "Project Gutenberg") + from nltk.corpus.reader.plaintext import PlaintextCorpusReader + + corpus = PlaintextCorpusReader( + os.getenv("HOME"), + ["argon.txt"] + ) + author = "Jim Theis" + + element.addEventListener( + "keyup", + MyEventHandler(corpus, author), + False + ) + +def cmd_extemporize(ensoapi): + element = ensoapi.get_selection().get("dom.element") + + text = "" + if element: + text = element.value + words = text.split() + if words: + from nltk.corpus.reader.plaintext import PlaintextCorpusReader + + corpus = PlaintextCorpusReader( + os.getenv("HOME"), + ["argon.txt"] + ) + + from nltk.probability import ConditionalFreqDist + import random + + cfd = ConditionalFreqDist() + prev_word = None + for word in corpus.words(): + cfd[prev_word].inc(word) + prev_word = word + + last_word = words[-1] + new_words = [] + for i in range(10): + potentials = cfd[last_word].samples() + if potentials: + next_word = random.choice(potentials) + else: + next_word = "Grignr" + new_words.append(next_word) + last_word = next_word + string = "" + for word in new_words: + if len(word) == 1 and not word.isalpha(): + string += "%s" % word + else: + string += " %s" % word + + element.value = text + string + def getFuelApplication(): from xpcom import components fuel_cls = components.classes["@mozilla.org/fuel/application;1"] @@ -16,22 +181,7 @@ fuel_if = components.interfaces.fuelIApplication return fuel_abs.queryInterface(fuel_if) -def getCommandDispatcher(): - from xpcom import components - - ci = components.interfaces - cc = components.classes - - Application = getFuelApplication() - document = Application.activeWindow.activeTab.document - - mediator = cc["@mozilla.org/appshell/window-mediator;1"].getService(ci.nsIWindowMediator) - window = mediator.getMostRecentWindow("navigator:browser") - return window.document.commandDispatcher - -def cmd_info(ensoapi): - thing = getCommandDispatcher() - +def getXpcomObjInfo(thing): thing._build_all_supported_interfaces_() lines = [] for iname in thing._interface_names_: @@ -47,15 +197,18 @@ lines.extend([" METHODS: %s" % ", ".join(methods)]) if properties: lines.extend([" PROPERTIES: %s" % ", ".join(properties)]) + return "\n\n".join(lines) - ensoapi.set_selection( {"text" : "\n\n".join(lines)} ) +def cmd_info(ensoapi): + thing = getFuelApplication() + ensoapi.set_selection( {"text" : getXpcomObjInfo(thing)} ) def cmd_highlight(ensoapi): """ Highlights your current selection. """ - window = getCommandDispatcher().focusedWindow + window = ensoapi.get_selection()["dom.window"] document = window.document sel = window.getSelection() if sel.rangeCount >= 1: @@ -829,3 +982,23 @@ else: msg = "an error occurred." ensoapi.display_message( msg ) + +def cmd_html_template(ensoapi): + ensoapi.set_selection({"text" : HTML_TEMPLATE}) + +HTML_TEMPLATE = """\ + + + + + + + + + + + + +"""