コード例 #1
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)
コード例 #2
0
ファイル: widgets.py プロジェクト: lemonmenta/spyder
    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

        # Process any pending results
        if self.partial_results:
            self.process_results()

        return True
コード例 #3
0
ファイル: view.py プロジェクト: yutiansut/mantid
    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)
コード例 #4
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
コード例 #5
0
ファイル: document.py プロジェクト: yogendras843/spyder
    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
コード例 #6
0
ファイル: document.py プロジェクト: imfaisalpk/spyder
    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
コード例 #7
0
 def find_string_in_files(self):
     self.results = {}
     self.nb = 0
     self.error_flag = False
     for fname in self.filenames:
         with QMutexLocker(self.mutex):
             if self.stopped:
                 return
         try:
             for lineno, line in enumerate(open(fname, 'rb')):
                 for text, enc in self.texts:
                     if self.text_re:
                         found = re.search(text, line)
                         if found is not None:
                             break
                     else:
                         found = line.find(text)
                         if found > -1:
                             break
                 try:
                     line_dec = line.decode(enc)
                 except UnicodeDecodeError:
                     line_dec = line
                 if self.text_re:
                     for match in re.finditer(text, line):
                         res = self.results.get(osp.abspath(fname), [])
                         res.append((lineno + 1, match.start(), line_dec))
                         self.results[osp.abspath(fname)] = res
                         self.nb += 1
                 else:
                     while found > -1:
                         res = self.results.get(osp.abspath(fname), [])
                         res.append((lineno + 1, found, line_dec))
                         self.results[osp.abspath(fname)] = res
                         for text, enc in self.texts:
                             found = line.find(text, found + 1)
                             if found > -1:
                                 break
                         self.nb += 1
         except IOError as xxx_todo_changeme:
             (_errno, _strerror) = xxx_todo_changeme.args
             self.error_flag = _(
                 "permission denied errors were encountered")
         except re.error:
             self.error_flag = _("invalid regular expression")
     self.completed = True
コード例 #8
0
ファイル: document.py プロジェクト: wkx228/spyder
    def document_did_open(self, params):
        request = {
            'source': 'spyder',
            'filename': osp.realpath(params['file']),
            'text': params['text'],
            'action': 'focus',
            'selections': [{
                'start': params['selection_start'],
                'end': params['selection_end'],
                'encoding': 'utf-16',
            }],
        }

        with QMutexLocker(self.mutex):
            self.get_status(params['file'])
            self.opened_files[params['file']] = params['text']
        return request
コード例 #9
0
ファイル: rules.py プロジェクト: tynanford/pydm
    def unregister(self, widget_ref):
        with QMutexLocker(self.map_lock):
            # If hash() is called the first time only after the object was
            # deleted, the call will raise TypeError.
            # We should just ignore it.
            w_data = None
            try:
                w_data = self.widget_map.pop(widget_ref, None)
            except TypeError:
                pass

        if not w_data:
            return

        for rule in w_data:
            for ch in rule['channels']:
                ch.disconnect()

        del w_data
コード例 #10
0
ファイル: view.py プロジェクト: ethoeng/mantid
    def append_to_plot_list(self, plot_number):
        """
        Appends to the plot list, if sorting is enabled this should
        automatically go to the correct place, and the flag can be
        set to determine whether it should initially be hidden or not
        :param plot_number: The unique number in GlobalFigureManager
        """
        plot_name_widget = PlotNameWidget(self.presenter, plot_number, self)

        number_item = HumanReadableSortItem(str(plot_number))
        number_item.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter)

        name_item = HumanReadableSortItem()
        name_item.set_data_sort_role(Qt.InitialSortOrderRole)
        plot_name = self.presenter.get_plot_name_from_number(plot_number)
        name_item.setData(Qt.InitialSortOrderRole, plot_name)
        name_item.setSizeHint(plot_name_widget.sizeHint())

        last_active_value = self.presenter.get_initial_last_active_value(
            plot_number)
        last_active_item = HumanReadableSortItem(last_active_value)

        is_shown_by_filter = self.presenter.is_shown_by_filter(plot_number)

        with QMutexLocker(self.mutex):
            self.table_widget.setSortingEnabled(False)
            row_number = self.table_widget.rowCount()
            self.table_widget.insertRow(row_number)
            # Hide the row early so it does not briefly appear with no filter applied
            self.table_widget.setRowHidden(row_number, not is_shown_by_filter)

            self.table_widget.setItem(row_number, Column.Number, number_item)

            self.table_widget.setItem(row_number, Column.Name, name_item)
            self.table_widget.setCellWidget(row_number, Column.Name,
                                            plot_name_widget)

            self.table_widget.setItem(row_number, Column.LastActive,
                                      last_active_item)

            self.table_widget.setSortingEnabled(True)
