Beispiel #1
0
def ping_host(ensoapi, host):
    assert host is not None
    
    pingres = os.popen(
        os.path.expandvars(
            "${WINDIR}\\system32\\ping.exe -n 1 -w 1000 %s") 
            % host, "r")
    sys.stdout.flush()
    average_ping = None
    while 1:
        line = pingres.readline()
        if not line: 
            break
        loss = re.findall("([0-9]+)% loss", line)
        if loss:
            if int(loss[0]) > 0:
                break
        average = re.findall("Average = ([0-9]+)ms", line)
        if average:
            average_ping = int(average[0])

    displayable_host = xml.sax.saxutils.escape(host)
    if average_ping is not None:
        displayMessage(u"<p>Host <command>%s</command> is up! (%dms)</p>" 
                       % (displayable_host, average_ping))
    else:
        displayMessage(u"<p>Host <command>%s</command> is down</p>" 
                       % displayable_host)
Beispiel #2
0
def cmd_ping(ensoapi, host = None):
    """ Ping the host (hostname or IP-address, use . for recently pinged) """
    if host is None:
        seldict = ensoapi.get_selection()
        if seldict.get("text"):
            host = seldict['text'].strip().strip("\0")

    if host is None:
        return

    if host == ".":
        host = None
        # User wants to ping again recet host
        if hasattr(enso.config, "CMD_PING_LAST_SITE"):
            host = enso.config.CMD_PING_LAST_SITE
        if host is None:
            ensoapi.display_message("No host has been pinged recently.")
    else:
        # Store it for later reuse
        enso.config.CMD_PING_LAST_SITE = host

    displayable_host = xml.sax.saxutils.escape(host)
    displayMessage(u"<p>Pinging host <command>%s</command></p>" % displayable_host)
    
    pt = threading.Thread(target = ping_host, args = (ensoapi, host))
    pt.start()
Beispiel #3
0
def ping_host(ensoapi, host):
    assert host is not None

    pingres = os.popen(
        os.path.expandvars("${WINDIR}\\system32\\ping.exe -n 1 -w 1000 %s") %
        host, "r")
    sys.stdout.flush()
    average_ping = None
    while 1:
        line = pingres.readline()
        if not line:
            break
        loss = re.findall("([0-9]+)% loss", line)
        if loss:
            if int(loss[0]) > 0:
                break
        average = re.findall("Average = ([0-9]+)ms", line)
        if average:
            average_ping = int(average[0])

    displayable_host = xml.sax.saxutils.escape(host)
    if average_ping is not None:
        displayMessage(u"<p>Host <command>%s</command> is up! (%dms)</p>" %
                       (displayable_host, average_ping))
    else:
        displayMessage(u"<p>Host <command>%s</command> is down</p>" %
                       displayable_host)
Beispiel #4
0
def cmd_ping(ensoapi, host=None):
    """ Ping the host (hostname or IP-address, use . for recently pinged) """
    if host is None:
        seldict = ensoapi.get_selection()
        if seldict.get("text"):
            host = seldict['text'].strip().strip("\0")

    if host is None:
        return

    if host == ".":
        host = None
        # User wants to ping again recet host
        if hasattr(enso.config, "CMD_PING_LAST_SITE"):
            host = enso.config.CMD_PING_LAST_SITE
        if host is None:
            ensoapi.display_message("No host has been pinged recently.")
    else:
        # Store it for later reuse
        enso.config.CMD_PING_LAST_SITE = host

    displayable_host = xml.sax.saxutils.escape(host)
    displayMessage(u"<p>Pinging host <command>%s</command></p>" %
                   displayable_host)

    pt = threading.Thread(target=ping_host, args=(ensoapi, host))
    pt.start()
Beispiel #5
0
def tray_on_enso_restart(systray, get_state = False):
    if not get_state:
        if not retreat.is_locked():
            subprocess.Popen([config.ENSO_EXECUTABLE, "--restart " + str(os.getpid())])
            tray_on_enso_quit(systray)
        else:
            displayMessage(config.BLOCKED_BY_RETREAT_MSG)
Beispiel #6
0
    def run(self):
        """
        Runs the google command.
        """

        # Google limits their search requests to 2048 bytes, so let's be
        # nice and not send them anything longer than that.
        #
        # See this link for more information:
        #
        #   http://code.google.com/apis/soapsearch/reference.html

        MAX_QUERY_LENGTH = 2048

        if self.parameter != None:
            text = self.parameter
            # '...' gets replaced with current selection
            if "..." in text:
                seldict = selection.get()
                text = text.replace(
                    "...",
                    seldict.get("text", "").strip().strip("\0"))
        else:
            seldict = selection.get()
            text = seldict.get("text", "")

        text = text.strip().strip("\0")
        if not text:
            displayMessage("<p>No text was selected.</p>")
            return

        BASE_URL = "http://www.google.com/search?q=%s"

        if enso.config.PLUGIN_GOOGLE_USE_DEFAULT_LOCALE:
            # Determine the user's default language setting.  Google
            # appears to use the two-letter ISO 639-1 code for setting
            # languages via the 'hl' query argument.
            languageCode, encoding = locale.getdefaultlocale()
            if languageCode:
                language = languageCode.split("_")[0]
            else:
                language = "en"
            BASE_URL = "%s&hl=%s" % (BASE_URL, language)

        # The following is standard convention for transmitting
        # unicode through a URL.
        text = urllib.parse.quote_plus(text.encode("utf-8"))

        finalQuery = BASE_URL % text

        if len(finalQuery) > MAX_QUERY_LENGTH:
            displayMessage("<p>Your query is too long.</p>")
        else:
            # Catch exception, because webbrowser.open sometimes raises exception
            # without any reason
            try:
                webbrowser.open_new_tab(finalQuery)
            except WindowsError as e:
                logging.warning(e)
def tray_on_enso_quit(systray):
    enso.config.SYSTRAY_ICON.change_tooltip("Closing Enso...")
    if not enso.config.CMDLINE_OPTIONS.quiet:
        displayMessage(u"<p>Closing Enso...</p><caption>Enso</caption>")
    #import win32gui
    #win32gui.PostQuitMessage(0)
    time.sleep(1)
    sys.exit(0)
Beispiel #8
0
def tray_on_enso_restart(systray, get_state=False):
    if not get_state:
        if not retreat.is_locked():
            subprocess.Popen(
                [config.ENSO_EXECUTABLE, "--restart " + str(os.getpid())])
            tray_on_enso_quit(systray)
        else:
            displayMessage(config.BLOCKED_BY_RETREAT_MSG)
def tray_on_enso_quit(systray):
    enso.config.SYSTRAY_ICON.change_tooltip("Closing Enso...")
    if not enso.config.CMDLINE_OPTIONS.quiet:
        displayMessage(u"<p>Closing Enso...</p><caption>Enso</caption>")
    #import win32gui
    #win32gui.PostQuitMessage(0)
    time.sleep(1)
    sys.exit(0)
Beispiel #10
0
def cmd_enso(ensoapi, cmd):
    """ Enso system command """
    if cmd == 'quit':
        enso.stop()
    elif cmd == 'about':
        displayMessage(enso.config.ABOUT_BOX_XML)
    elif cmd == "commands":
        ensoapi.display_message("Enso commands", "enso")
