Beispiel #1
0
 def find_files_in_path(self, path):
     if self.pathlist is None:
         self.pathlist = []
     self.pathlist.append(path)
     for path, dirs, files in os.walk(path):
         with QMutexLocker(self.mutex):
             if self.stopped:
                 return False
         try:
             for d in dirs[:]:
                 with QMutexLocker(self.mutex):
                     if self.stopped:
                         return False
                 dirname = os.path.join(path, d)
                 if (self.exclude and
                         re.search(self.exclude, dirname + os.sep)):
                     dirs.remove(d)
                 elif d == '.git' or d == '.hg':
                     dirs.remove(d)
             for f in files:
                 with QMutexLocker(self.mutex):
                     if self.stopped:
                         return False
                 filename = os.path.join(path, f)
                 if self.exclude and re.search(self.exclude, filename):
                     continue
                 if is_text_file(filename):
                     self.find_string_in_file(filename)
         except re.error:
             self.error_flag = _("invalid regular expression")
             return False
     return True
Beispiel #2
0
 def find_string_in_file(self, fname):
     self.error_flag = False
     self.sig_current_file.emit(fname)
     try:
         for lineno, line in enumerate(open(fname, 'rb')):
             for text, enc in self.texts:
                 with QMutexLocker(self.mutex):
                     if self.stopped:
                         return False
                 line_search = line
                 if not self.case_sensitive:
                     line_search = line_search.lower()
                 if self.text_re:
                     found = re.search(text, line_search)
                     if found is not None:
                         break
                 else:
                     found = line_search.find(text)
                     if found > -1:
                         break
             try:
                 line_dec = line.decode(enc)
             except UnicodeDecodeError:
                 line_dec = line
             if not self.case_sensitive:
                 line = line.lower()
             if self.text_re:
                 for match in re.finditer(text, line):
                     with QMutexLocker(self.mutex):
                         if self.stopped:
                             return False
                     self.total_matches += 1
                     self.sig_file_match.emit((osp.abspath(fname),
                                               lineno + 1,
                                               match.start(),
                                               match.end(), line_dec),
                                              self.total_matches)
             else:
                 found = line.find(text)
                 while found > -1:
                     with QMutexLocker(self.mutex):
                         if self.stopped:
                             return False
                     self.total_matches += 1
                     self.sig_file_match.emit((osp.abspath(fname),
                                               lineno + 1,
                                               found,
                                               found + len(text), line_dec),
                                              self.total_matches)
                     for text, enc in self.texts:
                         found = line.find(text, found + 1)
                         if found > -1:
                             break
     except IOError as xxx_todo_changeme:
         (_errno, _strerror) = xxx_todo_changeme.args
         self.error_flag = _("permission denied errors were encountered")
     self.completed = True
Beispiel #3
0
 def unhide_all_plots(self):
     """
     Set all plot names to be visible (not hidden)
     """
     with QMutexLocker(self.mutex):
         for row in range(self.table_widget.rowCount()):
             self.table_widget.setRowHidden(row, False)
Beispiel #4
0
 def set_sort_type(self, sort_type):
     """
     Set sorting to be by name
     :param sort_type: A Column enum for the column to sort on
     """
     with QMutexLocker(self.mutex):
         self.table_widget.sortItems(sort_type, self.sort_order())
Beispiel #5
0
    def register_element(self, element):
        # In a multi-threaded application, we can't risk assigning
        # the same ID to different elements, so we use a mutex here.
        with QMutexLocker(self._mutex):
            self.element_collection.add(element)

        return element
Beispiel #6
0
    def callback_value(self, widget_ref, index, ch_index, trigger, value):
        """
        Callback executed when a channel receives a new value.

        Parameters
        ----------
        widget_ref : weakref
            A weakref to the widget owner of the rule.
        index : int
            The index of the rule being processed.
        ch_index : int
            The channel index on the list for this rule.
        trigger : bool
            Whether or not this channel should trigger a calculation of the
            expression
        value : any
            The new value for this channel.

        Returns
        -------
        None
        """
        with QMutexLocker(self.map_lock):
            self.widget_map[widget_ref][index]['values'][ch_index] = value
            if trigger:
                if not all(self.widget_map[widget_ref][index]['conn']):
                    self.warn_unconnected_channels(widget_ref, index)
                    return
                self.widget_map[widget_ref][index]['calculate'] = True
