def _updateScripts(self):
        filesToReload = {}
        for fileName in self._fileDependencies:
            if os.path.isfile(fileName):
                lastMod = os.path.getmtime(fileName)
                if lastMod != self._lastMods.get(fileName, 0):
                    self._lastMods[fileName] = lastMod
                    filesToReload[fileName] = lastMod

        for fileName in self._getCommandFiles():
            if fileName not in self._fileDependencies:
                self._fileDependencies.append(fileName)
                self._lastMods[fileName] = os.path.getmtime(fileName)
                filesToReload[fileName] = lastMod

        if filesToReload:
            if not self._firstRun:
                display_xml_message(
                    u"<p>Reloading commands, please wait...</p><caption>enso</caption>"
                )
            # TODO: This can be enabled after issues in clearCommands are
            # solved...
            self._reloadPyScripts(filesToReload.keys())
            # self._reloadPyScripts()
            if not self._firstRun:
                # Force primary-message to disappear
                MessageManager.get().finishPrimaryMessage()
                # Display mini message with result
                display_xml_message(
                    u"<p>Commands have been reloaded.</p><caption>enso</caption>",
                    primaryMsg=False,
                    miniMsg=True,
                    miniWaitTime=10)
            if self._firstRun:
                self._firstRun = False
Beispiel #2
0
 def run(self):
     s = None
     try:
         s = open_command_impl.get_shortcut(self.target)
         print s
     except Exception:
         display_xml_message(u"<p>This shortcut can't be found</p>")
     else:
         msg = u"Target info of 'open' shortcut '%s'" % self.target
         result = "\n".join(
             (str(self.target), str(s.target), str(s.shortcut_filename)))
         RecentResult.get().push_result(result, msg)
         display_xml_message(
             u"<p>Target of <command>%s</command> is <command>%s</command>, saved in <command>%s</command></p>"
             % (str(self.target), str(s.target), s.shortcut_filename))
         try:
             # TODO: Implement platform independent
             import subprocess
             from shutilwhich import which
             editor_cmd = os.path.expandvars("$VISUAL")
             if not editor_cmd:
                 editor_cmd = which("gvim")
             if editor_cmd:
                 subprocess.Popen(
                     [editor_cmd, "--nofork", "--", s.shortcut_filename])
         except:
             pass
Beispiel #3
0
 def run(self):
     sh = open_command_impl.undo_remove_shortcut()
     if sh:
         display_xml_message(
             u"<p>Undo successful. <command>open %s</command> is now a command</p>"
             % sh.name)
     else:
         ensoapi.display_message(u"There is nothing to undo")
Beispiel #4
0
 def run(self):
     try:
         open_command_impl.remove_shortcut(self.target)
     except Exception:
         display_xml_message(u"<p>This shortcut can't be unlearned</p>")
     else:
         display_xml_message(
             u"<p>Unlearned <command>open %s</command></p>" % self.target)
Beispiel #5
0
    def run(self):
        #TODO: Implement opening current selection if no postfix provided?
        if not self.target:
            return

        display_xml_message(u"<p>Opening <command>%s</command>...</p>" %
                            xml_escape(self.target))

        recent_command_impl.run_shortcut(self.target)
Beispiel #6
0
    def display_xml_message(msg_xml,
                            show_mini_msg=False,
                            mini_msg_xml=None,
                            primary_wait=None,
                            mini_wait=None):
        """
        Displays the given message, with an optional caption.  Both
        parameters should be unicode strings.

        If mini_msg argument is not empty, mini-message is shown after
        primary-message disappears.

        If show_mini_msg argument is True, and mini_msg argument is not set,
        mini-message is shown after primary-message disappears, with
        text specified in the msg argument.

        Optional to_wait argument specifies how many seconds mini-message
        will stay on screen. It is set to None by default (wait until
        user dismiss the mini messages using 'hide mini messages' command).
        """

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

        if mini_msg_xml and not isinstance(mini_msg_xml, basestring):
            mini_msg_xml = unicode(mini_msg_xml)

        return display_xml_message(msg_xml,
                                   miniMsgXml=mini_msg_xml,
                                   primaryWaitTime=primary_wait,
                                   miniWaitTime=mini_wait)