Beispiel #11
0
    def run( self ):
        """
        Runs the google command.
        """

        # Google limits their search requests to 2048 bytes, so let's be
        # nice and not send them anything longer than that.
        #
        # See this link for more information:
        #
        #   http://code.google.com/apis/soapsearch/reference.html

        MAX_QUERY_LENGTH = 2048

        if self.parameter != None:
            text = self.parameter.decode()
            # '...' gets replaced with current selection
            if "..." in text:
                seldict = selection.get()
                text = text.replace(
                    "...", seldict.get( "text", u"" ).strip().strip("\0"))
        else:
            seldict = selection.get()
            text = seldict.get( "text", u"" )

        text = text.strip().strip("\0")
        if not text:
            displayMessage( "<p>No text was selected.</p>" )
            return

        BASE_URL = "http://www.google.com/search?q=%s"

        if enso.config.PLUGIN_GOOGLE_USE_DEFAULT_LOCALE:
            # Determine the user's default language setting.  Google
            # appears to use the two-letter ISO 639-1 code for setting
            # languages via the 'hl' query argument.
            languageCode, encoding = locale.getdefaultlocale()
            if languageCode:
                language = languageCode.split( "_" )[0]
            else:
                language = "en"
            BASE_URL = "%s&hl=%s" % (BASE_URL, language)

        # The following is standard convention for transmitting
        # unicode through a URL.
        text = urllib.quote_plus( text.encode("utf-8") )

        finalQuery = BASE_URL % text

        if len( finalQuery ) > MAX_QUERY_LENGTH:
            displayMessage( "<p>Your query is too long.</p>" )
        else:
            # Catch exception, because webbrowser.open sometimes raises exception
            # without any reason
            try:
                webbrowser.open_new_tab( finalQuery )
            except WindowsError, e:
                logging.warning(e)
Beispiel #12
0
def tray_on_enso_quit(systray):
    enso.config.SYSTRAY_ICON.change_tooltip("Closing Enso...")
    global options
    if not options.quiet:
        displayMessage(u"<p>Closing <command>Enso</command>...</p>")
    #import win32gui
    #win32gui.PostQuitMessage(0)
    time.sleep(1)
    sys.exit(0)
Beispiel #13
0
def tray_on_enso_quit(systray):
    enso.config.SYSTRAY_ICON.change_tooltip("Closing Enso...")
    global options
    if not options.quiet:
        displayMessage(u"<p>Closing <command>Enso</command>...</p>")
    #import win32gui
    #win32gui.PostQuitMessage(0)
    time.sleep(1)
    sys.exit(0)
Beispiel #14
0
def cmd_recycle_bin(ensoapi, operation="show"):
    """ Recycle bin {operation} """
    if operation.startswith("show"):
        #drive = operation.split(" ")[1]
        ensoapi.display_message("Opening Recycle Bin")
        """
        win32api.ShellExecute(
            0,
            "open",
            "explorer.exe " ,
            "/root,::{645FF040-5081-101B-9F08-00AA002F954E} ",
            None,
            1)
        """
        try:
            os.startfile(os.path.normpath(RECYCLE_BIN_LINK))
        except:
            pass
    elif operation.startswith("delete "):
        drive = operation.split(" ")[1]
        # SHERB_NOCONFIRMATION
        #    No dialog box confirming the deletion of the objects will be displayed.
        # SHERB_NOPROGRESSUI
        #    No dialog box indicating the progress will be displayed.
        # SHERB_NOSOUND
        #    No sound will be played when the operation is complete.
        print drive
        res = shell.SHEmptyRecycleBin(0, drive, 0)
    elif operation == "info":
        bins_info = _get_recycle_bins()
        if len(bins_info) > 0:
            infos = []
            for drive, size, files in bins_info:
                if files == 0 and size == 0:
                    infos.append(u"<command>%s</command> empty" % drive)
                else:
                    if size < 1024:
                        size_hr = "%.2f B" % size
                    elif size < 1024 * 1024:
                        size_hr = "%.2f kB" % (size / 1024)
                    elif size < 1024 * 1024 * 1024:
                        size_hr = "%.2f MB" % (size / 1024 / 1024)
                    elif size < 1024 * 1024 * 1024 * 1024:
                        size_hr = "%.2f GB" % (size / 1024 / 1024 / 1024)
                    elif size < 1024 * 1024 * 1024 * 1024 * 1024:
                        size_hr = "%.2f TB" % (size / 1024 / 1024 / 1024 /
                                               1024)
                    infos.append(u"<command>%s</command> %s in %d files" %
                                 (drive, size_hr, files))
                msg = u"<p>%s</p><caption>Recycle bin(s) information</caption>" % u"</p><p>".join(
                    infos)
            displayMessage(msg)
        else:
            ensoapi.display_message(
                u"There appears to be no recycle bins on this system")
    def run(self):
        """
        Runs the web-search command.
        """

        if self.parameter is not None:
            text = self.parameter.decode()
            # '...' gets replaced with current selection
            if "..." in text:
                seldict = selection.get()
                to_replace = " %s " % seldict.get(
                    "text", u"").strip().strip("\0")
                text = text.replace("...", to_replace)
                text = re.sub(r"\s+", " ", text)
                text = re.sub(r"\r\n", " ", text)
                text = re.sub(r"\n", " ", text)
        else:
            seldict = selection.get()
            text = seldict.get("text", u"")
            text = re.sub(r"\s+", " ", text)

        text = text.strip().strip("\0")
        if not text:
            displayMessage("<p>No text was selected.</p>")
            return

        if len(text) > MAX_QUERY_LENGTH:
            displayMessage("<p>Your query is too long.</p>")
            return

        # For compatibility with older core, use default locale if setting
        # is not used in the config...
        languageCode, _ = locale.getdefaultlocale()
        if languageCode:
            language = languageCode.split("_")[0]
        else:
            language = "en"

        # The following is standard convention for transmitting
        # unicode through a URL.
        text = urllib.quote_plus(text.encode("utf-8"))

        url = self.BASE_URL % {
            "local_tld": LOCAL_TLD, # Used just for Google services
            "langcode": language,
            "query": text,
        }

        # Catch exception, because webbrowser.open sometimes raises exception
        # without any reason
        try:
            webbrowser.open_new_tab(url)
        except Exception as e:
            logging.warning(e)
