text_prompt
stringlengths
100
17.7k
code_prompt
stringlengths
7
9.86k
<SYSTEM_TASK:> Qt override. <END_TASK> <USER_TASK:> Description: def filterAcceptsRow(self, row_num, parent): """Qt override. Reimplemented from base class to allow the use of custom filtering. """
model = self.sourceModel() name = model.row(row_num).name r = re.search(self.pattern, name) if r is None: return False else: return True
<SYSTEM_TASK:> Load shortcuts and assign to table model. <END_TASK> <USER_TASK:> Description: def load_shortcuts(self): """Load shortcuts and assign to table model."""
shortcuts = [] for context, name, keystr in iter_shortcuts(): shortcut = Shortcut(context, name, keystr) shortcuts.append(shortcut) shortcuts = sorted(shortcuts, key=lambda x: x.context+x.name) # Store the original order of shortcuts for i, shortcut in enumerate(shortcuts): shortcut.index = i self.source_model.shortcuts = shortcuts self.source_model.scores = [0]*len(shortcuts) self.source_model.rich_text = [s.name for s in shortcuts] self.source_model.reset() self.adjust_cells() self.sortByColumn(CONTEXT, Qt.AscendingOrder)
<SYSTEM_TASK:> Save shortcuts from table model. <END_TASK> <USER_TASK:> Description: def save_shortcuts(self): """Save shortcuts from table model."""
self.check_shortcuts() for shortcut in self.source_model.shortcuts: shortcut.save()
<SYSTEM_TASK:> Create, setup and display the shortcut editor dialog. <END_TASK> <USER_TASK:> Description: def show_editor(self): """Create, setup and display the shortcut editor dialog."""
index = self.proxy_model.mapToSource(self.currentIndex()) row, column = index.row(), index.column() shortcuts = self.source_model.shortcuts context = shortcuts[row].context name = shortcuts[row].name sequence_index = self.source_model.index(row, SEQUENCE) sequence = sequence_index.data() dialog = ShortcutEditor(self, context, name, sequence, shortcuts) if dialog.exec_(): new_sequence = dialog.new_sequence self.source_model.setData(sequence_index, new_sequence)
<SYSTEM_TASK:> Update the regex text for the shortcut finder. <END_TASK> <USER_TASK:> Description: def set_regex(self, regex=None, reset=False): """Update the regex text for the shortcut finder."""
if reset: text = '' else: text = self.finder.text().replace(' ', '').lower() self.proxy_model.set_filter(text) self.source_model.update_search_letters(text) self.sortByColumn(SEARCH_SCORE, Qt.AscendingOrder) if self.last_regex != regex: self.selectRow(0) self.last_regex = regex
<SYSTEM_TASK:> Reset to default values of the shortcuts making a confirmation. <END_TASK> <USER_TASK:> Description: def reset_to_default(self): """Reset to default values of the shortcuts making a confirmation."""
reset = QMessageBox.warning(self, _("Shortcuts reset"), _("Do you want to reset " "to default values?"), QMessageBox.Yes | QMessageBox.No) if reset == QMessageBox.No: return reset_shortcuts() self.main.apply_shortcuts() self.table.load_shortcuts() self.load_from_conf() self.set_modified(False)
<SYSTEM_TASK:> Get a color scheme from config using its name <END_TASK> <USER_TASK:> Description: def get_color_scheme(name): """Get a color scheme from config using its name"""
name = name.lower() scheme = {} for key in COLOR_SCHEME_KEYS: try: scheme[key] = CONF.get('appearance', name+'/'+key) except: scheme[key] = CONF.get('appearance', 'spyder/'+key) return scheme
<SYSTEM_TASK:> Returns a code cell name from a code cell comment. <END_TASK> <USER_TASK:> Description: def get_code_cell_name(text): """Returns a code cell name from a code cell comment."""
name = text.strip().lstrip("#% ") if name.startswith("<codecell>"): name = name[10:].lstrip() elif name.startswith("In["): name = name[2:] if name.endswith("]:"): name = name[:-1] name = name.strip() return name
<SYSTEM_TASK:> Factory to generate syntax highlighter for the given filename. <END_TASK> <USER_TASK:> Description: def guess_pygments_highlighter(filename): """Factory to generate syntax highlighter for the given filename. If a syntax highlighter is not available for a particular file, this function will attempt to generate one based on the lexers in Pygments. If Pygments is not available or does not have an appropriate lexer, TextSH will be returned instead. """
try: from pygments.lexers import get_lexer_for_filename, get_lexer_by_name except Exception: return TextSH root, ext = os.path.splitext(filename) if ext in custom_extension_lexer_mapping: try: lexer = get_lexer_by_name(custom_extension_lexer_mapping[ext]) except Exception: return TextSH else: try: lexer = get_lexer_for_filename(filename) except Exception: return TextSH class GuessedPygmentsSH(PygmentsSH): _lexer = lexer return GuessedPygmentsSH
<SYSTEM_TASK:> Implement highlight specific for Fortran. <END_TASK> <USER_TASK:> Description: def highlight_block(self, text): """Implement highlight specific for Fortran."""
text = to_text_string(text) self.setFormat(0, len(text), self.formats["normal"]) match = self.PROG.search(text) index = 0 while match: for key, value in list(match.groupdict().items()): if value: start, end = match.span(key) index += end-start self.setFormat(start, end-start, self.formats[key]) if value.lower() in ("subroutine", "module", "function"): match1 = self.IDPROG.match(text, end) if match1: start1, end1 = match1.span(1) self.setFormat(start1, end1-start1, self.formats["definition"]) match = self.PROG.search(text, match.end()) self.highlight_spaces(text)
<SYSTEM_TASK:> Implement highlight specific for Fortran77. <END_TASK> <USER_TASK:> Description: def highlight_block(self, text): """Implement highlight specific for Fortran77."""
text = to_text_string(text) if text.startswith(("c", "C")): self.setFormat(0, len(text), self.formats["comment"]) self.highlight_spaces(text) else: FortranSH.highlight_block(self, text) self.setFormat(0, 5, self.formats["comment"]) self.setFormat(73, max([73, len(text)]), self.formats["comment"])
<SYSTEM_TASK:> Implement highlight specific for CSS and HTML. <END_TASK> <USER_TASK:> Description: def highlight_block(self, text): """Implement highlight specific for CSS and HTML."""
text = to_text_string(text) previous_state = tbh.get_state(self.currentBlock().previous()) if previous_state == self.COMMENT: self.setFormat(0, len(text), self.formats["comment"]) else: previous_state = self.NORMAL self.setFormat(0, len(text), self.formats["normal"]) tbh.set_state(self.currentBlock(), previous_state) match = self.PROG.search(text) match_count = 0 n_characters = len(text) # There should never be more matches than characters in the text. while match and match_count < n_characters: match_dict = match.groupdict() for key, value in list(match_dict.items()): if value: start, end = match.span(key) if previous_state == self.COMMENT: if key == "multiline_comment_end": tbh.set_state(self.currentBlock(), self.NORMAL) self.setFormat(end, len(text), self.formats["normal"]) else: tbh.set_state(self.currentBlock(), self.COMMENT) self.setFormat(0, len(text), self.formats["comment"]) else: if key == "multiline_comment_start": tbh.set_state(self.currentBlock(), self.COMMENT) self.setFormat(start, len(text), self.formats["comment"]) else: tbh.set_state(self.currentBlock(), self.NORMAL) try: self.setFormat(start, end-start, self.formats[key]) except KeyError: # happens with unmatched end-of-comment; # see issue 1462 pass match = self.PROG.search(text, match.end()) match_count += 1 self.highlight_spaces(text)
<SYSTEM_TASK:> Parses the complete text and stores format for each character. <END_TASK> <USER_TASK:> Description: def make_charlist(self): """Parses the complete text and stores format for each character."""
def worker_output(worker, output, error): """Worker finished callback.""" self._charlist = output if error is None and output: self._allow_highlight = True self.rehighlight() self._allow_highlight = False text = to_text_string(self.document().toPlainText()) tokens = self._lexer.get_tokens(text) # Before starting a new worker process make sure to end previous # incarnations self._worker_manager.terminate_all() worker = self._worker_manager.create_python_worker( self._make_charlist, tokens, self._tokmap, self.formats, ) worker.sig_finished.connect(worker_output) worker.start()
<SYSTEM_TASK:> Parses the complete text and stores format for each character. <END_TASK> <USER_TASK:> Description: def _make_charlist(self, tokens, tokmap, formats): """ Parses the complete text and stores format for each character. Uses the attached lexer to parse into a list of tokens and Pygments token types. Then breaks tokens into individual letters, each with a Spyder token type attached. Stores this list as self._charlist. It's attached to the contentsChange signal of the parent QTextDocument so that the charlist is updated whenever the document changes. """
def _get_fmt(typ): """Get the Spyder format code for the given Pygments token type.""" # Exact matches first if typ in tokmap: return tokmap[typ] # Partial (parent-> child) matches for key, val in tokmap.items(): if typ in key: # Checks if typ is a subtype of key. return val return 'normal' charlist = [] for typ, token in tokens: fmt = formats[_get_fmt(typ)] for letter in token: charlist.append((fmt, letter)) return charlist
<SYSTEM_TASK:> Actually highlight the block <END_TASK> <USER_TASK:> Description: def highlightBlock(self, text): """ Actually highlight the block"""
# Note that an undefined blockstate is equal to -1, so the first block # will have the correct behaviour of starting at 0. if self._allow_highlight: start = self.previousBlockState() + 1 end = start + len(text) for i, (fmt, letter) in enumerate(self._charlist[start:end]): self.setFormat(i, 1, fmt) self.setCurrentBlockState(end) self.highlight_spaces(text)
<SYSTEM_TASK:> Get all submodules of the main scientific modules and others of our <END_TASK> <USER_TASK:> Description: def get_preferred_submodules(): """ Get all submodules of the main scientific modules and others of our interest """
# Path to the modules database modules_path = get_conf_path('db') # Modules database modules_db = PickleShareDB(modules_path) if 'submodules' in modules_db: return modules_db['submodules'] submodules = [] for m in PREFERRED_MODULES: submods = get_submodules(m) submodules += submods modules_db['submodules'] = submodules return submodules
<SYSTEM_TASK:> Return whether the dev configuration directory should used. <END_TASK> <USER_TASK:> Description: def use_dev_config_dir(use_dev_config_dir=USE_DEV_CONFIG_DIR): """Return whether the dev configuration directory should used."""
if use_dev_config_dir is not None: if use_dev_config_dir.lower() in {'false', '0'}: use_dev_config_dir = False else: use_dev_config_dir = DEV or not is_stable_version(__version__) return use_dev_config_dir
<SYSTEM_TASK:> Return user home directory <END_TASK> <USER_TASK:> Description: def get_home_dir(): """ Return user home directory """
try: # expanduser() returns a raw byte string which needs to be # decoded with the codec that the OS is using to represent # file paths. path = encoding.to_unicode_from_fs(osp.expanduser('~')) except Exception: path = '' if osp.isdir(path): return path else: # Get home from alternative locations for env_var in ('HOME', 'USERPROFILE', 'TMP'): # os.environ.get() returns a raw byte string which needs to be # decoded with the codec that the OS is using to represent # environment variables. path = encoding.to_unicode_from_fs(os.environ.get(env_var, '')) if osp.isdir(path): return path else: path = '' if not path: raise RuntimeError('Please set the environment variable HOME to ' 'your user/home directory path so Spyder can ' 'start properly.')
<SYSTEM_TASK:> Return the path to a temp clean configuration dir, for tests and safe mode. <END_TASK> <USER_TASK:> Description: def get_clean_conf_dir(): """ Return the path to a temp clean configuration dir, for tests and safe mode. """
if sys.platform.startswith("win"): current_user = '' else: current_user = '-' + str(getpass.getuser()) conf_dir = osp.join(str(tempfile.gettempdir()), 'pytest-spyder{0!s}'.format(current_user), SUBFOLDER) return conf_dir
<SYSTEM_TASK:> Return absolute path to the config file with the specified filename. <END_TASK> <USER_TASK:> Description: def get_conf_path(filename=None): """Return absolute path to the config file with the specified filename."""
# Define conf_dir if running_under_pytest() or SAFE_MODE: # Use clean config dir if running tests or the user requests it. conf_dir = get_clean_conf_dir() elif sys.platform.startswith('linux'): # This makes us follow the XDG standard to save our settings # on Linux, as it was requested on Issue 2629 xdg_config_home = os.environ.get('XDG_CONFIG_HOME', '') if not xdg_config_home: xdg_config_home = osp.join(get_home_dir(), '.config') if not osp.isdir(xdg_config_home): os.makedirs(xdg_config_home) conf_dir = osp.join(xdg_config_home, SUBFOLDER) else: conf_dir = osp.join(get_home_dir(), SUBFOLDER) # Create conf_dir if not osp.isdir(conf_dir): if running_under_pytest() or SAFE_MODE: os.makedirs(conf_dir) else: os.mkdir(conf_dir) if filename is None: return conf_dir else: return osp.join(conf_dir, filename)
<SYSTEM_TASK:> List available translations for spyder based on the folders found in the <END_TASK> <USER_TASK:> Description: def get_available_translations(): """ List available translations for spyder based on the folders found in the locale folder. This function checks if LANGUAGE_CODES contain the same information that is found in the 'locale' folder to ensure that when a new language is added, LANGUAGE_CODES is updated. """
locale_path = get_module_data_path("spyder", relpath="locale", attr_name='LOCALEPATH') listdir = os.listdir(locale_path) langs = [d for d in listdir if osp.isdir(osp.join(locale_path, d))] langs = [DEFAULT_LANGUAGE] + langs # Remove disabled languages langs = list( set(langs) - set(DISABLED_LANGUAGES) ) # Check that there is a language code available in case a new translation # is added, to ensure LANGUAGE_CODES is updated. for lang in langs: if lang not in LANGUAGE_CODES: error = ('Update LANGUAGE_CODES (inside config/base.py) if a new ' 'translation has been added to Spyder') print(error) # spyder: test-skip return ['en'] return langs
<SYSTEM_TASK:> Load language setting from language config file if it exists, otherwise <END_TASK> <USER_TASK:> Description: def load_lang_conf(): """ Load language setting from language config file if it exists, otherwise try to use the local settings if Spyder provides a translation, or return the default if no translation provided. """
if osp.isfile(LANG_FILE): with open(LANG_FILE, 'r') as f: lang = f.read() else: lang = get_interface_language() save_lang_conf(lang) # Save language again if it's been disabled if lang.strip('\n') in DISABLED_LANGUAGES: lang = DEFAULT_LANGUAGE save_lang_conf(lang) return lang
<SYSTEM_TASK:> Refresh explorer widget <END_TASK> <USER_TASK:> Description: def refresh_plugin(self, new_path=None, force_current=True): """Refresh explorer widget"""
self.fileexplorer.treewidget.update_history(new_path) self.fileexplorer.treewidget.refresh(new_path, force_current=force_current)
<SYSTEM_TASK:> Return True if `obj` is type text string, False if it is anything else, <END_TASK> <USER_TASK:> Description: def is_type_text_string(obj): """Return True if `obj` is type text string, False if it is anything else, like an instance of a class that extends the basestring class."""
if PY2: # Python 2 return type(obj) in [str, unicode] else: # Python 3 return type(obj) in [str, bytes]
<SYSTEM_TASK:> Return the widget to give focus to when <END_TASK> <USER_TASK:> Description: def get_focus_widget(self): """ Return the widget to give focus to when this plugin's dockwidget is raised on top-level """
self.pydocbrowser.url_combo.lineEdit().selectAll() return self.pydocbrowser.url_combo
<SYSTEM_TASK:> Catch clicks outside the object and ESC key press. <END_TASK> <USER_TASK:> Description: def eventFilter(self, widget, event): """Catch clicks outside the object and ESC key press."""
if ((event.type() == QEvent.MouseButtonPress and not self.geometry().contains(event.globalPos())) or (event.type() == QEvent.KeyPress and event.key() == Qt.Key_Escape)): # Exits editing self.hide() self.setFocus(False) return True # Event is not interessant, raise to parent return QLineEdit.eventFilter(self, widget, event)
<SYSTEM_TASK:> Override Qt method to trigger the tab name editor. <END_TASK> <USER_TASK:> Description: def mouseDoubleClickEvent(self, event): """Override Qt method to trigger the tab name editor."""
if self.rename_tabs is True and \ event.buttons() == Qt.MouseButtons(Qt.LeftButton): # Tab index index = self.tabAt(event.pos()) if index >= 0: # Tab is valid, call tab name editor self.tab_name_editor.edit_tab(index) else: # Event is not interesting, raise to parent QTabBar.mouseDoubleClickEvent(self, event)
<SYSTEM_TASK:> Setting Tabs close function <END_TASK> <USER_TASK:> Description: def set_close_function(self, func): """Setting Tabs close function None -> tabs are not closable"""
state = func is not None if state: self.sig_close_tab.connect(func) try: # Assuming Qt >= 4.5 QTabWidget.setTabsClosable(self, state) self.tabCloseRequested.connect(func) except AttributeError: # Workaround for Qt < 4.5 close_button = create_toolbutton(self, triggered=func, icon=ima.icon('fileclose'), tip=_("Close current tab")) self.setCornerWidget(close_button if state else None)
<SYSTEM_TASK:> Create dialog button box and add it to the dialog layout <END_TASK> <USER_TASK:> Description: def add_button_box(self, stdbtns): """Create dialog button box and add it to the dialog layout"""
bbox = QDialogButtonBox(stdbtns) run_btn = bbox.addButton(_("Run"), QDialogButtonBox.AcceptRole) run_btn.clicked.connect(self.run_btn_clicked) bbox.accepted.connect(self.accept) bbox.rejected.connect(self.reject) btnlayout = QHBoxLayout() btnlayout.addStretch(1) btnlayout.addWidget(bbox) self.layout().addLayout(btnlayout)
<SYSTEM_TASK:> Compute and return line number area width <END_TASK> <USER_TASK:> Description: def compute_width(self): """Compute and return line number area width"""
if not self._enabled: return 0 digits = 1 maxb = max(1, self.editor.blockCount()) while maxb >= 10: maxb /= 10 digits += 1 if self._margin: margin = 3+self.editor.fontMetrics().width('9'*digits) else: margin = 0 return margin+self.get_markers_margin()
<SYSTEM_TASK:> Returns a list with line number, definition name, fold and token. <END_TASK> <USER_TASK:> Description: def process_python_symbol_data(oedata): """Returns a list with line number, definition name, fold and token."""
symbol_list = [] for key in oedata: val = oedata[key] if val and key != 'found_cell_separators': if val.is_class_or_function(): symbol_list.append((key, val.def_name, val.fold_level, val.get_token())) return sorted(symbol_list)
<SYSTEM_TASK:> Return a list of icons for oedata of a python file. <END_TASK> <USER_TASK:> Description: def get_python_symbol_icons(oedata): """Return a list of icons for oedata of a python file."""
class_icon = ima.icon('class') method_icon = ima.icon('method') function_icon = ima.icon('function') private_icon = ima.icon('private1') super_private_icon = ima.icon('private2') symbols = process_python_symbol_data(oedata) # line - 1, name, fold level fold_levels = sorted(list(set([s[2] for s in symbols]))) parents = [None]*len(symbols) icons = [None]*len(symbols) indexes = [] parent = None for level in fold_levels: for index, item in enumerate(symbols): line, name, fold_level, token = item if index in indexes: continue if fold_level == level: indexes.append(index) parent = item else: parents[index] = parent for index, item in enumerate(symbols): parent = parents[index] if item[-1] == 'def': icons[index] = function_icon elif item[-1] == 'class': icons[index] = class_icon else: icons[index] = QIcon() if parent is not None: if parent[-1] == 'class': if item[-1] == 'def' and item[1].startswith('__'): icons[index] = super_private_icon elif item[-1] == 'def' and item[1].startswith('_'): icons[index] = private_icon else: icons[index] = method_icon return icons
<SYSTEM_TASK:> Detect when the focus goes out of this widget. <END_TASK> <USER_TASK:> Description: def focusOutEvent(self, event): """ Detect when the focus goes out of this widget. This is used to make the file switcher leave focus on the last selected file by the user. """
self.clicked_outside = True return super(QLineEdit, self).focusOutEvent(event)
<SYSTEM_TASK:> Save initial cursors and initial active widget. <END_TASK> <USER_TASK:> Description: def save_initial_state(self): """Save initial cursors and initial active widget."""
paths = self.paths self.initial_widget = self.get_widget() self.initial_cursors = {} for i, editor in enumerate(self.widgets): if editor is self.initial_widget: self.initial_path = paths[i] # This try is needed to make the fileswitcher work with # plugins that does not have a textCursor. try: self.initial_cursors[paths[i]] = editor.textCursor() except AttributeError: pass
<SYSTEM_TASK:> Restores initial cursors and initial active editor. <END_TASK> <USER_TASK:> Description: def restore_initial_state(self): """Restores initial cursors and initial active editor."""
self.list.clear() self.is_visible = False widgets = self.widgets_by_path if not self.edit.clicked_outside: for path in self.initial_cursors: cursor = self.initial_cursors[path] if path in widgets: self.set_editor_cursor(widgets[path], cursor) if self.initial_widget in self.paths_by_widget: index = self.paths.index(self.initial_path) self.sig_goto_file.emit(index)
<SYSTEM_TASK:> Adjusts the width and height of the file switcher <END_TASK> <USER_TASK:> Description: def fix_size(self, content): """ Adjusts the width and height of the file switcher based on the relative size of the parent and content. """
# Update size of dialog based on relative size of the parent if content: width, height = self.get_item_size(content) # Width parent = self.parent() relative_width = parent.geometry().width() * 0.65 if relative_width > self.MAX_WIDTH: relative_width = self.MAX_WIDTH self.list.setMinimumWidth(relative_width) # Height if len(content) < 15: max_entries = len(content) else: max_entries = 15 max_height = height * max_entries * 1.7 self.list.setMinimumHeight(max_height) # Resize self.list.resize(relative_width, self.list.height())
<SYSTEM_TASK:> Select row in list widget based on a number of steps with direction. <END_TASK> <USER_TASK:> Description: def select_row(self, steps): """Select row in list widget based on a number of steps with direction. Steps can be positive (next rows) or negative (previous rows). """
row = self.current_row() + steps if 0 <= row < self.count(): self.set_current_row(row)
<SYSTEM_TASK:> Select previous row in list widget. <END_TASK> <USER_TASK:> Description: def previous_row(self): """Select previous row in list widget."""
if self.mode == self.SYMBOL_MODE: self.select_row(-1) return prev_row = self.current_row() - 1 if prev_row >= 0: title = self.list.item(prev_row).text() else: title = '' if prev_row == 0 and '</b></big><br>' in title: self.list.scrollToTop() elif '</b></big><br>' in title: # Select the next previous row, the one following is a title self.select_row(-2) else: self.select_row(-1)
<SYSTEM_TASK:> Select next row in list widget. <END_TASK> <USER_TASK:> Description: def next_row(self): """Select next row in list widget."""
if self.mode == self.SYMBOL_MODE: self.select_row(+1) return next_row = self.current_row() + 1 if next_row < self.count(): if '</b></big><br>' in self.list.item(next_row).text(): # Select the next next row, the one following is a title self.select_row(+2) else: self.select_row(+1)
<SYSTEM_TASK:> Get the real index of the selected item. <END_TASK> <USER_TASK:> Description: def get_stack_index(self, stack_index, plugin_index): """Get the real index of the selected item."""
other_plugins_count = sum([other_tabs[0].count() \ for other_tabs in \ self.plugins_tabs[:plugin_index]]) real_index = stack_index - other_plugins_count return real_index
<SYSTEM_TASK:> Get the data object of the plugin's current tab manager. <END_TASK> <USER_TASK:> Description: def get_plugin_data(self, plugin): """Get the data object of the plugin's current tab manager."""
# The data object is named "data" in the editor plugin while it is # named "clients" in the notebook plugin. try: data = plugin.get_current_tab_manager().data except AttributeError: data = plugin.get_current_tab_manager().clients return data
<SYSTEM_TASK:> Get the tabwidget of the plugin's current tab manager. <END_TASK> <USER_TASK:> Description: def get_plugin_tabwidget(self, plugin): """Get the tabwidget of the plugin's current tab manager."""
# The tab widget is named "tabs" in the editor plugin while it is # named "tabwidget" in the notebook plugin. try: tabwidget = plugin.get_current_tab_manager().tabs except AttributeError: tabwidget = plugin.get_current_tab_manager().tabwidget return tabwidget
<SYSTEM_TASK:> Get widget by index. <END_TASK> <USER_TASK:> Description: def get_widget(self, index=None, path=None, tabs=None): """Get widget by index. If no tabs and index specified the current active widget is returned. """
if (index and tabs) or (path and tabs): return tabs.widget(index) elif self.plugin: return self.get_plugin_tabwidget(self.plugin).currentWidget() else: return self.plugins_tabs[0][0].currentWidget()
<SYSTEM_TASK:> Set the cursor of an editor. <END_TASK> <USER_TASK:> Description: def set_editor_cursor(self, editor, cursor): """Set the cursor of an editor."""
pos = cursor.position() anchor = cursor.anchor() new_cursor = QTextCursor() if pos == anchor: new_cursor.movePosition(pos) else: new_cursor.movePosition(anchor) new_cursor.movePosition(pos, QTextCursor.KeepAnchor) editor.setTextCursor(cursor)
<SYSTEM_TASK:> Go to specified line number in current active editor. <END_TASK> <USER_TASK:> Description: def goto_line(self, line_number): """Go to specified line number in current active editor."""
if line_number: line_number = int(line_number) try: self.plugin.go_to_line(line_number) except AttributeError: pass
<SYSTEM_TASK:> Setup list widget content for symbol list display. <END_TASK> <USER_TASK:> Description: def setup_symbol_list(self, filter_text, current_path): """Setup list widget content for symbol list display."""
# Get optional symbol name filter_text, symbol_text = filter_text.split('@') # Fetch the Outline explorer data, get the icons and values oedata = self.get_symbol_list() icons = get_python_symbol_icons(oedata) # The list of paths here is needed in order to have the same # point of measurement for the list widget size as in the file list # See issue 4648 paths = self.paths # Update list size self.fix_size(paths) symbol_list = process_python_symbol_data(oedata) line_fold_token = [(item[0], item[2], item[3]) for item in symbol_list] choices = [item[1] for item in symbol_list] scores = get_search_scores(symbol_text, choices, template="<b>{0}</b>") # Build the text that will appear on the list widget results = [] lines = [] self.filtered_symbol_lines = [] for index, score in enumerate(scores): text, rich_text, score_value = score line, fold_level, token = line_fold_token[index] lines.append(text) if score_value != -1: results.append((score_value, line, text, rich_text, fold_level, icons[index], token)) template = '{{0}}<span style="color:{0}">{{1}}</span>'.format( ima.MAIN_FG_COLOR) for (score, line, text, rich_text, fold_level, icon, token) in sorted(results): fold_space = '&nbsp;'*(fold_level) line_number = line + 1 self.filtered_symbol_lines.append(line_number) textline = template.format(fold_space, rich_text) item = QListWidgetItem(icon, textline) item.setSizeHint(QSize(0, 16)) self.list.addItem(item) # To adjust the delegate layout for KDE themes self.list.files_list = False # Select edit line when using symbol search initially. # See issue 5661 self.edit.setFocus()
<SYSTEM_TASK:> Setup list widget content. <END_TASK> <USER_TASK:> Description: def setup(self): """Setup list widget content."""
if len(self.plugins_tabs) == 0: self.close() return self.list.clear() current_path = self.current_path filter_text = self.filter_text # Get optional line or symbol to define mode and method handler trying_for_symbol = ('@' in self.filter_text) if trying_for_symbol: self.mode = self.SYMBOL_MODE self.setup_symbol_list(filter_text, current_path) else: self.mode = self.FILE_MODE self.setup_file_list(filter_text, current_path) # Set position according to size self.set_dialog_position()
<SYSTEM_TASK:> Return support status dict if path is under VCS root <END_TASK> <USER_TASK:> Description: def get_vcs_info(path): """Return support status dict if path is under VCS root"""
for info in SUPPORTED: vcs_path = osp.join(path, info['rootdir']) if osp.isdir(vcs_path): return info
<SYSTEM_TASK:> Qt Override. <END_TASK> <USER_TASK:> Description: def event(self, event): """Qt Override. Filter tab keys and process double tab keys. """
if (event.type() == QEvent.KeyPress) and (event.key() == Qt.Key_Tab): self.sig_tab_pressed.emit(True) self.numpress += 1 if self.numpress == 1: self.presstimer = QTimer.singleShot(400, self.handle_keypress) return True return QComboBox.event(self, event)
<SYSTEM_TASK:> When hitting tab, it handles if single or double tab <END_TASK> <USER_TASK:> Description: def handle_keypress(self): """When hitting tab, it handles if single or double tab"""
if self.numpress == 2: self.sig_double_tab_pressed.emit(True) self.numpress = 0
<SYSTEM_TASK:> Add current text to combo box history if valid <END_TASK> <USER_TASK:> Description: def add_current_text_if_valid(self): """Add current text to combo box history if valid"""
valid = self.is_valid(self.currentText()) if valid or valid is None: self.add_current_text() return True else: self.set_current_text(self.selected_text)
<SYSTEM_TASK:> Handle focus in event restoring to display the status icon. <END_TASK> <USER_TASK:> Description: def focusInEvent(self, event): """Handle focus in event restoring to display the status icon."""
show_status = getattr(self.lineEdit(), 'show_status_icon', None) if show_status: show_status() QComboBox.focusInEvent(self, event)
<SYSTEM_TASK:> Handle focus out event restoring the last valid selected path. <END_TASK> <USER_TASK:> Description: def focusOutEvent(self, event): """Handle focus out event restoring the last valid selected path."""
# Calling asynchronously the 'add_current_text' to avoid crash # https://groups.google.com/group/spyderlib/browse_thread/thread/2257abf530e210bd if not self.is_valid(): lineedit = self.lineEdit() QTimer.singleShot(50, lambda: lineedit.setText(self.selected_text)) hide_status = getattr(self.lineEdit(), 'hide_status_icon', None) if hide_status: hide_status() QComboBox.focusOutEvent(self, event)
<SYSTEM_TASK:> Find available completion options. <END_TASK> <USER_TASK:> Description: def _complete_options(self): """Find available completion options."""
text = to_text_string(self.currentText()) opts = glob.glob(text + "*") opts = sorted([opt for opt in opts if osp.isdir(opt)]) self.setCompleter(QCompleter(opts, self)) return opts
<SYSTEM_TASK:> If several options available a double tab displays options. <END_TASK> <USER_TASK:> Description: def double_tab_complete(self): """If several options available a double tab displays options."""
opts = self._complete_options() if len(opts) > 1: self.completer().complete()
<SYSTEM_TASK:> If there is a single option available one tab completes the option. <END_TASK> <USER_TASK:> Description: def tab_complete(self): """ If there is a single option available one tab completes the option. """
opts = self._complete_options() if len(opts) == 1: self.set_current_text(opts[0] + os.sep) self.hide_completer()
<SYSTEM_TASK:> Add a tooltip showing the full path of the currently highlighted item <END_TASK> <USER_TASK:> Description: def add_tooltip_to_highlighted_item(self, index): """ Add a tooltip showing the full path of the currently highlighted item of the PathComboBox. """
self.setItemData(index, self.itemText(index), Qt.ToolTipRole)
<SYSTEM_TASK:> Bind historylog instance to this console <END_TASK> <USER_TASK:> Description: def set_historylog(self, historylog): """Bind historylog instance to this console Not used anymore since v2.0"""
historylog.add_history(self.shell.history_filename) self.shell.append_to_history.connect(historylog.append_to_history)
<SYSTEM_TASK:> Exception ocurred in the internal console. <END_TASK> <USER_TASK:> Description: def exception_occurred(self, text, is_traceback): """ Exception ocurred in the internal console. Show a QDialog or the internal console to warn the user. """
# Skip errors without traceback or dismiss if (not is_traceback and self.error_dlg is None) or self.dismiss_error: return if CONF.get('main', 'show_internal_errors'): if self.error_dlg is None: self.error_dlg = SpyderErrorDialog(self) self.error_dlg.close_btn.clicked.connect(self.close_error_dlg) self.error_dlg.rejected.connect(self.remove_error_dlg) self.error_dlg.details.go_to_error.connect(self.go_to_error) self.error_dlg.show() self.error_dlg.append_traceback(text) elif DEV or get_debug_level(): self.dockwidget.show() self.dockwidget.raise_()
<SYSTEM_TASK:> Execute lines and give focus to shell <END_TASK> <USER_TASK:> Description: def execute_lines(self, lines): """Execute lines and give focus to shell"""
self.shell.execute_lines(to_text_string(lines)) self.shell.setFocus()
<SYSTEM_TASK:> Function executed when running the script with the -install switch <END_TASK> <USER_TASK:> Description: def install(): """Function executed when running the script with the -install switch"""
# Create Spyder start menu folder # Don't use CSIDL_COMMON_PROGRAMS because it requres admin rights # This is consistent with use of CSIDL_DESKTOPDIRECTORY below # CSIDL_COMMON_PROGRAMS = # C:\ProgramData\Microsoft\Windows\Start Menu\Programs # CSIDL_PROGRAMS = # C:\Users\<username>\AppData\Roaming\Microsoft\Windows\Start Menu\Programs start_menu = osp.join(get_special_folder_path('CSIDL_PROGRAMS'), 'Spyder (Py%i.%i %i bit)' % (sys.version_info[0], sys.version_info[1], struct.calcsize('P')*8)) if not osp.isdir(start_menu): os.mkdir(start_menu) directory_created(start_menu) # Create Spyder start menu entries python = osp.abspath(osp.join(sys.prefix, 'python.exe')) pythonw = osp.abspath(osp.join(sys.prefix, 'pythonw.exe')) script = osp.abspath(osp.join(sys.prefix, 'scripts', 'spyder')) if not osp.exists(script): # if not installed to the site scripts dir script = osp.abspath(osp.join(osp.dirname(osp.abspath(__file__)), 'spyder')) workdir = "%HOMEDRIVE%%HOMEPATH%" import distutils.sysconfig lib_dir = distutils.sysconfig.get_python_lib(plat_specific=1) ico_dir = osp.join(lib_dir, 'spyder', 'windows') # if user is running -install manually then icons are in Scripts/ if not osp.isdir(ico_dir): ico_dir = osp.dirname(osp.abspath(__file__)) desc = 'The Scientific Python Development Environment' fname = osp.join(start_menu, 'Spyder (full).lnk') create_shortcut(python, desc, fname, '"%s"' % script, workdir, osp.join(ico_dir, 'spyder.ico')) file_created(fname) fname = osp.join(start_menu, 'Spyder-Reset all settings.lnk') create_shortcut(python, 'Reset Spyder settings to defaults', fname, '"%s" --reset' % script, workdir) file_created(fname) current = True # only affects current user root = winreg.HKEY_CURRENT_USER if current else winreg.HKEY_LOCAL_MACHINE winreg.SetValueEx(winreg.CreateKey(root, KEY_C1 % ("", EWS)), "", 0, winreg.REG_SZ, '"%s" "%s\Scripts\spyder" "%%1"' % (pythonw, sys.prefix)) winreg.SetValueEx(winreg.CreateKey(root, KEY_C1 % ("NoCon", EWS)), "", 0, winreg.REG_SZ, '"%s" "%s\Scripts\spyder" "%%1"' % (pythonw, sys.prefix)) # Create desktop shortcut file desktop_folder = get_special_folder_path("CSIDL_DESKTOPDIRECTORY") fname = osp.join(desktop_folder, 'Spyder.lnk') desc = 'The Scientific Python Development Environment' create_shortcut(pythonw, desc, fname, '"%s"' % script, workdir, osp.join(ico_dir, 'spyder.ico')) file_created(fname)
<SYSTEM_TASK:> Function executed when running the script with the -remove switch <END_TASK> <USER_TASK:> Description: def remove(): """Function executed when running the script with the -remove switch"""
current = True # only affects current user root = winreg.HKEY_CURRENT_USER if current else winreg.HKEY_LOCAL_MACHINE for key in (KEY_C1 % ("", EWS), KEY_C1 % ("NoCon", EWS), KEY_C0 % ("", EWS), KEY_C0 % ("NoCon", EWS)): try: winreg.DeleteKey(root, key) except WindowsError: pass else: if not is_bdist_wininst: print("Successfully removed Spyder shortcuts from Windows "\ "Explorer context menu.", file=sys.stdout) if not is_bdist_wininst: # clean up desktop desktop_folder = get_special_folder_path("CSIDL_DESKTOPDIRECTORY") fname = osp.join(desktop_folder, 'Spyder.lnk') if osp.isfile(fname): try: os.remove(fname) except OSError: print("Failed to remove %s; you may be able to remove it "\ "manually." % fname, file=sys.stderr) else: print("Successfully removed Spyder shortcuts from your desktop.", file=sys.stdout) # clean up startmenu start_menu = osp.join(get_special_folder_path('CSIDL_PROGRAMS'), 'Spyder (Py%i.%i %i bit)' % (sys.version_info[0], sys.version_info[1], struct.calcsize('P')*8)) if osp.isdir(start_menu): for fname in os.listdir(start_menu): try: os.remove(osp.join(start_menu,fname)) except OSError: print("Failed to remove %s; you may be able to remove it "\ "manually." % fname, file=sys.stderr) else: print("Successfully removed Spyder shortcuts from your "\ " start menu.", file=sys.stdout) try: os.rmdir(start_menu) except OSError: print("Failed to remove %s; you may be able to remove it "\ "manually." % fname, file=sys.stderr) else: print("Successfully removed Spyder shortcut folder from your "\ " start menu.", file=sys.stdout)
<SYSTEM_TASK:> Set data that is displayed in each step of the tour. <END_TASK> <USER_TASK:> Description: def _set_data(self): """Set data that is displayed in each step of the tour."""
self.setting_data = True step, steps, frames = self.step_current, self.steps, self.frames current = '{0}/{1}'.format(step + 1, steps) frame = frames[step] combobox_frames = [u"{0}. {1}".format(i+1, f['title']) for i, f in enumerate(frames)] title, content, image = '', '', None widgets, dockwidgets, decoration = None, None, None run = None # Check if entry exists in dic and act accordingly if 'title' in frame: title = frame['title'] if 'content' in frame: content = frame['content'] if 'widgets' in frame: widget_names = frames[step]['widgets'] # Get the widgets based on their name widgets, dockwidgets = self._process_widgets(widget_names, self.spy_window) self.widgets = widgets self.dockwidgets = dockwidgets if 'decoration' in frame: widget_names = frames[step]['decoration'] deco, decoration = self._process_widgets(widget_names, self.spy_window) self.decoration = decoration if 'image' in frame: image = frames[step]['image'] if 'interact' in frame: self.canvas.set_interaction(frame['interact']) if frame['interact']: self._set_modal(False, [self.tips]) else: self._set_modal(True, [self.tips]) else: self.canvas.set_interaction(False) self._set_modal(True, [self.tips]) if 'run' in frame: # Asume that the frist widget is the console run = frame['run'] self.run = run self.tips.set_data(title, content, current, image, run, frames=combobox_frames, step=step) self._check_buttons() # Make canvas black when starting a new place of decoration self.canvas.update_widgets(dockwidgets) self.canvas.update_decoration(decoration) self.setting_data = False
<SYSTEM_TASK:> Confirm if the tour loses focus and hides the tips. <END_TASK> <USER_TASK:> Description: def lost_focus(self): """Confirm if the tour loses focus and hides the tips."""
if (self.is_running and not self.any_has_focus() and not self.setting_data and not self.hidden): self.hide_tips()
<SYSTEM_TASK:> Confirm if the tour regains focus and unhides the tips. <END_TASK> <USER_TASK:> Description: def gain_focus(self): """Confirm if the tour regains focus and unhides the tips."""
if (self.is_running and self.any_has_focus() and not self.setting_data and self.hidden): self.unhide_tips()
<SYSTEM_TASK:> Returns if tour or any of its components has focus. <END_TASK> <USER_TASK:> Description: def any_has_focus(self): """Returns if tour or any of its components has focus."""
f = (self.hasFocus() or self.parent.hasFocus() or self.tips.hasFocus() or self.canvas.hasFocus()) return f
<SYSTEM_TASK:> Reimplemented to handle communications between the figure explorer <END_TASK> <USER_TASK:> Description: def _handle_display_data(self, msg): """ Reimplemented to handle communications between the figure explorer and the kernel. """
img = None data = msg['content']['data'] if 'image/svg+xml' in data: fmt = 'image/svg+xml' img = data['image/svg+xml'] elif 'image/png' in data: # PNG data is base64 encoded as it passes over the network # in a JSON structure so we decode it. fmt = 'image/png' img = decodestring(data['image/png'].encode('ascii')) elif 'image/jpeg' in data and self._jpg_supported: fmt = 'image/jpeg' img = decodestring(data['image/jpeg'].encode('ascii')) if img is not None: self.sig_new_inline_figure.emit(img, fmt) if (self.figurebrowser is not None and self.figurebrowser.mute_inline_plotting): if not self.sended_render_message: msg['content']['data']['text/plain'] = '' self._append_html( _('<br><hr>' '\nFigures now render in the Plots pane by default. ' 'To make them also appear inline in the Console, ' 'uncheck "Mute Inline Plotting" under the Plots ' 'pane options menu. \n' '<hr><br>'), before_prompt=True) self.sended_render_message = True else: msg['content']['data']['text/plain'] = '' del msg['content']['data'][fmt] return super(FigureBrowserWidget, self)._handle_display_data(msg)
<SYSTEM_TASK:> Line edit's text has changed <END_TASK> <USER_TASK:> Description: def text_has_changed(self, text): """Line edit's text has changed"""
text = to_text_string(text) if text: self.lineno = int(text) else: self.lineno = None
<SYSTEM_TASK:> Save fig to fname in the format specified by fmt. <END_TASK> <USER_TASK:> Description: def save_figure_tofile(fig, fmt, fname): """Save fig to fname in the format specified by fmt."""
root, ext = osp.splitext(fname) if ext == '.png' and fmt == 'image/svg+xml': qimg = svg_to_image(fig) qimg.save(fname) else: if fmt == 'image/svg+xml' and is_unicode(fig): fig = fig.encode('utf-8') with open(fname, 'wb') as f: f.write(fig)
<SYSTEM_TASK:> Append a number to "root" to form a filename that does not already exist <END_TASK> <USER_TASK:> Description: def get_unique_figname(dirname, root, ext): """ Append a number to "root" to form a filename that does not already exist in "dirname". """
i = 1 figname = root + '_%d' % i + ext while True: if osp.exists(osp.join(dirname, figname)): i += 1 figname = root + '_%d' % i + ext else: return osp.join(dirname, figname)
<SYSTEM_TASK:> Setup the figure browser with provided settings. <END_TASK> <USER_TASK:> Description: def setup(self, mute_inline_plotting=None, show_plot_outline=None): """Setup the figure browser with provided settings."""
assert self.shellwidget is not None self.mute_inline_plotting = mute_inline_plotting self.show_plot_outline = show_plot_outline if self.figviewer is not None: self.mute_inline_action.setChecked(mute_inline_plotting) self.show_plot_outline_action.setChecked(show_plot_outline) return self.figviewer = FigureViewer(background_color=self.background_color) self.figviewer.setStyleSheet("FigureViewer{" "border: 1px solid lightgrey;" "border-top-width: 0px;" "border-bottom-width: 0px;" "border-left-width: 0px;" "}") self.thumbnails_sb = ThumbnailScrollBar( self.figviewer, background_color=self.background_color) # Option actions : self.setup_option_actions(mute_inline_plotting, show_plot_outline) # Create the layout : main_widget = QSplitter() main_widget.addWidget(self.figviewer) main_widget.addWidget(self.thumbnails_sb) main_widget.setFrameStyle(QScrollArea().frameStyle()) self.tools_layout = QHBoxLayout() toolbar = self.setup_toolbar() for widget in toolbar: self.tools_layout.addWidget(widget) self.tools_layout.addStretch() self.setup_options_button() layout = create_plugin_layout(self.tools_layout, main_widget) self.setLayout(layout)
<SYSTEM_TASK:> Create shortcuts for this widget. <END_TASK> <USER_TASK:> Description: def create_shortcuts(self): """Create shortcuts for this widget."""
# Configurable copyfig = config_shortcut(self.copy_figure, context='plots', name='copy', parent=self) prevfig = config_shortcut(self.go_previous_thumbnail, context='plots', name='previous figure', parent=self) nextfig = config_shortcut(self.go_next_thumbnail, context='plots', name='next figure', parent=self) return [copyfig, prevfig, nextfig]
<SYSTEM_TASK:> Handle when the value of an option has changed <END_TASK> <USER_TASK:> Description: def option_changed(self, option, value): """Handle when the value of an option has changed"""
setattr(self, to_text_string(option), value) self.shellwidget.set_namespace_view_settings() if self.setup_in_progress is False: self.sig_option_changed.emit(option, value)
<SYSTEM_TASK:> Draw a frame around the figure viewer if state is True. <END_TASK> <USER_TASK:> Description: def show_fig_outline_in_viewer(self, state): """Draw a frame around the figure viewer if state is True."""
if state is True: self.figviewer.figcanvas.setStyleSheet( "FigureCanvas{border: 1px solid lightgrey;}") else: self.figviewer.figcanvas.setStyleSheet("FigureCanvas{}") self.option_changed('show_plot_outline', state)
<SYSTEM_TASK:> Bind the shellwidget instance to the figure browser <END_TASK> <USER_TASK:> Description: def set_shellwidget(self, shellwidget): """Bind the shellwidget instance to the figure browser"""
self.shellwidget = shellwidget shellwidget.set_figurebrowser(self) shellwidget.sig_new_inline_figure.connect(self._handle_new_figure)
<SYSTEM_TASK:> Copy figure from figviewer to clipboard. <END_TASK> <USER_TASK:> Description: def copy_figure(self): """Copy figure from figviewer to clipboard."""
if self.figviewer and self.figviewer.figcanvas.fig: self.figviewer.figcanvas.copy_figure()
<SYSTEM_TASK:> Set a new figure in the figure canvas. <END_TASK> <USER_TASK:> Description: def load_figure(self, fig, fmt): """Set a new figure in the figure canvas."""
self.figcanvas.load_figure(fig, fmt) self.scale_image() self.figcanvas.repaint()
<SYSTEM_TASK:> A filter to control the zooming and panning of the figure canvas. <END_TASK> <USER_TASK:> Description: def eventFilter(self, widget, event): """A filter to control the zooming and panning of the figure canvas."""
# ---- Zooming if event.type() == QEvent.Wheel: modifiers = QApplication.keyboardModifiers() if modifiers == Qt.ControlModifier: if event.angleDelta().y() > 0: self.zoom_in() else: self.zoom_out() return True else: return False # ---- Panning # Set ClosedHandCursor: elif event.type() == QEvent.MouseButtonPress: if event.button() == Qt.LeftButton: QApplication.setOverrideCursor(Qt.ClosedHandCursor) self._ispanning = True self.xclick = event.globalX() self.yclick = event.globalY() # Reset Cursor: elif event.type() == QEvent.MouseButtonRelease: QApplication.restoreOverrideCursor() self._ispanning = False # Move ScrollBar: elif event.type() == QEvent.MouseMove: if self._ispanning: dx = self.xclick - event.globalX() self.xclick = event.globalX() dy = self.yclick - event.globalY() self.yclick = event.globalY() scrollBarH = self.horizontalScrollBar() scrollBarH.setValue(scrollBarH.value() + dx) scrollBarV = self.verticalScrollBar() scrollBarV.setValue(scrollBarV.value() + dy) return QWidget.eventFilter(self, widget, event)
<SYSTEM_TASK:> Scale the image up by one scale step. <END_TASK> <USER_TASK:> Description: def zoom_in(self): """Scale the image up by one scale step."""
if self._scalefactor <= self._sfmax: self._scalefactor += 1 self.scale_image() self._adjust_scrollbar(self._scalestep) self.sig_zoom_changed.emit(self.get_scaling())
<SYSTEM_TASK:> Scale the image down by one scale step. <END_TASK> <USER_TASK:> Description: def zoom_out(self): """Scale the image down by one scale step."""
if self._scalefactor >= self._sfmin: self._scalefactor -= 1 self.scale_image() self._adjust_scrollbar(1/self._scalestep) self.sig_zoom_changed.emit(self.get_scaling())
<SYSTEM_TASK:> Adjust the scrollbar position to take into account the zooming of <END_TASK> <USER_TASK:> Description: def _adjust_scrollbar(self, f): """ Adjust the scrollbar position to take into account the zooming of the figure. """
# Adjust horizontal scrollbar : hb = self.horizontalScrollBar() hb.setValue(int(f * hb.value() + ((f - 1) * hb.pageStep()/2))) # Adjust the vertical scrollbar : vb = self.verticalScrollBar() vb.setValue(int(f * vb.value() + ((f - 1) * vb.pageStep()/2)))
<SYSTEM_TASK:> Setup the scrollarea that will contain the FigureThumbnails. <END_TASK> <USER_TASK:> Description: def setup_scrollarea(self): """Setup the scrollarea that will contain the FigureThumbnails."""
self.view = QWidget() self.scene = QGridLayout(self.view) self.scene.setColumnStretch(0, 100) self.scene.setColumnStretch(2, 100) self.scrollarea = QScrollArea() self.scrollarea.setWidget(self.view) self.scrollarea.setWidgetResizable(True) self.scrollarea.setFrameStyle(0) self.scrollarea.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.scrollarea.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.scrollarea.setSizePolicy(QSizePolicy(QSizePolicy.Ignored, QSizePolicy.Preferred)) # Set the vertical scrollbar explicitely : # This is required to avoid a "RuntimeError: no access to protected # functions or signals for objects not created from Python" in Linux. self.scrollarea.setVerticalScrollBar(QScrollBar()) return self.scrollarea
<SYSTEM_TASK:> Setup the up and down arrow buttons that are placed at the top and <END_TASK> <USER_TASK:> Description: def setup_arrow_buttons(self): """ Setup the up and down arrow buttons that are placed at the top and bottom of the scrollarea. """
# Get the height of the up/down arrow of the default vertical # scrollbar : vsb = self.scrollarea.verticalScrollBar() style = vsb.style() opt = QStyleOptionSlider() vsb.initStyleOption(opt) vsb_up_arrow = style.subControlRect( QStyle.CC_ScrollBar, opt, QStyle.SC_ScrollBarAddLine, self) # Setup the up and down arrow button : up_btn = up_btn = QPushButton(icon=ima.icon('last_edit_location')) up_btn.setFlat(True) up_btn.setFixedHeight(vsb_up_arrow.size().height()) up_btn.clicked.connect(self.go_up) down_btn = QPushButton(icon=ima.icon('folding.arrow_down_on')) down_btn.setFlat(True) down_btn.setFixedHeight(vsb_up_arrow.size().height()) down_btn.clicked.connect(self.go_down) return up_btn, down_btn
<SYSTEM_TASK:> Save all the figures to a file. <END_TASK> <USER_TASK:> Description: def save_all_figures_as(self): """Save all the figures to a file."""
self.redirect_stdio.emit(False) dirname = getexistingdirectory(self, caption='Save all figures', basedir=getcwd_or_home()) self.redirect_stdio.emit(True) if dirname: return self.save_all_figures_todir(dirname)
<SYSTEM_TASK:> Save the currently selected figure. <END_TASK> <USER_TASK:> Description: def save_current_figure_as(self): """Save the currently selected figure."""
if self.current_thumbnail is not None: self.save_figure_as(self.current_thumbnail.canvas.fig, self.current_thumbnail.canvas.fmt)
<SYSTEM_TASK:> Save the figure to a file. <END_TASK> <USER_TASK:> Description: def save_figure_as(self, fig, fmt): """Save the figure to a file."""
fext, ffilt = { 'image/png': ('.png', 'PNG (*.png)'), 'image/jpeg': ('.jpg', 'JPEG (*.jpg;*.jpeg;*.jpe;*.jfif)'), 'image/svg+xml': ('.svg', 'SVG (*.svg);;PNG (*.png)')}[fmt] figname = get_unique_figname(getcwd_or_home(), 'Figure', fext) self.redirect_stdio.emit(False) fname, fext = getsavefilename( parent=self.parent(), caption='Save Figure', basedir=figname, filters=ffilt, selectedfilter='', options=None) self.redirect_stdio.emit(True) if fname: save_figure_tofile(fig, fmt, fname)
<SYSTEM_TASK:> Set the currently selected thumbnail. <END_TASK> <USER_TASK:> Description: def set_current_thumbnail(self, thumbnail): """Set the currently selected thumbnail."""
self.current_thumbnail = thumbnail self.figure_viewer.load_figure( thumbnail.canvas.fig, thumbnail.canvas.fmt) for thumbnail in self._thumbnails: thumbnail.highlight_canvas(thumbnail == self.current_thumbnail)
<SYSTEM_TASK:> Select the thumbnail previous to the currently selected one. <END_TASK> <USER_TASK:> Description: def go_previous_thumbnail(self): """Select the thumbnail previous to the currently selected one."""
if self.current_thumbnail is not None: index = self._thumbnails.index(self.current_thumbnail) - 1 index = index if index >= 0 else len(self._thumbnails) - 1 self.set_current_index(index) self.scroll_to_item(index)
<SYSTEM_TASK:> Select thumbnail next to the currently selected one. <END_TASK> <USER_TASK:> Description: def go_next_thumbnail(self): """Select thumbnail next to the currently selected one."""
if self.current_thumbnail is not None: index = self._thumbnails.index(self.current_thumbnail) + 1 index = 0 if index >= len(self._thumbnails) else index self.set_current_index(index) self.scroll_to_item(index)
<SYSTEM_TASK:> Scroll to the selected item of ThumbnailScrollBar. <END_TASK> <USER_TASK:> Description: def scroll_to_item(self, index): """Scroll to the selected item of ThumbnailScrollBar."""
spacing_between_items = self.scene.verticalSpacing() height_view = self.scrollarea.viewport().height() height_item = self.scene.itemAt(index).sizeHint().height() height_view_excluding_item = max(0, height_view - height_item) height_of_top_items = spacing_between_items for i in range(index): item = self.scene.itemAt(i) height_of_top_items += item.sizeHint().height() height_of_top_items += spacing_between_items pos_scroll = height_of_top_items - height_view_excluding_item // 2 vsb = self.scrollarea.verticalScrollBar() vsb.setValue(pos_scroll)
<SYSTEM_TASK:> Scroll the scrollbar of the scrollarea up by a single step. <END_TASK> <USER_TASK:> Description: def go_up(self): """Scroll the scrollbar of the scrollarea up by a single step."""
vsb = self.scrollarea.verticalScrollBar() vsb.setValue(int(vsb.value() - vsb.singleStep()))
<SYSTEM_TASK:> Set a colored frame around the FigureCanvas if highlight is True. <END_TASK> <USER_TASK:> Description: def highlight_canvas(self, highlight): """ Set a colored frame around the FigureCanvas if highlight is True. """
colorname = self.canvas.palette().highlight().color().name() if highlight: self.canvas.setStyleSheet( "FigureCanvas{border: 1px solid %s;}" % colorname) else: self.canvas.setStyleSheet("FigureCanvas{}")
<SYSTEM_TASK:> A filter that is used to send a signal when the figure canvas is <END_TASK> <USER_TASK:> Description: def eventFilter(self, widget, event): """ A filter that is used to send a signal when the figure canvas is clicked. """
if event.type() == QEvent.MouseButtonPress: if event.button() == Qt.LeftButton: self.sig_canvas_clicked.emit(self) return super(FigureThumbnail, self).eventFilter(widget, event)
<SYSTEM_TASK:> Emit a signal when the toolbutton to save the figure is clicked. <END_TASK> <USER_TASK:> Description: def emit_save_figure(self): """ Emit a signal when the toolbutton to save the figure is clicked. """
self.sig_save_figure.emit(self.canvas.fig, self.canvas.fmt)
<SYSTEM_TASK:> Clear the figure that was painted on the widget. <END_TASK> <USER_TASK:> Description: def clear_canvas(self): """Clear the figure that was painted on the widget."""
self.fig = None self.fmt = None self._qpix_buffer = [] self.repaint()
<SYSTEM_TASK:> Load the figure from a png, jpg, or svg image, convert it in <END_TASK> <USER_TASK:> Description: def load_figure(self, fig, fmt): """ Load the figure from a png, jpg, or svg image, convert it in a QPixmap, and force a repaint of the widget. """
self.fig = fig self.fmt = fmt if fmt in ['image/png', 'image/jpeg']: self._qpix_orig = QPixmap() self._qpix_orig.loadFromData(fig, fmt.upper()) elif fmt == 'image/svg+xml': self._qpix_orig = QPixmap(svg_to_image(fig)) self._qpix_buffer = [self._qpix_orig] self.fwidth = self._qpix_orig.width() self.fheight = self._qpix_orig.height()
<SYSTEM_TASK:> Qt method override to paint a custom image on the Widget. <END_TASK> <USER_TASK:> Description: def paintEvent(self, event): """Qt method override to paint a custom image on the Widget."""
super(FigureCanvas, self).paintEvent(event) # Prepare the rect on which the image is going to be painted : fw = self.frameWidth() rect = QRect(0 + fw, 0 + fw, self.size().width() - 2 * fw, self.size().height() - 2 * fw) if self.fig is None or self._blink_flag: return # Check/update the qpixmap buffer : qpix2paint = None for qpix in self._qpix_buffer: if qpix.size().width() == rect.width(): qpix2paint = qpix break else: if self.fmt in ['image/png', 'image/jpeg']: qpix2paint = self._qpix_orig.scaledToWidth( rect.width(), mode=Qt.SmoothTransformation) elif self.fmt == 'image/svg+xml': qpix2paint = QPixmap(svg_to_image(self.fig, rect.size())) self._qpix_buffer.append(qpix2paint) if qpix2paint is not None: # Paint the image on the widget : qp = QPainter() qp.begin(self) qp.drawPixmap(rect, qpix2paint) qp.end()
<SYSTEM_TASK:> Custom Python executable value has been changed <END_TASK> <USER_TASK:> Description: def python_executable_changed(self, pyexec): """Custom Python executable value has been changed"""
if not self.cus_exec_radio.isChecked(): return False def_pyexec = get_python_executable() if not is_text_string(pyexec): pyexec = to_text_string(pyexec.toUtf8(), 'utf-8') if pyexec == def_pyexec: return False if (not programs.is_python_interpreter(pyexec) or not self.warn_python_compatibility(pyexec)): QMessageBox.warning(self, _('Warning'), _("You selected an invalid Python interpreter for the " "console so the previous interpreter will stay. Please " "make sure to select a valid one."), QMessageBox.Ok) self.def_exec_radio.setChecked(True) return False return True
<SYSTEM_TASK:> Set UMR excluded modules name list <END_TASK> <USER_TASK:> Description: def set_umr_namelist(self): """Set UMR excluded modules name list"""
arguments, valid = QInputDialog.getText(self, _('UMR'), _("Set the list of excluded modules as " "this: <i>numpy, scipy</i>"), QLineEdit.Normal, ", ".join(self.get_option('umr/namelist'))) if valid: arguments = to_text_string(arguments) if arguments: namelist = arguments.replace(' ', '').split(',') fixed_namelist = [] non_ascii_namelist = [] for module_name in namelist: if PY2: if all(ord(c) < 128 for c in module_name): if programs.is_module_installed(module_name): fixed_namelist.append(module_name) else: QMessageBox.warning(self, _('Warning'), _("You are working with Python 2, this means that " "you can not import a module that contains non-" "ascii characters."), QMessageBox.Ok) non_ascii_namelist.append(module_name) elif programs.is_module_installed(module_name): fixed_namelist.append(module_name) invalid = ", ".join(set(namelist)-set(fixed_namelist)- set(non_ascii_namelist)) if invalid: QMessageBox.warning(self, _('UMR'), _("The following modules are not " "installed on your machine:\n%s" ) % invalid, QMessageBox.Ok) QMessageBox.information(self, _('UMR'), _("Please note that these changes will " "be applied only to new Python/IPython " "consoles"), QMessageBox.Ok) else: fixed_namelist = [] self.set_option('umr/namelist', fixed_namelist)
<SYSTEM_TASK:> Update the list of interpreters used and the current one. <END_TASK> <USER_TASK:> Description: def set_custom_interpreters_list(self, value): """Update the list of interpreters used and the current one."""
custom_list = self.get_option('custom_interpreters_list') if value not in custom_list and value != get_python_executable(): custom_list.append(value) self.set_option('custom_interpreters_list', custom_list)