コード例 #11
0
 def find_files_in_hg_manifest(self):
     p = programs.run_shell_command('hg manifest', cwd=self.rootpath)
     hgroot = get_vcs_root(self.rootpath)
     self.pathlist = [hgroot]
     for path in p.stdout.read().decode().splitlines():
         with QMutexLocker(self.mutex):
             if self.stopped:
                 return False
         dirname = osp.dirname(path)
         try:
             if re.search(self.exclude, dirname + os.sep):
                 continue
             filename = osp.basename(path)
             if re.search(self.exclude, filename):
                 continue
             if re.search(self.include, filename):
                 self.filenames.append(osp.join(hgroot, path))
         except re.error:
             self.error_flag = _("invalid regular expression")
             return False
     return True
コード例 #12
0
ファイル: view.py プロジェクト: yutiansut/mantid
    def set_last_active_values(self, last_active_values):
        """
        Sets the sort keys given a dictionary of plot numbers and
        last active values, e.g. {1: 2, 2: 1, 7: 3}
        :param last_active_values: A dictionary with keys as plot
                                   number and values as last active
                                   order
        """
        with QMutexLocker(self.mutex):
            self.table_widget.setSortingEnabled(False)
            for row in range(self.table_widget.rowCount()):
                plot_number = self.table_widget.cellWidget(row, Column.Name).plot_number

                last_active_item = self.table_widget.item(row, Column.LastActive)
                last_active_value = last_active_values.get(plot_number)

                if last_active_value:
                    last_active_item.setData(Qt.DisplayRole, str(last_active_value))

            # self.table_widget.sortItems(Column.LastActive, self.sort_order())
            self.table_widget.setSortingEnabled(True)
コード例 #13
0
ファイル: rules.py プロジェクト: tynanford/pydm
    def callback_conn(self, widget_ref, index, ch_index, value):
        """
        Callback executed when a channel connection status is changed.

        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.
        value : bool
            Whether or not this channel is connected.

        Returns
        -------
        None
        """
        with QMutexLocker(self.map_lock):
            self.widget_map[widget_ref][index]['conn'][ch_index] = value
コード例 #14
0
ファイル: plugin.py プロジェクト: imfaisalpk/spyder
 def receive_response(self, completion_source, req_id, resp):
     logger.debug("Completion plugin: Request {0} Got response "
                  "from {1}".format(req_id, completion_source))
     with QMutexLocker(self.collection_mutex):
         request_responses = self.requests[req_id]
         req_type = request_responses['req_type']
         language = request_responses['language']
         request_responses['sources'][completion_source] = resp
     corresponding_source = self.plugin_priority.get(req_type, 'lsp')
     is_src_ready = self.language_status[language].get(
         corresponding_source, False)
     if corresponding_source == completion_source:
         response_instance = request_responses['response_instance']
         self.gather_and_send(completion_source, response_instance,
                              req_type, req_id)
     else:
         # Preferred completion source is not available
         # Requests are handled in a first come, first served basis
         if not is_src_ready:
             response_instance = request_responses['response_instance']
             self.gather_and_send(completion_source, response_instance,
                                  req_type, req_id)
コード例 #15
0
ファイル: findinfiles.py プロジェクト: smathot/spyder
 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[:]:
                 dirname = os.path.join(path, d)
                 if re.search(self.exclude, dirname + os.sep):
                     dirs.remove(d)
             for f in files:
                 filename = os.path.join(path, f)
                 if 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