Beispiel #7
0
    def register(self, widget, rules):
        widget_ref = weakref.ref(widget, self.widget_destroyed)
        if widget_ref in self.widget_map:
            self.unregister(widget_ref)

        with QMutexLocker(self.map_lock):
            self.widget_map[widget_ref] = []
            for idx, rule in enumerate(rules):
                channels_list = rule.get('channels', [])

                item = dict()
                item['rule'] = rule
                item['calculate'] = False
                item['values'] = [None] * len(channels_list)
                item['conn'] = [False] * len(channels_list)
                item['channels'] = []

                for ch_idx, ch in enumerate(channels_list):
                    conn_cb = functools.partial(self.callback_conn, widget_ref,
                                                idx, ch_idx)
                    value_cb = functools.partial(self.callback_value,
                                                 widget_ref, idx, ch_idx,
                                                 ch['trigger'])
                    c = PyDMChannel(ch['channel'],
                                    connection_slot=conn_cb,
                                    value_slot=value_cb)
                    item['channels'].append(c)
                    c.connect()

                self.widget_map[widget_ref].append(item)
Beispiel #8
0
    def run(self):
        """Run actor."""
        logger.debug('Fallback plugin starting...')
        self.sig_fallback_ready.emit()

        while True:
            with QMutexLocker(self.mutex):
                if self.stopped:
                    logger.debug("Fallback plugin stopping...")
            message = self.mailbox.get()
            msg_type, file, msg, editor = [
                message[k] for k in ('type', 'file', 'msg', 'editor')
            ]
            if msg_type == 'update':
                if file not in self.file_tokens:
                    self.file_tokens[file] = {
                        'text': '',
                        'language': msg['language']
                    }
                diff = msg['diff']
                text = self.file_tokens[file]
                text, _ = self.diff_patch.patch_apply(diff, text['text'])
                self.file_tokens[file]['text'] = text
            elif msg_type == 'close':
                self.file_tokens.pop(file, {})
            elif msg_type == 'retrieve':
                tokens = []
                if file in self.file_tokens:
                    text_info = self.file_tokens[file]
                    tokens = self.tokenize(text_info['text'],
                                           text_info['language'])
                editor.receive_text_tokens(tokens)
Beispiel #9
0
    def _on_key_pressed(self, event):
        if event.isAccepted():
            return

        with QMutexLocker(self.event_lock):
            key = event.key()
            text = to_text_string(event.text())

            if self.is_snippet_active:
                line, column = self.editor.get_cursor_line_column()
                node, snippet, text_node = self._find_node_by_position(
                    line, column)
                if key == Qt.Key_Tab:
                    event.accept()
                    next_snippet = ((self.active_snippet + 1) %
                                    len(self.snippets_map))
                    self.select_snippet(next_snippet)
                elif key == Qt.Key_Escape:
                    self.reset()
                    event.accept()
                elif len(text) > 0:
                    if node is not None:
                        if snippet is None:
                            # Constant text identifier was modified
                            self.reset()
                        else:
                            self._process_text(text)
Beispiel #10
0
    def receive_response(self, completion_source, req_id, resp):
        logger.debug("Completion plugin: Request {0} Got response "
                     "from {1}".format(req_id, completion_source))

        if req_id not in self.requests:
            return

        with QMutexLocker(self.collection_mutex):
            request_responses = self.requests[req_id]
            request_responses['sources'][completion_source] = resp

            wait_for = self.WAIT_FOR_SOURCE[request_responses['req_type']]
            if not resp:
                # Any response is better than no response
                keep_waiting = any(
                    self._is_client_running(source)
                    and source not in request_responses['sources']
                    for source in self.clients)
            elif completion_source not in wait_for:
                # A wait_for response is better than non-wait_for
                keep_waiting = any(
                    self._is_client_running(source)
                    and source not in request_responses['sources']
                    for source in wait_for)
            else:
                keep_waiting = False

            if keep_waiting:
                return

            del self.requests[req_id]
            self.gather_and_send(request_responses)
Beispiel #11
0
 def run(self):
     while not self.isInterruptionRequested():
         with QMutexLocker(self.map_lock):
             for widget_ref in self.widget_map:
                 for rule in self.widget_map[widget_ref]:
                     if rule['calculate']:
                         self.calculate_expression(widget_ref, rule)
         self.msleep(33)  # 30Hz