Beispiel #16
0
def cmd_recycle_bin(ensoapi, operation = "show"):
    """ Recycle bin {operation} """
    if operation.startswith("show"):
        #drive = operation.split(" ")[1]
        ensoapi.display_message("Opening Recycle Bin")
        """
        win32api.ShellExecute(
            0,
            "open",
            "explorer.exe " ,
            "/root,::{645FF040-5081-101B-9F08-00AA002F954E} ",
            None,
            1)
        """
        try:
            os.startfile(os.path.normpath(RECYCLE_BIN_LINK))
        except:
            pass
    elif operation.startswith("delete "):
        drive = operation.split(" ")[1]
        # SHERB_NOCONFIRMATION
        #    No dialog box confirming the deletion of the objects will be displayed.
        # SHERB_NOPROGRESSUI
        #    No dialog box indicating the progress will be displayed.
        # SHERB_NOSOUND
        #    No sound will be played when the operation is complete.
        print drive
        res = shell.SHEmptyRecycleBin(0, drive, 0)
    elif operation == "info":
        bins_info = _get_recycle_bins()
        if len(bins_info) > 0:
            infos = []
            for drive, size, files in bins_info:
                if files == 0 and size == 0:
                    infos.append(u"<command>%s</command> empty" % drive)
                else:
                    if size < 1024:
                        size_hr = "%.2f B" % size
                    elif size < 1024*1024:
                        size_hr = "%.2f kB" % (size / 1024)
                    elif size < 1024*1024*1024:
                        size_hr = "%.2f MB" % (size / 1024 / 1024)
                    elif size < 1024*1024*1024*1024:
                        size_hr = "%.2f GB" % (size / 1024 / 1024 / 1024)
                    elif size < 1024*1024*1024*1024*1024:
                        size_hr = "%.2f TB" % (size / 1024 / 1024 / 1024 / 1024)
                    infos.append(u"<command>%s</command> %s in %d files" % (drive, size_hr, files))
                msg = u"<p>%s</p><caption>Recycle bin(s) information</caption>" % u"</p><p>".join(infos)
            displayMessage(msg)
        else:
            ensoapi.display_message(u"There appears to be no recycle bins on this system")
Beispiel #17
0
    def run( self ):
        """
        Runs the google command.
        """

        # Google limits their search requests to 2048 bytes, so let's be
        # nice and not send them anything longer than that.
        #
        # See this link for more information:
        #
        #   http://code.google.com/apis/soapsearch/reference.html

        MAX_QUERY_LENGTH = 2048

        if self.parameter != None:
            text = self.parameter.decode()
        else:
            seldict = selection.get()
            text = seldict.get( "text", u"" )

        text = text.strip()
        if not text:
            displayMessage( "<p>No text was selected.</p>" )
            return

        BASE_URL = "http://www.google.com/search?hl=%s&q=%s"

        # Determine the user's default language setting.  Google
        # appears to use the two-letter ISO 639-1 code for setting
        # languages via the 'hl' query argument.
        languageCode, encoding = locale.getdefaultlocale()
        if languageCode:
            language = languageCode.split( "_" )[0]
        else:
            language = "en"

        # The following is standard convention for transmitting
        # unicode through a URL.
        text = urllib.quote_plus( text.encode("utf-8") )

        finalQuery = BASE_URL % ( language, text )

        if len( finalQuery ) > MAX_QUERY_LENGTH:
            displayMessage( "<p>Your query is too long.</p>" )
        else:
            try:
                webbrowser.open_new_tab( finalQuery )
            except:
                pass
Beispiel #18
0
    def run(self):
        """
        Runs the google command.
        """

        # Google limits their search requests to 2048 bytes, so let's be
        # nice and not send them anything longer than that.
        #
        # See this link for more information:
        #
        #   http://code.google.com/apis/soapsearch/reference.html

        MAX_QUERY_LENGTH = 2048

        if self.parameter != None:
            text = self.parameter.decode()
        else:
            seldict = selection.get()
            text = seldict.get("text", u"")

        text = text.strip()
        if not text:
            displayMessage("<p>No text was selected.</p>")
            return

        BASE_URL = "http://www.google.com/search?hl=%s&q=%s"

        # Determine the user's default language setting.  Google
        # appears to use the two-letter ISO 639-1 code for setting
        # languages via the 'hl' query argument.
        languageCode, encoding = locale.getdefaultlocale()
        if languageCode:
            language = languageCode.split("_")[0]
        else:
            language = "en"

        # The following is standard convention for transmitting
        # unicode through a URL.
        text = urllib.quote_plus(text.encode("utf-8"))

        finalQuery = BASE_URL % (language, text)

        if len(finalQuery) > MAX_QUERY_LENGTH:
            displayMessage("<p>Your query is too long.</p>")
        else:
            try:
                webbrowser.open_new_tab(finalQuery)
            except:
                pass
def tray_on_enso_about(systray):
    _ = systray
    quasimode_key_name = {
        "KEYCODE_LSHIFT":"Left Shift",
        "KEYCODE_RSHIFT":"Right Shift",
        "KEYCODE_LCONTROL":"Left Ctrl",
        "KEYCODE_RCONTROL":"Right Ctrl",
        "KEYCODE_LWIN":"Left Win",
        "KEYCODE_RWIN":"Right Win",
        "KEYCODE_CAPITAL":"CapsLock"
        }[enso.config.QUASIMODE_START_KEY]
    displayMessage(
        "%s<p> </p><caption>Hold down the <command>%s</command> key to invoke Enso</caption>"
        % (enso.config.ABOUT_MSG_XML, quasimode_key_name),
        primaryWaitTime=2000)
def tray_on_enso_about(systray):
    _ = systray
    quasimode_key_name = {
        "KEYCODE_LSHIFT": "Left Shift",
        "KEYCODE_RSHIFT": "Right Shift",
        "KEYCODE_LCONTROL": "Left Ctrl",
        "KEYCODE_RCONTROL": "Right Ctrl",
        "KEYCODE_LWIN": "Left Win",
        "KEYCODE_RWIN": "Right Win",
        "KEYCODE_CAPITAL": "CapsLock"
    }[enso.config.QUASIMODE_START_KEY]
    displayMessage(
        "%s<p> </p><caption>Hold down the <command>%s</command> key to invoke Enso</caption>"
        % (enso.config.ABOUT_MSG_XML, quasimode_key_name),
        primaryWaitTime=2000)
Beispiel #21
0
    def run( self ):
        """
        Runs the google command.
        """
        if not self.parameter:
            return

        uc = EnsoUndoCache.get()

        print "Parameter: '%s'" % self.parameter
        command, values = uc.pop(self.parameter)
        print command
        print values
        if hasattr(command, "undo"):
            if command.undo(ensoapi.EnsoApi(), self.parameter, values):
                displayMessage(u"<p>Command <command>%s</command> has been undone.</p>" % self.parameter)
Beispiel #22
0
    def __showBadCommandMsg(self, userText):
        """
        Displays an error message telling the user that userText does
        not match any command.  Also, if there are any reasonable
        commands that were similar but not matching, offers those to
        the user as suggestions.
        """

        # Generate a caption for the message with a couple suggestions
        # for command names similar to the user's text
        caption = self.__commandSuggestionCaption(escape_xml(userText))
        badCmd = userText.lower()
        badCmd = escape_xml(badCmd)
        # Create and display a primary message.
        text = config.BAD_COMMAND_MSG
        text = text % (badCmd, caption)

        messages.displayMessage(text)
Beispiel #23
0
    def run(self):
        """
        Runs the google command.
        """
        if not self.parameter:
            return

        uc = EnsoUndoCache.get()

        print "Parameter: '%s'" % self.parameter
        command, values = uc.pop(self.parameter)
        print command
        print values
        if hasattr(command, "undo"):
            if command.undo(ensoapi.EnsoApi(), self.parameter, values):
                displayMessage(
                    u"<p>Command <command>%s</command> has been undone.</p>" %
                    self.parameter)
