Beispiel #1
0
 def dropEvent(self, e):
     logger.debug(msg("Drag drop event"))
     file_url = QUrl(e.mimeData().text())
     if file_url.isValid() and file_url.isLocalFile():
         fname = file_url.toLocalFile()
         if fname in self.watcher.files():
             logger.debug(msg("already watching file", fname))
         else:
             self.watch_file(file_url.toLocalFile())
Beispiel #2
0
 def watch_file(self, path):
     logger.debug(msg("Trying to watch file", path))
     if path not in self._watched_files_actions:
         logger.debug(msg("watching a new file", path))
         self.watcher.addPath(path)
         self._watched_files_actions[path] = self._watched_files_menu.addAction(
             QIcon.fromTheme("edit-delete"), path)
         self._watched_files_actions[path].triggered.connect(
             lambda: self.unwatch_file(path))
         logger.debug(msg("emmiting file changed signal"))
         self.watcher.fileChanged.emit(path)
         self.file_watched.emit(path)
Beispiel #3
0
    def _guessDictPrefix(self, char):
        """ Tries to determine whether the user is typing a string-key in a dict. If yes
            returns the dict name and the key typed so far. Otherwise returns None. """
        c = self._currentCursor
        block_content = self._currentBlock.content(include_decoration=True)
        pos = min(c.positionInBlock(), len(block_content))
        block_content = unicode(block_content[:pos]+char)

        double_quotes = block_content.count('"')
        single_quotes = block_content.count("'")

        if double_quotes % 2 == 0 and single_quotes % 2 == 0:
            return None

        stop_chars = '"\' '
        ret = []
        while pos >= 0 and block_content[pos] not in stop_chars:
            ret.append(block_content[pos])
            pos -= 1
        ret.reverse()
        if pos > 0 and block_content[pos-1] == '[':
            pos -= 1
            dct = []
            while pos >= 0 and block_content[pos] not in [ ' ', "\n", "\t"]:
                dct.append(block_content[pos])
                pos -= 1
            dct.reverse()
            logger.debug(msg('dct:',''.join(dct[:-1]), 'key:',''.join(ret)))
            return ''.join(dct[:-1]), ''.join(ret)
        else:
            return None
Beispiel #4
0
 def unwatch_file(self, path):
     logger.debug(msg("un-watching a file:", path))
     if path in self._watched_files_actions:
         self.watcher.removePath(path)
         self._watched_files_menu.removeAction(
             self._watched_files_actions[path])
         del self._watched_files_actions[path]
Beispiel #5
0
 def dict_completion(self, dict_name, key):
     logger.debug("Getting dict completions for '"+dict_name+"' with prefix '"+key+"'")
     try:
         return [str(x) for x in eval(dict_name+'.keys()',self.locals, self.locals) if str(x).startswith(key)]
     except Exception, e:
         logger.debug(msg("Exception ",e," when getting dict completions for '"+dict_name+"' with prefix '"+key+"'"))
         return None
Beispiel #6
0
 def _wantToSubmit(self):
     if self.parser.get_continuation_type():
         logger.debug(msg("Is continuation, returning False"))
         return False
     if self.parser.is_block_opener():
         logger.debug(msg("Is block opener, returning False"))
         return False
     cur_line_content = self._currentBlock.content()
     if len(cur_line_content) == cur_line_content.count(" "):
         logger.debug(msg("empty line, returning True"))
         return True
     if len(self.parser.get_base_indent_string()) == 0:
         logger.debug(msg("Base indent string is short, returning True "))
         return True
     logger.debug(msg("returning False"))
     return False
Beispiel #7
0
 def _activate(self):
     if len(self.hooks) > 0 and not self.waiting_for_shot and self.started:
         self.waiting_for_shot = True
         self.timer.start(10)
         if self.run_count % 1000 == 0:
             logger.debug(msg(
                 "Activating eventloop, timerID:", self.timer.timerId()))
Beispiel #8
0
 def watch_file(self, fname=None):
     logger.debug(msg("Watching file ... ", fname))
     if fname is None:
         fname = QFileDialog.getOpenFileName(self.console.widget,
                                             "Watch a Python Source File",
                                             QDir.currentPath(),
                                             "Python Source Files (*.py)")
     self.console.watch_file(fname)