コード例 #16
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)

                    if next_snippet == 0:
                        self.reset()
                elif key == Qt.Key_Escape:
                    self.reset()
                    event.accept()
                elif len(text) > 0:
                    not_brace = text not in {'(', ')', '[', ']', '{', '}'}
                    not_completion = (
                        text not in self.editor.auto_completion_characters)
                    not_signature = (
                        text not in self.editor.signature_completion_characters
                    )
                    valid = not_brace and not_completion and not_signature
                    if node is not None:
                        if snippet is None or text == '\n':
                            # Constant text identifier was modified
                            self.reset()
                        elif valid or text == '\b':
                            self._process_text(text)
コード例 #17
0
    def download_file(self):
        # chunks = []
        num_chunks = 0
        bytes_recd = 0

        with open(self.file, 'wb') as fp:
            while bytes_recd < self.msglen:
                with QMutexLocker(self.mutex):
                    if self.stopped:
                        return False
                chunk_size = int(1024 * 1)
                chunk = self.sock.recv(
                    min(self.msglen - bytes_recd, chunk_size))
                if chunk == b'':
                    raise RuntimeError("socket connection broken")
                # chunks.append(chunk)
                fp.write(chunk)
                bytes_recd = bytes_recd + len(chunk)
                num_chunks += 1
                self.sig_current_chunk.emit(num_chunks, bytes_recd)
                print('chunk # %d' % num_chunks)
                print('Size of chunk: %f' % len(chunk))
                print('Bytes received until now: %f' % bytes_recd)
        self.sock.send(b'OK')
コード例 #18
0
ファイル: search_thread.py プロジェクト: bnavigator/spyder
    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 directories
                for d in dirs[:]:
                    with QMutexLocker(self.mutex):
                        if self.stopped:
                            return False

                    dirname = os.path.join(path, d)

                    # Only search in regular directories
                    st_dir_mode = os.stat(dirname).st_mode
                    if not stat.S_ISDIR(st_dir_mode):
                        dirs.remove(d)

                    if (self.exclude
                            and re.search(self.exclude, dirname + os.sep)):
                        # Exclude patterns defined by the user
                        dirs.remove(d)
                    elif d.startswith('.'):
                        # Exclude all dot dirs.
                        dirs.remove(d)

                # For files
                for f in files:
                    with QMutexLocker(self.mutex):
                        if self.stopped:
                            return False

                    filename = os.path.join(path, f)
                    ext = osp.splitext(filename)[1]

                    # Only search in regular files (i.e. not pipes)
                    st_file_mode = os.stat(filename).st_mode
                    if not stat.S_ISREG(st_file_mode):
                        continue

                    # Exclude patterns defined by the user
                    if self.exclude and re.search(self.exclude, filename):
                        continue

                    # Don't search in plain text files with skipped extensions
                    # (e.g .svg)
                    if ext in self.SKIPPED_EXTENSIONS:
                        continue

                    # It's much faster to check for extension first before
                    # validating if the file is plain text.
                    if (ext in self.PYTHON_EXTENSIONS
                            or ext in self.USEFUL_EXTENSIONS
                            or is_text_file(filename)):
                        self.find_string_in_file(filename)
            except re.error:
                self.error_flag = _("invalid regular expression")
                return False

        # Process any pending results
        if self.partial_results:
            self.process_results()

        return True
コード例 #19
0
ファイル: widgets.py プロジェクト: lemonmenta/spyder
 def stop(self):
     with QMutexLocker(self.mutex):
         self.stopped = True
コード例 #20
0
ファイル: util.py プロジェクト: corrscope/corrscope
 def set(self, value: T) -> T:
     # We don't actually need a mutex since Python holds the GIL during reads and
     # writes. But keep it anyway.
     with QMutexLocker(self.lock):
         self.obj = value
     return value