Beispiel #24
0
    def __showBadCommandMsg( self, userText ):
        """
        Displays an error message telling the user that userText does
        not match any command.  Also, if there are any reasonable
        commands that were similar but not matching, offers those to
        the user as suggestions.
        """

        # Generate a caption for the message with a couple suggestions
        # for command names similar to the user's text
        caption = self.__commandSuggestionCaption( escape_xml( userText ) )
        badCmd = userText.lower()
        badCmd = escape_xml( badCmd )
        # Create and display a primary message.
        text = config.BAD_COMMAND_MSG
        text = text % ( badCmd, caption )

        messages.displayMessage( text )
def tray_on_enso_exec_at_startup(systray, get_state=False):
    _ = systray
    startup_dir = shell.SHGetFolderPath(0, shellcon.CSIDL_STARTUP, 0, 0)
    assert os.path.isdir(startup_dir)

    link_file = os.path.join(startup_dir, "Enso.lnk")

    if get_state:
        return os.path.isfile(link_file)
    else:
        if not os.path.isfile(link_file):
            try:
                pythoncom.CoInitialize()
            except:
                # already initialized.
                pass

            shortcut = pythoncom.CoCreateInstance(
                shell.CLSID_ShellLink, None, pythoncom.CLSCTX_INPROC_SERVER,
                shell.IID_IShellLink)

            shortcut.SetPath(ENSO_EXECUTABLE)
            enso_root_dir = os.path.dirname(ENSO_EXECUTABLE)
            shortcut.SetWorkingDirectory(enso_root_dir)
            shortcut.SetIconLocation(os.path.join(enso_root_dir, "Enso.ico"),
                                     0)

            shortcut.QueryInterface(pythoncom.IID_IPersistFile).Save(
                link_file, 0)
            try:
                pythoncom.CoUnInitialize()
            except:
                pass

            displayMessage(
                u"<p><command>Enso</command> will be automatically executed at system startup</p><caption>enso</caption>"
            )
        else:
            os.remove(link_file)
            displayMessage(
                u"<p><command>Enso</command> will not start at system startup</p><caption>enso</caption>"
            )
def tray_on_enso_exec_at_startup(systray, get_state = False):
    _ = systray
    startup_dir = shell.SHGetFolderPath(0, shellcon.CSIDL_STARTUP, 0, 0)
    assert os.path.isdir(startup_dir)

    link_file = os.path.join(startup_dir, "Enso.lnk")

    if get_state:
        return os.path.isfile(link_file)
    else:
        if not os.path.isfile(link_file):
            try:
                pythoncom.CoInitialize()
            except:
                # already initialized.
                pass

            shortcut = pythoncom.CoCreateInstance(
                shell.CLSID_ShellLink,
                None,
                pythoncom.CLSCTX_INPROC_SERVER,
                shell.IID_IShellLink
            )

            shortcut.SetPath(ENSO_EXECUTABLE)
            enso_root_dir = os.path.dirname(ENSO_EXECUTABLE)
            shortcut.SetWorkingDirectory(enso_root_dir)
            shortcut.SetIconLocation(os.path.join(enso_root_dir, "Enso.ico"), 0)

            shortcut.QueryInterface( pythoncom.IID_IPersistFile ).Save(
                link_file, 0 )
            try:
                pythoncom.CoUnInitialize()
            except:
                pass

            displayMessage(u"<p><command>Enso</command> will be automatically executed at system startup</p><caption>enso</caption>")
        else:
            os.remove(link_file)
            displayMessage(u"<p><command>Enso</command> will not start at system startup</p><caption>enso</caption>")
Beispiel #27
0
def run():
    """
    Initializes and runs Enso.
    """
    import logging
    import sys
    from enso.events import EventManager
    from enso.quasimode import Quasimode
    from enso import events, plugins, config, messages, quasimode, webui

    def except_hook(type, value, tback):
        # manage unhandled exception here
        logging.error(value)
        tback.print_exc()
        sys.__excepthook__(type, value, tback)  # then call the default handler

    sys.excepthook = except_hook

    eventManager = EventManager.get()
    Quasimode.install(eventManager)
    plugins.install(eventManager)

    webui_server = webui.start(eventManager)

    if enso.config.SHOW_SPLASH and config.OPENING_MSG_XML:
        eventManager.registerResponder(
            lambda: messages.displayMessage(config.OPENING_MSG_XML), 
            "init")

    try:
        eventManager.run()
    except SystemError as e:
        logging.error(e)
        import traceback
        traceback.print_exc()
        webui_server.stop()
    except SystemExit as e:
        logging.error(e)
        import traceback
        traceback.print_exc()
        webui_server.stop()
    except KeyboardInterrupt:
        webui_server.stop()
    except Exception as e:
        logging.error(e)
        import traceback
        traceback.print_exc()
        webui_server.stop()
    except:
        import traceback
        traceback.print_exc()
        webui_server.stop()
Beispiel #28
0
    def display_message(self, msg, caption=None):
        """
        Displays the given message, with an optional caption.  Both
        parameters should be unicode strings.
        """

        if not isinstance(msg, basestring):
            msg = unicode(msg)

        msg = xml.sax.saxutils.escape(msg)
        xmltext = "<p>%s</p>" % msg
        if caption:
            caption = xml.sax.saxutils.escape(caption)
            xmltext += "<caption>%s</caption>" % caption
        return displayMessage(xmltext)
Beispiel #29
0
    def display_message(self, msg, caption=None):
        """
        Displays the given message, with an optional caption.  Both
        parameters should be unicode strings.
        """

        if not isinstance(msg, basestring):
            msg = unicode(msg)

        msg = xml.sax.saxutils.escape(msg)
        xmltext = "<p>%s</p>" % msg
        if caption:
            caption = xml.sax.saxutils.escape(caption)
            xmltext += "<caption>%s</caption>" % caption
        return displayMessage(xmltext)
Beispiel #30
0
def cmd_enso(ensoapi, action):
    """ Enso system command
    <b>Actions:</b><br>
    &nbsp;&nbsp- quit - quit Enso<br>
    &nbsp;&nbsp- restart - restart Enso<br>
    &nbsp;&nbsp- refresh - reload shortcuts available for the 'open' command<br>
    &nbsp;&nbsp- settings - open Enso settings page<br>
    &nbsp;&nbsp- commands - open Enso command list<br>
    &nbsp;&nbsp- tasks - open Enso task editor<br>
    &nbsp;&nbsp- editor - open Enso command editor<br>
    &nbsp;&nbsp- about - show application information<br>
    """
    if action == 'quit':
        if not retreat.is_locked():
            EventManager.get().stop()
        else:
            displayMessage(config.BLOCKED_BY_RETREAT_MSG)
    elif action == 'restart':
        if not retreat.is_locked():
            EventManager.get().stop()
            subprocess.Popen(
                [config.ENSO_EXECUTABLE, "--restart " + str(os.getpid())])
        else:
            displayMessage(config.BLOCKED_BY_RETREAT_MSG)
    elif action == 'refresh':
        Shortcuts.get().refreshShortcuts()
        ScriptTracker.get()._reloadPyScripts()
        displayMessage(config.REFRESHING_MSG_XML)
    elif action == 'settings':
        if config.ENABLE_WEB_UI:
            os.startfile("http://" + webui.HOST + ":" + str(webui.PORT) +
                         "/options.html")
    elif action == 'commands':
        if config.ENABLE_WEB_UI:
            os.startfile("http://" + webui.HOST + ":" + str(webui.PORT) +
                         "/commands.html")
    elif action == 'tasks':
        if config.ENABLE_WEB_UI:
            os.startfile("http://" + webui.HOST + ":" + str(webui.PORT) +
                         "/tasks.html")
    elif action == 'editor':
        if config.ENABLE_WEB_UI:
            os.startfile("http://" + webui.HOST + ":" + str(webui.PORT) +
                         "/edit.html")
    elif action == 'about':
        displayMessage(enso.config.ABOUT_BOX_XML)