Beispiel #7
0
    def run(self):
        seldict = ensoapi.get_selection()
        if seldict.get('files'):
            # LONGTERM TODO: Handle opening of multiple files
            filename = seldict['files'][0]
        elif seldict.get('text'):
            filename = seldict['text'].strip()
        else:
            ensoapi.display_message(u"No file is selected")
            return

        if self.name is None:
            try:
                from enso.contrib.open.platform.win32.utils import get_exe_name
            except ImportError:
                pass
            else:
                product_name = get_exe_name(filename)
                if product_name:
                    self.name = product_name.lower()
        if self.name is None:
            ensoapi.display_message(u"You must provide name")
            return

        if (not os.path.isfile(filename) and not os.path.isdir(filename)
                and not open_command_impl._is_url(filename)):
            ensoapi.display_message(
                u"Selection is neither file, folder nor URL.")
            return

        shortcut = open_command_impl.add_shortcut(self.name, filename)
        if shortcut:
            display_xml_message(
                u"<p><command>open %s</command> is now a command</p>" %
                xml_escape(self.name))
        else:
            display_xml_message(
                u"<p><command>open %s</command> already exists. Please choose another name.</p>"
                % xml_escape(self.name))
            return
Beispiel #8
0
    def display_message(msg,
                        caption=None,
                        show_mini_msg=False,
                        mini_msg=None,
                        primary_wait=None,
                        mini_wait=None):
        """
        Displays the given message, with an optional caption.  Both
        parameters should be unicode strings.

        If mini_msg argument is not empty, mini-message is shown after
        primary-message disappears.

        If show_mini_msg argument is True, and mini_msg argument is not set,
        mini-message is shown after primary-message disappears, with
        text specified in the msg argument.

        Optional to_wait argument specifies how many seconds mini-message
        will stay on screen. It is set to None by default (wait until
        user dismiss the mini messages using 'hide mini messages' command).
        """

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

        if caption and not isinstance(caption, basestring):
            caption = unicode(caption)

        if mini_msg and not isinstance(mini_msg, basestring):
            mini_msg = unicode(mini_msg)

        xmltext = "<p>%s</p>" % xml_escape(msg)
        if caption:
            caption_escaped = xml_escape(caption)
            xmltext += "<caption>%s</caption>" % caption_escaped
        xmltext_mini = None
        if show_mini_msg or mini_msg is not None:
            if mini_msg is None:
                xmltext_mini = xmltext
            else:
                xmltext_mini = "<p>%s</p>" % xml_escape(mini_msg)
                if caption:
                    xmltext_mini += "<caption>%s</caption>" % caption_escaped
        return display_xml_message(xmltext,
                                   miniMsgXml=xmltext_mini,
                                   primaryWaitTime=primary_wait,
                                   miniWaitTime=mini_wait)
def install_command_from_url(command_url):
    try:
        resp = urlopen(command_url, timeout=15.0)
    except Exception as e:
        logging.error(e)
        display_xml_message("<p>Couldn't install that command</p>")
        return

    if "Content-Disposition" in resp.info():
        # If command file is provided as an attachment, parse the correct filename
        # from the headers
        command_file_name = resp.info()["Content-Disposition"].split(
            "filename=")[1].strip("\"'")
    elif resp.url != command_url:
        # If there was redirect, get the filename from the redirected URL
        command_file_name = urllib.unquote(resp.url.split("/")[-1])
    else:
        # Otherwise get the filename from the current URL
        command_file_name = urllib.unquote(command_url.split("/")[-1])

    if not command_file_name.endswith(".py"):
        display_xml_message(
            u"<p>Not a valid command <command>%s</command></p>"
            % command_file_name)
        return

    try:
        text = resp.read()
    except socket.timeout:
        display_xml_message(
            u"<p>Timeout occurred while downloading the command. Please try again.</p>")
        return
    finally:
        resp.close()

    # Normalize newlines to "\n"
    text = text.replace("\r\n", "\n").replace("\r", "\n")

    lines = text.split("\n")
    if len(lines) < 3:
        display_xml_message(u"<p>There was no command to install!</p>")
        return
    while lines[0].strip() == "":
        lines.pop(0)

    cmd_folder = tracker.getScriptsFolderName()
    command_file_path = os.path.expanduser(
        os.path.join(cmd_folder, command_file_name))
    short_name = os.path.splitext(command_file_name)[0]
    if os.path.exists(command_file_path):
        display_xml_message(
            u"<p>You already have a command named <command>%s</command></p>"
            % short_name)
        return

    commands = get_commands_from_object(text, command_file_path)
    if commands:
        installed_commands = [x["cmdName"] for x in commands]
        if len(installed_commands) == 1:
            install_message = (u"<command>%s</command> is now a command"
                               % installed_commands[0])
        elif len(installed_commands) > 1:
            install_message = (u"<command>%s</command> are now commands"
                               % u"</command>, <command>".join(installed_commands))
        display_xml_message(u"<p>%s</p>" % install_message)
        # Use binary mode for writing so endlines are not converted to "\r\n"
        # on win32
        with open(command_file_path, "wb") as fp:
            fp.write(text)
    else:
        display_xml_message(u"<p>No commands to install</p>")