Beispiel #1
0
 def run_script(self, filename=None, silent=False, set_focus=False,
                args=None):
     """Run a Python script"""
     if filename is None:
         self.shell.interpreter.restore_stds()
         filename, _selfilter = getopenfilename(
                 self, _("Run Python script"), getcwd_or_home(),
                 _("Python scripts")+" (*.py ; *.pyw ; *.ipy)")
         self.shell.interpreter.redirect_stds()
         if filename:
             os.chdir( osp.dirname(filename) )
             filename = osp.basename(filename)
         else:
             return
     debug_print(args)
     filename = osp.abspath(filename)
     rbs = remove_backslashes
     command = "runfile('%s', args='%s')" % (rbs(filename), rbs(args))
     if set_focus:
         self.shell.setFocus()
     if self.dockwidget and not self.ismaximized:
         self.dockwidget.setVisible(True)
         self.dockwidget.raise_()
     self.shell.write(command+'\n')
     self.shell.run_command(command)
Beispiel #2
0
    def keyReleaseEvent(self, e):
        """Qt override."""
        self.npressed -= 1
        if self.npressed <= 0:
            key = e.key()

            if len(self.keys) == 1 and key == Qt.Key_Tab:
                self.toggle_state()
                return

            if len(self.keys) == 1 and key == Qt.Key_Escape:
                self.set_sequence('')
                self.label_warning.setText(_("Please introduce a different "
                                             "shortcut"))

            if len(self.keys) == 1 and key in [Qt.Key_Return, Qt.Key_Enter]:
                self.toggle_state()
                return

            if not self.edit_state:
                self.nonedit_keyrelease(e)
            else:
                debug_print('keys: {}'.format(self.keys))
                if self.keys and key != Qt.Key_Escape:
                    self.validate_sequence()
                self.keys = set()
                self.key_modifiers = set()
                self.key_non_modifiers = list()
                self.key_text = list()
                self.npressed = 0
Beispiel #3
0
    def get_info(self, info):
        """
        Find the calltip and docs

        Returns a dict like the following:
           {'note': 'Function of numpy.core.numeric...',
            'argspec': "(shape, dtype=None, order='C')'
            'docstring': 'Return an array of given...'
            'name': 'ones',
            'calltip': 'ones(shape, dtype=None, order='C')'}
        """
        call_def = self.get_jedi_object('goto_definitions', info)
        for cd in call_def:
            if cd.doc and not cd.doc.rstrip().endswith(')'):
                call_def = cd
                break
        else:
            call_def = call_def[0]
        name = call_def.name
        if name is None:
            return
        if call_def.module_path:
            mod_name = get_parent_until(call_def.module_path)
        else:
            mod_name = None
        if not mod_name:
            mod_name = call_def.module_name
        if call_def.doc.startswith(name + '('):
            calltip = getsignaturefromtext(call_def.doc, name)
            argspec = calltip[calltip.find('('):]
            docstring = call_def.doc[call_def.doc.find(')') + 3:]
        elif '(' in call_def.doc.splitlines()[0]:
            calltip = call_def.doc.splitlines()[0]
            name = call_def.doc.split('(')[0]
            docstring = call_def.doc[call_def.doc.find(')') + 3:]
            argspec = calltip[calltip.find('('):]
        else:
            calltip = name + '(...)'
            argspec = '()'
            docstring = call_def.doc
        if call_def.type == 'module':
            note = 'Module %s' % mod_name
            argspec = ''
            calltip = name
        elif call_def.type == 'class':
            note = 'Class in %s module' % mod_name
        elif call_def.doc.startswith('%s(self' % name):
            class_name = call_def.full_name.split('.')[-2]
            note = 'Method of %s class in %s module' % (
                class_name.capitalize(), mod_name)
        else:
            note = '%s in %s module' % (call_def.type.capitalize(),
                                        mod_name)
        argspec = argspec.replace(' = ', '=')
        calltip = calltip.replace(' = ', '=')
        debug_print(call_def.name)

        doc_info = dict(name=name, argspec=argspec,
                        note=note, docstring=docstring, calltip=calltip)
        return doc_info
Beispiel #4
0
 def _handle_spyder_msg(self, msg):
     """
     Handle internal spyder messages
     """
     spyder_msg_type = msg['content'].get('spyder_msg_type')
     if spyder_msg_type == 'data':
         # Deserialize data
         try:
             if PY2:
                 value = cloudpickle.loads(msg['buffers'][0])
             else:
                 value = cloudpickle.loads(bytes(msg['buffers'][0]))
         except Exception as msg:
             self._kernel_value = None
             self._kernel_reply = repr(msg)
         else:
             self._kernel_value = value
         self.sig_got_reply.emit()
         return
     elif spyder_msg_type == 'pdb_state':
         pdb_state = msg['content']['pdb_state']
         if pdb_state is not None and isinstance(pdb_state, dict):
             self.refresh_from_pdb(pdb_state)
     elif spyder_msg_type == 'pdb_continue':
         # Run Pdb continue to get to the first breakpoint
         # Fixes 2034
         self.write_to_stdin('continue')
     else:
         debug_print("No such spyder message type: %s" % spyder_msg_type)
