code
stringlengths
9
189k
meta_data.file_name
stringclasses
538 values
meta_data.module
stringclasses
202 values
meta_data.contains_class
bool
2 classes
meta_data.contains_function
bool
2 classes
meta_data.file_imports
sequencelengths
0
97
meta_data.start_line
int64
-1
6.71k
meta_data.end_line
int64
-1
6.74k
Parameters ---------- before_section: str or None Make `section` appear before another one. """ inserted_before_other = False if before_section is not None: if before_section in self._sections: # If before_section was already introduced, we simply need to # insert the new section on its position, which will put it # exactly behind before_section. idx = self._sections.index(before_section) self._sections.insert(idx, section) inserted_before_other = True else: # If before_section hasn't been introduced yet, we know we need # to insert it after section when it's finally added to the # menu. So, we preserve that info in the _after_sections dict. self._after_sections[before_section] = section # Append section to the list of sections because we assume # people build menus from top to bottom, i.e. they add its # upper sections first. self._sections.append(section) else: self._sections.append(section) # Check if section should be inserted after another one, according to # what we have in _after_sections. after_section = self._after_sections.pop(section, None)
menus.py
spyder.spyder.api.widgets
false
false
[ "import sys", "from typing import Optional, Union, TypeVar", "import qstylizer.style", "from qtpy.QtWidgets import QAction, QMenu, QWidget", "from spyder.api.config.fonts import SpyderFontType, SpyderFontsMixin", "from spyder.utils.qthelpers import add_actions, set_menu_icons, SpyderAction", "from spyder.utils.palette import QStylePalette", "from spyder.utils.stylesheet import AppStyle, MAC, WIN" ]
65
95
# Check if section should be inserted after another one, according to # what we have in _after_sections. after_section = self._after_sections.pop(section, None) if after_section is not None: if not inserted_before_other: # Insert section to the right of after_section, if it was not # inserted before another one. if section in self._sections: self._sections.remove(section) index = self._sections.index(after_section) self._sections.insert(index + 1, section) else: # If section was already inserted before another one, then we # need to move after_section to its left instead. if after_section in self._sections: self._sections.remove(after_section) idx = self._sections.index(section) idx = idx if (idx == 0) else (idx - 1) self._sections.insert(idx, after_section) def _set_icons(self): """ Unset menu icons for app menus and set them for regular menus.
menus.py
spyder.spyder.api.widgets
false
true
[ "import sys", "from typing import Optional, Union, TypeVar", "import qstylizer.style", "from qtpy.QtWidgets import QAction, QMenu, QWidget", "from spyder.api.config.fonts import SpyderFontType, SpyderFontsMixin", "from spyder.utils.qthelpers import add_actions, set_menu_icons, SpyderAction", "from spyder.utils.palette import QStylePalette", "from spyder.utils.stylesheet import AppStyle, MAC, WIN" ]
317
342
def _set_icons(self): """ Unset menu icons for app menus and set them for regular menus. This is necessary only for Mac to follow its Human Interface Guidelines (HIG), which don't recommend icons in app menus. """ if sys.platform == "darwin": if self.APP_MENU or self._in_app_menu: set_menu_icons(self, False, in_app_menu=True) else: set_menu_icons(self, True) def _generate_stylesheet(self): """Generate base stylesheet for menus.""" css = qstylizer.style.StyleSheet() font = self.get_font(SpyderFontType.Interface) # Add padding and border radius to follow modern standards css.QMenu.setValues( # Only add top and bottom padding so that menu separators can go # completely from the left to right border. paddingTop=f'{2 * AppStyle.MarginSize}px', paddingBottom=f'{2 * AppStyle.MarginSize}px', # This uses the same color as the separator border=f"1px solid {QStylePalette.COLOR_BACKGROUND_6}" ) # Set the right background color This is the only way to do it! css['QWidget:disabled QMenu'].setValues( backgroundColor=QStylePalette.COLOR_BACKGROUND_3, )
menus.py
spyder.spyder.api.widgets
false
true
[ "import sys", "from typing import Optional, Union, TypeVar", "import qstylizer.style", "from qtpy.QtWidgets import QAction, QMenu, QWidget", "from spyder.api.config.fonts import SpyderFontType, SpyderFontsMixin", "from spyder.utils.qthelpers import add_actions, set_menu_icons, SpyderAction", "from spyder.utils.palette import QStylePalette", "from spyder.utils.stylesheet import AppStyle, MAC, WIN" ]
340
371
# Set the right background color This is the only way to do it! css['QWidget:disabled QMenu'].setValues( backgroundColor=QStylePalette.COLOR_BACKGROUND_3, ) # Add padding around separators to prevent that hovering on items hides # them. css["QMenu::separator"].setValues( # Only add top and bottom margins so that the separators can go # completely from the left to right border. margin=f'{2 * AppStyle.MarginSize}px 0px', ) # Set menu item properties delta_top = 0 if (MAC or WIN) else 1 delta_bottom = 0 if MAC else (2 if WIN else 1) css["QMenu::item"].setValues( height='1.1em' if MAC else ('1.35em' if WIN else '1.25em'), marginLeft=f'{2 * AppStyle.MarginSize}px', marginRight=f'{2 * AppStyle.MarginSize}px', paddingTop=f'{AppStyle.MarginSize + delta_top}px', paddingBottom=f'{AppStyle.MarginSize + delta_bottom}px', paddingLeft=f'{3 * AppStyle.MarginSize}px', paddingRight=f'{3 * AppStyle.MarginSize}px', fontFamily=font.family(), fontSize=f'{font.pointSize()}pt', backgroundColor='transparent' )
menus.py
spyder.spyder.api.widgets
false
false
[ "import sys", "from typing import Optional, Union, TypeVar", "import qstylizer.style", "from qtpy.QtWidgets import QAction, QMenu, QWidget", "from spyder.api.config.fonts import SpyderFontType, SpyderFontsMixin", "from spyder.utils.qthelpers import add_actions, set_menu_icons, SpyderAction", "from spyder.utils.palette import QStylePalette", "from spyder.utils.stylesheet import AppStyle, MAC, WIN" ]
368
395
# Set hover and pressed state of items for state in ['selected', 'pressed']: if state == 'selected': bg_color = QStylePalette.COLOR_BACKGROUND_4 else: bg_color = QStylePalette.COLOR_BACKGROUND_5 css[f"QMenu::item:{state}"].setValues( backgroundColor=bg_color, borderRadius=QStylePalette.SIZE_BORDER_RADIUS ) # Set disabled state of items for state in ['disabled', 'selected:disabled']: css[f"QMenu::item:{state}"].setValues( color=QStylePalette.COLOR_DISABLED, backgroundColor="transparent" ) return css def __str__(self): return f"SpyderMenu('{self.menu_id}')" def __repr__(self): return f"SpyderMenu('{self.menu_id}')" # ---- Qt methods # ------------------------------------------------------------------------- def showEvent(self, event): """Adjustments when the menu is shown.""" # Reposition menu vertically due to padding if ( not sys.platform == "darwin" and self._reposition and self._is_submenu and not self._is_shown ): self.move(self.pos().x(), self.pos().y() - 2 * AppStyle.MarginSize) self._is_shown = True super().showEvent(event)
menus.py
spyder.spyder.api.widgets
false
true
[ "import sys", "from typing import Optional, Union, TypeVar", "import qstylizer.style", "from qtpy.QtWidgets import QAction, QMenu, QWidget", "from spyder.api.config.fonts import SpyderFontType, SpyderFontsMixin", "from spyder.utils.qthelpers import add_actions, set_menu_icons, SpyderAction", "from spyder.utils.palette import QStylePalette", "from spyder.utils.stylesheet import AppStyle, MAC, WIN" ]
397
438
class PluginMainWidgetOptionsMenu(SpyderMenu): """ Options menu for PluginMainWidget. """ def render(self): """Render the menu's bottom section as expected.""" if self._dirty: self.clear() self._add_missing_actions() bottom = OptionsMenuSections.Bottom actions = [] for section in self._sections: for (sec, action) in self._actions: if sec == section and sec != bottom: actions.append(action) actions.append(MENU_SEPARATOR) # Add bottom actions for (sec, action) in self._actions: if sec == bottom: actions.append(action) add_actions(self, actions) self._set_icons() self._dirty = False
menus.py
spyder.spyder.api.widgets
false
true
[ "import sys", "from typing import Optional, Union, TypeVar", "import qstylizer.style", "from qtpy.QtWidgets import QAction, QMenu, QWidget", "from spyder.api.config.fonts import SpyderFontType, SpyderFontsMixin", "from spyder.utils.qthelpers import add_actions, set_menu_icons, SpyderAction", "from spyder.utils.palette import QStylePalette", "from spyder.utils.stylesheet import AppStyle, MAC, WIN" ]
441
469
# -*- coding: utf-8 -*- # # Copyright © Spyder Project Contributors # Licensed under the terms of the MIT License # (see spyder/__init__.py for details) """ Spyder combobox widgets. Use these widgets for any combobox you want to add to Spyder. """ # Standard library imports import sys # Third-party imports import qstylizer.style from qtpy.QtCore import QSize, Qt, Signal from qtpy.QtGui import QColor from qtpy.QtWidgets import ( QComboBox, QFontComboBox, QFrame, QLineEdit, QStyledItemDelegate ) # Local imports from spyder.utils.palette import QStylePalette from spyder.utils.stylesheet import AppStyle, WIN
comboboxes.py
spyder.spyder.api.widgets
false
false
[ "import sys", "import qstylizer.style", "from qtpy.QtCore import QSize, Qt, Signal", "from qtpy.QtGui import QColor", "from qtpy.QtWidgets import (", "from spyder.utils.palette import QStylePalette", "from spyder.utils.stylesheet import AppStyle, WIN" ]
1
30
class _SpyderComboBoxDelegate(QStyledItemDelegate): """ Delegate to make separators color follow our theme. Adapted from https://stackoverflow.com/a/33464045/438386 """ def paint(self, painter, option, index): data = index.data(Qt.AccessibleDescriptionRole) if data and data == "separator": painter.setPen(QColor(QStylePalette.COLOR_BACKGROUND_6)) painter.drawLine( option.rect.left() + AppStyle.MarginSize, option.rect.center().y(), option.rect.right() - AppStyle.MarginSize, option.rect.center().y() ) else: super().paint(painter, option, index) def sizeHint(self, option, index): data = index.data(Qt.AccessibleDescriptionRole) if data and data == "separator": return QSize(0, 3 * AppStyle.MarginSize) return super().sizeHint(option, index)
comboboxes.py
spyder.spyder.api.widgets
false
true
[ "import sys", "import qstylizer.style", "from qtpy.QtCore import QSize, Qt, Signal", "from qtpy.QtGui import QColor", "from qtpy.QtWidgets import (", "from spyder.utils.palette import QStylePalette", "from spyder.utils.stylesheet import AppStyle, WIN" ]
33
58
class _SpyderComboBoxLineEdit(QLineEdit): """Dummy lineedit used for non-editable comboboxes.""" sig_mouse_clicked = Signal() def __init__(self, parent): super().__init__(parent) # Fix style issues css = qstylizer.style.StyleSheet() css.QLineEdit.setValues( # These are necessary on Windows to prevent some ugly visual # glitches. backgroundColor="transparent", border="none", padding="0px", # Make text look centered for short comboboxes paddingRight=f"-{3 if WIN else 2}px" ) self.setStyleSheet(css.toString()) def mouseReleaseEvent(self, event): self.sig_mouse_clicked.emit() super().mouseReleaseEvent(event) def mouseDoubleClickEvent(self, event): # Avoid selecting the lineedit text with double clicks pass
comboboxes.py
spyder.spyder.api.widgets
false
true
[ "import sys", "import qstylizer.style", "from qtpy.QtCore import QSize, Qt, Signal", "from qtpy.QtGui import QColor", "from qtpy.QtWidgets import (", "from spyder.utils.palette import QStylePalette", "from spyder.utils.stylesheet import AppStyle, WIN" ]
61
89
class _SpyderComboBoxMixin: """Mixin with the basic style and functionality for our comboboxes.""" def __init__(self): # Style self._css = self._generate_stylesheet() self.setStyleSheet(self._css.toString()) def contextMenuEvent(self, event): # Prevent showing context menu for editable comboboxes because it's # added automatically by Qt. That means that the menu is not built # using our API and it's not localized. pass def _generate_stylesheet(self): """Base stylesheet for Spyder comboboxes.""" css = qstylizer.style.StyleSheet() # Make our comboboxes have a uniform height css.QComboBox.setValues( minHeight=f'{AppStyle.ComboBoxMinHeight}em' ) # Add top and bottom padding to the inner contents of comboboxes css["QComboBox QAbstractItemView"].setValues( paddingTop=f"{AppStyle.MarginSize + 1}px", paddingBottom=f"{AppStyle.MarginSize + 1}px" ) # Add margin and padding to combobox items css["QComboBox QAbstractItemView::item"].setValues( marginLeft=f"{AppStyle.MarginSize}px", marginRight=f"{AppStyle.MarginSize}px", padding=f"{AppStyle.MarginSize}px" )
comboboxes.py
spyder.spyder.api.widgets
true
true
[ "import sys", "import qstylizer.style", "from qtpy.QtCore import QSize, Qt, Signal", "from qtpy.QtGui import QColor", "from qtpy.QtWidgets import (", "from spyder.utils.palette import QStylePalette", "from spyder.utils.stylesheet import AppStyle, WIN" ]
92
127
# Make color of hovered combobox items match the one used in other # Spyder widgets css["QComboBox QAbstractItemView::item:selected:active"].setValues( backgroundColor=QStylePalette.COLOR_BACKGROUND_3, ) return css
comboboxes.py
spyder.spyder.api.widgets
false
false
[ "import sys", "import qstylizer.style", "from qtpy.QtCore import QSize, Qt, Signal", "from qtpy.QtGui import QColor", "from qtpy.QtWidgets import (", "from spyder.utils.palette import QStylePalette", "from spyder.utils.stylesheet import AppStyle, WIN" ]
129
135
class SpyderComboBox(QComboBox, _SpyderComboBoxMixin): """Combobox widget for Spyder when its items don't have icons.""" def __init__(self, parent=None): super().__init__(parent) self.is_editable = None self._is_shown = False self._is_popup_shown = False # This is also necessary to have more fine-grained control over the # style of our comboboxes with css, e.g. to add more padding between # its items. # See https://stackoverflow.com/a/33464045/438386 for the details. self.setItemDelegate(_SpyderComboBoxDelegate(self)) def showEvent(self, event): """Adjustments when the widget is shown.""" if not self._is_shown: if not self.isEditable(): self.is_editable = False self.setLineEdit(_SpyderComboBoxLineEdit(self)) # This is necessary to make Qt position the popup widget below # the combobox for non-editable ones. # Solution from https://stackoverflow.com/a/45191141/438386 self.setEditable(True) self.lineEdit().setReadOnly(True) # Show popup when the lineEdit is clicked, which is the default # behavior for non-editable comboboxes in Qt. self.lineEdit().sig_mouse_clicked.connect(self.showPopup) else: self.is_editable = True self._is_shown = True
comboboxes.py
spyder.spyder.api.widgets
false
true
[ "import sys", "import qstylizer.style", "from qtpy.QtCore import QSize, Qt, Signal", "from qtpy.QtGui import QColor", "from qtpy.QtWidgets import (", "from spyder.utils.palette import QStylePalette", "from spyder.utils.stylesheet import AppStyle, WIN" ]
138
174
self._is_shown = True super().showEvent(event) def showPopup(self): """Adjustments when the popup is shown.""" super().showPopup() if sys.platform == "darwin": # Reposition popup to display it in the right place. # Solution from https://forum.qt.io/post/349517 popup = self.findChild(QFrame) popup.move(popup.x() - 3, popup.y() + 4) # Adjust width to match the lineEdit one. if not self._is_popup_shown: popup.setFixedWidth(popup.width() + 2) self._is_popup_shown = True else: # Make borders straight to make popup feel as part of the combobox. # This doesn't work reliably on Mac. self._css.QComboBox.setValues( borderBottomLeftRadius="0px", borderBottomRightRadius="0px", ) self.setStyleSheet(self._css.toString()) def hidePopup(self): """Adjustments when the popup is hidden.""" super().hidePopup() if not sys.platform == "darwin": # Make borders rounded when popup is not visible. This doesn't work # reliably on Mac. self._css.QComboBox.setValues( borderBottomLeftRadius=QStylePalette.SIZE_BORDER_RADIUS, borderBottomRightRadius=QStylePalette.SIZE_BORDER_RADIUS, ) self.setStyleSheet(self._css.toString())
comboboxes.py
spyder.spyder.api.widgets
false
true
[ "import sys", "import qstylizer.style", "from qtpy.QtCore import QSize, Qt, Signal", "from qtpy.QtGui import QColor", "from qtpy.QtWidgets import (", "from spyder.utils.palette import QStylePalette", "from spyder.utils.stylesheet import AppStyle, WIN" ]
174
214
class SpyderComboBoxWithIcons(SpyderComboBox): """"Combobox widget for Spyder when its items have icons.""" def __init__(self, parent=None): super().__init__(parent) # Padding is not necessary because icons give items enough of it. self._css["QComboBox QAbstractItemView::item"].setValues( padding="0px" ) self.setStyleSheet(self._css.toString()) class SpyderFontComboBox(QFontComboBox, _SpyderComboBoxMixin): def __init__(self, parent=None): super().__init__(parent) # This is necessary for items to get the style set in our stylesheet. self.setItemDelegate(QStyledItemDelegate(self)) # Adjust popup width to contents. self.setSizeAdjustPolicy( QComboBox.AdjustToMinimumContentsLengthWithIcon ) def showPopup(self): """Adjustments when the popup is shown.""" super().showPopup() if sys.platform == "darwin": popup = self.findChild(QFrame) popup.move(popup.x() - 3, popup.y() + 4)
comboboxes.py
spyder.spyder.api.widgets
false
true
[ "import sys", "import qstylizer.style", "from qtpy.QtCore import QSize, Qt, Signal", "from qtpy.QtGui import QColor", "from qtpy.QtWidgets import (", "from spyder.utils.palette import QStylePalette", "from spyder.utils.stylesheet import AppStyle, WIN" ]
217
250
class SpyderPluginV2(QObject, SpyderActionMixin, SpyderConfigurationObserver, SpyderPluginObserver): """ A Spyder plugin to extend functionality without a dockable widget. If you want to create a plugin that adds a new pane, please use SpyderDockablePlugin. """ # --- API: Mandatory attributes ------------------------------------------ # ------------------------------------------------------------------------ # Name of the plugin that will be used to refer to it. # This name must be unique and will only be loaded once. NAME = None # --- API: Optional attributes ------------------------------------------ # ------------------------------------------------------------------------ # List of required plugin dependencies. # Example: [Plugins.Plots, Plugins.IPythonConsole, ...]. # These values are defined in the `Plugins` class present in this file. # If a plugin is using a widget from another plugin, that other # must be declared as a required dependency. REQUIRES = []
new_api.py
spyder.spyder.api.plugins
false
false
[ "from collections import OrderedDict", "import inspect", "import logging", "import os", "import os.path as osp", "import sys", "from typing import List, Union", "import warnings", "from qtpy.QtCore import QObject, Qt, Signal, Slot", "from qtpy.QtGui import QCursor", "from qtpy.QtWidgets import QApplication", "from spyder.api.config.fonts import SpyderFontType", "from spyder.api.config.mixins import SpyderConfigurationObserver", "from spyder.api.exceptions import SpyderAPIError", "from spyder.api.plugin_registration.mixins import SpyderPluginObserver", "from spyder.api.widgets.main_widget import PluginMainWidget", "from spyder.api.widgets.mixins import SpyderActionMixin", "from spyder.api.widgets.mixins import SpyderWidgetMixin", "from spyder.app.cli_options import get_options", "from spyder.config.gui import get_color_scheme, get_font", "from spyder.config.user import NoDefault", "from spyder.utils.icon_manager import ima", "from spyder.utils.image_path_manager import IMAGE_PATH_MANAGER", "from .enum import Plugins", "from .old_api import SpyderPluginWidget" ]
51
73
# List of optional plugin dependencies. # Example: [Plugins.Plots, Plugins.IPythonConsole, ...]. # These values are defined in the `Plugins` class present in this file. # A plugin might be performing actions when connectiong to other plugins, # but the main functionality of the plugin does not depend on other # plugins. For example, the Help plugin might render information from # the Editor or from the Console or from another source, but it does not # depend on either of those plugins. # Methods in the plugin that make use of optional plugins must check # existence before using those methods or applying signal connections. OPTIONAL = [] # This must subclass a `PluginMainContainer` for non dockable plugins that # create a widget, like a status bar widget, a toolbar, a menu, etc. # For non dockable plugins that do not define widgets of any kind this can # be `None`, for example a plugin that only exposes a configuration page. CONTAINER_CLASS = None # Name of the configuration section that's going to be # used to record the plugin's permanent data in Spyder # config system (i.e. in spyder.ini) CONF_SECTION = None # Use a separate configuration file for the plugin. CONF_FILE = True
new_api.py
spyder.spyder.api.plugins
false
false
[ "from collections import OrderedDict", "import inspect", "import logging", "import os", "import os.path as osp", "import sys", "from typing import List, Union", "import warnings", "from qtpy.QtCore import QObject, Qt, Signal, Slot", "from qtpy.QtGui import QCursor", "from qtpy.QtWidgets import QApplication", "from spyder.api.config.fonts import SpyderFontType", "from spyder.api.config.mixins import SpyderConfigurationObserver", "from spyder.api.exceptions import SpyderAPIError", "from spyder.api.plugin_registration.mixins import SpyderPluginObserver", "from spyder.api.widgets.main_widget import PluginMainWidget", "from spyder.api.widgets.mixins import SpyderActionMixin", "from spyder.api.widgets.mixins import SpyderWidgetMixin", "from spyder.app.cli_options import get_options", "from spyder.config.gui import get_color_scheme, get_font", "from spyder.config.user import NoDefault", "from spyder.utils.icon_manager import ima", "from spyder.utils.image_path_manager import IMAGE_PATH_MANAGER", "from .enum import Plugins", "from .old_api import SpyderPluginWidget" ]
75
99
# Use a separate configuration file for the plugin. CONF_FILE = True # Define configuration defaults if using a separate file. # List of tuples, with the first item in the tuple being the section # name and the second item being the default options dictionary. # # CONF_DEFAULTS_EXAMPLE = [ # ('section-name', {'option-1': 'some-value', # 'option-2': True,}), # ('another-section-name', {'option-3': 'some-other-value', # 'option-4': [1, 2, 3],}), # ] CONF_DEFAULTS = None # Define configuration version if using a separate file # # IMPORTANT NOTES: # 1. If you want to *change* the default value of a current option, you # need to do a MINOR update in config version, e.g. from 3.0.0 to 3.1.0 # 2. If you want to *remove* options that are no longer needed or if you # want to *rename* options, then you need to do a MAJOR update in # version, e.g. from 3.0.0 to 4.0.0 # 3. You don't need to touch this value if you're just adding a new option CONF_VERSION = None # Widget to be used as entry in Spyder Preferences dialog. CONF_WIDGET_CLASS = None # Some plugins may add configuration options for other plugins. # Example: # ADDITIONAL_CONF_OPTIONS = {'section': <new value to add>} ADDITIONAL_CONF_OPTIONS = None
new_api.py
spyder.spyder.api.plugins
false
false
[ "from collections import OrderedDict", "import inspect", "import logging", "import os", "import os.path as osp", "import sys", "from typing import List, Union", "import warnings", "from qtpy.QtCore import QObject, Qt, Signal, Slot", "from qtpy.QtGui import QCursor", "from qtpy.QtWidgets import QApplication", "from spyder.api.config.fonts import SpyderFontType", "from spyder.api.config.mixins import SpyderConfigurationObserver", "from spyder.api.exceptions import SpyderAPIError", "from spyder.api.plugin_registration.mixins import SpyderPluginObserver", "from spyder.api.widgets.main_widget import PluginMainWidget", "from spyder.api.widgets.mixins import SpyderActionMixin", "from spyder.api.widgets.mixins import SpyderWidgetMixin", "from spyder.app.cli_options import get_options", "from spyder.config.gui import get_color_scheme, get_font", "from spyder.config.user import NoDefault", "from spyder.utils.icon_manager import ima", "from spyder.utils.image_path_manager import IMAGE_PATH_MANAGER", "from .enum import Plugins", "from .old_api import SpyderPluginWidget" ]
98
130
# Some plugins may add configuration options for other plugins. # Example: # ADDITIONAL_CONF_OPTIONS = {'section': <new value to add>} ADDITIONAL_CONF_OPTIONS = None # Define additional configurable options (via a tab) to # another's plugin configuration page. All configuration tabs should # inherit from `SpyderPreferencesTab`. # Example: # ADDITIONAL_CONF_TABS = {'plugin_name': [<SpyderPreferencesTab classes>]} ADDITIONAL_CONF_TABS = None # Define custom layout classes that the plugin wantes to be registered. # THe custom classes should extend from # `spyder.pluginsl.layout.api::BaseGridLayoutType` CUSTOM_LAYOUTS = [] # Path for images relative to the plugin path # A Python package can include one or several Spyder plugins. In this case # the package may be using images from a global folder outside the plugin # folder IMG_PATH = None # Control the font size relative to the global fonts defined in Spyder MONOSPACE_FONT_SIZE_DELTA = 0 INTERFACE_FONT_SIZE_DELTA = 0 # Define context to store actions, toolbars, toolbuttons and menus. CONTEXT_NAME = None # Define if a plugin can be disabled in preferences. # If False, the plugin is considered "core" and therefore it cannot be # disabled. Default: True CAN_BE_DISABLED = True
new_api.py
spyder.spyder.api.plugins
false
false
[ "from collections import OrderedDict", "import inspect", "import logging", "import os", "import os.path as osp", "import sys", "from typing import List, Union", "import warnings", "from qtpy.QtCore import QObject, Qt, Signal, Slot", "from qtpy.QtGui import QCursor", "from qtpy.QtWidgets import QApplication", "from spyder.api.config.fonts import SpyderFontType", "from spyder.api.config.mixins import SpyderConfigurationObserver", "from spyder.api.exceptions import SpyderAPIError", "from spyder.api.plugin_registration.mixins import SpyderPluginObserver", "from spyder.api.widgets.main_widget import PluginMainWidget", "from spyder.api.widgets.mixins import SpyderActionMixin", "from spyder.api.widgets.mixins import SpyderWidgetMixin", "from spyder.app.cli_options import get_options", "from spyder.config.gui import get_color_scheme, get_font", "from spyder.config.user import NoDefault", "from spyder.utils.icon_manager import ima", "from spyder.utils.image_path_manager import IMAGE_PATH_MANAGER", "from .enum import Plugins", "from .old_api import SpyderPluginWidget" ]
127
160
# Define if a plugin can be disabled in preferences. # If False, the plugin is considered "core" and therefore it cannot be # disabled. Default: True CAN_BE_DISABLED = True # --- API: Signals ------------------------------------------------------- # ------------------------------------------------------------------------ # Signals here are automatically connected by the Spyder main window and # connected to the the respective global actions defined on it. sig_free_memory_requested = Signal() """ This signal can be emitted to request the main application to garbage collect deleted objects. """ sig_plugin_ready = Signal() """ This signal can be emitted to reflect that the plugin was initialized. """ sig_quit_requested = Signal() """ This signal can be emitted to request the main application to quit. """ sig_restart_requested = Signal() """ This signal can be emitted to request the main application to restart. """ sig_status_message_requested = Signal(str, int) """ This signal can be emitted to request the main application to display a message in the status bar. Parameters ---------- message: str The actual message to display. timeout: int The timeout before the message disappears. """
new_api.py
spyder.spyder.api.plugins
false
false
[ "from collections import OrderedDict", "import inspect", "import logging", "import os", "import os.path as osp", "import sys", "from typing import List, Union", "import warnings", "from qtpy.QtCore import QObject, Qt, Signal, Slot", "from qtpy.QtGui import QCursor", "from qtpy.QtWidgets import QApplication", "from spyder.api.config.fonts import SpyderFontType", "from spyder.api.config.mixins import SpyderConfigurationObserver", "from spyder.api.exceptions import SpyderAPIError", "from spyder.api.plugin_registration.mixins import SpyderPluginObserver", "from spyder.api.widgets.main_widget import PluginMainWidget", "from spyder.api.widgets.mixins import SpyderActionMixin", "from spyder.api.widgets.mixins import SpyderWidgetMixin", "from spyder.app.cli_options import get_options", "from spyder.config.gui import get_color_scheme, get_font", "from spyder.config.user import NoDefault", "from spyder.utils.icon_manager import ima", "from spyder.utils.image_path_manager import IMAGE_PATH_MANAGER", "from .enum import Plugins", "from .old_api import SpyderPluginWidget" ]
157
198
Parameters ---------- message: str The actual message to display. timeout: int The timeout before the message disappears. """ sig_redirect_stdio_requested = Signal(bool) """ This signal can be emitted to request the main application to redirect standard output/error when using Open/Save/Browse dialogs within widgets. Parameters ---------- enable: bool Enable/Disable standard input/output redirection. """ sig_exception_occurred = Signal(dict) """ This signal can be emitted to report an exception from any plugin. Parameters ---------- error_data: dict The dictionary containing error data. The expected keys are: >>> error_data= { "text": str, "is_traceback": bool, "repo": str, "title": str, "label": str, "steps": str, } Notes ----- The `is_traceback` key indicates if `text` contains plain text or a Python error traceback. The `title` and `repo` keys indicate how the error data should customize the report dialog and Github error submission. The `label` and `steps` keys allow customizing the content of the error dialog. This signal is automatically connected to the main container/widget. """ sig_mainwindow_resized = Signal("QResizeEvent") """ This signal is emitted when the main window is resized.
new_api.py
spyder.spyder.api.plugins
false
false
[ "from collections import OrderedDict", "import inspect", "import logging", "import os", "import os.path as osp", "import sys", "from typing import List, Union", "import warnings", "from qtpy.QtCore import QObject, Qt, Signal, Slot", "from qtpy.QtGui import QCursor", "from qtpy.QtWidgets import QApplication", "from spyder.api.config.fonts import SpyderFontType", "from spyder.api.config.mixins import SpyderConfigurationObserver", "from spyder.api.exceptions import SpyderAPIError", "from spyder.api.plugin_registration.mixins import SpyderPluginObserver", "from spyder.api.widgets.main_widget import PluginMainWidget", "from spyder.api.widgets.mixins import SpyderActionMixin", "from spyder.api.widgets.mixins import SpyderWidgetMixin", "from spyder.app.cli_options import get_options", "from spyder.config.gui import get_color_scheme, get_font", "from spyder.config.user import NoDefault", "from spyder.utils.icon_manager import ima", "from spyder.utils.image_path_manager import IMAGE_PATH_MANAGER", "from .enum import Plugins", "from .old_api import SpyderPluginWidget" ]
192
244
sig_mainwindow_resized = Signal("QResizeEvent") """ This signal is emitted when the main window is resized. Parameters ---------- resize_event: QResizeEvent The event triggered on main window resize. Notes ----- To be used by plugins tracking main window size changes. """ sig_mainwindow_moved = Signal("QMoveEvent") """ This signal is emitted when the main window is moved. Parameters ---------- move_event: QMoveEvent The event triggered on main window move. Notes ----- To be used by plugins tracking main window position changes. """ sig_unmaximize_plugin_requested = Signal((), (object,)) """ This signal is emitted to inform the main window that it needs to unmaximize the currently maximized plugin, if any. Parameters ---------- plugin_instance: SpyderDockablePlugin Unmaximize plugin only if it is not `plugin_instance`. """ sig_mainwindow_state_changed = Signal(object) """ This signal is emitted when the main window state has changed (for instance, between maximized and minimized states). Parameters ---------- window_state: Qt.WindowStates The window state. """
new_api.py
spyder.spyder.api.plugins
false
false
[ "from collections import OrderedDict", "import inspect", "import logging", "import os", "import os.path as osp", "import sys", "from typing import List, Union", "import warnings", "from qtpy.QtCore import QObject, Qt, Signal, Slot", "from qtpy.QtGui import QCursor", "from qtpy.QtWidgets import QApplication", "from spyder.api.config.fonts import SpyderFontType", "from spyder.api.config.mixins import SpyderConfigurationObserver", "from spyder.api.exceptions import SpyderAPIError", "from spyder.api.plugin_registration.mixins import SpyderPluginObserver", "from spyder.api.widgets.main_widget import PluginMainWidget", "from spyder.api.widgets.mixins import SpyderActionMixin", "from spyder.api.widgets.mixins import SpyderWidgetMixin", "from spyder.app.cli_options import get_options", "from spyder.config.gui import get_color_scheme, get_font", "from spyder.config.user import NoDefault", "from spyder.utils.icon_manager import ima", "from spyder.utils.image_path_manager import IMAGE_PATH_MANAGER", "from .enum import Plugins", "from .old_api import SpyderPluginWidget" ]
242
290
Parameters ---------- window_state: Qt.WindowStates The window state. """ # --- Private attributes ------------------------------------------------- # ------------------------------------------------------------------------ # Define configuration name map for plugin to split configuration # among several files. See spyder/config/main.py _CONF_NAME_MAP = None def __init__(self, parent, configuration=None): super().__init__(parent) # This is required since the MRO of this class does not go up until to # SpyderPluginObserver and SpyderConfigurationObserver when using # super(), see https://fuhm.net/super-harmful/ SpyderPluginObserver.__init__(self) SpyderConfigurationObserver.__init__(self) self._main = parent self._widget = None self._conf = configuration self._plugin_path = os.path.dirname(inspect.getfile(self.__class__)) self._container = None self._added_toolbars = OrderedDict() self._actions = {} self.is_compatible = None self.is_registered = None self.main = parent # Attribute used to access the action, toolbar, toolbutton and menu # registries self.PLUGIN_NAME = self.NAME
new_api.py
spyder.spyder.api.plugins
false
true
[ "from collections import OrderedDict", "import inspect", "import logging", "import os", "import os.path as osp", "import sys", "from typing import List, Union", "import warnings", "from qtpy.QtCore import QObject, Qt, Signal, Slot", "from qtpy.QtGui import QCursor", "from qtpy.QtWidgets import QApplication", "from spyder.api.config.fonts import SpyderFontType", "from spyder.api.config.mixins import SpyderConfigurationObserver", "from spyder.api.exceptions import SpyderAPIError", "from spyder.api.plugin_registration.mixins import SpyderPluginObserver", "from spyder.api.widgets.main_widget import PluginMainWidget", "from spyder.api.widgets.mixins import SpyderActionMixin", "from spyder.api.widgets.mixins import SpyderWidgetMixin", "from spyder.app.cli_options import get_options", "from spyder.config.gui import get_color_scheme, get_font", "from spyder.config.user import NoDefault", "from spyder.utils.icon_manager import ima", "from spyder.utils.image_path_manager import IMAGE_PATH_MANAGER", "from .enum import Plugins", "from .old_api import SpyderPluginWidget" ]
192
226
# Attribute used to access the action, toolbar, toolbutton and menu # registries self.PLUGIN_NAME = self.NAME if self.CONTAINER_CLASS is not None: self._container = container = self.CONTAINER_CLASS( name=self.NAME, plugin=self, parent=parent ) if isinstance(container, SpyderWidgetMixin): container.setup() container.update_actions() # Default signals to connect in main container or main widget. container.sig_free_memory_requested.connect( self.sig_free_memory_requested) container.sig_quit_requested.connect(self.sig_quit_requested) container.sig_restart_requested.connect(self.sig_restart_requested) container.sig_redirect_stdio_requested.connect( self.sig_redirect_stdio_requested) container.sig_exception_occurred.connect( self.sig_exception_occurred) container.sig_unmaximize_plugin_requested.connect( self.sig_unmaximize_plugin_requested) self.after_container_creation() if hasattr(container, '_setup'): container._setup() # Load the custom images of the plugin if self.IMG_PATH: plugin_path = osp.join(self.get_path(), self.IMG_PATH) IMAGE_PATH_MANAGER.add_image_path(plugin_path)
new_api.py
spyder.spyder.api.plugins
false
false
[ "from collections import OrderedDict", "import inspect", "import logging", "import os", "import os.path as osp", "import sys", "from typing import List, Union", "import warnings", "from qtpy.QtCore import QObject, Qt, Signal, Slot", "from qtpy.QtGui import QCursor", "from qtpy.QtWidgets import QApplication", "from spyder.api.config.fonts import SpyderFontType", "from spyder.api.config.mixins import SpyderConfigurationObserver", "from spyder.api.exceptions import SpyderAPIError", "from spyder.api.plugin_registration.mixins import SpyderPluginObserver", "from spyder.api.widgets.main_widget import PluginMainWidget", "from spyder.api.widgets.mixins import SpyderActionMixin", "from spyder.api.widgets.mixins import SpyderWidgetMixin", "from spyder.app.cli_options import get_options", "from spyder.config.gui import get_color_scheme, get_font", "from spyder.config.user import NoDefault", "from spyder.utils.icon_manager import ima", "from spyder.utils.image_path_manager import IMAGE_PATH_MANAGER", "from .enum import Plugins", "from .old_api import SpyderPluginWidget" ]
318
353
# Load the custom images of the plugin if self.IMG_PATH: plugin_path = osp.join(self.get_path(), self.IMG_PATH) IMAGE_PATH_MANAGER.add_image_path(plugin_path) # --- Private methods ---------------------------------------------------- # ------------------------------------------------------------------------ def _register(self, omit_conf=False): """ Setup and register plugin in Spyder's main window and connect it to other plugins. """ # Checks # -------------------------------------------------------------------- if self.NAME is None: raise SpyderAPIError('A Spyder Plugin must define a `NAME`!') # Setup configuration # -------------------------------------------------------------------- if self._conf is not None and not omit_conf: self._conf.register_plugin(self) # Signals # -------------------------------------------------------------------- self.is_registered = True self.update_font() def _unregister(self): """ Disconnect signals and clean up the plugin to be able to stop it while Spyder is running. """ if self._conf is not None: self._conf.unregister_plugin(self) self._container = None self.is_compatible = None self.is_registered = False
new_api.py
spyder.spyder.api.plugins
false
true
[ "from collections import OrderedDict", "import inspect", "import logging", "import os", "import os.path as osp", "import sys", "from typing import List, Union", "import warnings", "from qtpy.QtCore import QObject, Qt, Signal, Slot", "from qtpy.QtGui import QCursor", "from qtpy.QtWidgets import QApplication", "from spyder.api.config.fonts import SpyderFontType", "from spyder.api.config.mixins import SpyderConfigurationObserver", "from spyder.api.exceptions import SpyderAPIError", "from spyder.api.plugin_registration.mixins import SpyderPluginObserver", "from spyder.api.widgets.main_widget import PluginMainWidget", "from spyder.api.widgets.mixins import SpyderActionMixin", "from spyder.api.widgets.mixins import SpyderWidgetMixin", "from spyder.app.cli_options import get_options", "from spyder.config.gui import get_color_scheme, get_font", "from spyder.config.user import NoDefault", "from spyder.utils.icon_manager import ima", "from spyder.utils.image_path_manager import IMAGE_PATH_MANAGER", "from .enum import Plugins", "from .old_api import SpyderPluginWidget" ]
350
389
if self._conf is not None: self._conf.unregister_plugin(self) self._container = None self.is_compatible = None self.is_registered = False # --- API: available methods --------------------------------------------- # ------------------------------------------------------------------------ def get_path(self): """ Return the plugin's system path. """ return self._plugin_path def get_container(self): """ Return the plugin main container. """ return self._container def get_configuration(self): """ Return the Spyder configuration object. """ return self._conf def get_main(self): """ Return the Spyder main window.. """ return self._main def get_plugin(self, plugin_name, error=True): """ Get a plugin instance by providing its name. Parameters ---------- plugin_name: str Name of the plugin from which its instance will be returned. error: bool Whether to raise errors when trying to return the plugin's instance. """ # Ensure that this plugin has the plugin corresponding to # `plugin_name` listed as required or optional. requires = set(self.REQUIRES or []) optional = set(self.OPTIONAL or []) full_set = requires | optional
new_api.py
spyder.spyder.api.plugins
false
true
[ "from collections import OrderedDict", "import inspect", "import logging", "import os", "import os.path as osp", "import sys", "from typing import List, Union", "import warnings", "from qtpy.QtCore import QObject, Qt, Signal, Slot", "from qtpy.QtGui import QCursor", "from qtpy.QtWidgets import QApplication", "from spyder.api.config.fonts import SpyderFontType", "from spyder.api.config.mixins import SpyderConfigurationObserver", "from spyder.api.exceptions import SpyderAPIError", "from spyder.api.plugin_registration.mixins import SpyderPluginObserver", "from spyder.api.widgets.main_widget import PluginMainWidget", "from spyder.api.widgets.mixins import SpyderActionMixin", "from spyder.api.widgets.mixins import SpyderWidgetMixin", "from spyder.app.cli_options import get_options", "from spyder.config.gui import get_color_scheme, get_font", "from spyder.config.user import NoDefault", "from spyder.utils.icon_manager import ima", "from spyder.utils.image_path_manager import IMAGE_PATH_MANAGER", "from .enum import Plugins", "from .old_api import SpyderPluginWidget" ]
384
433
if plugin_name in full_set or Plugins.All in full_set: try: return self._main.get_plugin(plugin_name, error=error) except SpyderAPIError as e: if plugin_name in optional: return None else: raise e else: raise SpyderAPIError( 'Plugin "{}" not part of REQUIRES or ' 'OPTIONAL requirements!'.format(plugin_name) ) def is_plugin_enabled(self, plugin_name): """Determine if a given plugin is going to be loaded.""" return self._main.is_plugin_enabled(plugin_name) def is_plugin_available(self, plugin_name): """Determine if a given plugin is available.""" return self._main.is_plugin_available(plugin_name) def get_dockable_plugins(self): """ Return a list of the required plugin instances. Only required plugins that extend SpyderDockablePlugin are returned. """ requires = set(self.REQUIRES or []) dockable_plugins_required = [] for name, plugin_instance in self._main.get_dockable_plugins(): if (name in requires or Plugins.All in requires) and isinstance( plugin_instance, (SpyderDockablePlugin, SpyderPluginWidget)): dockable_plugins_required.append(plugin_instance) return dockable_plugins_required
new_api.py
spyder.spyder.api.plugins
false
true
[ "from collections import OrderedDict", "import inspect", "import logging", "import os", "import os.path as osp", "import sys", "from typing import List, Union", "import warnings", "from qtpy.QtCore import QObject, Qt, Signal, Slot", "from qtpy.QtGui import QCursor", "from qtpy.QtWidgets import QApplication", "from spyder.api.config.fonts import SpyderFontType", "from spyder.api.config.mixins import SpyderConfigurationObserver", "from spyder.api.exceptions import SpyderAPIError", "from spyder.api.plugin_registration.mixins import SpyderPluginObserver", "from spyder.api.widgets.main_widget import PluginMainWidget", "from spyder.api.widgets.mixins import SpyderActionMixin", "from spyder.api.widgets.mixins import SpyderWidgetMixin", "from spyder.app.cli_options import get_options", "from spyder.config.gui import get_color_scheme, get_font", "from spyder.config.user import NoDefault", "from spyder.utils.icon_manager import ima", "from spyder.utils.image_path_manager import IMAGE_PATH_MANAGER", "from .enum import Plugins", "from .old_api import SpyderPluginWidget" ]
435
470
def get_conf(self, option, default=NoDefault, section=None): """ Get an option from Spyder configuration system. Parameters ---------- option: str Name of the option to get its value from. default: bool, int, str, tuple, list, dict, NoDefault Value to get from the configuration system, passed as a Python object. section: str Section in the configuration system, e.g. `shortcuts`. Returns ------- bool, int, str, tuple, list, dict Value associated with `option`. """ if self._conf is not None: section = self.CONF_SECTION if section is None else section if section is None: raise SpyderAPIError( 'A spyder plugin must define a `CONF_SECTION` class ' 'attribute!' ) return self._conf.get(section, option, default) @Slot(str, object) @Slot(str, object, str) def set_conf(self, option, value, section=None, recursive_notification=True): """ Set an option in Spyder configuration system.
new_api.py
spyder.spyder.api.plugins
false
true
[ "from collections import OrderedDict", "import inspect", "import logging", "import os", "import os.path as osp", "import sys", "from typing import List, Union", "import warnings", "from qtpy.QtCore import QObject, Qt, Signal, Slot", "from qtpy.QtGui import QCursor", "from qtpy.QtWidgets import QApplication", "from spyder.api.config.fonts import SpyderFontType", "from spyder.api.config.mixins import SpyderConfigurationObserver", "from spyder.api.exceptions import SpyderAPIError", "from spyder.api.plugin_registration.mixins import SpyderPluginObserver", "from spyder.api.widgets.main_widget import PluginMainWidget", "from spyder.api.widgets.mixins import SpyderActionMixin", "from spyder.api.widgets.mixins import SpyderWidgetMixin", "from spyder.app.cli_options import get_options", "from spyder.config.gui import get_color_scheme, get_font", "from spyder.config.user import NoDefault", "from spyder.utils.icon_manager import ima", "from spyder.utils.image_path_manager import IMAGE_PATH_MANAGER", "from .enum import Plugins", "from .old_api import SpyderPluginWidget" ]
472
505
Parameters ---------- option: str Name of the option (e.g. 'case_sensitive') value: bool, int, str, tuple, list, dict Value to save in the configuration system, passed as a Python object. section: str Section in the configuration system, e.g. `shortcuts`. recursive_notification: bool If True, all objects that observe all changes on the configuration section and objects that observe partial tuple paths are notified. For example if the option `opt` of section `sec` changes, then the observers for section `sec` are notified. Likewise, if the option `(a, b, c)` changes, then observers for `(a, b, c)`, `(a, b)` and a are notified as well. """ if self._conf is not None: section = self.CONF_SECTION if section is None else section if section is None: raise SpyderAPIError( 'A spyder plugin must define a `CONF_SECTION` class ' 'attribute!' ) self._conf.set(section, option, value, recursive_notification=recursive_notification) self.apply_conf({option}, False) def remove_conf(self, option, section=None): """ Delete an option in the Spyder configuration system.
new_api.py
spyder.spyder.api.plugins
false
true
[ "from collections import OrderedDict", "import inspect", "import logging", "import os", "import os.path as osp", "import sys", "from typing import List, Union", "import warnings", "from qtpy.QtCore import QObject, Qt, Signal, Slot", "from qtpy.QtGui import QCursor", "from qtpy.QtWidgets import QApplication", "from spyder.api.config.fonts import SpyderFontType", "from spyder.api.config.mixins import SpyderConfigurationObserver", "from spyder.api.exceptions import SpyderAPIError", "from spyder.api.plugin_registration.mixins import SpyderPluginObserver", "from spyder.api.widgets.main_widget import PluginMainWidget", "from spyder.api.widgets.mixins import SpyderActionMixin", "from spyder.api.widgets.mixins import SpyderWidgetMixin", "from spyder.app.cli_options import get_options", "from spyder.config.gui import get_color_scheme, get_font", "from spyder.config.user import NoDefault", "from spyder.utils.icon_manager import ima", "from spyder.utils.image_path_manager import IMAGE_PATH_MANAGER", "from .enum import Plugins", "from .old_api import SpyderPluginWidget" ]
192
223
def remove_conf(self, option, section=None): """ Delete an option in the Spyder configuration system. Parameters ---------- option: Union[str, Tuple[str, ...]] Name of the option, either a string or a tuple of strings. section: str Section in the configuration system. """ if self._conf is not None: section = self.CONF_SECTION if section is None else section if section is None: raise SpyderAPIError( 'A spyder plugin must define a `CONF_SECTION` class ' 'attribute!' ) self._conf.remove_option(section, option) self.apply_conf({option}, False) def apply_conf(self, options_set, notify=True): """ Apply `options_set` to this plugin's widget. """ if self._conf is not None and options_set: if notify: self.after_configuration_update(list(options_set)) def disable_conf(self, option, section=None): """ Disable notifications for an option in the Spyder configuration system.
new_api.py
spyder.spyder.api.plugins
false
true
[ "from collections import OrderedDict", "import inspect", "import logging", "import os", "import os.path as osp", "import sys", "from typing import List, Union", "import warnings", "from qtpy.QtCore import QObject, Qt, Signal, Slot", "from qtpy.QtGui import QCursor", "from qtpy.QtWidgets import QApplication", "from spyder.api.config.fonts import SpyderFontType", "from spyder.api.config.mixins import SpyderConfigurationObserver", "from spyder.api.exceptions import SpyderAPIError", "from spyder.api.plugin_registration.mixins import SpyderPluginObserver", "from spyder.api.widgets.main_widget import PluginMainWidget", "from spyder.api.widgets.mixins import SpyderActionMixin", "from spyder.api.widgets.mixins import SpyderWidgetMixin", "from spyder.app.cli_options import get_options", "from spyder.config.gui import get_color_scheme, get_font", "from spyder.config.user import NoDefault", "from spyder.utils.icon_manager import ima", "from spyder.utils.image_path_manager import IMAGE_PATH_MANAGER", "from .enum import Plugins", "from .old_api import SpyderPluginWidget" ]
536
568
def disable_conf(self, option, section=None): """ Disable notifications for an option in the Spyder configuration system. Parameters ---------- option: Union[str, Tuple[str, ...]] Name of the option, either a string or a tuple of strings. section: str Section in the configuration system. """ if self._conf is not None: section = self.CONF_SECTION if section is None else section if section is None: raise SpyderAPIError( 'A spyder plugin must define a `CONF_SECTION` class ' 'attribute!' ) self._conf.disable_notifications(section, option) def restore_conf(self, option, section=None): """ Restore notifications for an option in the Spyder configuration system. Parameters ---------- option: Union[str, Tuple[str, ...]] Name of the option, either a string or a tuple of strings. section: str Section in the configuration system. """ if self._conf is not None: section = self.CONF_SECTION if section is None else section if section is None: raise SpyderAPIError( 'A spyder plugin must define a `CONF_SECTION` class ' 'attribute!' ) self._conf.restore_notifications(section, option)
new_api.py
spyder.spyder.api.plugins
false
true
[ "from collections import OrderedDict", "import inspect", "import logging", "import os", "import os.path as osp", "import sys", "from typing import List, Union", "import warnings", "from qtpy.QtCore import QObject, Qt, Signal, Slot", "from qtpy.QtGui import QCursor", "from qtpy.QtWidgets import QApplication", "from spyder.api.config.fonts import SpyderFontType", "from spyder.api.config.mixins import SpyderConfigurationObserver", "from spyder.api.exceptions import SpyderAPIError", "from spyder.api.plugin_registration.mixins import SpyderPluginObserver", "from spyder.api.widgets.main_widget import PluginMainWidget", "from spyder.api.widgets.mixins import SpyderActionMixin", "from spyder.api.widgets.mixins import SpyderWidgetMixin", "from spyder.app.cli_options import get_options", "from spyder.config.gui import get_color_scheme, get_font", "from spyder.config.user import NoDefault", "from spyder.utils.icon_manager import ima", "from spyder.utils.image_path_manager import IMAGE_PATH_MANAGER", "from .enum import Plugins", "from .old_api import SpyderPluginWidget" ]
566
604
@Slot(str) @Slot(str, int) def show_status_message(self, message, timeout=0): """ Show message in status bar. Parameters ---------- message: str Message to display in the status bar. timeout: int Amount of time to display the message. """ self.sig_status_message_requested.emit(message, timeout) def before_long_process(self, message): """ Show a message in main window's status bar and change the mouse pointer to Qt.WaitCursor when starting a long process. Parameters ---------- message: str Message to show in the status bar when the long process starts. """ if message: self.show_status_message(message) QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) QApplication.processEvents() def after_long_process(self, message=""): """ Clear main window's status bar after a long process and restore mouse pointer to the OS deault. Parameters ---------- message: str Message to show in the status bar when the long process finishes. """ QApplication.restoreOverrideCursor() self.show_status_message(message, timeout=2000) QApplication.processEvents() def get_color_scheme(self): """ Get the current color scheme.
new_api.py
spyder.spyder.api.plugins
false
true
[ "from collections import OrderedDict", "import inspect", "import logging", "import os", "import os.path as osp", "import sys", "from typing import List, Union", "import warnings", "from qtpy.QtCore import QObject, Qt, Signal, Slot", "from qtpy.QtGui import QCursor", "from qtpy.QtWidgets import QApplication", "from spyder.api.config.fonts import SpyderFontType", "from spyder.api.config.mixins import SpyderConfigurationObserver", "from spyder.api.exceptions import SpyderAPIError", "from spyder.api.plugin_registration.mixins import SpyderPluginObserver", "from spyder.api.widgets.main_widget import PluginMainWidget", "from spyder.api.widgets.mixins import SpyderActionMixin", "from spyder.api.widgets.mixins import SpyderWidgetMixin", "from spyder.app.cli_options import get_options", "from spyder.config.gui import get_color_scheme, get_font", "from spyder.config.user import NoDefault", "from spyder.utils.icon_manager import ima", "from spyder.utils.image_path_manager import IMAGE_PATH_MANAGER", "from .enum import Plugins", "from .old_api import SpyderPluginWidget" ]
606
653
def get_color_scheme(self): """ Get the current color scheme. Returns ------- dict Dictionary with properties and colors of the color scheme used in the Editor. Notes ----- This is useful to set the color scheme of all instances of CodeEditor used by the plugin. """ if self._conf is not None: return get_color_scheme(self._conf.get('appearance', 'selected')) def initialize(self): """ Initialize a plugin instance. Notes ----- This method should be called to initialize the plugin, but it should not be overridden, since it internally calls `on_initialize` and emits the `sig_plugin_ready` signal. """ self.on_initialize() self.sig_plugin_ready.emit() @staticmethod def create_icon(name): """ Provide icons from the theme and icon manager. """ return ima.icon(name) @classmethod def get_font(cls, font_type): """ Return one of font types used in Spyder.
new_api.py
spyder.spyder.api.plugins
false
true
[ "from collections import OrderedDict", "import inspect", "import logging", "import os", "import os.path as osp", "import sys", "from typing import List, Union", "import warnings", "from qtpy.QtCore import QObject, Qt, Signal, Slot", "from qtpy.QtGui import QCursor", "from qtpy.QtWidgets import QApplication", "from spyder.api.config.fonts import SpyderFontType", "from spyder.api.config.mixins import SpyderConfigurationObserver", "from spyder.api.exceptions import SpyderAPIError", "from spyder.api.plugin_registration.mixins import SpyderPluginObserver", "from spyder.api.widgets.main_widget import PluginMainWidget", "from spyder.api.widgets.mixins import SpyderActionMixin", "from spyder.api.widgets.mixins import SpyderWidgetMixin", "from spyder.app.cli_options import get_options", "from spyder.config.gui import get_color_scheme, get_font", "from spyder.config.user import NoDefault", "from spyder.utils.icon_manager import ima", "from spyder.utils.image_path_manager import IMAGE_PATH_MANAGER", "from .enum import Plugins", "from .old_api import SpyderPluginWidget" ]
651
692
@classmethod def get_font(cls, font_type): """ Return one of font types used in Spyder. Parameters ---------- font_type: str There are three types of font types in Spyder: SpyderFontType.Monospace, used in the Editor, IPython console, and History; SpyderFontType.Interface, used by the entire Spyder app; and SpyderFontType.MonospaceInterface, used by the Variable Explorer, Find, Debugger and others. Returns ------- QFont QFont object to be passed to other Qt widgets. Notes ----- All plugins in Spyder use the same, global fonts. In case some a plugin wants to use a delta font size based on the default one, they can set the MONOSPACE_FONT_SIZE_DELTA or INTERFACE_FONT_SIZE_DELTA class constants. """ if font_type == SpyderFontType.Monospace: font_size_delta = cls.MONOSPACE_FONT_SIZE_DELTA elif font_type in [SpyderFontType.Interface, SpyderFontType.MonospaceInterface]: font_size_delta = cls.INTERFACE_FONT_SIZE_DELTA else: raise SpyderAPIError("Unrecognized font type") return get_font(option=font_type, font_size_delta=font_size_delta)
new_api.py
spyder.spyder.api.plugins
false
true
[ "from collections import OrderedDict", "import inspect", "import logging", "import os", "import os.path as osp", "import sys", "from typing import List, Union", "import warnings", "from qtpy.QtCore import QObject, Qt, Signal, Slot", "from qtpy.QtGui import QCursor", "from qtpy.QtWidgets import QApplication", "from spyder.api.config.fonts import SpyderFontType", "from spyder.api.config.mixins import SpyderConfigurationObserver", "from spyder.api.exceptions import SpyderAPIError", "from spyder.api.plugin_registration.mixins import SpyderPluginObserver", "from spyder.api.widgets.main_widget import PluginMainWidget", "from spyder.api.widgets.mixins import SpyderActionMixin", "from spyder.api.widgets.mixins import SpyderWidgetMixin", "from spyder.app.cli_options import get_options", "from spyder.config.gui import get_color_scheme, get_font", "from spyder.config.user import NoDefault", "from spyder.utils.icon_manager import ima", "from spyder.utils.image_path_manager import IMAGE_PATH_MANAGER", "from .enum import Plugins", "from .old_api import SpyderPluginWidget" ]
689
723
return get_font(option=font_type, font_size_delta=font_size_delta) def get_command_line_options(self): """ Get command line options passed by the user when they started Spyder in a system terminal. See app/cli_options.py for the option names. """ if self._main is not None: return self._main._cli_options else: # This is necessary when the plugin has no parent. sys_argv = [sys.argv[0]] # Avoid options passed to pytest return get_options(sys_argv)[0] # --- API: Mandatory methods to define ----------------------------------- # ------------------------------------------------------------------------ @staticmethod def get_name(): """ Return the plugin localized name. Returns ------- str Localized name of the plugin. Notes ----- This method needs to be decorated with `staticmethod`. """ raise NotImplementedError('A plugin name must be defined!') @staticmethod def get_description(): """ Return the plugin localized description. Returns ------- str Localized description of the plugin. Notes ----- This method needs to be decorated with `staticmethod`. """ raise NotImplementedError('A plugin description must be defined!')
new_api.py
spyder.spyder.api.plugins
false
true
[ "from collections import OrderedDict", "import inspect", "import logging", "import os", "import os.path as osp", "import sys", "from typing import List, Union", "import warnings", "from qtpy.QtCore import QObject, Qt, Signal, Slot", "from qtpy.QtGui import QCursor", "from qtpy.QtWidgets import QApplication", "from spyder.api.config.fonts import SpyderFontType", "from spyder.api.config.mixins import SpyderConfigurationObserver", "from spyder.api.exceptions import SpyderAPIError", "from spyder.api.plugin_registration.mixins import SpyderPluginObserver", "from spyder.api.widgets.main_widget import PluginMainWidget", "from spyder.api.widgets.mixins import SpyderActionMixin", "from spyder.api.widgets.mixins import SpyderWidgetMixin", "from spyder.app.cli_options import get_options", "from spyder.config.gui import get_color_scheme, get_font", "from spyder.config.user import NoDefault", "from spyder.utils.icon_manager import ima", "from spyder.utils.image_path_manager import IMAGE_PATH_MANAGER", "from .enum import Plugins", "from .old_api import SpyderPluginWidget" ]
723
771
Notes ----- This method needs to be decorated with `staticmethod`. """ raise NotImplementedError('A plugin description must be defined!') @classmethod def get_icon(cls): """ Return the plugin associated icon. Returns ------- QIcon QIcon instance Notes ----- This method needs to be decorated with `classmethod` or `staticmethod`. """ raise NotImplementedError('A plugin icon must be defined!') def on_initialize(self): """ Setup the plugin. Notes ----- All calls performed on this method should not call other plugins. """ if hasattr(self, 'register'): raise SpyderAPIError( 'register was replaced by on_initialize, please check the ' 'Spyder 5.1.0 migration guide to get more information') raise NotImplementedError( f'The plugin {type(self)} is missing an implementation of ' 'on_initialize') # --- API: Optional methods to override ---------------------------------- # ------------------------------------------------------------------------ @staticmethod def check_compatibility(): """ This method can be reimplemented to check compatibility of a plugin with the user's current environment.
new_api.py
spyder.spyder.api.plugins
false
true
[ "from collections import OrderedDict", "import inspect", "import logging", "import os", "import os.path as osp", "import sys", "from typing import List, Union", "import warnings", "from qtpy.QtCore import QObject, Qt, Signal, Slot", "from qtpy.QtGui import QCursor", "from qtpy.QtWidgets import QApplication", "from spyder.api.config.fonts import SpyderFontType", "from spyder.api.config.mixins import SpyderConfigurationObserver", "from spyder.api.exceptions import SpyderAPIError", "from spyder.api.plugin_registration.mixins import SpyderPluginObserver", "from spyder.api.widgets.main_widget import PluginMainWidget", "from spyder.api.widgets.mixins import SpyderActionMixin", "from spyder.api.widgets.mixins import SpyderWidgetMixin", "from spyder.app.cli_options import get_options", "from spyder.config.gui import get_color_scheme, get_font", "from spyder.config.user import NoDefault", "from spyder.utils.icon_manager import ima", "from spyder.utils.image_path_manager import IMAGE_PATH_MANAGER", "from .enum import Plugins", "from .old_api import SpyderPluginWidget" ]
228
273
Returns ------- (bool, str) The first value tells Spyder if the plugin has passed the compatibility test defined in this method. The second value is a message that must explain users why the plugin was found to be incompatible (e.g. 'This plugin does not work with PyQt4'). It will be shown at startup in a QMessageBox. """ valid = True message = '' # Note: Remember to use _('') to localize the string return valid, message def on_first_registration(self): """ Actions to be performed the first time the plugin is started. It can also be used to perform actions that are needed only the first time this is loaded after installation. This method is called after the main window is visible. """ pass def before_mainwindow_visible(self): """ Actions to be performed after setup but before the main window's has been shown. """ pass def on_mainwindow_visible(self): """ Actions to be performed after the main window's has been shown. """ pass def on_close(self, cancelable=False): """ Perform actions before the plugin is closed.
new_api.py
spyder.spyder.api.plugins
false
true
[ "from collections import OrderedDict", "import inspect", "import logging", "import os", "import os.path as osp", "import sys", "from typing import List, Union", "import warnings", "from qtpy.QtCore import QObject, Qt, Signal, Slot", "from qtpy.QtGui import QCursor", "from qtpy.QtWidgets import QApplication", "from spyder.api.config.fonts import SpyderFontType", "from spyder.api.config.mixins import SpyderConfigurationObserver", "from spyder.api.exceptions import SpyderAPIError", "from spyder.api.plugin_registration.mixins import SpyderPluginObserver", "from spyder.api.widgets.main_widget import PluginMainWidget", "from spyder.api.widgets.mixins import SpyderActionMixin", "from spyder.api.widgets.mixins import SpyderWidgetMixin", "from spyder.app.cli_options import get_options", "from spyder.config.gui import get_color_scheme, get_font", "from spyder.config.user import NoDefault", "from spyder.utils.icon_manager import ima", "from spyder.utils.image_path_manager import IMAGE_PATH_MANAGER", "from .enum import Plugins", "from .old_api import SpyderPluginWidget" ]
486
525
def on_close(self, cancelable=False): """ Perform actions before the plugin is closed. This method **must** only operate on local attributes and not other plugins. """ if hasattr(self, 'unregister'): warnings.warn('The unregister method was deprecated and it ' 'was replaced by `on_close`. Please see the ' 'Spyder 5.2.0 migration guide to get more ' 'information.') def can_close(self) -> bool: """ Determine if a plugin can be closed. Returns ------- close: bool True if the plugin can be closed, False otherwise. """ return True def update_font(self): """ This must be reimplemented by plugins that need to adjust their fonts. The following plugins illustrate the usage of this method: * spyder/plugins/help/plugin.py * spyder/plugins/onlinehelp/plugin.py """ pass def update_style(self): """ This must be reimplemented by plugins that need to adjust their style. Changing from the dark to the light interface theme might require specific styles or stylesheets to be applied. When the theme is changed by the user through our Preferences, this method will be called for all plugins. """ pass
new_api.py
spyder.spyder.api.plugins
false
true
[ "from collections import OrderedDict", "import inspect", "import logging", "import os", "import os.path as osp", "import sys", "from typing import List, Union", "import warnings", "from qtpy.QtCore import QObject, Qt, Signal, Slot", "from qtpy.QtGui import QCursor", "from qtpy.QtWidgets import QApplication", "from spyder.api.config.fonts import SpyderFontType", "from spyder.api.config.mixins import SpyderConfigurationObserver", "from spyder.api.exceptions import SpyderAPIError", "from spyder.api.plugin_registration.mixins import SpyderPluginObserver", "from spyder.api.widgets.main_widget import PluginMainWidget", "from spyder.api.widgets.mixins import SpyderActionMixin", "from spyder.api.widgets.mixins import SpyderWidgetMixin", "from spyder.app.cli_options import get_options", "from spyder.config.gui import get_color_scheme, get_font", "from spyder.config.user import NoDefault", "from spyder.utils.icon_manager import ima", "from spyder.utils.image_path_manager import IMAGE_PATH_MANAGER", "from .enum import Plugins", "from .old_api import SpyderPluginWidget" ]
851
894
def after_container_creation(self): """ Perform necessary operations before setting up the container. This must be reimplemented by plugins whose containers emit signals in on_option_update that need to be connected before applying those options to our config system. """ pass def after_configuration_update(self, options: List[Union[str, tuple]]): """ Perform additional operations after updating the plugin configuration values. This can be implemented by plugins that do not have a container and need to act on configuration updates. Parameters ---------- options: List[Union[str, tuple]] A list that contains the options that were updated. """ pass
new_api.py
spyder.spyder.api.plugins
false
true
[ "from collections import OrderedDict", "import inspect", "import logging", "import os", "import os.path as osp", "import sys", "from typing import List, Union", "import warnings", "from qtpy.QtCore import QObject, Qt, Signal, Slot", "from qtpy.QtGui import QCursor", "from qtpy.QtWidgets import QApplication", "from spyder.api.config.fonts import SpyderFontType", "from spyder.api.config.mixins import SpyderConfigurationObserver", "from spyder.api.exceptions import SpyderAPIError", "from spyder.api.plugin_registration.mixins import SpyderPluginObserver", "from spyder.api.widgets.main_widget import PluginMainWidget", "from spyder.api.widgets.mixins import SpyderActionMixin", "from spyder.api.widgets.mixins import SpyderWidgetMixin", "from spyder.app.cli_options import get_options", "from spyder.config.gui import get_color_scheme, get_font", "from spyder.config.user import NoDefault", "from spyder.utils.icon_manager import ima", "from spyder.utils.image_path_manager import IMAGE_PATH_MANAGER", "from .enum import Plugins", "from .old_api import SpyderPluginWidget" ]
896
919
class SpyderDockablePlugin(SpyderPluginV2): """ A Spyder plugin to enhance functionality with a dockable widget. """ # --- API: Mandatory attributes ------------------------------------------ # ------------------------------------------------------------------------ # This is the main widget of the dockable plugin. # It needs to be a subclass of PluginMainWidget. WIDGET_CLASS = None # --- API: Optional attributes ------------------------------------------- # ------------------------------------------------------------------------ # Define a list of plugins next to which we want to to tabify this plugin. # Example: ['Plugins.Editor'] TABIFY = [] # Disable actions in Spyder main menus when the plugin is not visible DISABLE_ACTIONS_WHEN_HIDDEN = True # Raise and focus on switch to plugin calls. # If False, the widget will be raised but focus will not be given until # the action to switch is called a second time. RAISE_AND_FOCUS = False # --- API: Available signals --------------------------------------------- # ------------------------------------------------------------------------ sig_focus_changed = Signal() """ This signal is emitted to inform the focus of this plugin has changed. """ sig_toggle_view_changed = Signal(bool) """ This action is emitted to inform the visibility of a dockable plugin has changed.
new_api.py
spyder.spyder.api.plugins
false
false
[ "from collections import OrderedDict", "import inspect", "import logging", "import os", "import os.path as osp", "import sys", "from typing import List, Union", "import warnings", "from qtpy.QtCore import QObject, Qt, Signal, Slot", "from qtpy.QtGui import QCursor", "from qtpy.QtWidgets import QApplication", "from spyder.api.config.fonts import SpyderFontType", "from spyder.api.config.mixins import SpyderConfigurationObserver", "from spyder.api.exceptions import SpyderAPIError", "from spyder.api.plugin_registration.mixins import SpyderPluginObserver", "from spyder.api.widgets.main_widget import PluginMainWidget", "from spyder.api.widgets.mixins import SpyderActionMixin", "from spyder.api.widgets.mixins import SpyderWidgetMixin", "from spyder.app.cli_options import get_options", "from spyder.config.gui import get_color_scheme, get_font", "from spyder.config.user import NoDefault", "from spyder.utils.icon_manager import ima", "from spyder.utils.image_path_manager import IMAGE_PATH_MANAGER", "from .enum import Plugins", "from .old_api import SpyderPluginWidget" ]
922
956
sig_toggle_view_changed = Signal(bool) """ This action is emitted to inform the visibility of a dockable plugin has changed. This is triggered by checking/unchecking the entry for a pane in the `View > Panes` menu. Parameters ---------- visible: bool New visibility of the dockwidget. """ sig_switch_to_plugin_requested = Signal(object, bool) """ This signal can be emitted to inform the main window that this plugin requested to be displayed. Notes ----- This is automatically connected to main container/widget at plugin's registration. """ sig_update_ancestor_requested = Signal() """ This signal is emitted to inform the main window that a child widget needs its ancestor to be updated. """ # --- Private methods ---------------------------------------------------- # ------------------------------------------------------------------------ def __init__(self, parent, configuration): if not issubclass(self.WIDGET_CLASS, PluginMainWidget): raise SpyderAPIError( 'A SpyderDockablePlugin must define a valid WIDGET_CLASS ' 'attribute!') self.CONTAINER_CLASS = self.WIDGET_CLASS super().__init__(parent, configuration=configuration) # Defined on mainwindow.py self._shortcut = None
new_api.py
spyder.spyder.api.plugins
false
true
[ "from collections import OrderedDict", "import inspect", "import logging", "import os", "import os.path as osp", "import sys", "from typing import List, Union", "import warnings", "from qtpy.QtCore import QObject, Qt, Signal, Slot", "from qtpy.QtGui import QCursor", "from qtpy.QtWidgets import QApplication", "from spyder.api.config.fonts import SpyderFontType", "from spyder.api.config.mixins import SpyderConfigurationObserver", "from spyder.api.exceptions import SpyderAPIError", "from spyder.api.plugin_registration.mixins import SpyderPluginObserver", "from spyder.api.widgets.main_widget import PluginMainWidget", "from spyder.api.widgets.mixins import SpyderActionMixin", "from spyder.api.widgets.mixins import SpyderWidgetMixin", "from spyder.app.cli_options import get_options", "from spyder.config.gui import get_color_scheme, get_font", "from spyder.config.user import NoDefault", "from spyder.utils.icon_manager import ima", "from spyder.utils.image_path_manager import IMAGE_PATH_MANAGER", "from .enum import Plugins", "from .old_api import SpyderPluginWidget" ]
953
996
self.CONTAINER_CLASS = self.WIDGET_CLASS super().__init__(parent, configuration=configuration) # Defined on mainwindow.py self._shortcut = None # Widget setup # -------------------------------------------------------------------- self._widget = self._container widget = self._widget if widget is None: raise SpyderAPIError( 'A dockable plugin must define a WIDGET_CLASS!') if not isinstance(widget, PluginMainWidget): raise SpyderAPIError( 'The WIDGET_CLASS of a dockable plugin must be a subclass of ' 'PluginMainWidget!') widget.DISABLE_ACTIONS_WHEN_HIDDEN = self.DISABLE_ACTIONS_WHEN_HIDDEN widget.RAISE_AND_FOCUS = self.RAISE_AND_FOCUS widget.set_icon(self.get_icon()) widget.set_name(self.NAME) # Render all toolbars as a final separate step on the main window # in case some plugins want to extend a toolbar. Since the rendering # can only be done once! widget.render_toolbars() # Default Signals # -------------------------------------------------------------------- widget.sig_toggle_view_changed.connect(self.sig_toggle_view_changed) widget.sig_update_ancestor_requested.connect( self.sig_update_ancestor_requested)
new_api.py
spyder.spyder.api.plugins
false
false
[ "from collections import OrderedDict", "import inspect", "import logging", "import os", "import os.path as osp", "import sys", "from typing import List, Union", "import warnings", "from qtpy.QtCore import QObject, Qt, Signal, Slot", "from qtpy.QtGui import QCursor", "from qtpy.QtWidgets import QApplication", "from spyder.api.config.fonts import SpyderFontType", "from spyder.api.config.mixins import SpyderConfigurationObserver", "from spyder.api.exceptions import SpyderAPIError", "from spyder.api.plugin_registration.mixins import SpyderPluginObserver", "from spyder.api.widgets.main_widget import PluginMainWidget", "from spyder.api.widgets.mixins import SpyderActionMixin", "from spyder.api.widgets.mixins import SpyderWidgetMixin", "from spyder.app.cli_options import get_options", "from spyder.config.gui import get_color_scheme, get_font", "from spyder.config.user import NoDefault", "from spyder.utils.icon_manager import ima", "from spyder.utils.image_path_manager import IMAGE_PATH_MANAGER", "from .enum import Plugins", "from .old_api import SpyderPluginWidget" ]
992
1,025
# --- API: available methods --------------------------------------------- # ------------------------------------------------------------------------ def before_long_process(self, message): """ Show a message in main window's status bar, change the mouse pointer to Qt.WaitCursor and start spinner when starting a long process. Parameters ---------- message: str Message to show in the status bar when the long process starts. """ self.get_widget().start_spinner() super().before_long_process(message) def after_long_process(self, message=""): """ Clear main window's status bar after a long process, restore mouse pointer to the OS deault and stop spinner. Parameters ---------- message: str Message to show in the status bar when the long process finishes. """ super().after_long_process(message) self.get_widget().stop_spinner() def get_widget(self): """ Return the plugin main widget. """ if self._widget is None: raise SpyderAPIError('Dockable Plugin must have a WIDGET_CLASS!') return self._widget def update_title(self): """ Update plugin title, i.e. dockwidget or window title. """ self.get_widget().update_title()
new_api.py
spyder.spyder.api.plugins
false
true
[ "from collections import OrderedDict", "import inspect", "import logging", "import os", "import os.path as osp", "import sys", "from typing import List, Union", "import warnings", "from qtpy.QtCore import QObject, Qt, Signal, Slot", "from qtpy.QtGui import QCursor", "from qtpy.QtWidgets import QApplication", "from spyder.api.config.fonts import SpyderFontType", "from spyder.api.config.mixins import SpyderConfigurationObserver", "from spyder.api.exceptions import SpyderAPIError", "from spyder.api.plugin_registration.mixins import SpyderPluginObserver", "from spyder.api.widgets.main_widget import PluginMainWidget", "from spyder.api.widgets.mixins import SpyderActionMixin", "from spyder.api.widgets.mixins import SpyderWidgetMixin", "from spyder.app.cli_options import get_options", "from spyder.config.gui import get_color_scheme, get_font", "from spyder.config.user import NoDefault", "from spyder.utils.icon_manager import ima", "from spyder.utils.image_path_manager import IMAGE_PATH_MANAGER", "from .enum import Plugins", "from .old_api import SpyderPluginWidget" ]
391
432
return self._widget def update_title(self): """ Update plugin title, i.e. dockwidget or window title. """ self.get_widget().update_title() def update_margins(self, margin): """ Update margins of main widget inside dockable plugin. """ self.get_widget().update_margins(margin) @Slot() def switch_to_plugin(self, force_focus=False): """ Switch to plugin and define if focus should be given or not. """ if self.get_widget().windowwidget is None: self.sig_switch_to_plugin_requested.emit(self, force_focus) def set_ancestor(self, ancestor_widget): """ Update the ancestor/parent of child widgets when undocking. """ self.get_widget().set_ancestor(ancestor_widget) # --- Convenience methods from the widget exposed on the plugin # ------------------------------------------------------------------------ @property def dockwidget(self): return self.get_widget().dockwidget @property def options_menu(self): return self.get_widget().get_options_menu() @property def toggle_view_action(self): return self.get_widget().toggle_view_action def create_dockwidget(self, mainwindow): return self.get_widget().create_dockwidget(mainwindow) def create_window(self): self.get_widget().create_window()
new_api.py
spyder.spyder.api.plugins
false
true
[ "from collections import OrderedDict", "import inspect", "import logging", "import os", "import os.path as osp", "import sys", "from typing import List, Union", "import warnings", "from qtpy.QtCore import QObject, Qt, Signal, Slot", "from qtpy.QtGui import QCursor", "from qtpy.QtWidgets import QApplication", "from spyder.api.config.fonts import SpyderFontType", "from spyder.api.config.mixins import SpyderConfigurationObserver", "from spyder.api.exceptions import SpyderAPIError", "from spyder.api.plugin_registration.mixins import SpyderPluginObserver", "from spyder.api.widgets.main_widget import PluginMainWidget", "from spyder.api.widgets.mixins import SpyderActionMixin", "from spyder.api.widgets.mixins import SpyderWidgetMixin", "from spyder.app.cli_options import get_options", "from spyder.config.gui import get_color_scheme, get_font", "from spyder.config.user import NoDefault", "from spyder.utils.icon_manager import ima", "from spyder.utils.image_path_manager import IMAGE_PATH_MANAGER", "from .enum import Plugins", "from .old_api import SpyderPluginWidget" ]
1,062
1,108
def create_dockwidget(self, mainwindow): return self.get_widget().create_dockwidget(mainwindow) def create_window(self): self.get_widget().create_window() def close_window(self, save_undocked=False): self.get_widget().close_window(save_undocked=save_undocked) def change_visibility(self, state, force_focus=False): self.get_widget().change_visibility(state, force_focus) def toggle_view(self, value): self.get_widget().toggle_view(value)
new_api.py
spyder.spyder.api.plugins
false
true
[ "from collections import OrderedDict", "import inspect", "import logging", "import os", "import os.path as osp", "import sys", "from typing import List, Union", "import warnings", "from qtpy.QtCore import QObject, Qt, Signal, Slot", "from qtpy.QtGui import QCursor", "from qtpy.QtWidgets import QApplication", "from spyder.api.config.fonts import SpyderFontType", "from spyder.api.config.mixins import SpyderConfigurationObserver", "from spyder.api.exceptions import SpyderAPIError", "from spyder.api.plugin_registration.mixins import SpyderPluginObserver", "from spyder.api.widgets.main_widget import PluginMainWidget", "from spyder.api.widgets.mixins import SpyderActionMixin", "from spyder.api.widgets.mixins import SpyderWidgetMixin", "from spyder.app.cli_options import get_options", "from spyder.config.gui import get_color_scheme, get_font", "from spyder.config.user import NoDefault", "from spyder.utils.icon_manager import ima", "from spyder.utils.image_path_manager import IMAGE_PATH_MANAGER", "from .enum import Plugins", "from .old_api import SpyderPluginWidget" ]
1,104
1,117
# -*- coding: utf-8 -*- # # Copyright © Spyder Project Contributors # Licensed under the terms of the MIT License # (see spyder/__init__.py for details) """ New API for plugins. All plugins in Spyder 5+ must inherit from the classes present in this file. """ # Standard library imports from collections import OrderedDict import inspect import logging import os import os.path as osp import sys from typing import List, Union import warnings # Third party imports from qtpy.QtCore import QObject, Qt, Signal, Slot from qtpy.QtGui import QCursor from qtpy.QtWidgets import QApplication # Local imports from spyder.api.config.fonts import SpyderFontType from spyder.api.config.mixins import SpyderConfigurationObserver from spyder.api.exceptions import SpyderAPIError from spyder.api.plugin_registration.mixins import SpyderPluginObserver from spyder.api.widgets.main_widget import PluginMainWidget from spyder.api.widgets.mixins import SpyderActionMixin from spyder.api.widgets.mixins import SpyderWidgetMixin from spyder.app.cli_options import get_options from spyder.config.gui import get_color_scheme, get_font from spyder.config.user import NoDefault from spyder.utils.icon_manager import ima from spyder.utils.image_path_manager import IMAGE_PATH_MANAGER # Package imports from .enum import Plugins from .old_api import SpyderPluginWidget # Logging logger = logging.getLogger(__name__) # Code for: class SpyderPluginV2(QObject, SpyderActionMixin, SpyderConfigurationObserver,
new_api.py
spyder.spyder.api.plugins
false
false
[ "from collections import OrderedDict", "import inspect", "import logging", "import os", "import os.path as osp", "import sys", "from typing import List, Union", "import warnings", "from qtpy.QtCore import QObject, Qt, Signal, Slot", "from qtpy.QtGui import QCursor", "from qtpy.QtWidgets import QApplication", "from spyder.api.config.fonts import SpyderFontType", "from spyder.api.config.mixins import SpyderConfigurationObserver", "from spyder.api.exceptions import SpyderAPIError", "from spyder.api.plugin_registration.mixins import SpyderPluginObserver", "from spyder.api.widgets.main_widget import PluginMainWidget", "from spyder.api.widgets.mixins import SpyderActionMixin", "from spyder.api.widgets.mixins import SpyderWidgetMixin", "from spyder.app.cli_options import get_options", "from spyder.config.gui import get_color_scheme, get_font", "from spyder.config.user import NoDefault", "from spyder.utils.icon_manager import ima", "from spyder.utils.image_path_manager import IMAGE_PATH_MANAGER", "from .enum import Plugins", "from .old_api import SpyderPluginWidget" ]
1
51
# Logging logger = logging.getLogger(__name__) # Code for: class SpyderPluginV2(QObject, SpyderActionMixin, SpyderConfigurationObserver, # Code for: class SpyderDockablePlugin(SpyderPluginV2):
new_api.py
spyder.spyder.api.plugins
false
false
[ "from collections import OrderedDict", "import inspect", "import logging", "import os", "import os.path as osp", "import sys", "from typing import List, Union", "import warnings", "from qtpy.QtCore import QObject, Qt, Signal, Slot", "from qtpy.QtGui import QCursor", "from qtpy.QtWidgets import QApplication", "from spyder.api.config.fonts import SpyderFontType", "from spyder.api.config.mixins import SpyderConfigurationObserver", "from spyder.api.exceptions import SpyderAPIError", "from spyder.api.plugin_registration.mixins import SpyderPluginObserver", "from spyder.api.widgets.main_widget import PluginMainWidget", "from spyder.api.widgets.mixins import SpyderActionMixin", "from spyder.api.widgets.mixins import SpyderWidgetMixin", "from spyder.app.cli_options import get_options", "from spyder.config.gui import get_color_scheme, get_font", "from spyder.config.user import NoDefault", "from spyder.utils.icon_manager import ima", "from spyder.utils.image_path_manager import IMAGE_PATH_MANAGER", "from .enum import Plugins", "from .old_api import SpyderPluginWidget" ]
47
54
# -*- coding: utf-8 -*- # # Copyright © Spyder Project Contributors # Licensed under the terms of the MIT License # (see spyder/__init__.py for details) """ spyder.api.plugins ================== Here, 'plugins' are Qt objects that can make changes to Spyder's main window and call other plugins directly. There are two types of plugins available: 1. SpyderPluginV2 is a plugin that does not create a new dock/pane on Spyder's main window. Note: SpyderPluginV2 will be renamed to SpyderPlugin once the migration to the new API is finished 2. SpyderDockablePlugin is a plugin that does create a new dock/pane on Spyder's main window. """ from .enum import Plugins, DockablePlugins # noqa from .old_api import SpyderPlugin, SpyderPluginWidget # noqa from .new_api import SpyderDockablePlugin, SpyderPluginV2 # noqa
__init__.py
spyder.spyder.api.plugins
false
false
[ "from .enum import Plugins, DockablePlugins # noqa", "from .old_api import SpyderPlugin, SpyderPluginWidget # noqa", "from .new_api import SpyderDockablePlugin, SpyderPluginV2 # noqa" ]
1
26
class BasePlugin(BasePluginMixin): """ Basic functionality for Spyder plugins. WARNING: Don't override any methods or attributes present here! """ # Use this signal to display a message in the status bar. # str: The message you want to display # int: Amount of time to display the message sig_show_status_message = Signal(str, int) # Use this signal to inform another plugin that a configuration # value has changed. sig_option_changed = Signal(str, object) def __init__(self, parent=None): super(BasePlugin, self).__init__(parent) # This is the plugin parent, which corresponds to the main # window. self.main = parent # Filesystem path to the root directory that contains the # plugin self.PLUGIN_PATH = self._get_plugin_path() # Connect signals to slots. self.sig_show_status_message.connect(self.show_status_message) self.sig_option_changed.connect(self.set_option) @Slot(str) @Slot(str, int) def show_status_message(self, message, timeout=0): """ Show message in main window's status bar. Parameters ---------- message: str Message to display in the status bar. timeout: int Amount of time to display the message. """ super(BasePlugin, self)._show_status_message(message, timeout)
old_api.py
spyder.spyder.api.plugins
false
true
[ "from qtpy.QtCore import Signal, Slot", "from qtpy.QtWidgets import QWidget", "from spyder.config.user import NoDefault", "from spyder.plugins.base import BasePluginMixin, BasePluginWidgetMixin", "from spyder.utils.icon_manager import ima" ]
28
71
@Slot(str, object) def set_option(self, option, value, section=None, recursive_notification=True): """ Set an option in Spyder configuration file. Parameters ---------- option: str Name of the option (e.g. 'case_sensitive') value: bool, int, str, tuple, list, dict Value to save in configuration file, passed as a Python object. Notes ----- * Use sig_option_changed to call this method from widgets of the same or another plugin. * CONF_SECTION needs to be defined for this to work. """ super(BasePlugin, self)._set_option( option, value, section=section, recursive_notification=recursive_notification) def get_option(self, option, default=NoDefault, section=None): """ Get an option from Spyder configuration file. Parameters ---------- option: str Name of the option to get its value from. Returns ------- bool, int, str, tuple, list, dict Value associated with `option`. """ return super(BasePlugin, self)._get_option(option, default, section=section) def remove_option(self, option, section=None): """ Remove an option from the Spyder configuration file.
old_api.py
spyder.spyder.api.plugins
false
true
[ "from qtpy.QtCore import Signal, Slot", "from qtpy.QtWidgets import QWidget", "from spyder.config.user import NoDefault", "from spyder.plugins.base import BasePluginMixin, BasePluginWidgetMixin", "from spyder.utils.icon_manager import ima" ]
73
116
def remove_option(self, option, section=None): """ Remove an option from the Spyder configuration file. Parameters ---------- option: Union[str, Tuple[str, ...]] A string or a Tuple of strings containing an option name to remove. section: Optional[str] Name of the section where the option belongs to. """ return super(BasePlugin, self)._remove_option(option, section=section) def starting_long_process(self, message): """ Show a message in main window's status bar and changes the mouse to Qt.WaitCursor when starting a long process. Parameters ---------- message: str Message to show in the status bar when the long process starts. """ super(BasePlugin, self)._starting_long_process(message) def ending_long_process(self, message=""): """ Clear main window's status bar after a long process and restore mouse to the OS deault. Parameters ---------- message: str Message to show in the status bar when the long process finishes. """ super(BasePlugin, self)._ending_long_process(message)
old_api.py
spyder.spyder.api.plugins
false
true
[ "from qtpy.QtCore import Signal, Slot", "from qtpy.QtWidgets import QWidget", "from spyder.config.user import NoDefault", "from spyder.plugins.base import BasePluginMixin, BasePluginWidgetMixin", "from spyder.utils.icon_manager import ima" ]
114
151
class SpyderPlugin(BasePlugin): """ Spyder plugin class. All plugins *must* inherit this class and reimplement its interface. """ # ---------------------------- ATTRIBUTES --------------------------------- # Name of the configuration section that's going to be # used to record the plugin's permanent data in Spyder # config system (i.e. in spyder.ini) # Status: Optional CONF_SECTION = None # One line localized description of the features this plugin implements # Status: Optional DESCRIPTION = None # Widget to be used as entry in Spyder Preferences dialog # Status: Optional CONFIGWIDGET_CLASS = None # Use separate configuration file for plugin # Status: Optional CONF_FILE = True # Define configuration defaults if using a separate file. # List of tuples, with the first item in the tuple being the section # name and the second item being the default options dictionary. # Status: Optional # # CONF_DEFAULTS_EXAMPLE = [ # ('section-name', {'option-1': 'some-value', # 'option-2': True,}), # ('another-section-name', {'option-3': 'some-other-value', # 'option-4': [1, 2, 3],}), # ] CONF_DEFAULTS = None
old_api.py
spyder.spyder.api.plugins
false
false
[ "from qtpy.QtCore import Signal, Slot", "from qtpy.QtWidgets import QWidget", "from spyder.config.user import NoDefault", "from spyder.plugins.base import BasePluginMixin, BasePluginWidgetMixin", "from spyder.utils.icon_manager import ima" ]
154
191
# Define configuration version if using a separate file # Status: Optional # # IMPORTANT NOTES: # 1. If you want to *change* the default value of a current option, you # need to do a MINOR update in config version, e.g. from 3.0.0 to 3.1.0 # 2. If you want to *remove* options that are no longer needed or if you # want to *rename* options, then you need to do a MAJOR update in # version, e.g. from 3.0.0 to 4.0.0 # 3. You don't need to touch this value if you're just adding a new option CONF_VERSION = None # ------------------------------ METHODS ---------------------------------- def check_compatibility(self): """ This method can be reimplemented to check compatibility of a plugin for a given condition. Returns ------- (bool, str) The first value tells Spyder if the plugin has passed the compatibility test defined in this method. The second value is a message that must explain users why the plugin was found to be incompatible (e.g. 'This plugin does not work with PyQt4'). It will be shown at startup in a QMessageBox. """ message = '' valid = True return valid, message
old_api.py
spyder.spyder.api.plugins
false
true
[ "from qtpy.QtCore import Signal, Slot", "from qtpy.QtWidgets import QWidget", "from spyder.config.user import NoDefault", "from spyder.plugins.base import BasePluginMixin, BasePluginWidgetMixin", "from spyder.utils.icon_manager import ima" ]
193
223
class BasePluginWidget(QWidget, BasePluginWidgetMixin): """ Basic functionality for Spyder plugin widgets. WARNING: Don't override any methods or attributes present here! """ # Signal used to update the plugin title when it's undocked sig_update_plugin_title = Signal() def __init__(self, main=None): QWidget.__init__(self) BasePluginWidgetMixin.__init__(self, main) # Dockwidget for the plugin, i.e. the pane that's going to be # displayed in Spyder for this plugin. # Note: This is created when you call the `add_dockwidget` # method, which must be done in the `register_plugin` one. self.dockwidget = None def add_dockwidget(self): """Add the plugin's QDockWidget to the main window.""" super(BasePluginWidget, self)._add_dockwidget() def tabify(self, core_plugin): """ Tabify plugin next to one of the core plugins. Parameters ---------- core_plugin: SpyderPluginWidget Core Spyder plugin this one will be tabified next to. Examples -------- >>> self.tabify(self.main.variableexplorer) >>> self.tabify(self.main.ipyconsole)
old_api.py
spyder.spyder.api.plugins
false
true
[ "from qtpy.QtCore import Signal, Slot", "from qtpy.QtWidgets import QWidget", "from spyder.config.user import NoDefault", "from spyder.plugins.base import BasePluginMixin, BasePluginWidgetMixin", "from spyder.utils.icon_manager import ima" ]
229
265
Examples -------- >>> self.tabify(self.main.variableexplorer) >>> self.tabify(self.main.ipyconsole) Notes ----- The names of variables associated with each of the core plugins can be found in the `setup` method of `MainWindow`, present in `spyder/app/mainwindow.py`. """ super(BasePluginWidget, self)._tabify(core_plugin) def get_font(self, rich_text=False): """ Return plain or rich text font used in Spyder. Parameters ---------- rich_text: bool Return rich text font (i.e. the one used in the Help pane) or plain text one (i.e. the one used in the Editor). Returns ------- QFont: QFont object to be passed to other Qt widgets. Notes ----- All plugins in Spyder use the same, global font. This is a convenience method in case some plugins want to use a delta size based on the default one. That can be controlled by using FONT_SIZE_DELTA or RICH_FONT_SIZE_DELTA (declared below in `SpyderPluginWidget`). """ return super(BasePluginWidget, self)._get_font(rich_text) def register_shortcut(self, qaction_or_qshortcut, context, name, add_shortcut_to_tip=False): """ Register a shortcut associated to a QAction or a QShortcut to Spyder main application.
old_api.py
spyder.spyder.api.plugins
false
true
[ "from qtpy.QtCore import Signal, Slot", "from qtpy.QtWidgets import QWidget", "from spyder.config.user import NoDefault", "from spyder.plugins.base import BasePluginMixin, BasePluginWidgetMixin", "from spyder.utils.icon_manager import ima" ]
262
304
Parameters ---------- qaction_or_qshortcut: QAction or QShortcut QAction to register the shortcut for or QShortcut. context: str Name of the plugin this shortcut applies to. For instance, if you pass 'Editor' as context, the shortcut will only work when the editor is focused. Note: You can use '_' if you want the shortcut to be work for the entire application. name: str Name of the action the shortcut refers to (e.g. 'Debug exit'). add_shortcut_to_tip: bool If True, the shortcut is added to the action's tooltip. This is useful if the action is added to a toolbar and users hover it to see what it does. """ self.main.register_shortcut( qaction_or_qshortcut, context, name, add_shortcut_to_tip, self.CONF_SECTION) def unregister_shortcut(self, qaction_or_qshortcut, context, name, add_shortcut_to_tip=False): """ Unregister a shortcut associated to a QAction or a QShortcut to Spyder main application.
old_api.py
spyder.spyder.api.plugins
false
false
[ "from qtpy.QtCore import Signal, Slot", "from qtpy.QtWidgets import QWidget", "from spyder.config.user import NoDefault", "from spyder.plugins.base import BasePluginMixin, BasePluginWidgetMixin", "from spyder.utils.icon_manager import ima" ]
64
93
Parameters ---------- qaction_or_qshortcut: QAction or QShortcut QAction to register the shortcut for or QShortcut. context: str Name of the plugin this shortcut applies to. For instance, if you pass 'Editor' as context, the shortcut will only work when the editor is focused. Note: You can use '_' if you want the shortcut to be work for the entire application. name: str Name of the action the shortcut refers to (e.g. 'Debug exit'). add_shortcut_to_tip: bool If True, the shortcut is added to the action's tooltip. This is useful if the action is added to a toolbar and users hover it to see what it does. """ self.main.unregister_shortcut( qaction_or_qshortcut, context, name, add_shortcut_to_tip, self.CONF_SECTION) def register_widget_shortcuts(self, widget): """ Register shortcuts defined by a plugin's widget so they take effect when the plugin is focused. Parameters ---------- widget: QWidget Widget to register shortcuts for.
old_api.py
spyder.spyder.api.plugins
false
true
[ "from qtpy.QtCore import Signal, Slot", "from qtpy.QtWidgets import QWidget", "from spyder.config.user import NoDefault", "from spyder.plugins.base import BasePluginMixin, BasePluginWidgetMixin", "from spyder.utils.icon_manager import ima" ]
64
97
Parameters ---------- widget: QWidget Widget to register shortcuts for. Notes ----- The widget interface must have a method called `get_shortcut_data` for this to work. Please see `spyder/widgets/findreplace.py` for an example. """ for qshortcut, context, name in widget.get_shortcut_data(): self.register_shortcut(qshortcut, context, name) def unregister_widget_shortcuts(self, widget): """ Unregister shortcuts defined by a plugin's widget. Parameters ---------- widget: QWidget Widget to register shortcuts for. Notes ----- The widget interface must have a method called `get_shortcut_data` for this to work. Please see `spyder/widgets/findreplace.py` for an example. """ for qshortcut, context, name in widget.get_shortcut_data(): self.unregister_shortcut(qshortcut, context, name) def get_color_scheme(self): """ Get the current color scheme. Returns ------- dict Dictionary with properties and colors of the color scheme used in the Editor. Notes ----- This is useful to set the color scheme of all instances of CodeEditor used by the plugin. """ return super(BasePluginWidget, self)._get_color_scheme()
old_api.py
spyder.spyder.api.plugins
false
true
[ "from qtpy.QtCore import Signal, Slot", "from qtpy.QtWidgets import QWidget", "from spyder.config.user import NoDefault", "from spyder.plugins.base import BasePluginMixin, BasePluginWidgetMixin", "from spyder.utils.icon_manager import ima" ]
64
111
def switch_to_plugin(self): """ Switch to this plugin. Notes ----- This operation unmaximizes the current plugin (if any), raises this plugin to view (if it's hidden) and gives it focus (if possible). """ super(BasePluginWidget, self)._switch_to_plugin()
old_api.py
spyder.spyder.api.plugins
false
true
[ "from qtpy.QtCore import Signal, Slot", "from qtpy.QtWidgets import QWidget", "from spyder.config.user import NoDefault", "from spyder.plugins.base import BasePluginMixin, BasePluginWidgetMixin", "from spyder.utils.icon_manager import ima" ]
416
426
class SpyderPluginWidget(SpyderPlugin, BasePluginWidget): """ Spyder plugin widget class. All plugin widgets *must* inherit this class and reimplement its interface. """ # ---------------------------- ATTRIBUTES --------------------------------- # Path for images relative to the plugin path # Status: Optional IMG_PATH = 'images' # Control the size of the fonts used in the plugin # relative to the fonts defined in Spyder # Status: Optional FONT_SIZE_DELTA = 0 RICH_FONT_SIZE_DELTA = 0 # Disable actions in Spyder main menus when the plugin # is not visible # Status: Optional DISABLE_ACTIONS_WHEN_HIDDEN = True # Shortcut to give focus to the plugin. In Spyder we try # to reserve shortcuts that start with Ctrl+Shift+... for # these actions # Status: Optional shortcut = None # ------------------------------ METHODS ---------------------------------- def get_plugin_title(self): """ Get plugin's title. Returns ------- str Name of the plugin. """ raise NotImplementedError def get_plugin_icon(self): """ Get plugin's associated icon. Returns ------- QIcon QIcon instance """ return ima.icon('outline_explorer') def get_focus_widget(self): """ Get the plugin widget to give focus to.
old_api.py
spyder.spyder.api.plugins
false
true
[ "from qtpy.QtCore import Signal, Slot", "from qtpy.QtWidgets import QWidget", "from spyder.config.user import NoDefault", "from spyder.plugins.base import BasePluginMixin, BasePluginWidgetMixin", "from spyder.utils.icon_manager import ima" ]
429
485
def get_focus_widget(self): """ Get the plugin widget to give focus to. Returns ------- QWidget QWidget to give focus to. Notes ----- This is applied when plugin's dockwidget is raised on top-level. """ pass def closing_plugin(self, cancelable=False): """ Perform actions before the main window is closed. Returns ------- bool Whether the plugin may be closed immediately or not. Notes ----- The returned value is ignored if *cancelable* is False. """ return True def refresh_plugin(self): """ Refresh plugin after it receives focus. Notes ----- For instance, this is used to maintain in sync the Variable Explorer with the currently focused IPython console. """ pass def get_plugin_actions(self): """ Return a list of QAction's related to plugin. Notes ----- These actions will be shown in the plugins Options menu (i.e. the hambuger menu on the right of each plugin). """ return [] def register_plugin(self): """ Register plugin in Spyder's main window and connect it to other plugins.
old_api.py
spyder.spyder.api.plugins
false
true
[ "from qtpy.QtCore import Signal, Slot", "from qtpy.QtWidgets import QWidget", "from spyder.config.user import NoDefault", "from spyder.plugins.base import BasePluginMixin, BasePluginWidgetMixin", "from spyder.utils.icon_manager import ima" ]
483
538
def register_plugin(self): """ Register plugin in Spyder's main window and connect it to other plugins. Notes ----- Below is the minimal call necessary to register the plugin. If you override this method, please don't forget to make that call here too. """ self.add_dockwidget() def on_first_registration(self): """ Action to be performed on first plugin registration. Notes ----- This is mostly used to tabify the plugin next to one of the core plugins, like this: self.tabify(self.main.variableexplorer) """ raise NotImplementedError def apply_plugin_settings(self, options): """ Determine what to do to apply configuration plugin settings. """ pass def update_font(self): """ This must be reimplemented by plugins that need to adjust their fonts. """ pass def toggle_view(self, checked): """ Toggle dockwidget's visibility when its entry is selected in the menu `View > Panes`. Parameters ---------- checked: bool Is the entry in `View > Panes` checked or not?
old_api.py
spyder.spyder.api.plugins
false
true
[ "from qtpy.QtCore import Signal, Slot", "from qtpy.QtWidgets import QWidget", "from spyder.config.user import NoDefault", "from spyder.plugins.base import BasePluginMixin, BasePluginWidgetMixin", "from spyder.utils.icon_manager import ima" ]
535
582
Parameters ---------- checked: bool Is the entry in `View > Panes` checked or not? Notes ----- Redefining this method can be useful to execute certain actions when the plugin is made visible. For an example, please see `spyder/plugins/ipythonconsole/plugin.py` """ if not self.dockwidget: return if checked: self.dockwidget.show() self.dockwidget.raise_() else: self.dockwidget.hide() def set_ancestor(self, ancestor): """ Needed to update the ancestor/parent of child widgets when undocking. """ pass
old_api.py
spyder.spyder.api.plugins
false
true
[ "from qtpy.QtCore import Signal, Slot", "from qtpy.QtWidgets import QWidget", "from spyder.config.user import NoDefault", "from spyder.plugins.base import BasePluginMixin, BasePluginWidgetMixin", "from spyder.utils.icon_manager import ima" ]
64
87
# -*- coding: utf-8 -*- # # Copyright © Spyder Project Contributors # Licensed under the terms of the MIT License # (see spyder/__init__.py for details) """ Old API for plugins. These plugins were supported until Spyder 4, but they will be deprecated in the future. Please don't rely on them for new plugins and use instead the classes present in new_api.py """ # Third-party imports from qtpy.QtCore import Signal, Slot from qtpy.QtWidgets import QWidget # Local imports from spyder.config.user import NoDefault from spyder.plugins.base import BasePluginMixin, BasePluginWidgetMixin from spyder.utils.icon_manager import ima # ============================================================================= # SpyderPlugin # ============================================================================= # Code for: class BasePlugin(BasePluginMixin): # Code for: class SpyderPlugin(BasePlugin): # ============================================================================= # SpyderPluginWidget # ============================================================================= # Code for: class BasePluginWidget(QWidget, BasePluginWidgetMixin): # Code for: class SpyderPluginWidget(SpyderPlugin, BasePluginWidget):
old_api.py
spyder.spyder.api.plugins
false
false
[ "from qtpy.QtCore import Signal, Slot", "from qtpy.QtWidgets import QWidget", "from spyder.config.user import NoDefault", "from spyder.plugins.base import BasePluginMixin, BasePluginWidgetMixin", "from spyder.utils.icon_manager import ima" ]
1
40
# -*- coding: utf-8 -*- # # Copyright © Spyder Project Contributors # Licensed under the terms of the MIT License # (see spyder/__init__.py for details) """Enum of Spyder internal plugins.""" class Plugins: """ Convenience class for accessing Spyder internal plugins. """ All = "all" # Wildcard to populate REQUIRES with all available plugins Appearance = 'appearance' Application = 'application' Completions = 'completions' Console = 'internal_console' Debugger = 'debugger' Editor = 'editor' Explorer = 'explorer' ExternalTerminal = 'external_terminal' Find = 'find_in_files' Help = 'help' History = 'historylog' IPythonConsole = 'ipython_console' Layout = 'layout' MainInterpreter = 'main_interpreter' MainMenu = 'mainmenu' OnlineHelp = 'onlinehelp' OutlineExplorer = 'outline_explorer' Plots = 'plots' Preferences = 'preferences' Profiler = 'profiler' Projects = 'project_explorer' Pylint = 'pylint' PythonpathManager = 'pythonpath_manager' Run = 'run' Shortcuts = 'shortcuts' StatusBar = 'statusbar' Switcher = 'switcher' Toolbar = "toolbar" Tours = 'tours' VariableExplorer = 'variable_explorer' WorkingDirectory = 'workingdir'
enum.py
spyder.spyder.api.plugins
true
false
[]
1
45
class DockablePlugins: Console = 'internal_console' Debugger = 'debugger' Editor = 'editor' Explorer = 'explorer' Find = 'find_in_files' Help = 'help' History = 'historylog' IPythonConsole = 'ipython_console' OnlineHelp = 'onlinehelp' OutlineExplorer = 'outline_explorer' Plots = 'plots' Profiler = 'profiler' Projects = 'project_explorer' Pylint = 'pylint' VariableExplorer = 'variable_explorer'
enum.py
spyder.spyder.api.plugins
true
false
[]
48
63
# -*- coding: utf-8 -*- # # Copyright © Spyder Project Contributors # Licensed under the terms of the MIT License # (see spyder/__init__.py for details) """ Spyder API plugin registration decorators. """ # Standard library imports import functools from typing import Callable, Optional import inspect def on_plugin_available(func: Callable = None, plugin: Optional[str] = None): """ Method decorator used to handle plugin availability on Spyder. The methods that use this decorator must have the following signature: `def method(self)` when observing a single plugin or `def method(self, plugin): ...` when observing multiple plugins or all plugins that were listed as dependencies. Parameters ---------- func: Callable Method to decorate. Given by default when applying the decorator. plugin: Optional[str] Name of the requested plugin whose availability triggers the method. Returns ------- func: Callable The same method that was given as input. """ if func is None: return functools.partial(on_plugin_available, plugin=plugin) if plugin is None: # Use special __all identifier to signal that the function # observes all plugins listed as dependencies. plugin = '__all' func._plugin_listen = plugin return func
decorators.py
spyder.spyder.api.plugin_registration
false
true
[ "import functools", "from typing import Callable, Optional", "import inspect" ]
1
48
def on_plugin_teardown(func: Callable = None, plugin: Optional[str] = None): """ Method decorator used to handle plugin teardown on Spyder. This decorator will be called **before** the specified plugin is deleted and also **before** the plugin that uses the decorator is destroyed. The methods that use this decorator must have the following signature: `def method(self)`. Parameters ---------- func: Callable Method to decorate. Given by default when applying the decorator. plugin: str Name of the requested plugin whose teardown triggers the method. Returns ------- func: Callable The same method that was given as input. """ if func is None: return functools.partial(on_plugin_teardown, plugin=plugin) if plugin is None: raise ValueError('on_plugin_teardown must have a well defined ' 'plugin keyword argument value, ' 'e.g., plugin=Plugins.Editor') func._plugin_teardown = plugin return func
decorators.py
spyder.spyder.api.plugin_registration
false
false
[ "import functools", "from typing import Callable, Optional", "import inspect" ]
51
83
# -*- coding: utf-8 -*- # # Copyright © Spyder Project Contributors # Licensed under the terms of the MIT License # (see spyder/__init__.py for details) """ Spyder API plugin registration mixins. """ # Standard library imports import logging from spyder.api.exceptions import SpyderAPIError from spyder.api.plugins import Plugins logger = logging.getLogger(__name__)
mixins.py
spyder.spyder.api.plugin_registration
false
false
[ "import logging", "from spyder.api.exceptions import SpyderAPIError", "from spyder.api.plugins import Plugins" ]
1
17
class SpyderPluginObserver: """ This mixin enables a class to receive notifications when a plugin is available, by registering methods using the :function:`spyder.api.plugin_registration.decorators.on_plugin_available` decorator. When any of the requested plugins is ready, the corresponding registered method is called. Notes ----- This mixin will only operate over the plugin requirements listed under `REQUIRES` and `OPTIONAL` class constants. """ def __init__(self): self._plugin_listeners = {} self._plugin_teardown_listeners = {} for method_name in dir(self): method = getattr(self, method_name, None) if hasattr(method, '_plugin_listen'): plugin_listen = method._plugin_listen # Check if plugin is listed among REQUIRES and OPTIONAL. # Note: We can't do this validation for the Layout plugin # because it depends on all plugins through the Plugins.All # wildcard. if ( self.NAME != Plugins.Layout and (plugin_listen not in self.REQUIRES + self.OPTIONAL) ): raise SpyderAPIError( f"Method {method_name} of {self} is trying to watch " f"plugin {plugin_listen}, but that plugin is not " f"listed in REQUIRES nor OPTIONAL." )
mixins.py
spyder.spyder.api.plugin_registration
true
true
[ "import logging", "from spyder.api.exceptions import SpyderAPIError", "from spyder.api.plugins import Plugins" ]
20
56
logger.debug( f'Method {method_name} is watching plugin {plugin_listen}' ) self._plugin_listeners[plugin_listen] = method_name if hasattr(method, '_plugin_teardown'): plugin_teardown = method._plugin_teardown # Check if plugin is listed among REQUIRES and OPTIONAL. # Note: We can't do this validation for the Layout plugin # because it depends on all plugins through the Plugins.All # wildcard. if ( self.NAME != Plugins.Layout and (plugin_teardown not in self.REQUIRES + self.OPTIONAL) ): raise SpyderAPIError( f"Method {method_name} of {self} is trying to watch " f"plugin {plugin_teardown}, but that plugin is not " f"listed in REQUIRES nor OPTIONAL." ) logger.debug(f'Method {method_name} will handle plugin ' f'teardown for {plugin_teardown}') self._plugin_teardown_listeners[plugin_teardown] = method_name def _on_plugin_available(self, plugin: str): """ Handle plugin availability and redirect it to plugin-specific startup handlers.
mixins.py
spyder.spyder.api.plugin_registration
false
true
[ "import logging", "from spyder.api.exceptions import SpyderAPIError", "from spyder.api.plugins import Plugins" ]
58
87
def _on_plugin_available(self, plugin: str): """ Handle plugin availability and redirect it to plugin-specific startup handlers. Parameters ---------- plugin: str Name of the plugin that was notified as available. """ # Call plugin specific handler if plugin in self._plugin_listeners: method_name = self._plugin_listeners[plugin] method = getattr(self, method_name) logger.debug(f'Calling {method}') method() # Call global plugin handler if '__all' in self._plugin_listeners: method_name = self._plugin_listeners['__all'] method = getattr(self, method_name) method(plugin) def _on_plugin_teardown(self, plugin: str): """ Handle plugin teardown and redirect it to plugin-specific teardown handlers. Parameters ---------- plugin: str Name of the plugin that is going through its teardown process. """ # Call plugin specific handler if plugin in self._plugin_teardown_listeners: method_name = self._plugin_teardown_listeners[plugin] method = getattr(self, method_name) logger.debug(f'Calling {method}') method()
mixins.py
spyder.spyder.api.plugin_registration
false
true
[ "import logging", "from spyder.api.exceptions import SpyderAPIError", "from spyder.api.plugins import Plugins" ]
84
122
class PreferencesAdapter(SpyderConfigurationAccessor): # Fake class constants used to register the configuration page CONF_WIDGET_CLASS = PluginsConfigPage NAME = 'plugin_registry' CONF_VERSION = None ADDITIONAL_CONF_OPTIONS = None ADDITIONAL_CONF_TABS = None CONF_SECTION = "" def apply_plugin_settings(self, _unused): pass def apply_conf(self, _unused): pass
registry.py
spyder.spyder.api.plugin_registration
false
true
[ "import logging", "from typing import Dict, List, Union, Type, Any, Set, Optional", "from qtpy.QtCore import QObject, Signal", "from spyder import dependencies", "from spyder.config.base import _, running_under_pytest", "from spyder.config.manager import CONF", "from spyder.api.config.mixins import SpyderConfigurationAccessor", "from spyder.api.plugin_registration._confpage import PluginsConfigPage", "from spyder.api.exceptions import SpyderAPIError", "from spyder.api.plugins import (", "from spyder.utils.icon_manager import ima" ]
42
55
class SpyderPluginRegistry(QObject, PreferencesAdapter): """ Global plugin registry. This class handles a plugin initialization/teardown lifetime, including notifications when a plugin is available or not. This registry alleviates the limitations of a topological sort-based plugin initialization by enabling plugins to have bidirectional dependencies instead of unidirectional ones. Notes ----- 1. This class should be instantiated as a singleton. 2. A plugin should not depend on other plugin to perform its initialization since it could cause deadlocks. """ sig_plugin_ready = Signal(str, bool) """ This signal is used to let the main window know that a plugin is ready. Parameters ---------- plugin_name: str Name of the plugin that is available. omit_conf: bool True if the plugin configuration does not need to be written. """ def __init__(self): super().__init__() PreferencesAdapter.__init__(self) # Reference to the main window self.main = None # Dictionary that maps a plugin name to a list of the plugin names # that depend on it. self.plugin_dependents = {} # type: Dict[str, Dict[str, List[str]]] # Dictionary that maps a plugin name to a list of the plugin names # that the plugin depends on. self.plugin_dependencies = {} # type: Dict[str, Dict[str, List[str]]]
registry.py
spyder.spyder.api.plugin_registration
false
true
[ "import logging", "from typing import Dict, List, Union, Type, Any, Set, Optional", "from qtpy.QtCore import QObject, Signal", "from spyder import dependencies", "from spyder.config.base import _, running_under_pytest", "from spyder.config.manager import CONF", "from spyder.api.config.mixins import SpyderConfigurationAccessor", "from spyder.api.plugin_registration._confpage import PluginsConfigPage", "from spyder.api.exceptions import SpyderAPIError", "from spyder.api.plugins import (", "from spyder.utils.icon_manager import ima" ]
58
101
# Dictionary that maps a plugin name to a list of the plugin names # that the plugin depends on. self.plugin_dependencies = {} # type: Dict[str, Dict[str, List[str]]] # Plugin dictionary mapped by their names self.plugin_registry = {} # type: Dict[str, SpyderPluginClass] # Dictionary that maps a plugin name to its availability. self.plugin_availability = {} # type: Dict[str, bool] # Set that stores the plugin names of all Spyder 4 plugins. self.old_plugins = set({}) # type: set[str] # Set that stores the names of the plugins that are enabled self.enabled_plugins = set({}) # type: set[str] # Set that stores the names of the internal plugins self.internal_plugins = set({}) # type: set[str] # Set that stores the names of the external plugins self.external_plugins = set({}) # type: set[str] # Dictionary that contains all the internal plugins (enabled or not) self.all_internal_plugins = {} # type: Dict[str, Tuple[str, Type[SpyderPluginClass]]] # Dictionary that contains all the external plugins (enabled or not) self.all_external_plugins = {} # type: Dict[str, Tuple[str, Type[SpyderPluginClass]]] # This is used to allow disabling external plugins through Preferences self._external_plugins_conf_section = "external_plugins"
registry.py
spyder.spyder.api.plugin_registration
false
false
[ "import logging", "from typing import Dict, List, Union, Type, Any, Set, Optional", "from qtpy.QtCore import QObject, Signal", "from spyder import dependencies", "from spyder.config.base import _, running_under_pytest", "from spyder.config.manager import CONF", "from spyder.api.config.mixins import SpyderConfigurationAccessor", "from spyder.api.plugin_registration._confpage import PluginsConfigPage", "from spyder.api.exceptions import SpyderAPIError", "from spyder.api.plugins import (", "from spyder.utils.icon_manager import ima" ]
99
128
# This is used to allow disabling external plugins through Preferences self._external_plugins_conf_section = "external_plugins" # ------------------------- PRIVATE API ----------------------------------- def _update_dependents(self, plugin: str, dependent_plugin: str, key: str): """Add `dependent_plugin` to the list of dependents of `plugin`.""" plugin_dependents = self.plugin_dependents.get(plugin, {}) plugin_strict_dependents = plugin_dependents.get(key, []) plugin_strict_dependents.append(dependent_plugin) plugin_dependents[key] = plugin_strict_dependents self.plugin_dependents[plugin] = plugin_dependents def _update_dependencies(self, plugin: str, required_plugin: str, key: str): """Add `required_plugin` to the list of dependencies of `plugin`.""" plugin_dependencies = self.plugin_dependencies.get(plugin, {}) plugin_strict_dependencies = plugin_dependencies.get(key, []) plugin_strict_dependencies.append(required_plugin) plugin_dependencies[key] = plugin_strict_dependencies self.plugin_dependencies[plugin] = plugin_dependencies
registry.py
spyder.spyder.api.plugin_registration
false
true
[ "import logging", "from typing import Dict, List, Union, Type, Any, Set, Optional", "from qtpy.QtCore import QObject, Signal", "from spyder import dependencies", "from spyder.config.base import _, running_under_pytest", "from spyder.config.manager import CONF", "from spyder.api.config.mixins import SpyderConfigurationAccessor", "from spyder.api.plugin_registration._confpage import PluginsConfigPage", "from spyder.api.exceptions import SpyderAPIError", "from spyder.api.plugins import (", "from spyder.utils.icon_manager import ima" ]
127
146
def _update_plugin_info(self, plugin_name: str, required_plugins: List[str], optional_plugins: List[str]): """Update the dependencies and dependents of `plugin_name`.""" for plugin in required_plugins: self._update_dependencies(plugin_name, plugin, 'requires') self._update_dependents(plugin, plugin_name, 'requires') for plugin in optional_plugins: self._update_dependencies(plugin_name, plugin, 'optional') self._update_dependents(plugin, plugin_name, 'optional') def _instantiate_spyder5_plugin( self, main_window: Any, PluginClass: Type[Spyder5PluginClass], external: bool) -> Spyder5PluginClass: """Instantiate and register a Spyder 5+ plugin.""" required_plugins = list(set(PluginClass.REQUIRES)) optional_plugins = list(set(PluginClass.OPTIONAL)) plugin_name = PluginClass.NAME logger.debug(f'Registering plugin {plugin_name} - {PluginClass}') if PluginClass.CONF_FILE: CONF.register_plugin(PluginClass) for plugin in list(required_plugins): if plugin == Plugins.All: required_plugins = list(set(required_plugins + ALL_PLUGINS)) for plugin in list(optional_plugins): if plugin == Plugins.All: optional_plugins = list(set(optional_plugins + ALL_PLUGINS))
registry.py
spyder.spyder.api.plugin_registration
false
false
[ "import logging", "from typing import Dict, List, Union, Type, Any, Set, Optional", "from qtpy.QtCore import QObject, Signal", "from spyder import dependencies", "from spyder.config.base import _, running_under_pytest", "from spyder.config.manager import CONF", "from spyder.api.config.mixins import SpyderConfigurationAccessor", "from spyder.api.plugin_registration._confpage import PluginsConfigPage", "from spyder.api.exceptions import SpyderAPIError", "from spyder.api.plugins import (", "from spyder.utils.icon_manager import ima" ]
148
180
for plugin in list(optional_plugins): if plugin == Plugins.All: optional_plugins = list(set(optional_plugins + ALL_PLUGINS)) # Update plugin dependency information self._update_plugin_info(plugin_name, required_plugins, optional_plugins) # Create and store plugin instance plugin_instance = PluginClass(main_window, configuration=CONF) self.plugin_registry[plugin_name] = plugin_instance # Connect plugin availability signal to notification system plugin_instance.sig_plugin_ready.connect( lambda: self.notify_plugin_availability( plugin_name, omit_conf=PluginClass.CONF_FILE)) # Initialize plugin instance plugin_instance.initialize() # Register plugins that are already available self._notify_plugin_dependencies(plugin_name) # Register the plugin name under the external or internal # plugin set if external: self.external_plugins |= {plugin_name} else: self.internal_plugins |= {plugin_name}
registry.py
spyder.spyder.api.plugin_registration
false
false
[ "import logging", "from typing import Dict, List, Union, Type, Any, Set, Optional", "from qtpy.QtCore import QObject, Signal", "from spyder import dependencies", "from spyder.config.base import _, running_under_pytest", "from spyder.config.manager import CONF", "from spyder.api.config.mixins import SpyderConfigurationAccessor", "from spyder.api.plugin_registration._confpage import PluginsConfigPage", "from spyder.api.exceptions import SpyderAPIError", "from spyder.api.plugins import (", "from spyder.utils.icon_manager import ima" ]
178
206
if external: # These attributes come from spyder.app.find_plugins module = PluginClass._spyder_module_name package_name = PluginClass._spyder_package_name version = PluginClass._spyder_version description = plugin_instance.get_description() dependencies.add(module, package_name, description, version, None, kind=dependencies.PLUGIN) return plugin_instance def _instantiate_spyder4_plugin( self, main_window: Any, PluginClass: Type[Spyder4PluginClass], external: bool, args: tuple, kwargs: dict) -> Spyder4PluginClass: """Instantiate and register a Spyder 4 plugin.""" plugin_name = PluginClass.NAME # Create old plugin instance plugin_instance = PluginClass(main_window, *args, **kwargs) if hasattr(plugin_instance, 'COMPLETION_PROVIDER_NAME'): if Plugins.Completions in self: completions = self.get_plugin(Plugins.Completions) completions.register_completion_plugin(plugin_instance) else: plugin_instance.register_plugin() # Register plugin in the registry self.plugin_registry[plugin_name] = plugin_instance
registry.py
spyder.spyder.api.plugin_registration
false
false
[ "import logging", "from typing import Dict, List, Union, Type, Any, Set, Optional", "from qtpy.QtCore import QObject, Signal", "from spyder import dependencies", "from spyder.config.base import _, running_under_pytest", "from spyder.config.manager import CONF", "from spyder.api.config.mixins import SpyderConfigurationAccessor", "from spyder.api.plugin_registration._confpage import PluginsConfigPage", "from spyder.api.exceptions import SpyderAPIError", "from spyder.api.plugins import (", "from spyder.utils.icon_manager import ima" ]
208
238
# Register plugin in the registry self.plugin_registry[plugin_name] = plugin_instance # Register the name of the plugin under the external or # internal plugin set if external: self.external_plugins |= {plugin_name} else: self.internal_plugins |= {plugin_name} # Since Spyder 5+ plugins are loaded before old ones, preferences # will be available at this point. preferences = self.get_plugin(Plugins.Preferences) preferences.register_plugin_preferences(plugin_instance) # Notify new-API plugins that depend on old ones self.notify_plugin_availability(plugin_name, False) return plugin_instance def _notify_plugin_dependencies(self, plugin_name: str): """Notify a plugin of its available dependencies.""" plugin_instance = self.plugin_registry[plugin_name] plugin_dependencies = self.plugin_dependencies.get(plugin_name, {}) required_plugins = plugin_dependencies.get('requires', []) optional_plugins = plugin_dependencies.get('optional', []) for plugin in required_plugins + optional_plugins: if plugin in self.plugin_registry: if self.plugin_availability.get(plugin, False): logger.debug(f'Plugin {plugin} has already loaded') plugin_instance._on_plugin_available(plugin)
registry.py
spyder.spyder.api.plugin_registration
false
true
[ "import logging", "from typing import Dict, List, Union, Type, Any, Set, Optional", "from qtpy.QtCore import QObject, Signal", "from spyder import dependencies", "from spyder.config.base import _, running_under_pytest", "from spyder.config.manager import CONF", "from spyder.api.config.mixins import SpyderConfigurationAccessor", "from spyder.api.plugin_registration._confpage import PluginsConfigPage", "from spyder.api.exceptions import SpyderAPIError", "from spyder.api.plugins import (", "from spyder.utils.icon_manager import ima" ]
237
268
def _notify_plugin_teardown(self, plugin_name: str): """Notify dependents of a plugin that is going to be unavailable.""" plugin_dependents = self.plugin_dependents.get(plugin_name, {}) required_plugins = plugin_dependents.get('requires', []) optional_plugins = plugin_dependents.get('optional', []) for plugin in required_plugins + optional_plugins: if plugin in self.plugin_registry: if self.plugin_availability.get(plugin, False): logger.debug(f'Notifying plugin {plugin} that ' f'{plugin_name} is going to be turned off') plugin_instance = self.plugin_registry[plugin] plugin_instance._on_plugin_teardown(plugin_name) def _teardown_plugin(self, plugin_name: str): """Disconnect a plugin from its dependencies.""" plugin_instance = self.plugin_registry[plugin_name] plugin_dependencies = self.plugin_dependencies.get(plugin_name, {}) required_plugins = plugin_dependencies.get('requires', []) optional_plugins = plugin_dependencies.get('optional', []) for plugin in required_plugins + optional_plugins: if plugin in self.plugin_registry: if self.plugin_availability.get(plugin, False): logger.debug(f'Disconnecting {plugin_name} from {plugin}') plugin_instance._on_plugin_teardown(plugin)
registry.py
spyder.spyder.api.plugin_registration
false
true
[ "import logging", "from typing import Dict, List, Union, Type, Any, Set, Optional", "from qtpy.QtCore import QObject, Signal", "from spyder import dependencies", "from spyder.config.base import _, running_under_pytest", "from spyder.config.manager import CONF", "from spyder.api.config.mixins import SpyderConfigurationAccessor", "from spyder.api.plugin_registration._confpage import PluginsConfigPage", "from spyder.api.exceptions import SpyderAPIError", "from spyder.api.plugins import (", "from spyder.utils.icon_manager import ima" ]
270
295
# -------------------------- PUBLIC API ----------------------------------- def register_plugin( self, main_window: Any, PluginClass: Type[SpyderPluginClass], *args: tuple, external: bool = False, **kwargs: dict) -> SpyderPluginClass: """ Register a plugin into the Spyder registry. Parameters ---------- main_window: spyder.app.mainwindow.MainWindow Reference to Spyder's main window. PluginClass: type[SpyderPluginClass] The plugin class to register and create. It must be one of `spyder.app.registry.SpyderPluginClass`. *args: tuple Positional arguments used to initialize the plugin instance. external: bool If True, then the plugin is stored as a external plugin. Otherwise it will be marked as an internal plugin. Default: False **kwargs: dict Optional keyword arguments used to initialize the plugin instance. Returns ------- plugin: SpyderPluginClass The instance of the registered plugin. Raises ------ TypeError If the `PluginClass` does not inherit from any of `spyder.app.registry.SpyderPluginClass`
registry.py
spyder.spyder.api.plugin_registration
false
false
[ "import logging", "from typing import Dict, List, Union, Type, Any, Set, Optional", "from qtpy.QtCore import QObject, Signal", "from spyder import dependencies", "from spyder.config.base import _, running_under_pytest", "from spyder.config.manager import CONF", "from spyder.api.config.mixins import SpyderConfigurationAccessor", "from spyder.api.plugin_registration._confpage import PluginsConfigPage", "from spyder.api.exceptions import SpyderAPIError", "from spyder.api.plugins import (", "from spyder.utils.icon_manager import ima" ]
297
331
Raises ------ TypeError If the `PluginClass` does not inherit from any of `spyder.app.registry.SpyderPluginClass` Notes ----- The optional `*args` and `**kwargs` will be removed once all plugins are migrated. """ if not issubclass(PluginClass, (SpyderPluginV2, SpyderPlugin)): raise TypeError(f'{PluginClass} does not inherit from ' f'{SpyderPluginV2} nor {SpyderPlugin}') instance = None if issubclass(PluginClass, SpyderPluginV2): # Register a Spyder 5+ plugin instance = self._instantiate_spyder5_plugin( main_window, PluginClass, external) elif issubclass(PluginClass, SpyderPlugin): # Register a Spyder 4 plugin instance = self._instantiate_spyder4_plugin( main_window, PluginClass, external, args, kwargs) return instance def notify_plugin_availability(self, plugin_name: str, notify_main: bool = True, omit_conf: bool = False): """ Notify dependent plugins of a given plugin of its availability.
registry.py
spyder.spyder.api.plugin_registration
false
false
[ "import logging", "from typing import Dict, List, Union, Type, Any, Set, Optional", "from qtpy.QtCore import QObject, Signal", "from spyder import dependencies", "from spyder.config.base import _, running_under_pytest", "from spyder.config.manager import CONF", "from spyder.api.config.mixins import SpyderConfigurationAccessor", "from spyder.api.plugin_registration._confpage import PluginsConfigPage", "from spyder.api.exceptions import SpyderAPIError", "from spyder.api.plugins import (", "from spyder.utils.icon_manager import ima" ]
327
358
Parameters ---------- plugin_name: str Name of the plugin that is available. notify_main: bool If True, then a signal is emitted to the main window to perform further registration steps. omit_conf: bool If True, then the main window is instructed to not write the plugin configuration into the Spyder configuration file. """ logger.debug(f'Plugin {plugin_name} has finished loading, ' 'sending notifications') # Set plugin availability to True self.plugin_availability[plugin_name] = True # Notify the main window that the plugin is ready if notify_main: self.sig_plugin_ready.emit(plugin_name, omit_conf) # Notify plugin dependents plugin_dependents = self.plugin_dependents.get(plugin_name, {}) required_plugins = plugin_dependents.get('requires', []) optional_plugins = plugin_dependents.get('optional', []) for plugin in required_plugins + optional_plugins: if plugin in self.plugin_registry: plugin_instance = self.plugin_registry[plugin] plugin_instance._on_plugin_available(plugin_name) if plugin_name == Plugins.Preferences and not running_under_pytest(): plugin_instance = self.plugin_registry[plugin_name] plugin_instance.register_plugin_preferences(self)
registry.py
spyder.spyder.api.plugin_registration
false
false
[ "import logging", "from typing import Dict, List, Union, Type, Any, Set, Optional", "from qtpy.QtCore import QObject, Signal", "from spyder import dependencies", "from spyder.config.base import _, running_under_pytest", "from spyder.config.manager import CONF", "from spyder.api.config.mixins import SpyderConfigurationAccessor", "from spyder.api.plugin_registration._confpage import PluginsConfigPage", "from spyder.api.exceptions import SpyderAPIError", "from spyder.api.plugins import (", "from spyder.utils.icon_manager import ima" ]
80
113
def can_delete_plugin(self, plugin_name: str) -> bool: """ Check if a plugin from the registry can be deleted by its name. Paremeters ---------- plugin_name: str Name of the plugin to check for deletion. Returns ------- plugin_deleted: bool True if the plugin can be deleted. False otherwise. """ plugin_instance = self.plugin_registry[plugin_name] # Determine if plugin can be closed can_delete = True if isinstance(plugin_instance, SpyderPluginV2): can_delete = plugin_instance.can_close() elif isinstance(plugin_instance, SpyderPlugin): can_delete = plugin_instance.closing_plugin(True) return can_delete def dock_undocked_plugin( self, plugin_name: str, save_undocked: bool = False): """ Dock plugin if undocked and save undocked state if requested Parameters ---------- plugin_name: str Name of the plugin to check for deletion. save_undocked : bool, optional True if the undocked state needs to be saved. The default is False. Returns ------- None. """ plugin_instance = self.plugin_registry[plugin_name]
registry.py
spyder.spyder.api.plugin_registration
false
false
[ "import logging", "from typing import Dict, List, Union, Type, Any, Set, Optional", "from qtpy.QtCore import QObject, Signal", "from spyder import dependencies", "from spyder.config.base import _, running_under_pytest", "from spyder.config.manager import CONF", "from spyder.api.config.mixins import SpyderConfigurationAccessor", "from spyder.api.plugin_registration._confpage import PluginsConfigPage", "from spyder.api.exceptions import SpyderAPIError", "from spyder.api.plugins import (", "from spyder.utils.icon_manager import ima" ]
395
435
Returns ------- None. """ plugin_instance = self.plugin_registry[plugin_name] if isinstance(plugin_instance, SpyderDockablePlugin): # Close undocked plugin if needed and save undocked state plugin_instance.close_window(save_undocked=save_undocked) elif isinstance(plugin_instance, SpyderPluginWidget): # Save if plugin was undocked to restore it the next time. if plugin_instance._undocked_window and save_undocked: plugin_instance.set_option( 'undocked_on_window_close', True) else: plugin_instance.set_option( 'undocked_on_window_close', False) # Close undocked plugins. plugin_instance._close_window() def delete_plugin(self, plugin_name: str, teardown: bool = True, check_can_delete: bool = True) -> bool: """ Remove and delete a plugin from the registry by its name. Paremeters ---------- plugin_name: str Name of the plugin to delete. teardown: bool True if the teardown notification to other plugins should be sent when deleting the plugin, False otherwise. check_can_delete: bool True if the plugin should validate if it can be closed when this method is called, False otherwise.
registry.py
spyder.spyder.api.plugin_registration
false
false
[ "import logging", "from typing import Dict, List, Union, Type, Any, Set, Optional", "from qtpy.QtCore import QObject, Signal", "from spyder import dependencies", "from spyder.config.base import _, running_under_pytest", "from spyder.config.manager import CONF", "from spyder.api.config.mixins import SpyderConfigurationAccessor", "from spyder.api.plugin_registration._confpage import PluginsConfigPage", "from spyder.api.exceptions import SpyderAPIError", "from spyder.api.plugins import (", "from spyder.utils.icon_manager import ima" ]
322
357
Returns ------- plugin_deleted: bool True if the registry was able to teardown and remove the plugin. False otherwise. """ logger.debug(f'Deleting plugin {plugin_name}') plugin_instance = self.plugin_registry[plugin_name] # Determine if plugin can be closed if check_can_delete: can_delete = self.can_delete_plugin(plugin_name) if not can_delete: return False if isinstance(plugin_instance, SpyderPluginV2): # Cleanly delete plugin widgets. This avoids segfautls with # PyQt 5.15 if isinstance(plugin_instance, SpyderDockablePlugin): try: plugin_instance.get_widget().close() plugin_instance.get_widget().deleteLater() except RuntimeError: pass else: container = plugin_instance.get_container() if container: try: container.close() container.deleteLater() except RuntimeError: pass # Delete plugin try: plugin_instance.deleteLater() except RuntimeError: pass if teardown: # Disconnect plugin from other plugins self._teardown_plugin(plugin_name)
registry.py
spyder.spyder.api.plugin_registration
false
false
[ "import logging", "from typing import Dict, List, Union, Type, Any, Set, Optional", "from qtpy.QtCore import QObject, Signal", "from spyder import dependencies", "from spyder.config.base import _, running_under_pytest", "from spyder.config.manager import CONF", "from spyder.api.config.mixins import SpyderConfigurationAccessor", "from spyder.api.plugin_registration._confpage import PluginsConfigPage", "from spyder.api.exceptions import SpyderAPIError", "from spyder.api.plugins import (", "from spyder.utils.icon_manager import ima" ]
322
362
# Disconnect depending plugins from the plugin to delete self._notify_plugin_teardown(plugin_name) # Perform plugin closure tasks try: plugin_instance.on_close(True) except RuntimeError: pass elif isinstance(plugin_instance, SpyderPlugin): try: plugin_instance.deleteLater() except RuntimeError: pass if teardown: # Disconnect depending plugins from the plugin to delete self._notify_plugin_teardown(plugin_name) # Delete plugin from the registry and auxiliary structures self.plugin_dependents.pop(plugin_name, None) self.plugin_dependencies.pop(plugin_name, None) if plugin_instance.CONF_FILE: # This must be done after on_close() so that plugins can modify # their (external) config therein. CONF.unregister_plugin(plugin_instance) for plugin in self.plugin_dependents: all_plugin_dependents = self.plugin_dependents[plugin] for key in {'requires', 'optional'}: plugin_dependents = all_plugin_dependents.get(key, []) if plugin_name in plugin_dependents: plugin_dependents.remove(plugin_name)
registry.py
spyder.spyder.api.plugin_registration
false
false
[ "import logging", "from typing import Dict, List, Union, Type, Any, Set, Optional", "from qtpy.QtCore import QObject, Signal", "from spyder import dependencies", "from spyder.config.base import _, running_under_pytest", "from spyder.config.manager import CONF", "from spyder.api.config.mixins import SpyderConfigurationAccessor", "from spyder.api.plugin_registration._confpage import PluginsConfigPage", "from spyder.api.exceptions import SpyderAPIError", "from spyder.api.plugins import (", "from spyder.utils.icon_manager import ima" ]
510
540
for plugin in self.plugin_dependencies: all_plugin_dependencies = self.plugin_dependencies[plugin] for key in {'requires', 'optional'}: plugin_dependencies = all_plugin_dependencies.get(key, []) if plugin_name in plugin_dependencies: plugin_dependencies.remove(plugin_name) self.plugin_availability.pop(plugin_name) self.old_plugins -= {plugin_name} self.enabled_plugins -= {plugin_name} self.internal_plugins -= {plugin_name} self.external_plugins -= {plugin_name} # Remove the plugin from the registry self.plugin_registry.pop(plugin_name) return True def dock_all_undocked_plugins(self, save_undocked: bool = False): """ Dock undocked plugins and save undocked state if required. Parameters ---------- save_undocked : bool, optional True if the undocked state needs to be saved. The default is False. Returns ------- None. """ for plugin_name in ( set(self.external_plugins) | set(self.internal_plugins)): self.dock_undocked_plugin( plugin_name, save_undocked=save_undocked) def can_delete_all_plugins(self, excluding: Optional[Set[str]] = None) -> bool: """ Determine if all plugins can be deleted except the ones to exclude.
registry.py
spyder.spyder.api.plugin_registration
false
true
[ "import logging", "from typing import Dict, List, Union, Type, Any, Set, Optional", "from qtpy.QtCore import QObject, Signal", "from spyder import dependencies", "from spyder.config.base import _, running_under_pytest", "from spyder.config.manager import CONF", "from spyder.api.config.mixins import SpyderConfigurationAccessor", "from spyder.api.plugin_registration._confpage import PluginsConfigPage", "from spyder.api.exceptions import SpyderAPIError", "from spyder.api.plugins import (", "from spyder.utils.icon_manager import ima" ]
542
582
Parameters ---------- excluding: Optional[Set[str]] A set that lists plugins (by name) that will not be deleted. Returns ------- bool True if all plugins can be closed. False otherwise. """ excluding = excluding or set({}) can_close = True # Check external plugins for plugin_name in ( set(self.external_plugins) | set(self.internal_plugins)): if plugin_name not in excluding: plugin_instance = self.plugin_registry[plugin_name] if isinstance(plugin_instance, SpyderPlugin): can_close &= self.can_delete_plugin(plugin_name) if not can_close: break return can_close def delete_all_plugins(self, excluding: Optional[Set[str]] = None, close_immediately: bool = False) -> bool: """ Remove all plugins from the registry. The teardown mechanism will remove external plugins first and then internal ones, where the Spyder 4 plugins will be removed first and then the Spyder 5 ones. Parameters ---------- excluding: Optional[Set[str]] A set that lists plugins (by name) that will not be deleted. close_immediately: bool If true, then the `can_close` status will be ignored.
registry.py
spyder.spyder.api.plugin_registration
false
false
[ "import logging", "from typing import Dict, List, Union, Type, Any, Set, Optional", "from qtpy.QtCore import QObject, Signal", "from spyder import dependencies", "from spyder.config.base import _, running_under_pytest", "from spyder.config.manager import CONF", "from spyder.api.config.mixins import SpyderConfigurationAccessor", "from spyder.api.plugin_registration._confpage import PluginsConfigPage", "from spyder.api.exceptions import SpyderAPIError", "from spyder.api.plugins import (", "from spyder.utils.icon_manager import ima" ]
80
119
Returns ------- all_deleted: bool True if all the plugins were closed and deleted. False otherwise. """ excluding = excluding or set({}) can_close = True # Check if all the plugins can be closed can_close = self.can_delete_all_plugins(excluding=excluding) if not can_close and not close_immediately: return False # Dock undocked plugins self.dock_all_undocked_plugins(save_undocked=True) # Delete Spyder 4 external plugins for plugin_name in set(self.external_plugins): if plugin_name not in excluding: plugin_instance = self.plugin_registry[plugin_name] if isinstance(plugin_instance, SpyderPlugin): can_close &= self.delete_plugin( plugin_name, teardown=False, check_can_delete=False) if not can_close and not close_immediately: break if not can_close: return False
registry.py
spyder.spyder.api.plugin_registration
false
false
[ "import logging", "from typing import Dict, List, Union, Type, Any, Set, Optional", "from qtpy.QtCore import QObject, Signal", "from spyder import dependencies", "from spyder.config.base import _, running_under_pytest", "from spyder.config.manager import CONF", "from spyder.api.config.mixins import SpyderConfigurationAccessor", "from spyder.api.plugin_registration._confpage import PluginsConfigPage", "from spyder.api.exceptions import SpyderAPIError", "from spyder.api.plugins import (", "from spyder.utils.icon_manager import ima" ]
322
350
if not can_close: return False # Delete Spyder 4 internal plugins for plugin_name in set(self.internal_plugins): if plugin_name not in excluding: plugin_instance = self.plugin_registry[plugin_name] if isinstance(plugin_instance, SpyderPlugin): can_close &= self.delete_plugin( plugin_name, teardown=False, check_can_delete=False) if not can_close and not close_immediately: break if not can_close: return False # Delete Spyder 5+ external plugins for plugin_name in set(self.external_plugins): if plugin_name not in excluding: plugin_instance = self.plugin_registry[plugin_name] if isinstance(plugin_instance, SpyderPluginV2): can_close &= self.delete_plugin( plugin_name, teardown=False, check_can_delete=False) if not can_close and not close_immediately: break if not can_close and not close_immediately: return False
registry.py
spyder.spyder.api.plugin_registration
false
false
[ "import logging", "from typing import Dict, List, Union, Type, Any, Set, Optional", "from qtpy.QtCore import QObject, Signal", "from spyder import dependencies", "from spyder.config.base import _, running_under_pytest", "from spyder.config.manager import CONF", "from spyder.api.config.mixins import SpyderConfigurationAccessor", "from spyder.api.plugin_registration._confpage import PluginsConfigPage", "from spyder.api.exceptions import SpyderAPIError", "from spyder.api.plugins import (", "from spyder.utils.icon_manager import ima" ]
652
679
if not can_close and not close_immediately: return False # Delete Spyder 5 internal plugins for plugin_name in set(self.internal_plugins): if plugin_name not in excluding: plugin_instance = self.plugin_registry[plugin_name] if isinstance(plugin_instance, SpyderPluginV2): can_close &= self.delete_plugin( plugin_name, teardown=False, check_can_delete=False) if not can_close and not close_immediately: break return can_close def get_plugin(self, plugin_name: str) -> SpyderPluginClass: """ Get a reference to a plugin instance by its name. Parameters ---------- plugin_name: str Name of the plugin to retrieve. Returns ------- plugin: SpyderPluginClass The instance of the requested plugin. Raises ------ SpyderAPIError If the plugin name was not found in the registry. """ if plugin_name in self.plugin_registry: plugin_instance = self.plugin_registry[plugin_name] return plugin_instance else: raise SpyderAPIError(f'Plugin {plugin_name} was not found in ' 'the registry') def set_plugin_enabled(self, plugin_name: str): """ Add a plugin name to the set of enabled plugins.
registry.py
spyder.spyder.api.plugin_registration
false
true
[ "import logging", "from typing import Dict, List, Union, Type, Any, Set, Optional", "from qtpy.QtCore import QObject, Signal", "from spyder import dependencies", "from spyder.config.base import _, running_under_pytest", "from spyder.config.manager import CONF", "from spyder.api.config.mixins import SpyderConfigurationAccessor", "from spyder.api.plugin_registration._confpage import PluginsConfigPage", "from spyder.api.exceptions import SpyderAPIError", "from spyder.api.plugins import (", "from spyder.utils.icon_manager import ima" ]
636
679
def set_plugin_enabled(self, plugin_name: str): """ Add a plugin name to the set of enabled plugins. Parameters ---------- plugin_name: str Name of the plugin to add. """ self.enabled_plugins |= {plugin_name} def is_plugin_enabled(self, plugin_name: str) -> bool: """ Determine if a given plugin is enabled and is going to be loaded. Parameters ---------- plugin_name: str Name of the plugin to query. Returns ------- plugin_enabled: bool True if the plugin is enabled and False if not. """ return plugin_name in self.enabled_plugins def is_plugin_available(self, plugin_name: str) -> bool: """ Determine if a given plugin was loaded and is available. Parameters ---------- plugin_name: str Name of the plugin to query. Returns ------- plugin_available: bool True if the plugin is available and False if not. """ return self.plugin_availability.get(plugin_name, False) def reset(self): """Reset and empty the plugin registry.""" # Dictionary that maps a plugin name to a list of the plugin names # that depend on it. self.plugin_dependents = {} # type: Dict[str, Dict[str, List[str]]]
registry.py
spyder.spyder.api.plugin_registration
false
true
[ "import logging", "from typing import Dict, List, Union, Type, Any, Set, Optional", "from qtpy.QtCore import QObject, Signal", "from spyder import dependencies", "from spyder.config.base import _, running_under_pytest", "from spyder.config.manager import CONF", "from spyder.api.config.mixins import SpyderConfigurationAccessor", "from spyder.api.plugin_registration._confpage import PluginsConfigPage", "from spyder.api.exceptions import SpyderAPIError", "from spyder.api.plugins import (", "from spyder.utils.icon_manager import ima" ]
719
767
# Dictionary that maps a plugin name to a list of the plugin names # that the plugin depends on. self.plugin_dependencies = {} # type: Dict[str, Dict[str, List[str]]] # Plugin dictionary mapped by their names self.plugin_registry = {} # type: Dict[str, SpyderPluginClass] # Dictionary that maps a plugin name to its availability. self.plugin_availability = {} # type: Dict[str, bool] # Set that stores the plugin names of all Spyder 4 plugins. self.old_plugins = set({}) # type: set[str] # Set that stores the names of the plugins that are enabled self.enabled_plugins = set({}) # Set that stores the names of the internal plugins self.internal_plugins = set({}) # Set that stores the names of the external plugins self.external_plugins = set({}) try: self.sig_plugin_ready.disconnect() except (TypeError, RuntimeError): # Omit failures if there are no slots connected pass def set_all_internal_plugins( self, all_plugins: Dict[str, Type[SpyderPluginClass]]): self.all_internal_plugins = all_plugins def set_all_external_plugins( self, all_plugins: Dict[str, Type[SpyderPluginClass]]): self.all_external_plugins = all_plugins def set_main(self, main): self.main = main def get_icon(self): return ima.icon('plugins')
registry.py
spyder.spyder.api.plugin_registration
false
true
[ "import logging", "from typing import Dict, List, Union, Type, Any, Set, Optional", "from qtpy.QtCore import QObject, Signal", "from spyder import dependencies", "from spyder.config.base import _, running_under_pytest", "from spyder.config.manager import CONF", "from spyder.api.config.mixins import SpyderConfigurationAccessor", "from spyder.api.plugin_registration._confpage import PluginsConfigPage", "from spyder.api.exceptions import SpyderAPIError", "from spyder.api.plugins import (", "from spyder.utils.icon_manager import ima" ]
99
139
def set_main(self, main): self.main = main def get_icon(self): return ima.icon('plugins') def get_name(self): return _('Plugins') def __contains__(self, plugin_name: str) -> bool: """ Determine if a plugin name is contained in the registry. Parameters ---------- plugin_name: str Name of the plugin to seek. Returns ------- is_contained: bool If True, the plugin name is contained on the registry, False otherwise. """ return plugin_name in self.plugin_registry def __iter__(self): return iter(self.plugin_registry)
registry.py
spyder.spyder.api.plugin_registration
false
true
[ "import logging", "from typing import Dict, List, Union, Type, Any, Set, Optional", "from qtpy.QtCore import QObject, Signal", "from spyder import dependencies", "from spyder.config.base import _, running_under_pytest", "from spyder.config.manager import CONF", "from spyder.api.config.mixins import SpyderConfigurationAccessor", "from spyder.api.plugin_registration._confpage import PluginsConfigPage", "from spyder.api.exceptions import SpyderAPIError", "from spyder.api.plugins import (", "from spyder.utils.icon_manager import ima" ]
805
832
# -*- coding: utf-8 -*- # # Copyright © Spyder Project Contributors # Licensed under the terms of the MIT License # (see spyder/__init__.py for details) """Global plugin registry.""" # Standard library imports import logging from typing import Dict, List, Union, Type, Any, Set, Optional # Third-party library imports from qtpy.QtCore import QObject, Signal # Local imports from spyder import dependencies from spyder.config.base import _, running_under_pytest from spyder.config.manager import CONF from spyder.api.config.mixins import SpyderConfigurationAccessor from spyder.api.plugin_registration._confpage import PluginsConfigPage from spyder.api.exceptions import SpyderAPIError from spyder.api.plugins import ( Plugins, SpyderPluginV2, SpyderDockablePlugin, SpyderPluginWidget, SpyderPlugin) from spyder.utils.icon_manager import ima # TODO: Remove SpyderPlugin and SpyderPluginWidget once the migration # is complete. Spyder5PluginClass = Union[SpyderPluginV2, SpyderDockablePlugin] Spyder4PluginClass = Union[SpyderPlugin, SpyderPluginWidget] SpyderPluginClass = Union[Spyder4PluginClass, Spyder5PluginClass] ALL_PLUGINS = [getattr(Plugins, attr) for attr in dir(Plugins) if not attr.startswith('_') and attr != 'All'] logger = logging.getLogger(__name__) # Code for: class PreferencesAdapter(SpyderConfigurationAccessor): # Code for: class SpyderPluginRegistry(QObject, PreferencesAdapter): PLUGIN_REGISTRY = SpyderPluginRegistry()
registry.py
spyder.spyder.api.plugin_registration
false
false
[ "import logging", "from typing import Dict, List, Union, Type, Any, Set, Optional", "from qtpy.QtCore import QObject, Signal", "from spyder import dependencies", "from spyder.config.base import _, running_under_pytest", "from spyder.config.manager import CONF", "from spyder.api.config.mixins import SpyderConfigurationAccessor", "from spyder.api.plugin_registration._confpage import PluginsConfigPage", "from spyder.api.exceptions import SpyderAPIError", "from spyder.api.plugins import (", "from spyder.utils.icon_manager import ima" ]
1
48
# -*- coding: utf-8 -*- # # Copyright © Spyder Project Contributors # Licensed under the terms of the MIT License # (see spyder/__init__.py for details) """Plugin registry configuration page.""" # Third party imports from pyuca import Collator from qtpy.QtWidgets import QVBoxLayout, QLabel # Local imports from spyder.api.preferences import PluginConfigPage from spyder.config.base import _ from spyder.widgets.elementstable import ElementsTable
_confpage.py
spyder.spyder.api.plugin_registration
false
false
[ "from pyuca import Collator", "from qtpy.QtWidgets import QVBoxLayout, QLabel", "from spyder.api.preferences import PluginConfigPage", "from spyder.config.base import _", "from spyder.widgets.elementstable import ElementsTable" ]
1
16
class PluginsConfigPage(PluginConfigPage): def setup_page(self): newcb = self.create_checkbox self.plugins_checkboxes = {} header_label = QLabel( _("Disable a Spyder plugin (external or built-in) to prevent it " "from loading until re-enabled here, to simplify the interface " "or in case it causes problems.") ) header_label.setWordWrap(True) # To save the plugin elements internal_elements = [] external_elements = [] # ------------------ Internal plugins --------------------------------- for plugin_name in self.plugin.all_internal_plugins: (conf_section_name, PluginClass) = self.plugin.all_internal_plugins[plugin_name] if not getattr(PluginClass, 'CAN_BE_DISABLED', True): # Do not list core plugins that can not be disabled continue plugin_state = self.get_option( 'enable', section=conf_section_name, default=True) cb = newcb('', 'enable', default=True, section=conf_section_name, restart=True)
_confpage.py
spyder.spyder.api.plugin_registration
false
true
[ "from pyuca import Collator", "from qtpy.QtWidgets import QVBoxLayout, QLabel", "from spyder.api.preferences import PluginConfigPage", "from spyder.config.base import _", "from spyder.widgets.elementstable import ElementsTable" ]
19
48
internal_elements.append( dict( title=PluginClass.get_name(), description=PluginClass.get_description(), icon=PluginClass.get_icon(), widget=cb, additional_info=_("Built-in") ) ) self.plugins_checkboxes[plugin_name] = (cb.checkbox, plugin_state) # ------------------ External plugins --------------------------------- for plugin_name in self.plugin.all_external_plugins: (conf_section_name, PluginClass) = self.plugin.all_external_plugins[plugin_name] if not getattr(PluginClass, 'CAN_BE_DISABLED', True): # Do not list external plugins that can not be disabled continue plugin_state = self.get_option( f'{conf_section_name}/enable', section=self.plugin._external_plugins_conf_section, default=True ) cb = newcb('', f'{conf_section_name}/enable', default=True, section=self.plugin._external_plugins_conf_section, restart=True) external_elements.append( dict( title=PluginClass.get_name(), description=PluginClass.get_description(), icon=PluginClass.get_icon(), widget=cb ) )
_confpage.py
spyder.spyder.api.plugin_registration
false
false
[ "from pyuca import Collator", "from qtpy.QtWidgets import QVBoxLayout, QLabel", "from spyder.api.preferences import PluginConfigPage", "from spyder.config.base import _", "from spyder.widgets.elementstable import ElementsTable" ]
50
87
self.plugins_checkboxes[plugin_name] = (cb.checkbox, plugin_state) # Sort elements by title for easy searching collator = Collator() internal_elements.sort(key=lambda e: collator.sort_key(e['title'])) external_elements.sort(key=lambda e: collator.sort_key(e['title'])) # Build plugins table, showing external plugins first. plugins_table = ElementsTable( self, external_elements + internal_elements ) # Layout layout = QVBoxLayout() layout.addWidget(header_label) layout.addSpacing(15) layout.addWidget(plugins_table) layout.addSpacing(15) self.setLayout(layout) def apply_settings(self): for plugin_name in self.plugins_checkboxes: cb, previous_state = self.plugins_checkboxes[plugin_name] if cb.isChecked() and not previous_state: self.plugin.set_plugin_enabled(plugin_name) PluginClass = None external = False if plugin_name in self.plugin.all_internal_plugins: (__, PluginClass) = self.plugin.all_internal_plugins[plugin_name] elif plugin_name in self.plugin.all_external_plugins: (__, PluginClass) = self.plugin.all_external_plugins[plugin_name] external = True # noqa
_confpage.py
spyder.spyder.api.plugin_registration
false
true
[ "from pyuca import Collator", "from qtpy.QtWidgets import QVBoxLayout, QLabel", "from spyder.api.preferences import PluginConfigPage", "from spyder.config.base import _", "from spyder.widgets.elementstable import ElementsTable" ]
60
93