コード例 #21
0
    def insert_snippet(self, text):
        line, column = self.editor.get_cursor_line_column()
        visitor = SnippetSearcherVisitor(line, column, self.node_number)
        ast = build_snippet_ast(text)
        ast.compute_position((line, column))
        ast.accept(visitor)

        self.inserting_snippet = True
        self.editor.insert_text(ast.text(), will_insert_text=False)
        self.editor.document_did_change()

        if not self.editor.code_snippets:
            return

        if not rtree_available:
            return

        new_snippet = True
        if self.is_snippet_active:
            with QMutexLocker(self.modification_lock):
                # This is a nested snippet / text on snippet
                leaf, snippet_root, _ = self._find_node_by_position(
                    line, column)
                if snippet_root is not None:
                    new_snippet = False
                    root_number = snippet_root.number
                    next_number = root_number + 1
                    snippet_map = visitor.snippet_map
                    for snippet_number in snippet_map:
                        snippet_nodes = snippet_map[snippet_number]
                        for snippet_node in snippet_nodes:
                            snippet_node.number = next_number
                        next_number += 1
                    for snippet_number in self.snippets_map:
                        if snippet_number > root_number:
                            snippet_nodes = self.snippets_map[snippet_number]
                            for snippet_node in snippet_nodes:
                                snippet_node.number = next_number
                            next_number += 1
                    self.update_undo_stack()
                    self._insert_snippet_at_node(
                        leaf, snippet_root, ast, line, column)
                    self._update_ast()
                    if len(snippet_map) > 0:
                        self.select_snippet(snippet_number=root_number + 1)
                    self.draw_snippets()
                elif leaf is not None:
                    self.reset()

        if new_snippet:
            self.reset()
            self.ast = ast
            self.snippets_map = visitor.snippet_map
            if len(self.snippets_map) > 0:
                # Completion contains snippets
                self.is_snippet_active = True
                self.starting_position = (line, column)
                self.update_position_tree(visitor)
                self.draw_snippets()
                self.select_snippet(snippet_number=1)
            else:
                # Completion does not contain snippets
                self.reset()
コード例 #22
0
ファイル: util.py プロジェクト: corrscope/corrscope
 def get(self) -> T:
     with QMutexLocker(self.lock):
         return self.obj
コード例 #23
0
ファイル: widgets.py プロジェクト: lemonmenta/spyder
    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
                        bstart, bend = match.start(), match.end()
                        try:
                            # Go from binary position to utf8 position
                            start = len(line[:bstart].decode(enc))
                            end = start + len(line[bstart:bend].decode(enc))
                        except UnicodeDecodeError:
                            start = bstart
                            end = bend
                        self.partial_results.append(
                            (osp.abspath(fname), lineno + 1, start, end,
                             line_dec))
                        if len(self.partial_results) > (2**self.power):
                            self.process_results()
                            if self.power < self.max_power:
                                self.power += 1
                else:
                    found = line.find(text)
                    while found > -1:
                        with QMutexLocker(self.mutex):
                            if self.stopped:
                                return False
                        self.total_matches += 1
                        try:
                            # Go from binary position to utf8 position
                            start = len(line[:found].decode(enc))
                            end = start + len(text.decode(enc))
                        except UnicodeDecodeError:
                            start = found
                            end = found + len(text)

                        self.partial_results.append(
                            (osp.abspath(fname), lineno + 1, start, end,
                             line_dec))
                        if len(self.partial_results) > (2**self.power):
                            self.process_results()
                            if self.power < self.max_power:
                                self.power += 1

                        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
コード例 #24
0
 def stop(self):
     """Stop actor."""
     with QMutexLocker(self.mutex):
         self.stopped = True
コード例 #25
0
 def stop(self):
     """Stop actor."""
     with QMutexLocker(self.mutex):
         logger.debug("Snippets plugin stopping...")
         self.thread.quit()
         self.thread.wait()
コード例 #26
0
 def stop(self):
     """Stop actor."""
     with QMutexLocker(self.mutex):
         logger.debug("Fallback plugin stopping...")
         self.thread.quit()
コード例 #27
0
 def stop(self):
     with QMutexLocker(self.mutex):
         self.stopped = True
         self.canceled = True
         self.sock.close()
         print("Time elapsed: {0}".format(time.time() - self.start_time))