Beispiel #5
0
    def get_jedi_object(self, func_name, info, use_filename=True):
        """Call a desired function on a Jedi Script and return the result"""
        if not jedi:
            return
        if DEBUG_EDITOR:
            t0 = time.time()
        # override IPython qt_loaders ImportDenier behavior
        metas = sys.meta_path
        for meta in metas:
            if (meta.__class__.__name__ == 'ImportDenier'
                    and hasattr(meta, 'forbid')):
                sys.meta_path.remove(meta)

        if use_filename:
            filename = info['filename']
        else:
            filename = None

        try:
            script = jedi.Script(info['source_code'], info['line_num'],
                                 info['column'], filename)
            func = getattr(script, func_name)
            val = func()
        except Exception as e:
            val = None
            debug_print('Jedi error (%s)' % func_name)
            debug_print(str(e))
            if DEBUG_EDITOR:
                log_last_error(LOG_FILENAME, str(e))
        if DEBUG_EDITOR:
            log_dt(LOG_FILENAME, func_name, t0)
        if not val and filename:
            return self.get_jedi_object(func_name, info, False)
        else:
            return val
Beispiel #6
0
 def get_completions(self, info):
     """Return a list of (completion, type) tuples"""
     completions = self.get_jedi_object('completions', info)
     if DEBUG_EDITOR:
         log_last_error(LOG_FILENAME, str("comp: " + str(completions)[:100]))
     completions = [(c.name, c.type) for c in completions]
     debug_print(str(completions)[:100])
     return completions
Beispiel #7
0
 def _send(self, obj):
     """Send an object to the server.
     """
     try:
         self.socket.send_pyobj(obj, zmq.NOBLOCK)
     except Exception as e:
         debug_print(e)
         self.is_initialized = False
         self._on_finished()
Beispiel #8
0
    def add(self, extension):
        """
        Add a extension to the editor.

        :param extension: The extension instance to add.

        """
        debug_print('adding extension {}'.format(extension.name))
        self._extensions[extension.name] = extension
        extension.on_install(self.editor)
        return extension
Beispiel #9
0
    def setVisible(self, visible):
        """
        Shows/Hides the panel.

        Automatically call PanelsManager.refresh_panels.

        :param visible: Visible state
        """
        debug_print('{} visibility changed'.format(self.name))
        super(Panel, self).setVisible(visible)
        if self.editor:
            self.editor.panels.refresh()
Beispiel #10
0
 def handle_response(self, response):
     name = self.ids.get(response['request_id'], None)
     if not name:
         return
     if response.get('error', None):
         debug_print('Response error:', response['error'])
         return
     if name == self.desired[0] or not self.waiting:
         if response.get('result', None):
             self._finalize(response)
     else:
         self.pending = response
Beispiel #11
0
    def remove(self, name_or_klass):
        """
        Remove a extension from the editor.

        :param name_or_klass: The name (or class) of the extension to remove.
        :returns: The removed extension.
        """
        debug_print('removing extension {}'.format(name_or_klass))
        extension = self.get(name_or_klass)
        extension.on_uninstall()
        self._extensions.pop(extension.name)
        return extension
Beispiel #12
0
    def __init__(
        self, parent=None, namespace=None, commands=[], message=None, exitfunc=None, profile=False, multithreaded=False
    ):
        if PYQT5:
            SpyderPluginWidget.__init__(self, parent, main=parent)
        else:
            SpyderPluginWidget.__init__(self, parent)

        debug_print("    ..internal console: initializing")
        self.dialog_manager = DialogManager()

        # Shell
        light_background = self.get_option("light_background")
        self.shell = InternalShell(
            parent,
            namespace,
            commands,
            message,
            self.get_option("max_line_count"),
            self.get_plugin_font(),
            exitfunc,
            profile,
            multithreaded,
            light_background=light_background,
        )
        self.shell.status.connect(lambda msg: self.show_message.emit(msg, 0))
        self.shell.go_to_error.connect(self.go_to_error)
        self.shell.focus_changed.connect(lambda: self.focus_changed.emit())

        # Redirecting some signals:
        self.shell.redirect_stdio.connect(lambda state: self.redirect_stdio.emit(state))

        # Initialize plugin
        self.initialize_plugin()

        # Find/replace widget
        self.find_widget = FindReplace(self)
        self.find_widget.set_editor(self.shell)
        self.find_widget.hide()
        self.register_widget_shortcuts(self.find_widget)

        # Main layout
        layout = QVBoxLayout()
        layout.addWidget(self.shell)
        layout.addWidget(self.find_widget)
        self.setLayout(layout)

        # Parameters
        self.shell.toggle_wrap_mode(self.get_option("wrap"))

        # Accepting drops
        self.setAcceptDrops(True)
Beispiel #13
0
    def remove(self, name_or_klass):
        """
        Removes the specified panel.

        :param name_or_klass: Name or class of the panel to remove.
        :return: The removed panel
        """
        debug_print('removing panel {}'.format(name_or_klass))
        panel = self.get(name_or_klass)
        panel.on_uninstall()
        panel.hide()
        panel.setParent(None)
        return self._panels[panel.position].pop(panel.name, None)