Beispiel #31
0
def cmd_enso(ensoapi, cmd):
    """ Enso system command """
    if cmd == 'quit':
        displayMessage(u"<p>Closing <command>Enso</command>...</p>")
        time.sleep(1)
        sys.exit(0)
    if cmd == 'restart':
        subprocess.Popen([enso.enso_executable, "--restart " + str(os.getpid())])
        displayMessage(u"<p>Closing <command>Enso</command>...</p>")
        time.sleep(1)
        sys.exit(0)
    elif cmd == 'about':
        displayMessage(enso.config.ABOUT_BOX_XML)
Beispiel #32
0
def cmd_is_down(ensoapi, url = None):
    """ Check if the site is down """
    if url is None:
        get_selection_thread = ThreadedFunc(
            target = ensoapi.get_selection
        )
        while get_selection_thread.isAlive():
            yield
        if get_selection_thread.wasSuccessful():
            seldict = get_selection_thread.getRetval()
            if seldict.get("text"):
                url = seldict['text'].strip().strip("\0")

    if url is None:
        return

    parsed_url = _extract_url_from_text(url)
    
    if not parsed_url:
        ensoapi.display_message("Unrecognized URL format.")
        return

    scheme = parsed_url.scheme
    netloc = parsed_url.netloc
    if netloc.endswith(":80"):
        netloc = netloc[:-3]
    base_url = scheme + "://" + netloc

    print base_url

    query_url = "http://downforeveryoneorjustme.com/%s" % urllib.quote_plus(base_url)
    t = ThreadedFunc(
        target = get_html,
        args = (ensoapi, query_url))

    while t.isAlive():
        yield

    if t.wasSuccessful():
        html = t.getRetval()
        if html.find("It's just you") > -1:
            displayMessage(u"<p>Site <command>%s</command> is online</p>" % base_url)
        elif html.find("doesn't look like a site") > -1:
            displayMessage(u"<p>Site <command>%s</command> is unknown!</p>" % base_url)
        elif html.find("It's not just you") > -1:
            displayMessage(u"<p>Site <command>%s</command> is down!</p>" % base_url)
        else:    
            print html
Beispiel #33
0
def cmd_is_down(ensoapi, url=None):
    """ Check if the site is down """
    if url is None:
        get_selection_thread = ThreadedFunc(target=ensoapi.get_selection)
        while get_selection_thread.isAlive():
            yield
        if get_selection_thread.wasSuccessful():
            seldict = get_selection_thread.getRetval()
            if seldict.get("text"):
                url = seldict['text'].strip().strip("\0")

    if url is None:
        return

    parsed_url = _extract_url_from_text(url)

    if not parsed_url:
        ensoapi.display_message("Unrecognized URL format.")
        return

    scheme = parsed_url.scheme
    netloc = parsed_url.netloc
    if netloc.endswith(":80"):
        netloc = netloc[:-3]
    base_url = scheme + "://" + netloc

    print base_url

    query_url = "http://downforeveryoneorjustme.com/%s" % urllib.quote_plus(
        base_url)
    t = ThreadedFunc(target=get_html, args=(ensoapi, query_url))

    while t.isAlive():
        yield

    if t.wasSuccessful():
        html = t.getRetval()
        if html.find("It's just you") > -1:
            displayMessage(u"<p>Site <command>%s</command> is online</p>" %
                           base_url)
        elif html.find("doesn't look like a site") > -1:
            displayMessage(u"<p>Site <command>%s</command> is unknown!</p>" %
                           base_url)
        elif html.find("It's not just you") > -1:
            displayMessage(u"<p>Site <command>%s</command> is down!</p>" %
                           base_url)
        else:
            print html
Beispiel #34
0
def cmd_enso(ensoapi, cmd):
    """ Enso system command """
    if cmd == 'quit':
        displayMessage(
            u"<p>Closing <command>Enso</command>...</p><caption>enso</caption>"
        )
        time.sleep(1)
        sys.exit(0)
    if cmd == 'restart':
        subprocess.Popen(
            [enso.enso_executable, "--restart " + str(os.getpid())])
        displayMessage(
            u"<p>Closing <command>Enso</command>...</p><caption>enso</caption>"
        )
        time.sleep(1)
        sys.exit(0)
    elif cmd == 'about':
        displayMessage(enso.config.ABOUT_BOX_XML)
Beispiel #35
0
def cmd_enso(ensoapi, action):
    """ Enso system command
    <b>Actions:</b><br>
    &nbsp;&nbsp- quit - quit Enso<br>
    &nbsp;&nbsp- restart - restart Enso<br>
    &nbsp;&nbsp- settings - open Enso settings page<br>
    &nbsp;&nbsp- commands - open Enso command list<br>
    &nbsp;&nbsp- task - open Enso task editor<br>
    &nbsp;&nbsp- editor - open Enso command editor<br>
    &nbsp;&nbsp- about - show application information<br>
    """
    if action == 'quit':
        if not retreat.is_locked():
            EventManager.get().stop()
        else:
            displayMessage(config.BLOCKED_BY_RETREAT_MSG)
    elif action == 'restart':
        if not retreat.is_locked():
            EventManager.get().stop()
            subprocess.Popen([config.ENSO_EXECUTABLE, "--restart " + str(os.getpid())])
        else:
            displayMessage(config.BLOCKED_BY_RETREAT_MSG)
    elif action == 'settings':
        if config.ENABLE_WEB_UI:
            os.startfile("http://" + webui.HOST + ":" + str(webui.PORT) + "/options.html")
    elif action == 'commands':
        if config.ENABLE_WEB_UI:
            os.startfile("http://" + webui.HOST + ":" + str(webui.PORT) + "/commands.html")
    elif action == 'tasks':
        if config.ENABLE_WEB_UI:
            os.startfile("http://" + webui.HOST + ":" + str(webui.PORT) + "/tasks.html")
    elif action == 'editor':
        if config.ENABLE_WEB_UI:
            os.startfile("http://" + webui.HOST + ":" + str(webui.PORT) + "/edit.html")
    elif action == 'about':
        displayMessage(enso.config.ABOUT_BOX_XML)
Beispiel #36
0
 def setTracebackInfo(cls):
     tbText = "Scriptotron exception:\n%s" % \
         traceback.format_exc()
     cls.tracebackText = tbText
     displayMessage(_makeExcInfoMsgText(*sys.exc_info()))