Beispiel #12
0
 def remove_from_plot_list(self, plot_number):
     """
     Remove the given plot name from the list
     :param plot_number: The unique number in GlobalFigureManager
     """
     with QMutexLocker(self.mutex):
         row, widget = self._get_row_and_widget_from_plot_number(plot_number)
         self.table_widget.removeRow(row)
Beispiel #13
0
 def filter_plot_list(self):
     """
     Run through the plot list and show only if matching filter
     """
     with QMutexLocker(self.mutex):
         for row in range(self.table_widget.rowCount()):
             widget = self.table_widget.cellWidget(row, Column.Name)
             is_shown_by_filter = self.presenter.is_shown_by_filter(widget.plot_number)
             self.table_widget.setRowHidden(row, not is_shown_by_filter)
Beispiel #14
0
 def set_visibility_icon(self, plot_number, is_visible):
     """
     Toggles the plot name widget icon between visible and hidden
     :param plot_number: The unique number in GlobalFigureManager
     :param is_visible: If true set visible, else set hidden
     """
     with QMutexLocker(self.mutex):
         row, widget = self._get_row_and_widget_from_plot_number(plot_number)
         widget.set_visibility_icon(is_visible)
Beispiel #15
0
 def wrapper(self, *args, **kwargs):
     if not self.editor.code_snippets:
         return
     if not rtree_available:
         return
     with QMutexLocker(self.modification_lock):
         if not hasattr(f, 'no_undo'):
             self.update_undo_stack()
         return f(self, *args, **kwargs)
Beispiel #16
0
    def receive_response(self, completion_source, req_id, resp):
        logger.debug("Completion plugin: Request {0} Got response "
                     "from {1}".format(req_id, completion_source))

        if req_id not in self.requests:
            return

        with QMutexLocker(self.collection_mutex):
            request_responses = self.requests[req_id]
            request_responses['sources'][completion_source] = resp
            self.howto_send_to_codeeditor(req_id)
Beispiel #17
0
    def receive_timeout(self, req_id):
        # On timeout, collect all completions and return to the user
        if req_id not in self.requests:
            return

        logger.debug("Completion plugin: Request {} timed out".format(req_id))

        with QMutexLocker(self.collection_mutex):
            request_responses = self.requests[req_id]
            request_responses['timed_out'] = True
            self.howto_send_to_codeeditor(req_id)
Beispiel #18
0
    def receive_timeout(self, req_id: int):
        """Collect all provider completions and reply on timeout."""
        # On timeout, collect all completions and return to the user
        if req_id not in self.requests:
            return

        logger.debug("Completion plugin: Request {} timed out".format(req_id))

        with QMutexLocker(self.collection_mutex):
            request_responses = self.requests[req_id]
            request_responses['timed_out'] = True
            self.match_and_reply(req_id)
Beispiel #19
0
 def document_did_change(self, params):
     request = {
         'source': 'spyder',
         'filename': osp.realpath(params['file']),
         'text': params['text'],
         'action': 'edit',
         'selections': []
     }
     with QMutexLocker(self.mutex):
         file_info = self.opened_files[params['file']]
         file_info['text'] = params['text']
     return request
Beispiel #20
0
 def recv_files(self):
     info = str(self.sock.recv(1024), "utf-8")
     while info != 'END':
         with QMutexLocker(self.mutex):
             if self.stopped:
                 return False
         print(info)
         print(info.split(','))
         file, size = info.split(',')
         size = int(size)
         self.sig_file_recv.emit(file, size)
         self.sock.send(b'OK')
         info = str(self.sock.recv(1024), "UTF-8")
Beispiel #21
0
    def set_plot_list(self, plot_list):
        """
        Populate the plot list from the Presenter. This is reserved
        for a 'things have gone wrong' scenario, and should only be
        used when errors are encountered.
        :param plot_list: the list of plot numbers
        """
        with QMutexLocker(self.mutex):
            self.table_widget.clearContents()

        self.filter_box.clear()
        for plot_number in plot_list:
            self.append_to_plot_list(plot_number)
Beispiel #22
0
    def receive_response(self, completion_source: str, req_id: int,
                         resp: dict):
        """Process request response from a completion provider."""
        logger.debug("Completion plugin: Request {0} Got response "
                     "from {1}".format(req_id, completion_source))

        if req_id not in self.requests:
            return

        with QMutexLocker(self.collection_mutex):
            request_responses = self.requests[req_id]
            request_responses['sources'][completion_source] = resp
            self.match_and_reply(req_id)