Beispiel #14
0
    def __init__(self, parent=None, namespace=None, commands=[], message=None,
                 exitfunc=None, profile=False, multithreaded=False):
        SpyderPluginWidget.__init__(self, parent)

        debug_print("    ..internal console: initializing")
        self.dialog_manager = DialogManager()

        # Shell
        light_background = self.get_option('light_background')
        self.shell = InternalShell(parent, namespace, commands, message,
                                   self.get_option('max_line_count'),
                                   self.get_plugin_font(), exitfunc, profile,
                                   multithreaded,
                                   light_background=light_background)
        self.shell.status.connect(lambda msg: self.show_message.emit(msg, 0))
        self.shell.go_to_error.connect(self.go_to_error)
        self.shell.focus_changed.connect(lambda: self.focus_changed.emit())

        # Redirecting some signals:
        self.shell.redirect_stdio.connect(lambda state:
                                          self.redirect_stdio.emit(state))
        
        # Initialize plugin
        self.initialize_plugin()

        # Find/replace widget
        self.find_widget = FindReplace(self)
        self.find_widget.set_editor(self.shell)
        self.find_widget.hide()
        self.register_widget_shortcuts(self.find_widget)

        # Main layout
        btn_layout = QHBoxLayout()
        btn_layout.setAlignment(Qt.AlignLeft)
        btn_layout.addStretch()
        btn_layout.addWidget(self.options_button, Qt.AlignRight)
        layout = create_plugin_layout(btn_layout)
        layout.addWidget(self.shell)
        layout.addWidget(self.find_widget)
        self.setLayout(layout)
        
        # Parameters
        self.shell.toggle_wrap_mode(self.get_option('wrap'))
            
        # Accepting drops
        self.setAcceptDrops(True)

        # Traceback MessageBox
        self.error_dlg = None
        self.error_traceback = ""
        self.dismiss_error = False
Beispiel #15
0
 def _finalize(self, response):
     self.waiting = False
     self.pending = None
     if self.info:
         delta = time.time() - self._start_time
         debug_print('%s request from %s finished: "%s" in %.1f sec'
             % (self.info.name, response['name'],
                str(response['result'])[:100], delta))
         response['info'] = self.info
         self.introspection_complete.emit(response)
         self.info = None
     if self.pending_request:
         info = self.pending_request
         self.pending_request = None
         self.send_request(info)
Beispiel #16
0
 def stop(self):
     # self.shutdown()
     # self.exit()
     debug_print('LSP Client ==> Stopping...')
     if self.notifier is not None:
         self.notifier.activated.disconnect(self.on_msg_received)
         self.notifier.setEnabled(False)
         self.notifier = None
     # if WINDOWS:
     #     self.transport_client.send_signal(signal.CTRL_BREAK_EVENT)
     # else:
     self.transport_client.kill()
     self.context.destroy()
     if not self.external_server:
         self.lsp_server.kill()
Beispiel #17
0
 def _finalize(self, response):
     self.waiting = False
     self.pending = None
     if self.info:
         delta = time.time() - self._start_time
         debug_print('%s request from %s finished: "%s" in %.1f sec' %
                     (self.info.name, response['name'],
                      str(response['result'])[:100], delta))
         response['info'] = self.info
         self.introspection_complete.emit(response)
         self.info = None
     if self.pending_request:
         info = self.pending_request
         self.pending_request = None
         self.send_request(info)
Beispiel #18
0
    def _draw_breakpoint_icon(self, top, painter, icon_name):
        """Draw the given breakpoint pixmap.

        Args:
            top (int): top of the line to draw the breakpoint icon.
            painter (QPainter)
            icon_name (srt): key of icon to draw (see: self.icons)
        """
        rect = QRect(0, top, self.sizeHint().width(),
                     self.sizeHint().height())
        try:
            icon = self.icons[icon_name]
        except KeyError as e:
            debug_print("Breakpoint icon doen't exist, {}".format(e))
        else:
            icon.paint(painter, rect)
Beispiel #19
0
    def send(self, method, params, requires_response):
        if ClientConstants.CANCEL in params:
            return
        msg = {
            'id': self.request_seq,
            'method': method,
            'params': params
        }
        if requires_response:
            self.req_status[self.request_seq] = method

        debug_print('\n[{0}] LSP-Client ===>'.format(self.language))
        debug_print(method)
        # debug_print('')
        self.zmq_out_socket.send_pyobj(msg)
        self.request_seq += 1
        return int(msg['id'])