Beispiel #37
0
def cmd_calculate(ensoapi, expression = None):
    u""" Calculate the given expression
    Calculate mathematical expression.<br><br>
    Supported operators:<br>
    <code>
    -, +, /, *, ^, **, (, ), %, mod
    </code><br>
    functions:<br>
    <code>
    mod, currency, acos, asin, atan, atan2, ceil, cos, cosh,
    degrees, exp, fabs, floor, fmod, frexp, hypot, ldexp,
    log, log10, modf, pow, radians, sin, sinh, sqrt, tan, tanh
    </code><br>
    constants:<br>
    <code>
    pi, e
    </code><br>
    conversions:<br>
    <code>
    abs, chr, hex
    </code><br>
    currency conversion:<br>
    <code>150eur in usd</code><br>
    <code>1 gbp to eur</code><br>
    <code>usd in eur</code><br>
    <code>to eur</code>
    (when some text representing amount + currency is selected,
    like $1000, gbp10, €4.5, 10 GBP)<br>
    """
    #_cache_currencies()
    #print "TO CURRENCIES: " + "|".join(_to_currencies.keys())

    got_selection = False

    if expression is None:
        seldict = ensoapi.get_selection()
        if seldict.get(u"text"):
            selected_text = seldict[u"text"].strip().strip("\0")
        else:
            selected_text = None

        if selected_text:
            expression = selected_text
            got_selection = expression is not None

        if not got_selection:
            ensoapi.display_message("No expression given.")
            return

    math_funcs = [f for f in dir(math) if f[:2] != '__']

    whitelist = '|'.join(
        # oprators, digits
        [' ', '\.', ',', '\-', '\+', '/', '\\', '\*', '\^', '\*\*', '\(', '\)', '%', '\d+']
        + ['abs', 'chr\([0-9]+\)', 'hex\([0-9]+\)', 'mod', 'currency']
        # functions of math module (ex. __xxx__)
        + math_funcs)

    print whitelist

    math_funcs_dict = dict([ (mf, eval('math.%s' % mf)) for mf in math_funcs])
    math_funcs_dict['abs'] = abs
    math_funcs_dict['chr'] = chr
    math_funcs_dict['hex'] = hex
    math_funcs_dict['currency'] = currency

    expression = expression.replace(' mod ', ' % ')

    currconv_match = complete_currency_re.search(expression)
    if currconv_match:
        #print "currconv match"
        if currconv_match.group(1):
            amount = currconv_match.group(1)
            print amount
        else:
            amount_str = (selected_text if selected_text else "1").replace(" ", "")
            print amount_str
            try:
                amount = float(amount_str)
            except:
                amount = 1

        #print  r"(.*)(" + "|".join(_from_currencies.keys()) + ") (in|to) (" + "|".join(_to_currencies.keys()) + ")(.*)"
        expression = "currency(%s, '%s', '%s') %s" % (
            amount,
            currconv_match.group(2).upper(),
            currconv_match.group(4).upper(),
            currconv_match.group(5))
        #print expression
    else:
        currconv_match = partial_currency_re.match(expression.strip())
        if currconv_match:
            #print "partial match"
            amount_str, from_currency, amount = _handle_currency_symbols(
                (selected_text if selected_text else "1").replace(" ", ""))
            #print amount_str, from_currency, amount
            #print currconv_match.groups()
            expression = "currency(%s, '%s', '%s') %s" % (
                amount,
                from_currency,
                currconv_match.group(2).upper(),
                currconv_match.group(3)
            )
        #print expression

    #print expression = expression.replace(' in ', ' % ')

    #print math_funcs_dict

    if re.match(whitelist, expression):
        if expression.endswith("="):
            expression = expression[:-1]
            append_result = True
        else:
            append_result = False

        try:
            result = eval(expression, {"__builtins__": None}, math_funcs_dict)
            global last_calculation
            last_calculation = result

            if got_selection:
                if append_result:
                    selection.set({ "text" : expression.strip() + " = " + unicode(result) })
                else:
                    selection.set({ "text" : unicode(result) })
            else:
                displayMessage(u"<p>%s</p><caption>%s</caption>" % (result, expression))

        except Exception, e:
            logging.info(e)
            ensoapi.display_message("Invalid syntax", "Error")
Beispiel #38
0
def main(argv=None):
    opts, args = process_options(argv)
    config.ENSO_IS_QUIET = opts.quiet

    loglevel = {
        'CRITICAL': logging.CRITICAL,
        'ERROR': logging.ERROR,
        'INFO': logging.INFO,
        'WARNING': logging.WARNING,
        'DEBUG': logging.DEBUG
    }[opts.loglevel]

    if opts.show_console:
        print("Showing console")
        logging.basicConfig(level=loglevel)
    else:
        print("Hiding console")
        user_log = os.path.join(config.ENSO_USER_DIR, "enso.log")
        print("Logging into '%s'" % user_log)
        sys.stdout = open(user_log, "w")  #NullDevice()
        sys.stderr = open(user_log, "w")  #NullDevice()
        logging.basicConfig(filename=user_log, level=loglevel)

    if loglevel == logging.DEBUG:
        print(opts)
        print(args)

    if not os.path.isdir(config.ENSO_USER_DIR):
        os.makedirs(config.ENSO_USER_DIR)

    user_lib_dir = os.path.join(config.ENSO_USER_DIR, "lib")
    if not os.path.isdir(user_lib_dir):
        os.makedirs(user_lib_dir)

    user_commands_dir = os.path.join(config.ENSO_USER_DIR, "commands")
    user_commands = os.path.join(user_commands_dir, "user.py")

    if not os.path.isdir(user_commands_dir):
        os.makedirs(user_commands_dir)

    open(user_commands, 'a').close()

    default_enso_rc = os.path.join(config.ENSO_USER_DIR, "ensorc.py")
    if not os.path.exists(default_enso_rc):
        shutil.copyfile(
            os.path.join(config.ENSO_DIR, "scripts", "ensorc.py.default"),
            os.path.join(config.ENSO_USER_DIR, "ensorc.py"))

    load_rc_config(default_enso_rc)

    # legacy ensorc, currently undocumented
    load_rc_config(os.path.expanduser("~/.ensorc"))

    if opts.show_tray_icon:
        # Execute tray-icon code in separate thread
        threading.Thread(target=systray, args=(config, )).start()

    retreat.start()

    enso.run()

    config.SYSTRAY_ICON.change_tooltip("Closing Enso...")
    if not config.ENSO_IS_QUIET:
        displayMessage("<p>Closing Enso...</p><caption>Enso</caption>")

    win32gui.PostMessage(config.SYSTRAY_ICON.hwnd, win32con.WM_COMMAND,
                         config.SYSTRAY_ICON.CMD_FINALIZE, 0)

    retreat.stop()

    time.sleep(1)
    os._exit(0)

    return 0
Beispiel #39
0
def tray_on_enso_quit(systray):
    if not retreat.is_locked():
        EventManager.get().stop()
    else:
        displayMessage(config.BLOCKED_BY_RETREAT_MSG)
Beispiel #40
0
 def setTracebackInfo( cls ):
     tbText = "Scriptotron exception:\n%s" % \
         traceback.format_exc()
     cls.tracebackText = tbText
     displayMessage( _makeExcInfoMsgText(*sys.exc_info()) )
Beispiel #41
0
def tray_on_enso_about(systray):
    displayMessage(
        enso.config.ABOUT_BOX_XML +
        "<p> </p><caption>Hit the <command>CapsLock</command> key to invoke Enso</caption>" )