Beispiel #9
0
 def import_completion(self, prefix):
     logger.debug("Getting import completions for '"+prefix+"'")
     ret = []
     for c in self.packages:
         if c.startswith(prefix):
             ret.append(c)
     logger.debug(msg("Got",len(ret),"completions, first 10:", ','.join(ret[:10])))
     return ret
Beispiel #10
0
 def execute(self, code):
     code = unicode(code)
     logger.debug("Running code")
     logger.debug("*" * 30)
     logger.debug(code)
     logger.debug("*" * 30)
     ret = self.interpreter.runsource(code + "\n")
     logger.debug(msg("Finished run, ret == ", ret))
     SignalStream.keyboard_interrupt.cancel()
     self.execute_finished.emit()
Beispiel #11
0
 def _sourceChanged(self, fname):
     """ Change to the diretory containing @fname (absolute path)
         and execute the file. """
     fname = unicode(fname)
     logger.debug(fname)
     if self._mode == Console.MODE_CODE_EDITING:
         self._write_message("Changing dir to ", os.path.dirname(fname),
                             " and Reloading file ", os.path.basename(fname))
         self._appendBlock(TextBlock.TYPE_OUTPUT_STDOUT)
         logger.debug(msg("Changing to directory", os.path.dirname(fname)))
         os.chdir(os.path.dirname(fname))
         self._mode = Console.MODE_RUNNING
         self.run_code.emit(unicode(
             "__shell__.os.chdir(__shell__.os.path.dirname('"+fname+"'))\n"))
         logger.debug(msg("MODE:", self._mode))
         self._mode = Console.MODE_RUNNING
         logger.debug(msg("MODE:", self._mode))
         self.run_code.emit(unicode("execfile('"+fname+"')\n"))
         logger.debug(msg("MODE:", self._mode))
     else:
         logger.debug(msg(
             "Ignoring change, because not in CODE EDITING MODE", fname))
     if fname not in self.watcher.files():
         self._lost_files.append(fname)
         logger.debug(msg("Lost watched file", fname))
     QTimer.singleShot(500,self._reload_watch_files)
Beispiel #12
0
 def display_hook(self, obj):
     try:
         if obj is None:
             return
         if print_hooks.is_pretty_printable(obj):
             if print_hooks.needs_packing(obj):
                 packed = print_hooks.pack_for_transport(obj)
                 if not self.write_object.emit(packed):
                     logger.debug(msg("error sending packed object"))
                     sys.stdout.write(print_hooks.html_repr(obj))
             else:
                 if not self.write_object.emit(obj):
                     logger.debug(msg("error sending object"))
                     logger.debug(msg("error sending packed object"))
                     sys.stdout.write(print_hooks.html_repr(obj))
         else:
             logger.debug(msg("object", obj, "is not prettyprintable"))
             sys.stdout.write(repr(obj))
         return
     except Exception, e:
         logger.debug(msg("Exception", e, "encountered while printing object", obj))
         sys.__displayhook__(obj)
Beispiel #13
0
 def exec_command(self,*args, **kwargs):
     """ Executes a command in the console context.
         The command is given by the cmd keyword argument.
         It is either a predefined command or the name of
         a method of the console object, in which case this
         method is called with *args and **kwargs (where cmd
         is first deleted from kwargs) """
     if 'cmd' in kwargs:
         cmd = kwargs['cmd']
         del kwargs['cmd']
         if cmd == 'watch.list_files':
             self._write_message("Currently watching the following files:")
             self._write_message([unicode(x) for x in self.watcher.files()])
             self._write_message("Total watched:",len(self.watcher.files()))
             logger.debug(msg([x for x in self.watcher.files()]))
         elif cmd == 'watch.reload':
             self._reload_watch_files()
         elif cmd in dir(self):
             attr = self.__getattribute__(cmd)
             if type(attr) == type(self.exec_command):
                 attr(*args, **kwargs)
             else:
                 self.write_object(attr)
Beispiel #14
0
 def register_hook(self, hook):
     logger.debug(msg("Registering hook", hook))
     self.hooks.append(hook)
     self._activate()
Beispiel #15
0
 def isolated_init(self):
     logger.debug("Shell connecting stdin _wait.")
     try:
         sys.stdin._wait.connect(self._wait)
     except Exception, e:
         logger.debug(msg("Unable to connect _wait:", e))