Beispiel #20
0
    def __init__(self, parent=None, namespace=None, commands=[], message=None,
                 exitfunc=None, profile=False, multithreaded=False):
        SpyderPluginWidget.__init__(self, parent)

        debug_print("    ..internal console: initializing")
        self.dialog_manager = DialogManager()

        # Shell
        light_background = self.get_option('light_background')
        self.shell = InternalShell(parent, namespace, commands, message,
                                   self.get_option('max_line_count'),
                                   self.get_plugin_font(), exitfunc, profile,
                                   multithreaded,
                                   light_background=light_background)
        self.shell.status.connect(lambda msg: self.show_message.emit(msg, 0))
        self.shell.go_to_error.connect(self.go_to_error)
        self.shell.focus_changed.connect(lambda: self.focus_changed.emit())

        # Redirecting some signals:
        self.shell.redirect_stdio.connect(lambda state:
                                          self.redirect_stdio.emit(state))
        
        # Initialize plugin
        self.initialize_plugin()

        # Find/replace widget
        self.find_widget = FindReplace(self)
        self.find_widget.set_editor(self.shell)
        self.find_widget.hide()
        self.register_widget_shortcuts(self.find_widget)

        # Main layout
        layout = QVBoxLayout()
        layout.addWidget(self.shell)
        layout.addWidget(self.find_widget)
        self.setLayout(layout)
        
        # Parameters
        self.shell.toggle_wrap_mode(self.get_option('wrap'))
            
        # Accepting drops
        self.setAcceptDrops(True)

        # Traceback MessageBox
        self.msgbox_traceback= None
        self.error_traceback = ""
Beispiel #21
0
 def _on_msg_received(self):
     """Handle a message trigger from the socket.
     """
     self.notifier.setEnabled(False)
     while 1:
         try:
             resp = self.socket.recv_pyobj(flags=zmq.NOBLOCK)
         except zmq.ZMQError:
             self.notifier.setEnabled(True)
             return
         if not self.is_initialized:
             self.is_initialized = True
             debug_print('Initialized %s' % self.name)
             self.initialized.emit()
             self.timer.start(HEARTBEAT)
             continue
         resp['name'] = self.name
         self.received.emit(resp)
Beispiel #22
0
    def _introspection_complete(self, response):
        """
        Handle an introspection response completion.

        Route the response to the correct handler.
        """
        result = response.get('result', None)
        if result is None:
            return
        info = response['info']
        current = self._get_code_info(response['info']['name'])

        if result and current.filename == info.filename:
            func = getattr(self, '_handle_%s_result' % info.name)
            try:
                func(result, current, info)
            except Exception as e:
                debug_print(e)
Beispiel #23
0
 def _on_msg_received(self):
     """Handle a message trigger from the socket.
     """
     self.notifier.setEnabled(False)
     while 1:
         try:
             resp = self.socket.recv_pyobj(flags=zmq.NOBLOCK)
         except zmq.ZMQError:
             self.notifier.setEnabled(True)
             return
         if not self.is_initialized:
             self.is_initialized = True
             debug_print('Initialized %s' % self.name)
             self.initialized.emit()
             self.timer.start(HEARTBEAT)
             continue
         resp['name'] = self.name
         self.received.emit(resp)
Beispiel #24
0
    def _introspection_complete(self, response):
        """
        Handle an introspection response completion.

        Route the response to the correct handler.
        """
        result = response.get('result', None)
        if result is None:
            return
        info = response['info']
        current = self._get_code_info(response['info']['name'])

        if result and current.filename == info.filename:
            func = getattr(self, '_handle_%s_result' % info.name)
            try:
                func(result, current, info)
            except Exception as e:
                debug_print(e)
Beispiel #25
0
 def load_data(self, profdatafile):
     """Load profiler data saved by profile/cProfile module"""
     import pstats
     stats_indi = [pstats.Stats(profdatafile),]
     self.profdata = stats_indi[0]
     
     if self.compare_file is not None:
         try:
             stats_indi.append(pstats.Stats(self.compare_file))
         except IOError as e:
             QMessageBox.critical(
                 self, _("Error"),
                 _("Error when trying to load profiler results"))
             debug_print("Error when calling pstats, {}".format(e))
             self.compare_file = None
     map(lambda x: x.calc_callees(), stats_indi)
     self.profdata.calc_callees()
     self.stats1 = stats_indi
     self.stats = stats_indi[0].stats
Beispiel #26
0
    def send_request(self, info):
        """Handle an incoming request from the user."""
        if self.waiting:
            if info.serialize() != self.info.serialize():
                self.pending_request = info
            else:
                debug_print('skipping duplicate request')
            return
        debug_print('%s request' % info.name)
        desired = None
        self.info = info
        editor = info.editor
        if (info.name == 'completion' and 'jedi' not in self.plugins and
                info.line.lstrip().startswith(('import ', 'from '))):
            desired = 'fallback'

        if ((not editor.is_python_like()) or
                sourcecode.is_keyword(info.obj) or
                (editor.in_comment_or_string() and info.name != 'info')):
            desired = 'fallback'

        plugins = self.plugins.values()
        if desired:
            plugins = [self.plugins[desired]]
            self.desired = [desired]
        elif (info.name == 'definition' and not info.editor.is_python() or
              info.name == 'info'):
            self.desired = list(self.plugins.keys())
        else:
            # Use all but the fallback
            plugins = list(self.plugins.values())[:-1]
            self.desired = list(self.plugins.keys())[:-1]

        self._start_time = time.time()
        self.waiting = True
        method = 'get_%s' % info.name
        value = info.serialize()
        self.ids = dict()
        for plugin in plugins:
            request_id = plugin.request(method, value)
            self.ids[request_id] = plugin.name
        self.timer.stop()
        self.timer.singleShot(LEAD_TIME_SEC * 1000, self._handle_timeout)