Beispiel #42
0
def tray_on_enso_about(systray):
    displayMessage(enso.config.ABOUT_BOX_XML)
Beispiel #43
0
def tray_on_enso_quit(systray):
    if not retreat.is_locked():
        EventManager.get().stop()
    else:
        displayMessage(config.BLOCKED_BY_RETREAT_MSG)
            exec compiledContents in {}, {}
        else:
            logging.warning(".ensorc file can't be read!")
    else:
        logging.info("Ignoring your .ensorc startup script")

    if opts.hotkey in ("default", "CAPITAL", "LSHIFT", "RSHIFT", "LCONTROL", "RCONTROL", "LWIN", "RWIN"):
        if opts.hotkey != "default":
            #contents += "enso.config.QUASIMODE_START_KEY = \"KEYCODE_%s\"\n" % opts.hotkey
            enso.config.QUASIMODE_START_KEY = "KEYCODE_%s" % opts.hotkey
            logging.info("Enso hotkey has been set to %s" % opts.hotkey)
    else:
        logging.error("Invalid hotkey spec: %s" % opts.hotkey)

    if not opts.quiet and opts.show_splash:
        displayMessage("<p><command>Enso</command> is starting...</p>")
    
    if sys.platform.startswith("win"):
        # Add tray-icon support for win32 platform
        if opts.show_tray_icon:
            # tray-icon code must be run in separate thread otherwise it blocks
            # current thread (using PumpMessages() )
            try:
                import enso.platform.win32.taskbar as taskbar
                threading.Thread(target = taskbar.systray, args = (enso.config,)).start()
            except Exception, e:
                logging.error("Error initializing taskbar systray icon: %s", e)

    if opts.commands_dir != "default":
        logging.info("Default commands directory changed to \"%s\"" % opts.commands_dir)
        enso.config.SCRIPTS_FOLDER_NAME = opts.commands_dir
Beispiel #45
0
def tray_on_enso_about(systray):
    displayMessage(
        enso.config.ABOUT_BOX_XML +
        "<p> </p><caption>Hit the <command>CapsLock</command> key to invoke Enso</caption>"
    )
Beispiel #46
0
def tray_on_enso_about(systray):
    displayMessage(enso.config.ABOUT_BOX_XML)
Beispiel #47
0
def cmd_calculate(ensoapi, expression = None):
    """ Calculate the given expression
    Calculate mathematical expression.<br/><br/>
    Supported operators:<br/>
    <code>
    -, +, /, *, ^, **, (, ), %, mod
    </code><br/>
    functions:<br/>
    <code>
    mod, acos, asin, atan, atan2, ceil, cos, cosh,
    degrees, exp, fabs, floor, fmod, frexp, hypot, ldexp,
    log, log10, modf, pow, radians, sin, sinh, sqrt, tan, tanh
    </code><br/>
    constants:<br/>
    <code>
    pi, e
    </code><br/>
    conversions:<br/>
    <code>
    abs, chr, hex
    </code>
    """
    seldict = ensoapi.get_selection()
    if seldict.get("text"):
        selected_text = seldict['text'].strip().strip("\0")
    else:
        selected_text = None

    got_selection = False
    if expression is None:
        if selected_text:
            expression = selected_text
            got_selection = expression is not None

    if expression is None:
        ensoapi.display_message("No expression given.")
        return        
    
    math_funcs = [f for f in dir(math) if f[:2] != '__']

    whitelist = '|'.join(
        # oprators, digits
        [' ', '\.', ',', '\-', '\+', '/', '\\', '\*', '\^', '\*\*', '\(', '\)', '%', '\d+']
        + ['abs', 'chr\([0-9]+\)', 'hex\([0-9]+\)', 'mod']
        # functions of math module (ex. __xxx__)
        + math_funcs)

    print(whitelist)

    math_funcs_dict = dict([ (mf, eval('math.%s' % mf)) for mf in math_funcs])
    math_funcs_dict['abs'] = abs
    math_funcs_dict['chr'] = chr
    math_funcs_dict['hex'] = hex

    expression = expression.replace(' mod ', ' % ')

    if re.match(whitelist, expression):
        if expression.endswith("="):
            expression = expression[:-1]
            append_result = True
        else:
            append_result = False
        
        try:
            result = eval(expression, {"__builtins__": None}, math_funcs_dict)
            global last_calculation
            last_calculation = result

            pasted = False
            if got_selection:
                if append_result:
                    pasted = selection.set({ "text" : expression.strip() + " = " + str(result) })
                else:
                    pasted = selection.set({ "text" : str(result) })
            
            if not pasted:
                displayMessage("<p>%s</p><caption>%s</caption>" % (result, expression))
        except Exception as e:
            logging.info(e)
            ensoapi.display_message("Invalid syntax", "Error")
    else:
        ensoapi.display_message("Invalid expression", "Error")
Beispiel #48
0
def main(argv = None):
    opts, args = process_options(argv)
    config.ENSO_IS_QUIET = opts.quiet

    loglevel = {
        'CRITICAL' : logging.CRITICAL,
        'ERROR' : logging.ERROR,
        'INFO' : logging.INFO,
        'WARNING' : logging.WARNING,
        'DEBUG' : logging.DEBUG
        }[opts.loglevel]

    if opts.show_console:
        print("Showing console")
        logging.basicConfig( level = loglevel )
    else:
        print("Hiding console")
        user_log = os.path.join(config.ENSO_USER_DIR, "enso.log")
        print("Logging into '%s'" % user_log)
        sys.stdout = open(user_log, "w") #NullDevice()
        sys.stderr = open(user_log, "w") #NullDevice()
        logging.basicConfig(
            filename = user_log,
            level = loglevel )

    if loglevel == logging.DEBUG:
        print(opts)
        print(args)

    if not os.path.isdir(config.ENSO_USER_DIR):
        os.makedirs(config.ENSO_USER_DIR)

    user_lib_dir = os.path.join(config.ENSO_USER_DIR, "lib")
    if not os.path.isdir(user_lib_dir):
        os.makedirs(user_lib_dir)

    user_commands_dir = os.path.join(config.ENSO_USER_DIR, "commands")
    user_commands = os.path.join(user_commands_dir, "user.py")

    if not os.path.isdir(user_commands_dir):
        os.makedirs(user_commands_dir)

    open(user_commands, 'a').close()

    default_enso_rc = os.path.join(config.ENSO_USER_DIR, "ensorc.py")
    if not os.path.exists( default_enso_rc ):
        shutil.copyfile(os.path.join(config.ENSO_DIR, "scripts", "ensorc.py.default"),
                        os.path.join(config.ENSO_USER_DIR, "ensorc.py"))

    load_rc_config(default_enso_rc)

    # legacy ensorc, currently undocumented
    load_rc_config(os.path.expanduser("~/.ensorc"))

    if opts.show_tray_icon:
        # Execute tray-icon code in separate thread
        threading.Thread(target = systray, args = (config,)).start()

    retreat.start()

    enso.run()

    config.SYSTRAY_ICON.change_tooltip("Closing Enso...")
    if not config.ENSO_IS_QUIET:
        displayMessage("<p>Closing Enso...</p><caption>Enso</caption>")

    win32gui.PostMessage(config.SYSTRAY_ICON.hwnd, win32con.WM_COMMAND, config.SYSTRAY_ICON.CMD_FINALIZE, 0)

    retreat.stop()

    time.sleep(1)
    os._exit(0)

    return 0