Beispiel #23
0
    def rename_selected_in_context_menu(self):
        """
        Triggered when rename is selected from the context menu,
        makes the plot name directly editable
        """
        plot_number = self.get_currently_selected_plot_number()

        if plot_number is None:
            return

        with QMutexLocker(self.mutex):
            row, widget = self._get_row_and_widget_from_plot_number(plot_number)
        widget.toggle_plot_name_editable(True)
Beispiel #24
0
    def set_sort_order(self, is_ascending):
        """
        Set the order of the sort list

        See also HumanReadableSortItem class
        :param is_ascending: If true sort ascending, else descending
        """
        if is_ascending:
            sort_order = Qt.AscendingOrder
        else:
            sort_order = Qt.DescendingOrder

        with QMutexLocker(self.mutex):
            self.table_widget.sortItems(self.sort_type(), sort_order)
Beispiel #25
0
 def set_visibility_icon(self, plot_number, is_visible):
     """
     Toggles the plot name widget icon between visible and hidden
     :param plot_number: The unique number in GlobalFigureManager
     :param is_visible: If true set visible, else set hidden
     """
     with QMutexLocker(self.mutex):
         row, widget = self._get_row_and_widget_from_plot_number(
             plot_number)
         if row is None or widget is None:
             raise ValueError(
                 f'Unable to find row and/or widget from plot_number {plot_number}'
             )
         widget.set_visibility_icon(is_visible)
Beispiel #26
0
 def set_active_font(self, plot_number, is_active):
     """
     Makes the active plot number bold, and makes a previously
     active bold plot number normal
     :param plot_number: The unique number in GlobalFigureManager
     :param is_active: True if plot is the active one or false to
                       make the plot number not bold
     """
     with QMutexLocker(self.mutex):
         row, widget = self._get_row_and_widget_from_plot_number(plot_number)
         font = self.table_widget.item(row, Column.Number).font()
         font.setBold(is_active)
         self.table_widget.item(row, Column.Number).setFont(font)
         self.table_widget.cellWidget(row, Column.Name).line_edit.setFont(font)
Beispiel #27
0
    def document_did_open(self, params):
        request = {
            'source': 'spyder',
            'filename': osp.realpath(params['file']),
            'text': params['text'],
            'action': 'focus',
            'selections': [{
                'start': params['offset'],
                'end': params['offset']
            }]
        }

        with QMutexLocker(self.mutex):
            self.opened_files[params['file']] = params['text']
        return request
Beispiel #28
0
 def document_did_change(self, params):
     request = {
         'source': 'spyder',
         'filename': osp.realpath(params['file']),
         'text': params['text'],
         'action': 'edit',
         'selections': [{
             'start': params['offset'],
             'end': params['offset'],
             'encoding': 'utf-16',
         }],
     }
     with QMutexLocker(self.mutex):
         self.opened_files[params['file']] = params['text']
     return request
Beispiel #29
0
    def rename_in_plot_list(self, plot_number, new_name):
        """
        Rename a plot in the plot list, also setting the sort key
        :param plot_number: The unique number in GlobalFigureManager
        :param new_name: The new plot name
          """
        with QMutexLocker(self.mutex):
            row, widget = self._get_row_and_widget_from_plot_number(plot_number)

            old_key = self.table_widget.item(row, Column.LastActive).data(Qt.DisplayRole)
            new_last_active_value = self.presenter.get_renamed_last_active_value(plot_number, old_key)
            self.table_widget.item(row, Column.LastActive).setData(Qt.DisplayRole, new_last_active_value)

            self.table_widget.item(row, Column.Name).setData(Qt.InitialSortOrderRole, new_name)
            widget.set_plot_name(new_name)
Beispiel #30
0
    def document_did_open(self, params):
        request = {
            'source': 'spyder',
            'filename': osp.realpath(params['file']),
            'text': params['text'],
            'action': 'focus',
            'selections': []
        }

        default_info = {'text': '', 'count': 0}
        with QMutexLocker(self.mutex):
            file_info = self.opened_files.get(params['file'], default_info)
            file_info['count'] += 1
            file_info['text'] = params['text']
            self.opened_files[params['file']] = file_info
        return request