Beispiel #27
0
    def send_request(self, info):
        """Handle an incoming request from the user."""
        if self.waiting:
            if info.serialize() != self.info.serialize():
                self.pending_request = info
            else:
                debug_print('skipping duplicate request')
            return
        debug_print('%s request' % info.name)
        desired = None
        self.info = info
        editor = info.editor
        if (info.name == 'completion' and 'jedi' not in self.plugins and
                info.line.lstrip().startswith(('import ', 'from '))):
            desired = 'fallback'

        if ((not editor.is_python_like()) or
                sourcecode.is_keyword(info.obj) or
                (editor.in_comment_or_string() and info.name != 'info')):
            desired = 'fallback'

        plugins = self.plugins.values()
        if desired:
            plugins = [self.plugins[desired]]
            self.desired = [desired]
        elif (info.name == 'definition' and not info.editor.is_python() or
              info.name == 'info'):
            self.desired = list(self.plugins.keys())
        else:
            # Use all but the fallback
            plugins = list(self.plugins.values())[:-1]
            self.desired = list(self.plugins.keys())[:-1]

        self._start_time = time.time()
        self.waiting = True
        method = 'get_%s' % info.name
        value = info.serialize()
        self.ids = dict()
        for plugin in plugins:
            request_id = plugin.request(method, value)
            self.ids[request_id] = plugin.name
        self.timer.stop()
        self.timer.singleShot(LEAD_TIME_SEC * 1000, self._handle_timeout)
Beispiel #28
0
    def get_jedi_object(self, func_name, info, use_filename=True):
        """Call a desired function on a Jedi Script and return the result"""
        if not jedi:
            return
        if DEBUG_EDITOR:
            t0 = time.time()
        # override IPython qt_loaders ImportDenier behavior
        metas = sys.meta_path
        for meta in metas:
            if (meta.__class__.__name__ == 'ImportDenier'
                    and hasattr(meta, 'forbid')):
                sys.meta_path.remove(meta)

        if use_filename:
            filename = info['filename']
        else:
            filename = None

        try:
            if JEDI_010:
                script = jedi.api.Script(info['source_code'],
                                         info['line_num'],
                                         info['column'],
                                         filename,
                                         sys_path=info['sys_path'])
            else:
                script = jedi.api.Script(info['source_code'], info['line_num'],
                                         info['column'], filename)
            func = getattr(script, func_name)
            val = func()
        except Exception as e:
            val = None
            debug_print('Jedi error (%s)' % func_name)
            debug_print(str(e))
            if DEBUG_EDITOR:
                log_last_error(LOG_FILENAME, str(e))
        if DEBUG_EDITOR:
            log_dt(LOG_FILENAME, func_name, t0)
        if not val and filename:
            return self.get_jedi_object(func_name, info, False)
        else:
            return val
Beispiel #29
0
    def keyPressEvent(self, e):
        """Qt override."""
        key = e.key()
        # Check if valid keys
        if key not in VALID_KEYS:
            self.invalid_key_flag = True
            return

        self.npressed += 1
        self.key_non_modifiers.append(key)
        self.key_modifiers.add(key)
        self.key_text.append(e.text())
        self.invalid_key_flag = False

        debug_print('key {0}, npressed: {1}'.format(key, self.npressed))

        if key == Qt.Key_unknown:
            return

        # The user clicked just and only the special keys
        # Ctrl, Shift, Alt, Meta.
        if (key == Qt.Key_Control or
                key == Qt.Key_Shift or
                key == Qt.Key_Alt or
                key == Qt.Key_Meta):
            return

        modifiers = e.modifiers()
        if modifiers & Qt.ShiftModifier:
            key += Qt.SHIFT
        if modifiers & Qt.ControlModifier:
            key += Qt.CTRL
            if sys.platform == 'darwin':
                self.npressed -= 1
            debug_print('decrementing')
        if modifiers & Qt.AltModifier:
            key += Qt.ALT
        if modifiers & Qt.MetaModifier:
            key += Qt.META

        self.keys.add(key)
Beispiel #30
0
    def keyPressEvent(self, e):
        """Qt override."""
        key = e.key()
        # Check if valid keys
        if key not in VALID_KEYS:
            self.invalid_key_flag = True
            return

        self.npressed += 1
        self.key_non_modifiers.append(key)
        self.key_modifiers.add(key)
        self.key_text.append(e.text())
        self.invalid_key_flag = False

        debug_print('key {0}, npressed: {1}'.format(key, self.npressed))

        if key == Qt.Key_unknown:
            return

        # The user clicked just and only the special keys
        # Ctrl, Shift, Alt, Meta.
        if (key == Qt.Key_Control or
                key == Qt.Key_Shift or
                key == Qt.Key_Alt or
                key == Qt.Key_Meta):
            return

        modifiers = e.modifiers()
        if modifiers & Qt.ShiftModifier:
            key += Qt.SHIFT
        if modifiers & Qt.ControlModifier:
            key += Qt.CTRL
            if sys.platform == 'darwin':
                self.npressed -= 1
            debug_print('decrementing')
        if modifiers & Qt.AltModifier:
            key += Qt.ALT
        if modifiers & Qt.MetaModifier:
            key += Qt.META

        self.keys.add(key)