Beispiel #49
0
def cmd_calculate(ensoapi, expression = None):
    u""" Calculate the given expression
    Calculate mathematical expression.<br/><br/>
    Supported operators:<br/>
    <code>
    -, +, /, *, ^, **, (, ), %, mod
    </code><br/>
    functions:<br/>
    <code>
    mod, currency, acos, asin, atan, atan2, ceil, cos, cosh,
    degrees, exp, fabs, floor, fmod, frexp, hypot, ldexp,
    log, log10, modf, pow, radians, sin, sinh, sqrt, tan, tanh
    </code><br/>
    constants:<br/>
    <code>
    pi, e
    </code><br/>
    conversions:<br/>
    <code>
    abs, chr, hex
    </code><br/>
    currency conversion:<br/>
    <code>150eur in usd</code><br/>
    <code>1 gbp to eur</code><br/>
    <code>usd in eur</code><br/>
    <code>to eur</code> 
    (when some text representing amount + currency is selected, 
    like $1000, gbp10, €4.5, 10 GBP)<br/>
    """
    #_cache_currencies()
    #print "TO CURRENCIES: " + "|".join(_to_currencies.keys())
    seldict = ensoapi.get_selection()
    if seldict.get(u"text"):
        selected_text = seldict[u'text'].strip().strip("\0")
    else:
        selected_text = None

    got_selection = False
    if expression is None:
        if selected_text:
            expression = selected_text
            got_selection = expression is not None

    if expression is None:
        ensoapi.display_message("No expression given.")
        return        
    
    math_funcs = [f for f in dir(math) if f[:2] != '__']

    whitelist = '|'.join(
        # oprators, digits
        [' ', '\.', ',', '\-', '\+', '/', '\\', '\*', '\^', '\*\*', '\(', '\)', '%', '\d+']
        + ['abs', 'chr\([0-9]+\)', 'hex\([0-9]+\)', 'mod', 'currency']
        # functions of math module (ex. __xxx__)
        + math_funcs)

    print whitelist

    math_funcs_dict = dict([ (mf, eval('math.%s' % mf)) for mf in math_funcs])
    math_funcs_dict['abs'] = abs
    math_funcs_dict['chr'] = chr
    math_funcs_dict['hex'] = hex
    math_funcs_dict['currency'] = currency

    expression = expression.replace(' mod ', ' % ')

    currconv_match = complete_currency_re.search(expression)
    if currconv_match:
        #print "currconv match"
        if currconv_match.group(1):
            amount = currconv_match.group(1)
            print amount
        else:
            amount_str = (selected_text if selected_text else "1").replace(" ", "")
            print amount_str
            try:
                amount = float(amount_str)
            except:
                amount = 1
        
        #print  r"(.*)(" + "|".join(_from_currencies.keys()) + ") (in|to) (" + "|".join(_to_currencies.keys()) + ")(.*)"
        expression = "currency(%s, '%s', '%s') %s" % (
            amount, 
            currconv_match.group(2).upper(), 
            currconv_match.group(4).upper(), 
            currconv_match.group(5))
        #print expression
    else:
        currconv_match = partial_currency_re.match(expression.strip())
        if currconv_match:
            #print "partial match"
            amount_str, from_currency, amount = _handle_currency_symbols(
                (selected_text if selected_text else "1").replace(" ", ""))
            #print amount_str, from_currency, amount
            #print currconv_match.groups()
            expression = "currency(%s, '%s', '%s') %s" % (
                amount, 
                from_currency, 
                currconv_match.group(2).upper(),
                currconv_match.group(3)
            )
        #print expression

    #print expression = expression.replace(' in ', ' % ')

    #print math_funcs_dict

    if re.match(whitelist, expression):
        if expression.endswith("="):
            expression = expression[:-1]
            append_result = True
        else:
            append_result = False
        
        try:
            result = eval(expression, {"__builtins__": None}, math_funcs_dict)
            global last_calculation
            last_calculation = result

            pasted = False
            if got_selection:
                if append_result:
                    pasted = selection.set({ "text" : expression.strip() + " = " + unicode(result) })
                else:
                    pasted = selection.set({ "text" : unicode(result) })
            
            if not pasted:
                displayMessage(u"<p>%s</p><caption>%s</caption>" % (result, expression))
        except Exception, e:
            logging.info(e)
            ensoapi.display_message("Invalid syntax", "Error")
Beispiel #50
0
def cmd_calculate(ensoapi, expression=None):
    """ Calculate the given expression
    Calculate mathematical expression.<br/><br/>
    Supported operators:<br/>
    <code>
    -, +, /, *, ^, **, (, ), %, mod
    </code><br/>
    functions:<br/>
    <code>
    mod, acos, asin, atan, atan2, ceil, cos, cosh,
    degrees, exp, fabs, floor, fmod, frexp, hypot, ldexp,
    log, log10, modf, pow, radians, sin, sinh, sqrt, tan, tanh
    </code><br/>
    constants:<br/>
    <code>
    pi, e
    </code><br/>
    conversions:<br/>
    <code>
    abs, chr, hex
    </code>
    """
    seldict = ensoapi.get_selection()
    if seldict.get("text"):
        selected_text = seldict['text'].strip().strip("\0")
    else:
        selected_text = None

    got_selection = False
    if expression is None:
        if selected_text:
            expression = selected_text
            got_selection = expression is not None

    if expression is None:
        ensoapi.display_message("No expression given.")
        return

    math_funcs = [f for f in dir(math) if f[:2] != '__']

    whitelist = '|'.join(
        # oprators, digits
        [
            ' ', '\.', ',', '\-', '\+', '/', '\\', '\*', '\^', '\*\*', '\(',
            '\)', '%', '\d+'
        ] + ['abs', 'chr\([0-9]+\)', 'hex\([0-9]+\)', 'mod']
        # functions of math module (ex. __xxx__)
        + math_funcs)

    print(whitelist)

    math_funcs_dict = dict([(mf, eval('math.%s' % mf)) for mf in math_funcs])
    math_funcs_dict['abs'] = abs
    math_funcs_dict['chr'] = chr
    math_funcs_dict['hex'] = hex

    expression = expression.replace(' mod ', ' % ')

    if re.match(whitelist, expression):
        if expression.endswith("="):
            expression = expression[:-1]
            append_result = True
        else:
            append_result = False

        try:
            result = eval(expression, {"__builtins__": None}, math_funcs_dict)
            global last_calculation
            last_calculation = result

            pasted = False
            if got_selection:
                if append_result:
                    pasted = selection.set(
                        {"text": expression.strip() + " = " + str(result)})
                else:
                    pasted = selection.set({"text": str(result)})

            if not pasted:
                displayMessage("<p>%s</p><caption>%s</caption>" %
                               (result, expression))
        except Exception as e:
            logging.info(e)
            ensoapi.display_message("Invalid syntax", "Error")
    else:
        ensoapi.display_message("Invalid expression", "Error")