text
stringlengths
81
112k
Select next row in list widget. 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(...
Get the real index of the selected item. 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[:p...
Get the data object of the plugin's current tab manager. 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 =...
Get the tabwidget of the plugin's current tab manager. 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: tabw...
Get widget by index. If no tabs and index specified the current active widget is returned. 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...
Set the cursor of an editor. 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_curs...
Go to specified line number in current active editor. 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 Attribut...
List widget item selection change handler. def item_selection_changed(self): """List widget item selection change handler.""" row = self.current_row() if self.count() and row >= 0: if '</b></big><br>' in self.list.currentItem().text() and row == 0: self.next_row() ...
Setup list widget content for file list display. def setup_file_list(self, filter_text, current_path): """Setup list widget content for file list display.""" short_paths = shorten_paths(self.paths, self.save_status) paths = self.paths icons = self.icons results = [] tryi...
Setup list widget content for symbol list display. 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 ic...
Setup list widget content. 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 d...
Add a plugin to display its files. def add_plugin(self, plugin, tabs, data, icon): """Add a plugin to display its files.""" self.plugins_tabs.append((tabs, plugin)) self.plugins_data.append((data, icon)) self.plugins_instances.append(plugin)
:param filename: File to check. :returns: True if it's a binary file, otherwise False. def is_binary(filename): """ :param filename: File to check. :returns: True if it's a binary file, otherwise False. """ logger.debug('is_binary: %(filename)r', locals()) # Check if the file extension is ...
Return support status dict if path is under VCS root 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
Return VCS root directory path Return None if path is not within a supported VCS repository def get_vcs_root(path): """Return VCS root directory path Return None if path is not within a supported VCS repository""" previous_path = path while get_vcs_info(path) is None: path = abspardir...
If path is a valid VCS repository, run the corresponding VCS tool Supported VCS actions: 'commit', 'browse' Return False if the VCS tool is not installed def run_vcs_tool(path, action): """If path is a valid VCS repository, run the corresponding VCS tool Supported VCS actions: 'commit', 'browse' ...
Return Mercurial revision for the repository located at repopath Result is a tuple (global, local, branch), with None values on error For example: >>> get_hg_revision(".") ('eba7273c69df+', '2015+', 'default') def get_hg_revision(repopath): """Return Mercurial revision for ...
Return Git revision for the repository located at repopath Result is a tuple (latest commit hash, branch), with None values on error def get_git_revision(repopath): """ Return Git revision for the repository located at repopath Result is a tuple (latest commit hash, branch), with N...
Return Git active branch, state, branches (plus tags). def get_git_refs(repopath): """ Return Git active branch, state, branches (plus tags). """ tags = [] branches = [] branch = '' files_modifed = [] if os.path.isfile(repopath): repopath = os.path.dirname(repopath) ...
Return True if path is a Python module/package def is_module_or_package(path): """Return True if path is a Python module/package""" is_module = osp.isfile(path) and osp.splitext(path)[1] in ('.py', '.pyw') is_package = osp.isdir(path) and osp.isfile(osp.join(path, '__init__.py')) return is_module o...
Qt Override. Filter tab keys and process double tab keys. 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) ...
Qt Override. Handle key press events. def keyPressEvent(self, event): """Qt Override. Handle key press events. """ if event.key() == Qt.Key_Return or event.key() == Qt.Key_Enter: if self.add_current_text_if_valid(): self.selected() ...
When hitting tab, it handles if single or double tab 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
Add text to combo box: add a new item if text is not found in combo box items. def add_text(self, text): """Add text to combo box: add a new item if text is not found in combo box items.""" index = self.findText(text) while index != -1: self.removeItem(index) ...
Add current text to combo box history if valid 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: ...
Show tip def show_tip(self, tip=""): """Show tip""" QToolTip.showText(self.mapToGlobal(self.pos()), tip, self)
Validate entered path def validate(self, qstr, editing=True): """Validate entered path""" if self.selected_text == qstr and qstr != '': self.valid.emit(True, True) return valid = self.is_valid(qstr) if editing: if valid: self...
Handle focus in event restoring to display the status icon. 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.focusInE...
Handle focus out event restoring the last valid selected path. 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/...
Find available completion options. 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)) ...
If several options available a double tab displays options. 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()
If there is a single option available one tab completes the option. 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) ...
Return True if string is valid def is_valid(self, qstr=None): """Return True if string is valid""" if qstr is None: qstr = self.currentText() return osp.isdir(to_text_string(qstr))
Action to be executed when a valid item has been selected def selected(self): """Action to be executed when a valid item has been selected""" self.selected_text = self.currentText() self.valid.emit(True, True) self.open_dir.emit(self.selected_text)
Add current text to combo box history (convenient method). If path ends in os separator ("\" windows, "/" unix) remove it. def add_current_text(self): """ Add current text to combo box history (convenient method). If path ends in os separator ("\" windows, "/" unix) remove it. ...
Add a tooltip showing the full path of the currently highlighted item of the PathComboBox. 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, s...
Return True if string is valid def is_valid(self, qstr=None): """Return True if string is valid""" if qstr is None: qstr = self.currentText() return QUrl(qstr).isValid()
Return True if string is valid def is_valid(self, qstr=None): """Return True if string is valid""" if qstr is None: qstr = self.currentText() return osp.isfile(to_text_string(qstr))
Return True if string is valid def is_valid(self, qstr=None): """Return True if string is valid""" if qstr is None: qstr = self.currentText() return is_module_or_package(to_text_string(qstr))
Action to be executed when a valid item has been selected def selected(self): """Action to be executed when a valid item has been selected""" EditableComboBox.selected(self) self.open_dir.emit(self.currentText())
Bind historylog instance to this console Not used anymore since v2.0 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(his...
Perform actions before parent main window is closed def closing_plugin(self, cancelable=False): """Perform actions before parent main window is closed""" self.dialog_manager.close_all() self.shell.exit_interpreter() return True
Return a list of actions related to plugin def get_plugin_actions(self): """Return a list of actions related to plugin""" quit_action = create_action(self, _("&Quit"), icon=ima.icon('exit'), tip=_("Quit"), ...
Register plugin in Spyder's main window def register_plugin(self): """Register plugin in Spyder's main window""" self.focus_changed.connect(self.main.plugin_focus_changed) self.main.add_dockwidget(self) # Connecting the following signal once the dockwidget has been created: ...
Exception ocurred in the internal console. Show a QDialog or the internal console to warn the user. def exception_occurred(self, text, is_traceback): """ Exception ocurred in the internal console. Show a QDialog or the internal console to warn the user. """ # S...
Close error dialog. def close_error_dlg(self): """Close error dialog.""" if self.error_dlg.dismiss_box.isChecked(): self.dismiss_error = True self.error_dlg.reject()
Show sys.path def show_syspath(self): """Show sys.path""" editor = CollectionsEditor(parent=self) editor.setup(sys.path, title="sys.path", readonly=True, width=600, icon=ima.icon('syspath')) self.dialog_manager.show(editor)
Run a Python script def run_script(self, filename=None, silent=False, set_focus=False, args=None): """Run a Python script""" if filename is None: self.shell.interpreter.restore_stds() filename, _selfilter = getopenfilename( self, _("R...
Go to error if relevant def go_to_error(self, text): """Go to error if relevant""" match = get_error_match(to_text_string(text)) if match: fname, lnb = match.groups() self.edit_script(fname, int(lnb))
Edit script def edit_script(self, filename=None, goto=-1): """Edit script""" # Called from InternalShell if not hasattr(self, 'main') \ or not hasattr(self.main, 'editor'): self.shell.external_editor(filename, goto) return if filename is not Non...
Execute lines and give focus to shell def execute_lines(self, lines): """Execute lines and give focus to shell""" self.shell.execute_lines(to_text_string(lines)) self.shell.setFocus()
Change external editor path def change_exteditor(self): """Change external editor path""" path, valid = QInputDialog.getText(self, _('External editor'), _('External editor executable path:'), QLineEdit.Normal, self.get_o...
Toggle wrap mode def toggle_wrap_mode(self, checked): """Toggle wrap mode""" self.shell.toggle_wrap_mode(checked) self.set_option('wrap', checked)
Toggle automatic code completion def toggle_codecompletion(self, checked): """Toggle automatic code completion""" self.shell.set_codecompletion_auto(checked) self.set_option('codecompletion/auto', checked)
Reimplement Qt method Inform Qt about the types of data that the widget accepts def dragEnterEvent(self, event): """Reimplement Qt method Inform Qt about the types of data that the widget accepts""" source = event.mimeData() if source.hasUrls(): if mimedata2url...
Reimplement Qt method Unpack dropped data and handle it def dropEvent(self, event): """Reimplement Qt method Unpack dropped data and handle it""" source = event.mimeData() if source.hasUrls(): pathlist = mimedata2url(source) self.shell.drop_pathlis...
Function executed when running the script with the -install switch 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_DESKT...
Function executed when running the script with the -remove switch 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...
This function generates a list of tours. The index argument is used to retrieve a particular tour. If None is passed, it will return the full list of tours. If instead -1 is given, this function will return a test tour To add more tours a new variable needs to be created to hold the list of ...
Override Qt method def paintEvent(self, event): """Override Qt method""" painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing) # Decoration painter.fillPath(self.path_current, QBrush(self.color)) painter.strokePath(self.path_decoration, QPen(self.co...
Override Qt method def reject(self): """Override Qt method""" if not self.is_fade_running(): key = Qt.Key_Escape self.key_pressed = key self.sig_key_pressed.emit()
override Qt method def mousePressEvent(self, event): """override Qt method""" # Raise the main application window on click self.parent.raise_() self.raise_() if event.button() == Qt.RightButton: pass
Set data that is displayed in each step of the tour. 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 =...
Confirm if the tour loses focus and hides the tips. 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()
Confirm if the tour regains focus and unhides the tips. 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()
Returns if tour or any of its components has focus. 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
Reimplemented to handle communications between the figure explorer and the kernel. def _handle_display_data(self, msg): """ Reimplemented to handle communications between the figure explorer and the kernel. """ img = None data = msg['content']['data'] if ...
Get file language from filename def get_file_language(filename, text=None): """Get file language from filename""" ext = osp.splitext(filename)[1] if ext.startswith('.'): ext = ext[1:] # file extension with leading dot language = ext if not ext: if text is None: t...
Line edit's text has changed 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
Save fig to fname in the format specified by fmt. 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 ...
Append a number to "root" to form a filename that does not already exist in "dirname". 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...
Setup the figure browser with provided settings. 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...
Setup the toolbar def setup_toolbar(self): """Setup the toolbar""" savefig_btn = create_toolbutton( self, icon=ima.icon('filesave'), tip=_("Save Image As..."), triggered=self.save_figure) saveall_btn = create_toolbutton( self, ico...
Setup the actions to show in the cog menu. def setup_option_actions(self, mute_inline_plotting, show_plot_outline): """Setup the actions to show in the cog menu.""" self.setup_in_progress = True self.mute_inline_action = create_action( self, _("Mute inline plotting"), ti...
Create shortcuts for this widget. 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_thumbn...
Handle when the value of an option has changed 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.s...
Draw a frame around the figure viewer if state is True. 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;}") ...
Bind the shellwidget instance to the figure browser 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)
Copy figure from figviewer to clipboard. def copy_figure(self): """Copy figure from figviewer to clipboard.""" if self.figviewer and self.figviewer.figcanvas.fig: self.figviewer.figcanvas.copy_figure()
Setup the FigureCanvas. def setup_figcanvas(self): """Setup the FigureCanvas.""" self.figcanvas = FigureCanvas(background_color=self.background_color) self.figcanvas.installEventFilter(self) self.setWidget(self.figcanvas)
Set a new figure in the figure canvas. 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()
A filter to control the zooming and panning of the figure canvas. 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() i...
Scale the image up by one scale step. 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...
Scale the image down by one scale step. 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(s...
Scale the image size. def scale_image(self): """Scale the image size.""" new_width = int(self.figcanvas.fwidth * self._scalestep ** self._scalefactor) new_height = int(self.figcanvas.fheight * self._scalestep ** self._scalefactor) self.fi...
Adjust the scrollbar position to take into account the zooming of the figure. def _adjust_scrollbar(self, f): """ Adjust the scrollbar position to take into account the zooming of the figure. """ # Adjust horizontal scrollbar : hb = self.horizontalScrollBar() ...
Setup the main layout of the widget. def setup_gui(self): """Setup the main layout of the widget.""" scrollarea = self.setup_scrollarea() up_btn, down_btn = self.setup_arrow_buttons() self.setFixedWidth(150) layout = QVBoxLayout(self) layout.setContentsMargins(0, 0, 0, ...
Setup the scrollarea that will contain the FigureThumbnails. 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(...
Setup the up and down arrow buttons that are placed at the top and bottom of the scrollarea. 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 d...
Save all the figures to a file. 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...
Save all figure in dirname. def save_all_figures_todir(self, dirname): """Save all figure in dirname.""" fignames = [] for thumbnail in self._thumbnails: fig = thumbnail.canvas.fig fmt = thumbnail.canvas.fmt fext = {'image/png': '.png', 'i...
Save the currently selected figure. 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)
Save the figure to a file. 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)')}[fm...
Remove all thumbnails. def remove_all_thumbnails(self): """Remove all thumbnails.""" for thumbnail in self._thumbnails: self.layout().removeWidget(thumbnail) thumbnail.sig_canvas_clicked.disconnect() thumbnail.sig_remove_figure.disconnect() thumbnail.sig_...
Remove thumbnail. def remove_thumbnail(self, thumbnail): """Remove thumbnail.""" if thumbnail in self._thumbnails: index = self._thumbnails.index(thumbnail) self._thumbnails.remove(thumbnail) self.layout().removeWidget(thumbnail) thumbnail.deleteLater() t...
Set the currently selected thumbnail. 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:...
Select the thumbnail previous to the currently selected one. 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 ind...
Select thumbnail next to the currently selected one. 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._thumbnai...
Scroll to the selected item of ThumbnailScrollBar. 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).size...
Scroll the scrollbar of the scrollarea up by a single step. 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()))