Beispiel #31
0
 def on_msg_received(self):
     self.notifier.setEnabled(False)
     while True:
         try:
             # events = self.zmq_in_socket.poll(1500)
             resp = self.zmq_in_socket.recv_pyobj(flags=zmq.NOBLOCK)
             debug_print('\n[{0}] LSP-Client <==='.format(self.language))
             debug_print(resp)
             debug_print('')
             if 'method' in resp:
                 if resp['method'][0] != '$':
                     if resp['method'] in self.handler_registry:
                         handler_name = (
                             self.handler_registry[resp['method']])
                         handler = getattr(self, handler_name)
                         handler(resp['params'])
                     if 'id' in resp:
                         self.request_seq = resp['id']
             elif 'result' in resp:
                 if resp['result'] is not None:
                     req_id = resp['id']
                     if req_id in self.req_status:
                         req_type = self.req_status[req_id]
                         if req_type in self.handler_registry:
                             handler_name = self.handler_registry[req_type]
                             handler = getattr(self, handler_name)
                             handler(resp['result'], req_id)
                             self.req_status.pop(req_id)
                             if req_id in self.req_reply:
                                 self.req_reply.pop(req_id)
         except zmq.ZMQError as e:
             self.notifier.setEnabled(True)
             return
Beispiel #32
0
 def load_data(self, profdatafile):
     """Load profiler data saved by profile/cProfile module"""
     import pstats
     try:
         stats_indi = [pstats.Stats(profdatafile), ]
     except (OSError, IOError):
         return
     self.profdata = stats_indi[0]
     
     if self.compare_file is not None:
         try:
             stats_indi.append(pstats.Stats(self.compare_file))
         except (OSError, IOError) as e:
             QMessageBox.critical(
                 self, _("Error"),
                 _("Error when trying to load profiler results"))
             debug_print("Error when calling pstats, {}".format(e))
             self.compare_file = None
     map(lambda x: x.calc_callees(), stats_indi)
     self.profdata.calc_callees()
     self.stats1 = stats_indi
     self.stats = stats_indi[0].stats
Beispiel #33
0
    def document_did_close(self, params):
        file_signal = params['signal']
        debug_print('[{0}] File: {1}'.format(
            LSPRequestTypes.DOCUMENT_DID_CLOSE, params['file']))
        filename = path_as_uri(params['file'])

        params = {'textDocument': {'uri': filename}}
        if filename not in self.watched_files:
            params[ClientConstants.CANCEL] = True
        else:
            signals = self.watched_files[filename]
            idx = -1
            for i, signal in enumerate(signals):
                if id(file_signal) == id(signal):
                    idx = i
                    break
            if idx > 0:
                signals.pop(idx)

            if len(signals) == 0:
                self.watched_files.pop(filename)
        return params
Beispiel #34
0
    def register(self, panel, position=Panel.Position.LEFT):
        """
        Installs a panel on the editor.

        :param panel: Panel to install
        :param position: Position where the panel must be installed.
        :return: The installed panel
        """
        assert panel is not None
        pos_to_string = {
            Panel.Position.BOTTOM: 'bottom',
            Panel.Position.LEFT: 'left',
            Panel.Position.RIGHT: 'right',
            Panel.Position.TOP: 'top'
        }
        debug_print('adding panel {} at {}'.format(panel.name,
                                                   pos_to_string[position]))
        panel.order_in_zone = len(self._panels[position])
        self._panels[position][panel.name] = panel
        panel.position = position
        panel.on_install(self.editor)
        debug_print('panel {} installed'.format(panel.name))
        return panel
Beispiel #35
0
    def register(self, panel, position=Panel.Position.LEFT):
        """
        Installs a panel on the editor.

        :param panel: Panel to install
        :param position: Position where the panel must be installed.
        :return: The installed panel
        """
        assert panel is not None
        pos_to_string = {
            Panel.Position.BOTTOM: 'bottom',
            Panel.Position.LEFT: 'left',
            Panel.Position.RIGHT: 'right',
            Panel.Position.TOP: 'top',
            Panel.Position.FLOATING: 'floating'
        }
        debug_print('adding panel {} at {}'.format(panel.name,
                                                   pos_to_string[position]))
        panel.order_in_zone = len(self._panels[position])
        self._panels[position][panel.name] = panel
        panel.position = position
        panel.on_install(self.editor)
        debug_print('panel {} installed'.format(panel.name))
        return panel