Beispiel #16
0
 def _tab_name_changed(self, tab_id, tab_name):
     logger.debug(msg("ID:", tab_id, "NAME:", tab_name))
     self.tabwidget.setTabText(self._index_of(tab_id), tab_name)
Beispiel #17
0
 def input_handler(self, str):
     logger.debug(msg("Got input", str))
     self.have_input = True
     self.input = str
Beispiel #18
0
 def _joinCurrentToPreviousBlock(self):
     logger.debug(msg("Deleting current block"))
     cur = self._currentBlock
     prev = cur.previous()
     prev.appendText(cur.content())
     cur.deleteBlock()
Beispiel #19
0
 def write_object(self, obj):
     logger.debug(msg("Received object", obj, "writing it to stdout"))
     self.write('stdout',print_hooks.html_repr(obj, self._document))
Beispiel #20
0
 def input_handler(self, string):
     logger.debug(msg("Got input", string))
     sys.stdin.input_handler(string)
Beispiel #21
0
    def _completion_event(self, event):
        if (self.completion_enabled) and ((self.mode == Console.MODE_CODE_EDITING or self.mode == Console.MODE_RAW_INPUT) and len(event.text()) != 0):
            completion_prefix = self.wordUnderCursor() + event.text()
            try:
                dct, key = self._guessDictPrefix(event.text())
                need_dict_completion = True
                in_string_prefix = None
            except:
                need_dict_completion = False
                in_string_prefix = self._guessStringPrefix(event.text())
            len_or_dot = len(completion_prefix) >= 3 or event.text() == '.' or (event.text() == ' ' and (event.modifiers() & Qt.ControlModifier)) or need_dict_completion
            if event.modifiers() & Qt.ControlModifier:
                completion_prefix = completion_prefix[:-1]
            need_import_completion = self.textToCursor()[:-len(completion_prefix)].strip(' ') in ['from', 'import']

            if (len_or_dot and unicode(completion_prefix[-1]) not in TextBlock.WORD_STOP_CHARS and len(event.text()) > 0) or in_string_prefix is not None:
                try:
                    # Filename completion when in string
                    if in_string_prefix is not None:
                        logger.debug(msg("Filename completion"))
                        model = QDirModel()
                        # model = QFileSystemModel()
                        # logger.debug(msg("Current Path:", QDir.currentPath()))
                        # model.setRootPath(QDir.currentPath())
                        if len(in_string_prefix) == 0 or not in_string_prefix[0] == os.sep:
                            in_string_prefix = unicode(
                                QDir.currentPath()+QDir.separator() + in_string_prefix)
                        logger.debug(msg("prefix", in_string_prefix))
                        self.completer.setModel(model)
                        self.completer.setCompletionPrefix(in_string_prefix)
                    # Complete import of packages
                    elif need_import_completion:
                        logger.debug(msg(
                            "Getting import completions for ", completion_prefix, "..."))
                        completions = self.get_import_completions(
                            unicode(completion_prefix).strip(' '), _timeout=0.1, _default=None)
                        if completions is None:
                            logger.debug(msg("Completions timeouted ..."))
                            self._widgetKeyPressEvent(event)
                            return True
                        logger.debug(msg(
                            "Got completions:", ','.join(completions)))
                        model = QStringListModel(completions)
                        self.completer.setModel(model)
                        self.completer.setCompletionPrefix(unicode(completion_prefix).strip(' '))
                    elif need_dict_completion:
                        logger.debug(msg(
                            "Getting dict completions for ", dct, "key == ", key))
                        completions = self.get_dict_completions(dct, key, _timeout=0.01, _default=None)
                        if completions is None:
                            logger.debug(msg("No completions ..."))
                            self._widgetKeyPressEvent(event)
                            return True
                        logger.debug(msg(
                            "Got completions:", ','.join(completions)))
                        model = QStringListModel(completions)
                        self.completer.setModel(model)
                        self.completer.setCompletionPrefix(key)
                    # Otherwise we do normal code completion
                    else:
                        logger.debug(msg(
                            "Getting code completions for ", completion_prefix, "..."))
                        completions = self.get_completions(
                            completion_prefix, _timeout=0.1, _default=None)
                        if completions is None:
                            logger.debug(msg("Completions timeouted ..."))
                            self._widgetKeyPressEvent(event)
                            return True
                        logger.debug(msg(
                            "Got completions:", ','.join(completions)))
                        model = QStringListModel(completions)
                        self.completer.setModel(model)
                        self.completer.setCompletionPrefix(completion_prefix)
                    self.completer.popup().setCurrentIndex(
                        self.completer.completionModel().index(0, 0))
                except Exception, e:
                    logger.debug(msg("Exception when completing:", str(e)))
                    if completion_prefix != self.completer.completionPrefix():
                        self.completer.setCompletionPrefix(completion_prefix)
                        self.completer.popup().setCurrentIndex(
                            self.completer.completionModel().index(0, 0))
                cursor_rect = self.widget.cursorRect()
                cursor_rect.setWidth(self.completer.popup().sizeHintForColumn(
                    0) + self.completer.popup().verticalScrollBar().sizeHint().width())
                self.completer.complete(cursor_rect)
            else:
                self.completer.popup().hide()
                self.widget.clearFocus()
                self.widget.setFocus(Qt.ActiveWindowFocusReason)
            return False
Beispiel #22
0
    def _process_enter(self):
        logger.debug(msg("running..."))
        # Apply History
        if not self._lastBlock.isCursorInRelatedCodeBlock(self._currentCursor) and not self._lastBlock.containsCursor(self._currentCursor):
            logger.debug(msg("applying history..."))
            if self._currentBlock.type in TextBlock.CODE_TYPES:
                hist = map(
                    lambda x: x.content(), self._currentBlock.relatedCodeBlocks())
            else:
                hist = [self._currentBlock.activeContent()]
            cur_block = self._lastBlock
            cur_block.appendText(hist[0])
            if self.mode == Console.MODE_RAW_INPUT:
                typ = TextBlock.TYPE_RAW_INPUT
            else:
                typ = TextBlock.TYPE_CODE_CONTINUED
            for h in hist[1:]:
                    b = self._appendBlock(typ, h)
                    if typ == TextBlock.TYPE_RAW_INPUT:
                        b.first_input_block = cur_block
            self._gotoEnd()
        # Editing code
        elif self.mode == Console.MODE_CODE_EDITING:
            # decide whether to run the code
            # if self._lastBlock.containsCursor(self._currentCursor):
            if self._last_but_space():
                logger.debug(msg("Deciding whether to run code..."))
                code = ("\n".join(map(
                    lambda x: x.content(), self._currentBlock.relatedCodeBlocks()))).rstrip(" \n\t")
                self.parser.set_str(code+"\n")
                if self._wantToSubmit():
                    self._mode = Console.MODE_RUNNING
                    self._appendBlock(TextBlock.TYPE_OUTPUT_STDOUT)
                    self.run_code.emit(code.rstrip()+"\n")
                else:
                    indent_string = self.parser.get_base_indent_string()
                    indent_level = indent_string.count("\t")
                    if self.parser.is_block_opener():
                        indent_level += 1
                    b = self._appendBlock(
                        TextBlock.TYPE_CODE_CONTINUED, " "*indent_string.count(" "))
                    b.indent(indent_level)
                    self._gotoEnd()
            # In the middle of the code, add a newline + indentation
            else:
                code = "\n".join(map(
                    lambda x: x.content(), self._currentBlock.relatedCodeBlocks(only_previous=True)))
                self.parser.set_str(code+"\n")
                indent_string = self.parser.get_base_indent_string()
                indent_level = indent_string.count("\t")
                if self.parser.is_block_opener():
                    indent_level += 1
                b = self._insertBlock(
                    self._currentCursor, block_type=TextBlock.TYPE_CODE_CONTINUED, content=" "*indent_string.count(" "))
                b.indent(indent_level)
                self._gotoBlockEnd()

        # Entering input
        elif self.mode == Console.MODE_RAW_INPUT:
            ret = "\n".join(map(
                lambda x: x.activeContent(), self._currentBlock.relatedInputBlocks()))
            self._appendBlock(TextBlock.TYPE_OUTPUT_STDOUT)
            self._mode = Console.MODE_RUNNING
            self.read_line.emit(ret)

        logger.debug(msg("finished."))