Beispiel #36
0
 def run_script(self, filename=None, silent=False, set_focus=False,
                args=None):
     """Run a Python script"""
     if filename is None:
         self.shell.interpreter.restore_stds()
         filename, _selfilter = getopenfilename(self, _("Run Python script"),
                getcwd(), _("Python scripts")+" (*.py ; *.pyw ; *.ipy)")
         self.shell.interpreter.redirect_stds()
         if filename:
             os.chdir( osp.dirname(filename) )
             filename = osp.basename(filename)
         else:
             return
     debug_print(args)
     filename = osp.abspath(filename)
     rbs = remove_backslashes
     command = "runfile('%s', args='%s')" % (rbs(filename), rbs(args))
     if set_focus:
         self.shell.setFocus()
     if self.dockwidget and not self.ismaximized:
         self.dockwidget.setVisible(True)
         self.dockwidget.raise_()
     self.shell.write(command+'\n')
     self.shell.run_command(command)
Beispiel #37
0
 def __init__(self, executable):
     super(PluginManager, self).__init__()
     plugins = OrderedDict()
     for name in PLUGINS:
         try:
             plugin = PluginClient(name, executable)
             plugin.run()
         except Exception as e:
             debug_print('Introspection Plugin Failed: %s' % name)
             debug_print(str(e))
             continue
         debug_print('Introspection Plugin Loaded: %s' % name)
         plugins[name] = plugin
         plugin.received.connect(self.handle_response)
     self.plugins = plugins
     self.timer = QTimer()
     self.desired = []
     self.ids = dict()
     self.info = None
     self.request = None
     self.pending = None
     self.pending_request = None
     self.waiting = False
Beispiel #38
0
 def __init__(self, executable):
     super(PluginManager, self).__init__()
     plugins = OrderedDict()
     for name in PLUGINS:
         try:
             plugin = PluginClient(name, executable)
             plugin.run()
         except Exception as e:
             debug_print('Introspection Plugin Failed: %s' % name)
             debug_print(str(e))
             continue
         debug_print('Introspection Plugin Loaded: %s' % name)
         plugins[name] = plugin
         plugin.received.connect(self.handle_response)
     self.plugins = plugins
     self.timer = QTimer()
     self.desired = []
     self.ids = dict()
     self.info = None
     self.request = None
     self.pending = None
     self.pending_request = None
     self.waiting = False
Beispiel #39
0
    def get_info(self, info):
        """
        Find the calltip and docs

        Returns a dict like the following:
           {'note': 'Function of numpy.core.numeric...',
            'argspec': "(shape, dtype=None, order='C')'
            'docstring': 'Return an array of given...'
            'name': 'ones',
            'calltip': 'ones(shape, dtype=None, order='C')'}
        """
        call_def = self.get_jedi_object('goto_definitions', info)
        for cd in call_def:
            # For compatibility with Jedi 0.11
            try:
                cd.doc = cd.docstring()
            except AttributeError:
                pass

            if cd.doc and not cd.doc.rstrip().endswith(')'):
                call_def = cd
                break
        else:
            call_def = call_def[0]
        name = call_def.name
        if name is None:
            return
        if call_def.module_path:
            mod_name = get_parent_until(call_def.module_path)
        else:
            mod_name = None
        if not mod_name:
            mod_name = call_def.module_name
        if call_def.doc.startswith(name + '('):
            calltip = getsignaturefromtext(call_def.doc, name)
            argspec = calltip[calltip.find('('):]
            docstring = call_def.doc[call_def.doc.find(')') + 3:]
        elif '(' in call_def.doc.splitlines()[0]:
            calltip = call_def.doc.splitlines()[0]
            name = call_def.doc.split('(')[0]
            docstring = call_def.doc[call_def.doc.find(')') + 3:]
            argspec = calltip[calltip.find('('):]
        else:
            calltip = name + '(...)'
            argspec = '()'
            docstring = call_def.doc
        if call_def.type == 'module':
            note = 'Module %s' % mod_name
            argspec = ''
            calltip = name
        elif call_def.type == 'class':
            note = 'Class in %s module' % mod_name
        elif call_def.doc.startswith('%s(self' % name):
            class_name = call_def.full_name.split('.')[-2]
            note = 'Method of %s class in %s module' % (
                class_name.capitalize(), mod_name)
        else:
            note = '%s in %s module' % (call_def.type.capitalize(), mod_name)
        argspec = argspec.replace(' = ', '=')
        calltip = calltip.replace(' = ', '=')
        debug_print(call_def.name)

        doc_info = dict(name=name,
                        argspec=argspec,
                        note=note,
                        docstring=docstring,
                        calltip=calltip)
        return doc_info
Beispiel #40
0
 def _handle_timeout(self):
     self.waiting = False
     if self.pending:
         self._finalize(self.pending)
     else:
         debug_print('No valid responses acquired')
Beispiel #41
0
 def get_completions(self, info):
     """Return a list of (completion, type) tuples"""
     completions = self.get_jedi_object('completions', info)
     completions = [(c.name, c.type) for c in completions]
     debug_print(str(completions)[:100])
     return completions
Beispiel #42
0
 def get_completions(self, info):
     """Return a list of (completion, type) tuples"""
     completions = self.get_jedi_object('completions', info)
     completions = [(c.name, c.type) for c in completions]
     debug_print(str(completions)[:100])
     return completions
Beispiel #43
0
 def _handle_timeout(self):
     self.waiting = False
     if self.pending:
         self._finalize(self.pending)
     else:
         debug_print('No valid responses acquired')
Beispiel #44
0
 def close(self):
     for name, plugin in self.plugins.items():
         plugin.close()
         debug_print("Introspection Plugin Closed: {}".format(name))
Beispiel #45
0
 def refresh(self):
     """Refreshes the editor panels (resize and update margins)."""
     debug_print('refresh_panels')
     self.resize()
     self._update(self.editor.contentsRect(), 0,
                  force_update_margins=True)
Beispiel #46
0
 def close(self):
     for name, plugin in self.plugins.items():
         plugin.close()
         debug_print("Introspection Plugin Closed: {}".format(name))
Beispiel #47
0
 def _on_finished(self):
     """Handle a finished signal from the process.
     """
     if self.closing:
         return
     if self.is_initialized:
         debug_print('Restarting %s' % self.name)
         debug_print(self.process.readAllStandardOutput())
         debug_print(self.process.readAllStandardError())
         self.is_initialized = False
         self.notifier.setEnabled(False)
         self.run()
     else:
         debug_print('Errored %s' % self.name)
         debug_print(self.process.readAllStandardOutput())
         debug_print(self.process.readAllStandardError())
         self.errored.emit()
Beispiel #48
0
 def __del__(self):
     debug_print('{}.__del__'.format(type(self)))
Beispiel #49
0
 def refresh(self):
     """Refreshes the editor panels (resize and update margins)."""
     debug_print('refresh_panels')
     self.resize()
     self._update(self.editor.contentsRect(), 0, force_update_margins=True)
Beispiel #50
0
 def _on_finished(self):
     """Handle a finished signal from the process.
     """
     if self.closing:
         return
     if self.is_initialized:
         debug_print('Restarting %s' % self.name)
         debug_print(self.process.readAllStandardOutput())
         debug_print(self.process.readAllStandardError())
         self.is_initialized = False
         self.notifier.setEnabled(False)
         self.run()
     else:
         debug_print('Errored %s' % self.name)
         debug_print(self.process.readAllStandardOutput())
         debug_print(self.process.readAllStandardError())
         self.errored.emit()
Beispiel #51
0
    def _handle_modelx_msg(self, msg):
        """
        Handle internal spyder messages
        """
        msg_id = msg['parent_header']['msg_id']
        info = self._request_info['execute'].get(msg_id)

        msgtype = msg['content'].get('mx_msgtype')

        if msgtype in self.mx_msgtypes:
            # Deserialize data
            try:
                if PY2:
                    value = cloudpickle.loads(msg['buffers'][0])
                else:
                    value = cloudpickle.loads(bytes(msg['buffers'][0]))
            except Exception as msg:
                value = None
                self._kernel_reply = repr(msg)

            if msgtype == 'mxupdated':
                self.sig_mxupdated.emit()
            elif msgtype == 'dataview':
                self.sig_mxdataview_eval.emit(value)
            elif msgtype == 'dataview_getval':
                if spyder.version_info > (4, ):
                    raise AssertionError("must not happen")
                self._mx_value = value
                self.sig_mxdataview_getval.emit()
            elif msgtype == 'codelist':
                self.sig_mxcodelist.emit(value)
            elif msgtype == 'explorer':
                self.sig_mxexplorer.emit(value)
            elif msgtype == 'modellist':
                if spyder.version_info > (4, ):
                    raise AssertionError("must not happen")
                self._mx_value = value
                self.sig_mxmodellist.emit()
            elif msgtype == 'analyze_precedents_setnode':
                self.sig_mxanalyzer.emit('precedents', value)
            elif msgtype == 'analyze_succs_setnode':
                self.sig_mxanalyzer.emit('succs', value)
            elif msgtype == 'analyze_precedents':
                if spyder.version_info > (4, ):
                    raise AssertionError("must not happen")
                self._mx_value = value
                self.sig_mxanalyzer_precedents.emit()
            elif msgtype == 'analyze_succs':
                if spyder.version_info > (4, ):
                    raise AssertionError("must not happen")
                self._mx_value = value
                self.sig_mxanalyzer_succs.emit()
            elif msgtype == 'analyze_getval':
                if spyder.version_info > (4, ):
                    raise AssertionError("must not happen")
                self._mx_value = value
                self.sig_mxanalyzer_getval.emit()
            elif msgtype == 'property':
                self.sig_mxproperty.emit(value)
            elif msgtype == 'get_attrdict':
                self._mx_value = value
                self.sig_mxgetattrdict.emit()
            elif msgtype == 'get_value_info':
                self.sig_mxgetvalueinfo.emit(value)

            # Copied _handle_execute_reply
            if info and info.kind == 'silent_exec_method' and not self._hidden:
                self._request_info['execute'].pop(msg_id)
            return

        else:
            debug_print("No such modelx message type: %s" % msgtype)