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
|
---|---|---|---|---|---|---|---|
# TODO: Once we can test that all plugins can be restarted
# without problems during runtime, we can enable the
# autorestart feature provided by the plugin registry:
# self.plugin.register_plugin(self.main, PluginClass,
# external=external)
elif not cb.isChecked() and previous_state:
# TODO: Once we can test that all plugins can be restarted
# without problems during runtime, we can enable the
# autorestart feature provided by the plugin registry:
# self.plugin.delete_plugin(plugin_name)
pass
return set({}) | _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"
] | 124 | 135 |
# -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
# (see spyder/__init__.py for details)
"""
Main widget to use in plugins that show content that comes from the IPython
console, such as the Variable Explorer or Plots.
"""
# Third party imports
from qtpy.QtWidgets import QStackedWidget, QVBoxLayout
# Local imports
from spyder.api.translations import _
from spyder.api.widgets.main_widget import PluginMainWidget
from spyder.widgets.helperwidgets import PaneEmptyWidget | main_widget.py | spyder.spyder.api.shellconnect | false | false | [
"from qtpy.QtWidgets import QStackedWidget, QVBoxLayout",
"from spyder.api.translations import _",
"from spyder.api.widgets.main_widget import PluginMainWidget",
"from spyder.widgets.helperwidgets import PaneEmptyWidget"
] | 1 | 18 |
class ShellConnectMainWidget(PluginMainWidget):
"""
Main widget to use in a plugin that shows console-specific content.
Notes
-----
* This is composed of a QStackedWidget to stack widgets associated to each
shell widget in the console and only show one of them at a time.
* The current widget in the stack will display the content associated to
the console with focus.
"""
def __init__(self, *args, set_layout=True, **kwargs):
super().__init__(*args, **kwargs)
# Widgets
self._stack = QStackedWidget(self)
self._shellwidgets = {}
if set_layout:
# Layout
layout = QVBoxLayout()
layout.addWidget(self._stack)
self.setLayout(layout)
# ---- PluginMainWidget API
# ------------------------------------------------------------------------
def current_widget(self):
"""
Return the current widget in the stack.
Returns
-------
QWidget
The current widget.
"""
return self._stack.currentWidget()
def get_focus_widget(self):
return self.current_widget()
# ---- SpyderWidgetMixin API
# ------------------------------------------------------------------------
def update_style(self):
self._stack.setStyleSheet("QStackedWidget {padding: 0px; border: 0px}") | main_widget.py | spyder.spyder.api.shellconnect | false | true | [
"from qtpy.QtWidgets import QStackedWidget, QVBoxLayout",
"from spyder.api.translations import _",
"from spyder.api.widgets.main_widget import PluginMainWidget",
"from spyder.widgets.helperwidgets import PaneEmptyWidget"
] | 21 | 64 |
# ---- Stack accesors
# ------------------------------------------------------------------------
def count(self):
"""
Return the number of widgets in the stack.
Returns
-------
int
The number of widgets in the stack.
"""
return self._stack.count()
def get_widget_for_shellwidget(self, shellwidget):
"""return widget corresponding to shellwidget."""
shellwidget_id = id(shellwidget)
if shellwidget_id in self._shellwidgets:
return self._shellwidgets[shellwidget_id]
return None
# ---- Public API
# ------------------------------------------------------------------------
def add_shellwidget(self, shellwidget):
"""Create a new widget in the stack and associate it to shellwidget."""
shellwidget_id = id(shellwidget)
if shellwidget_id not in self._shellwidgets:
widget = self.create_new_widget(shellwidget)
self._stack.addWidget(widget)
self._shellwidgets[shellwidget_id] = widget
# Add all actions to new widget for shortcuts to work.
for __, action in self.get_actions().items():
if action:
widget_actions = widget.actions()
if action not in widget_actions:
widget.addAction(action)
self.set_shellwidget(shellwidget) | main_widget.py | spyder.spyder.api.shellconnect | false | true | [
"from qtpy.QtWidgets import QStackedWidget, QVBoxLayout",
"from spyder.api.translations import _",
"from spyder.api.widgets.main_widget import PluginMainWidget",
"from spyder.widgets.helperwidgets import PaneEmptyWidget"
] | 66 | 103 |
self.set_shellwidget(shellwidget)
def remove_shellwidget(self, shellwidget):
"""Remove widget associated to shellwidget."""
shellwidget_id = id(shellwidget)
if shellwidget_id in self._shellwidgets:
widget = self._shellwidgets.pop(shellwidget_id)
self._stack.removeWidget(widget)
self.close_widget(widget)
self.update_actions()
def set_shellwidget(self, shellwidget):
"""Set widget associated with shellwidget as the current widget."""
old_widget = self.current_widget()
widget = self.get_widget_for_shellwidget(shellwidget)
if widget is None:
return
self._stack.setCurrentWidget(widget)
self.switch_widget(widget, old_widget)
self.update_actions()
def add_errored_shellwidget(self, shellwidget):
"""
Create a new PaneEmptyWidget in the stack and associate it to
shellwidget.
This is necessary to show a meaningful message when switching to
consoles with dead kernels.
"""
shellwidget_id = id(shellwidget)
if shellwidget_id not in self._shellwidgets:
widget = PaneEmptyWidget(
self,
"console-off",
_("No connected console"),
_("The current console failed to start, so there is no "
"content to show here.")
) | main_widget.py | spyder.spyder.api.shellconnect | false | true | [
"from qtpy.QtWidgets import QStackedWidget, QVBoxLayout",
"from spyder.api.translations import _",
"from spyder.api.widgets.main_widget import PluginMainWidget",
"from spyder.widgets.helperwidgets import PaneEmptyWidget"
] | 103 | 141 |
self._stack.addWidget(widget)
self._shellwidgets[shellwidget_id] = widget
self.set_shellwidget(shellwidget)
def create_new_widget(self, shellwidget):
"""Create a widget to communicate with shellwidget."""
raise NotImplementedError
def close_widget(self, widget):
"""Close the widget."""
raise NotImplementedError
def switch_widget(self, widget, old_widget):
"""Switch the current widget."""
raise NotImplementedError
def refresh(self):
"""Refresh widgets."""
if self.count():
widget = self.current_widget()
widget.refresh()
def is_current_widget_empty(self):
"""Check if the current widget is a PaneEmptyWidget."""
return isinstance(self.current_widget(), PaneEmptyWidget) | main_widget.py | spyder.spyder.api.shellconnect | false | true | [
"from qtpy.QtWidgets import QStackedWidget, QVBoxLayout",
"from spyder.api.translations import _",
"from spyder.api.widgets.main_widget import PluginMainWidget",
"from spyder.widgets.helperwidgets import PaneEmptyWidget"
] | 93 | 117 |
# -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
# (see spyder/__init__.py for details)
"""
Classes to connect a plugin to the shell widgets in the IPython console.
""" | __init__.py | spyder.spyder.api.shellconnect | false | false | [] | 1 | 9 |
# -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
# (see spyder/__init__.py for details)
"""
Mixin to connect a plugin to the IPython console.
"""
from spyder.api.plugin_registration.decorators import (
on_plugin_available, on_plugin_teardown)
from spyder.api.plugins import Plugins | mixins.py | spyder.spyder.api.shellconnect | false | false | [
"from spyder.api.plugin_registration.decorators import (",
"from spyder.api.plugins import Plugins"
] | 1 | 13 |
class ShellConnectMixin:
"""
Mixin to connect any widget or object to the shell widgets in the IPython
console.
"""
# ---- Connection to the IPython console
# -------------------------------------------------------------------------
def register_ipythonconsole(self, ipyconsole):
"""Register signals from the console."""
ipyconsole.sig_shellwidget_changed.connect(self.set_shellwidget)
ipyconsole.sig_shellwidget_created.connect(self.add_shellwidget)
ipyconsole.sig_shellwidget_deleted.connect(self.remove_shellwidget)
ipyconsole.sig_shellwidget_errored.connect(
self.add_errored_shellwidget)
def unregister_ipythonconsole(self, ipyconsole):
"""Unregister signals from the console."""
ipyconsole.sig_shellwidget_changed.disconnect(self.set_shellwidget)
ipyconsole.sig_shellwidget_created.disconnect(self.add_shellwidget)
ipyconsole.sig_shellwidget_deleted.disconnect(self.remove_shellwidget)
ipyconsole.sig_shellwidget_errored.disconnect(
self.add_errored_shellwidget)
# ---- Public API
# -------------------------------------------------------------------------
def set_shellwidget(self, shellwidget):
"""Update the current shellwidget."""
raise NotImplementedError
def add_shellwidget(self, shellwidget):
"""Add a new shellwidget to be registered."""
raise NotImplementedError | mixins.py | spyder.spyder.api.shellconnect | true | true | [
"from spyder.api.plugin_registration.decorators import (",
"from spyder.api.plugins import Plugins"
] | 16 | 48 |
def add_shellwidget(self, shellwidget):
"""Add a new shellwidget to be registered."""
raise NotImplementedError
def remove_shellwidget(self, shellwidget):
"""Remove a registered shellwidget."""
raise NotImplementedError
def add_errored_shellwidget(self, shellwidget):
"""Register a new shellwidget whose kernel failed to start."""
raise NotImplementedError | mixins.py | spyder.spyder.api.shellconnect | false | true | [
"from spyder.api.plugin_registration.decorators import (",
"from spyder.api.plugins import Plugins"
] | 46 | 56 |
class ShellConnectPluginMixin(ShellConnectMixin):
"""
Mixin to connect a plugin composed of stacked widgets to the shell widgets
in the IPython console.
It is assumed that self.get_widget() returns an instance of
ShellConnectMainWidget.
"""
# ---- Connection to the IPython console
# -------------------------------------------------------------------------
@on_plugin_available(plugin=Plugins.IPythonConsole)
def on_ipython_console_available(self):
"""Connect to the IPython console."""
ipyconsole = self.get_plugin(Plugins.IPythonConsole)
self.register_ipythonconsole(ipyconsole)
@on_plugin_teardown(plugin=Plugins.IPythonConsole)
def on_ipython_console_teardown(self):
"""Disconnect from the IPython console."""
ipyconsole = self.get_plugin(Plugins.IPythonConsole)
self.unregister_ipythonconsole(ipyconsole)
# ---- Public API
# -------------------------------------------------------------------------
def set_shellwidget(self, shellwidget):
"""
Update the current shellwidget.
Parameters
----------
shellwidget: spyder.plugins.ipyconsole.widgets.shell.ShellWidget
The shell widget.
"""
self.get_widget().set_shellwidget(shellwidget)
def add_shellwidget(self, shellwidget):
"""
Add a new shellwidget to be registered. | mixins.py | spyder.spyder.api.shellconnect | false | true | [
"from spyder.api.plugin_registration.decorators import (",
"from spyder.api.plugins import Plugins"
] | 59 | 97 |
def add_shellwidget(self, shellwidget):
"""
Add a new shellwidget to be registered.
This function registers a new widget to display content that
comes from shellwidget.
Parameters
----------
shellwidget: spyder.plugins.ipyconsole.widgets.shell.ShellWidget
The shell widget.
"""
self.get_widget().add_shellwidget(shellwidget)
def remove_shellwidget(self, shellwidget):
"""
Remove a registered shellwidget.
Parameters
----------
shellwidget: spyder.plugins.ipyconsole.widgets.shell.ShellWidget
The shell widget.
"""
self.get_widget().remove_shellwidget(shellwidget)
def add_errored_shellwidget(self, shellwidget):
"""
Add a new shellwidget whose kernel failed to start.
Parameters
----------
shellwidget: spyder.plugins.ipyconsole.widgets.shell.ShellWidget
The shell widget.
"""
self.get_widget().add_errored_shellwidget(shellwidget)
def current_widget(self):
"""
Return the current widget displayed at the moment.
Returns
-------
current_widget: QWidget
The widget displayed in the current tab.
"""
return self.get_widget().current_widget()
def get_widget_for_shellwidget(self, shellwidget):
"""
Return the widget registered with the given shellwidget. | mixins.py | spyder.spyder.api.shellconnect | false | true | [
"from spyder.api.plugin_registration.decorators import (",
"from spyder.api.plugins import Plugins"
] | 95 | 144 |
def get_widget_for_shellwidget(self, shellwidget):
"""
Return the widget registered with the given shellwidget.
Parameters
----------
shellwidget: spyder.plugins.ipyconsole.widgets.shell.ShellWidget
The shell widget.
Returns
-------
current_widget: QWidget
The widget corresponding to the shellwidget, or None if not found.
"""
return self.get_widget().get_widget_for_shellwidget(shellwidget) | mixins.py | spyder.spyder.api.shellconnect | false | true | [
"from spyder.api.plugin_registration.decorators import (",
"from spyder.api.plugins import Plugins"
] | 142 | 156 |
# -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
# (see spyder/__init__.py for details)
"""
Mixins, decorators and enums to access Spyder configuration system.
""" | __init__.py | spyder.spyder.api.config | false | false | [] | 1 | 9 |
# -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
# (see spyder/__init__.py for details)
"""
Spyder API helper decorators.
"""
# Standard library imports
import functools
from typing import Callable, Optional, Union, List
# Local imports
from spyder.config.types import ConfigurationKey
ConfigurationKeyList = List[ConfigurationKey]
ConfigurationKeyOrList = Union[ConfigurationKeyList, ConfigurationKey] | decorators.py | spyder.spyder.api.config | false | false | [
"import functools",
"from typing import Callable, Optional, Union, List",
"from spyder.config.types import ConfigurationKey"
] | 1 | 20 |
def on_conf_change(func: Callable = None,
section: Optional[str] = None,
option: Optional[ConfigurationKeyOrList] = None) -> Callable:
"""
Method decorator used to handle changes on the configuration option
`option` of the section `section`.
The methods that use this decorator must have the following signature
`def method(self, value)` when observing a single value or the whole
section and `def method(self, option, value): ...` when observing
multiple values.
Parameters
----------
func: Callable
Method to decorate. Given by default when applying the decorator.
section: Optional[str]
Name of the configuration whose option is going to be observed for
changes. If None, then the `CONF_SECTION` attribute of the class
where the method is defined is used.
option: Optional[ConfigurationKeyOrList]
Name/tuple of the option to observe or a list of name/tuples if the
method expects updates from multiple keys. If None, then all changes
on the specified section are observed.
Returns
-------
func: Callable
The same method that was given as input.
"""
if func is None:
return functools.partial(
on_conf_change, section=section, option=option) | decorators.py | spyder.spyder.api.config | false | true | [
"import functools",
"from typing import Callable, Optional, Union, List",
"from spyder.config.types import ConfigurationKey"
] | 23 | 55 |
if option is None:
# Use special __section identifier to signal that the function
# observes any change on the section options.
option = '__section'
info = []
if isinstance(option, list):
info = [(section, opt) for opt in option]
else:
info = [(section, option)]
func._conf_listen = info
return func | decorators.py | spyder.spyder.api.config | false | false | [
"import functools",
"from typing import Callable, Optional, Union, List",
"from spyder.config.types import ConfigurationKey"
] | 57 | 69 |
# -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
# (see spyder/__init__.py for details)
"""
Spyder API helper mixins.
"""
# Standard library imports
import logging
from typing import Any, Union, Optional
import warnings
# Third-party imports
from qtpy.QtWidgets import QAction, QWidget
# Local imports
from spyder.config.gui import Shortcut
from spyder.config.manager import CONF
from spyder.config.types import ConfigurationKey
from spyder.config.user import NoDefault
logger = logging.getLogger(__name__)
BasicTypes = Union[bool, int, str, tuple, list, dict] | mixins.py | spyder.spyder.api.config | false | false | [
"import logging",
"from typing import Any, Union, Optional",
"import warnings",
"from qtpy.QtWidgets import QAction, QWidget",
"from spyder.config.gui import Shortcut",
"from spyder.config.manager import CONF",
"from spyder.config.types import ConfigurationKey",
"from spyder.config.user import NoDefault"
] | 1 | 28 |
class SpyderConfigurationAccessor:
"""
Mixin used to access options stored in the Spyder configuration system.
"""
# Name of the configuration section that's going to be
# used to record the object's permanent data in Spyder
# config system.
CONF_SECTION = None
def get_conf(self,
option: ConfigurationKey,
default: Union[NoDefault, BasicTypes] = NoDefault,
section: Optional[str] = None):
"""
Get an option from the Spyder configuration system.
Parameters
----------
option: ConfigurationKey
Name/Tuple path of the option to get its value from.
default: Union[NoDefault, BasicTypes]
Fallback value to return if the option is not found on the
configuration system.
section: str
Section in the configuration system, e.g. `shortcuts`. If None,
then the value of `CONF_SECTION` is used.
Returns
-------
value: BasicTypes
Value of the option in the configuration section. | mixins.py | spyder.spyder.api.config | true | false | [
"import logging",
"from typing import Any, Union, Optional",
"import warnings",
"from qtpy.QtWidgets import QAction, QWidget",
"from spyder.config.gui import Shortcut",
"from spyder.config.manager import CONF",
"from spyder.config.types import ConfigurationKey",
"from spyder.config.user import NoDefault"
] | 31 | 62 |
Returns
-------
value: BasicTypes
Value of the option in the configuration section.
Raises
------
configparser.NoOptionError
If the section does not exist in the configuration.
"""
section = self.CONF_SECTION if section is None else section
if section is None:
raise AttributeError(
'A SpyderConfigurationAccessor must define a `CONF_SECTION` '
'class attribute!'
)
return CONF.get(section, option, default)
def get_conf_options(self, section: Optional[str] = None):
"""
Get all options from the given section.
Parameters
----------
section: Optional[str]
Section in the configuration system, e.g. `shortcuts`. If None,
then the value of `CONF_SECTION` is used.
Returns
-------
values: BasicTypes
Values of the option in the configuration section.
Raises
------
configparser.NoOptionError
If the section does not exist in the configuration.
"""
section = self.CONF_SECTION if section is None else section
if section is None:
raise AttributeError(
'A SpyderConfigurationAccessor must define a `CONF_SECTION` '
'class attribute!'
)
return CONF.options(section) | mixins.py | spyder.spyder.api.config | false | true | [
"import logging",
"from typing import Any, Union, Optional",
"import warnings",
"from qtpy.QtWidgets import QAction, QWidget",
"from spyder.config.gui import Shortcut",
"from spyder.config.manager import CONF",
"from spyder.config.types import ConfigurationKey",
"from spyder.config.user import NoDefault"
] | 59 | 104 |
def set_conf(self,
option: ConfigurationKey,
value: BasicTypes,
section: Optional[str] = None,
recursive_notification: bool = True):
"""
Set an option in the Spyder configuration system. | mixins.py | spyder.spyder.api.config | false | false | [
"import logging",
"from typing import Any, Union, Optional",
"import warnings",
"from qtpy.QtWidgets import QAction, QWidget",
"from spyder.config.gui import Shortcut",
"from spyder.config.manager import CONF",
"from spyder.config.types import ConfigurationKey",
"from spyder.config.user import NoDefault"
] | 106 | 112 |
Parameters
----------
option: ConfigurationKey
Name/Tuple path of the option to set its value.
value: BasicTypes
Value to set on the configuration system.
section: Optional[str]
Section in the configuration system, e.g. `shortcuts`. If None,
then the value of `CONF_SECTION` is used.
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.
"""
section = self.CONF_SECTION if section is None else section
if section is None:
raise AttributeError(
'A SpyderConfigurationAccessor must define a `CONF_SECTION` '
'class attribute!'
)
CONF.set(
section,
option,
value,
recursive_notification=recursive_notification
)
def remove_conf(self,
option: ConfigurationKey,
section: Optional[str] = None):
"""
Remove an option in the Spyder configuration system. | mixins.py | spyder.spyder.api.config | false | false | [
"import logging",
"from typing import Any, Union, Optional",
"import warnings",
"from qtpy.QtWidgets import QAction, QWidget",
"from spyder.config.gui import Shortcut",
"from spyder.config.manager import CONF",
"from spyder.config.types import ConfigurationKey",
"from spyder.config.user import NoDefault"
] | 48 | 82 |
def remove_conf(self,
option: ConfigurationKey,
section: Optional[str] = None):
"""
Remove an option in the Spyder configuration system.
Parameters
----------
option: ConfigurationKey
Name/Tuple path of the option to remove its value.
section: Optional[str]
Section in the configuration system, e.g. `shortcuts`. If None,
then the value of `CONF_SECTION` is used.
"""
section = self.CONF_SECTION if section is None else section
if section is None:
raise AttributeError(
'A SpyderConfigurationAccessor must define a `CONF_SECTION` '
'class attribute!'
)
CONF.remove_option(section, option)
def get_conf_default(self,
option: ConfigurationKey,
section: Optional[str] = None):
"""
Get an option default value in the Spyder configuration system. | mixins.py | spyder.spyder.api.config | false | false | [
"import logging",
"from typing import Any, Union, Optional",
"import warnings",
"from qtpy.QtWidgets import QAction, QWidget",
"from spyder.config.gui import Shortcut",
"from spyder.config.manager import CONF",
"from spyder.config.types import ConfigurationKey",
"from spyder.config.user import NoDefault"
] | 144 | 170 |
Parameters
----------
option: ConfigurationKey
Name/Tuple path of the option to remove its value.
section: Optional[str]
Section in the configuration system, e.g. `shortcuts`. If None,
then the value of `CONF_SECTION` is used.
"""
section = self.CONF_SECTION if section is None else section
if section is None:
raise AttributeError(
'A SpyderConfigurationAccessor must define a `CONF_SECTION` '
'class attribute!'
)
return CONF.get_default(section, option)
def get_shortcut(
self, name: str, context: Optional[str] = None,
plugin_name: Optional[str] = None) -> str:
"""
Get a shortcut sequence stored under the given name and context.
Parameters
----------
name: str
Key identifier under which the shortcut is stored.
context: Optional[str]
Name of the shortcut context.
plugin: Optional[str]
Name of the plugin where the shortcut is defined.
Returns
-------
shortcut: str
Key sequence of the shortcut.
Raises
------
configparser.NoOptionError
If the section does not exist in the configuration.
"""
context = self.CONF_SECTION if context is None else context
return CONF.get_shortcut(context, name, plugin_name) | mixins.py | spyder.spyder.api.config | false | false | [
"import logging",
"from typing import Any, Union, Optional",
"import warnings",
"from qtpy.QtWidgets import QAction, QWidget",
"from spyder.config.gui import Shortcut",
"from spyder.config.manager import CONF",
"from spyder.config.types import ConfigurationKey",
"from spyder.config.user import NoDefault"
] | 48 | 90 |
def config_shortcut(
self, action: QAction, name: str, parent: QWidget,
context: Optional[str] = None) -> Shortcut:
"""
Create a Shortcut namedtuple for a widget.
The data contained in this tuple will be registered in our shortcuts
preferences page.
Parameters
----------
action: QAction
Action that will use the shortcut.
name: str
Key identifier under which the shortcut is stored.
parent: QWidget
Parent widget for the shortcut.
context: Optional[str]
Name of the context (plugin) where the shortcut was defined.
Returns
-------
shortcut: Shortcut
Namedtuple with the information of the shortcut as used for the
shortcuts preferences page.
"""
shortcut_context = self.CONF_SECTION if context is None else context
return CONF.config_shortcut(
action,
shortcut_context,
name,
parent
)
@property
def old_conf_version(self):
"""Get old Spyder configuration version."""
return CONF.old_spyder_version | mixins.py | spyder.spyder.api.config | false | true | [
"import logging",
"from typing import Any, Union, Optional",
"import warnings",
"from qtpy.QtWidgets import QAction, QWidget",
"from spyder.config.gui import Shortcut",
"from spyder.config.manager import CONF",
"from spyder.config.types import ConfigurationKey",
"from spyder.config.user import NoDefault"
] | 216 | 253 |
class SpyderConfigurationObserver(SpyderConfigurationAccessor):
"""
Concrete implementation of the protocol
:class:`spyder.config.types.ConfigurationObserver`.
This mixin enables a class to receive configuration updates seamlessly,
by registering methods using the
:function:`spyder.api.config.decorators.on_conf_change` decorator, which
receives a configuration section and option to observe.
When a change occurs on any of the registered configuration options,
the corresponding registered method is called with the new value.
"""
def __init__(self):
super().__init__()
if self.CONF_SECTION is None:
warnings.warn(
'A SpyderConfigurationObserver must define a `CONF_SECTION` '
f'class attribute! Hint: {self} or its parent should define '
'the section.'
)
self._configuration_listeners = {}
self._multi_option_listeners = set({})
self._gather_observers()
self._merge_none_observers() | mixins.py | spyder.spyder.api.config | false | true | [
"import logging",
"from typing import Any, Union, Optional",
"import warnings",
"from qtpy.QtWidgets import QAction, QWidget",
"from spyder.config.gui import Shortcut",
"from spyder.config.manager import CONF",
"from spyder.config.types import ConfigurationKey",
"from spyder.config.user import NoDefault"
] | 256 | 282 |
self._configuration_listeners = {}
self._multi_option_listeners = set({})
self._gather_observers()
self._merge_none_observers()
# Register class to listen for changes in all registered options
for section in self._configuration_listeners:
section = self.CONF_SECTION if section is None else section
observed_options = self._configuration_listeners[section]
for option in observed_options:
logger.debug(f'{self} is observing {option} '
f'in section {section}')
CONF.observe_configuration(self, section, option)
def __del__(self):
# Remove object from the configuration observer
CONF.unobserve_configuration(self)
def _gather_observers(self):
"""Gather all the methods decorated with `on_conf_change`."""
for method_name in dir(self):
method = getattr(self, method_name, None)
if hasattr(method, '_conf_listen'):
info = method._conf_listen
if len(info) > 1:
self._multi_option_listeners |= {method_name} | mixins.py | spyder.spyder.api.config | false | true | [
"import logging",
"from typing import Any, Union, Optional",
"import warnings",
"from qtpy.QtWidgets import QAction, QWidget",
"from spyder.config.gui import Shortcut",
"from spyder.config.manager import CONF",
"from spyder.config.types import ConfigurationKey",
"from spyder.config.user import NoDefault"
] | 279 | 304 |
for section, option in info:
section_listeners = self._configuration_listeners.get(
section, {})
option_listeners = section_listeners.get(option, [])
option_listeners.append(method_name)
section_listeners[option] = option_listeners
self._configuration_listeners[section] = section_listeners
def _merge_none_observers(self):
"""Replace observers that declared section as None by CONF_SECTION."""
default_selectors = self._configuration_listeners.get(None, {})
section_selectors = self._configuration_listeners.get(
self.CONF_SECTION, {})
for option in default_selectors:
default_option_receivers = default_selectors.get(option, [])
section_option_receivers = section_selectors.get(option, [])
merged_receivers = (
default_option_receivers + section_option_receivers)
section_selectors[option] = merged_receivers
self._configuration_listeners[self.CONF_SECTION] = section_selectors
self._configuration_listeners.pop(None, None)
def on_configuration_change(self, option: ConfigurationKey, section: str,
value: Any):
"""
Handle configuration updates for the option `option` on the section
`section`, whose new value corresponds to `value`. | mixins.py | spyder.spyder.api.config | false | true | [
"import logging",
"from typing import Any, Union, Optional",
"import warnings",
"from qtpy.QtWidgets import QAction, QWidget",
"from spyder.config.gui import Shortcut",
"from spyder.config.manager import CONF",
"from spyder.config.types import ConfigurationKey",
"from spyder.config.user import NoDefault"
] | 306 | 334 |
Parameters
----------
option: ConfigurationKey
Configuration option that did change.
section: str
Name of the section where `option` is contained.
value: Any
New value of the configuration option that produced the event.
"""
section_receivers = self._configuration_listeners.get(section, {})
option_receivers = section_receivers.get(option, [])
for receiver in option_receivers:
method = getattr(self, receiver)
if receiver in self._multi_option_listeners:
method(option, value)
else:
method(value) | mixins.py | spyder.spyder.api.config | false | false | [
"import logging",
"from typing import Any, Union, Optional",
"import warnings",
"from qtpy.QtWidgets import QAction, QWidget",
"from spyder.config.gui import Shortcut",
"from spyder.config.manager import CONF",
"from spyder.config.types import ConfigurationKey",
"from spyder.config.user import NoDefault"
] | 48 | 64 |
# -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
# (see spyder/__init__.py for details)
"""
Helper utilities to get the fonts used in Spyder from our config system.
"""
# Standard library imports
from typing import Optional
# Third-party imports
from qtpy.QtGui import QFont
# Local imports
from spyder.config.gui import get_font
class SpyderFontType:
"""
Font types used in Spyder plugins and the entire application.
Notes
-----
* This enum is meant to be used to get the QFont object corresponding to
each type.
* The names associated to the values in this enum depend on historical
reasons that go back to Spyder 2 and are not easy to change now.
* Monospace is the font used used in the Editor, IPython console and
History; Interface is used by the entire Spyder app; and
MonospaceInterface is used, for instance, by the Variable Explorer and
corresponds to Monospace font resized to look good against the
Interface one.
"""
Monospace = 'font'
Interface = 'app_font'
MonospaceInterface = 'monospace_app_font' | fonts.py | spyder.spyder.api.config | true | false | [
"from typing import Optional",
"from qtpy.QtGui import QFont",
"from spyder.config.gui import get_font"
] | 1 | 39 |
class SpyderFontsMixin:
"""Mixin to get the different Spyder font types from our config system."""
@classmethod
def get_font(
cls,
font_type: str,
font_size_delta: Optional[int] = 0
) -> QFont:
"""
Get a font type as a QFont object.
Parameters
----------
font_type: str
A Spyder font type. This must be one of the `SpyderFontType` enum
values.
font_size_delta: int, optional
Small increase or decrease over the default font size. The default
is 0.
"""
return get_font(option=font_type, font_size_delta=font_size_delta) | fonts.py | spyder.spyder.api.config | true | false | [
"from typing import Optional",
"from qtpy.QtGui import QFont",
"from spyder.config.gui import get_font"
] | 42 | 63 |
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright (c) 2009- Spyder Project Contributors
#
# Distributed under the terms of the MIT License
# (see spyder/__init__.py for details)
# -----------------------------------------------------------------------------
# Remove PYTHONPATH paths from sys.path before other imports to protect against
# shadowed standard libraries.
import os
import sys
if os.environ.get('PYTHONPATH'):
for path in os.environ['PYTHONPATH'].split(os.pathsep):
try:
sys.path.remove(path.rstrip(os.sep))
except ValueError:
pass
# Standard library imports
import ctypes
import logging
import os.path as osp
import random
import socket
import time
# Prevent showing internal logging errors
# Fixes spyder-ide/spyder#15768
logging.raiseExceptions = False
# Prevent that our dependencies display warnings when not in debug mode.
# Some of them are reported in the console and others through our
# report error dialog.
# Note: The log level when debugging is set on the main window.
# Fixes spyder-ide/spyder#15163
root_logger = logging.getLogger()
root_logger.setLevel(logging.ERROR)
# Prevent a race condition with ZMQ
# See spyder-ide/spyder#5324.
import zmq
# Load GL library to prevent segmentation faults on some Linux systems
# See spyder-ide/spyder#3226 and spyder-ide/spyder#3332.
try:
ctypes.CDLL("libGL.so.1", mode=ctypes.RTLD_GLOBAL)
except:
pass | start.py | spyder.spyder.app | false | false | [
"import os",
"import sys",
"import ctypes",
"import logging",
"import os.path as osp",
"import random",
"import socket",
"import time",
"import zmq",
"from spyder.app.cli_options import get_options",
"from spyder.config.base import (get_conf_path, reset_config_files,",
"from spyder.utils.conda import get_conda_root_prefix",
"from spyder.utils.external import lockfile",
"from spyder.py3compat import is_text_string",
"from spyder.config.manager import CONF",
"from spyder.config.manager import CONF",
"from locale import getlocale",
"from spyder.config.base import get_conf_paths",
"import shutil",
"from spyder.app import mainwindow",
"from spyder.app import mainwindow",
"from spyder.app import mainwindow"
] | 1 | 49 |
# Local imports
from spyder.app.cli_options import get_options
from spyder.config.base import (get_conf_path, reset_config_files,
running_under_pytest, is_conda_based_app)
from spyder.utils.conda import get_conda_root_prefix
from spyder.utils.external import lockfile
from spyder.py3compat import is_text_string
# Enforce correct CONDA_EXE environment variable
# Do not rely on CONDA_PYTHON_EXE or CONDA_PREFIX in case Spyder is started
# from the commandline
if is_conda_based_app():
conda_root = get_conda_root_prefix()
if os.name == 'nt':
os.environ['CONDA_EXE'] = conda_root + r'\Scripts\conda.exe'
else:
os.environ['CONDA_EXE'] = conda_root + '/bin/conda'
# Get argv
if running_under_pytest():
sys_argv = [sys.argv[0]]
CLI_OPTIONS, CLI_ARGS = get_options(sys_argv)
else:
CLI_OPTIONS, CLI_ARGS = get_options()
# Start Spyder with a clean configuration directory for testing purposes
if CLI_OPTIONS.safe_mode:
os.environ['SPYDER_SAFE_MODE'] = 'True'
if CLI_OPTIONS.conf_dir:
os.environ['SPYDER_CONFDIR'] = CLI_OPTIONS.conf_dir | start.py | spyder.spyder.app | false | false | [
"import os",
"import sys",
"import ctypes",
"import logging",
"import os.path as osp",
"import random",
"import socket",
"import time",
"import zmq",
"from spyder.app.cli_options import get_options",
"from spyder.config.base import (get_conf_path, reset_config_files,",
"from spyder.utils.conda import get_conda_root_prefix",
"from spyder.utils.external import lockfile",
"from spyder.py3compat import is_text_string",
"from spyder.config.manager import CONF",
"from spyder.config.manager import CONF",
"from locale import getlocale",
"from spyder.config.base import get_conf_paths",
"import shutil",
"from spyder.app import mainwindow",
"from spyder.app import mainwindow",
"from spyder.app import mainwindow"
] | 51 | 81 |
def send_args_to_spyder(args):
"""
Simple socket client used to send the args passed to the Spyder
executable to an already running instance.
Args can be Python scripts or files with these extensions: .spydata, .mat,
.npy, or .h5, which can be imported by the Variable Explorer.
"""
from spyder.config.manager import CONF
port = CONF.get('main', 'open_files_port')
print_warning = True
# Wait ~50 secs for the server to be up
# Taken from https://stackoverflow.com/a/4766598/438386
for __ in range(200):
try:
for arg in args:
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
socket.IPPROTO_TCP)
client.connect(("127.0.0.1", port))
if is_text_string(arg):
arg = arg.encode('utf-8')
client.send(osp.abspath(arg))
client.close()
except socket.error:
# Print informative warning to let users know what Spyder is doing
if print_warning:
print("Waiting for the server to open files and directories "
"to be up (perhaps it failed to be started).")
print_warning = False
# Wait 250 ms before trying again
time.sleep(0.25)
continue
break | start.py | spyder.spyder.app | false | true | [
"import os",
"import sys",
"import ctypes",
"import logging",
"import os.path as osp",
"import random",
"import socket",
"import time",
"import zmq",
"from spyder.app.cli_options import get_options",
"from spyder.config.base import (get_conf_path, reset_config_files,",
"from spyder.utils.conda import get_conda_root_prefix",
"from spyder.utils.external import lockfile",
"from spyder.py3compat import is_text_string",
"from spyder.config.manager import CONF",
"from spyder.config.manager import CONF",
"from locale import getlocale",
"from spyder.config.base import get_conf_paths",
"import shutil",
"from spyder.app import mainwindow",
"from spyder.app import mainwindow",
"from spyder.app import mainwindow"
] | 84 | 118 |
def main():
"""
Start Spyder application.
If single instance mode is turned on (default behavior) and an instance of
Spyder is already running, this will just parse and send command line
options to the application.
"""
# Parse command line options
options, args = (CLI_OPTIONS, CLI_ARGS)
# This is to allow reset without reading our conf file
if options.reset_config_files:
# <!> Remove all configuration files!
reset_config_files()
return
from spyder.config.manager import CONF
# Store variable to be used in self.restart (restart spyder instance)
os.environ['SPYDER_ARGS'] = str(sys.argv[1:])
#==========================================================================
# Proper high DPI scaling is available in Qt >= 5.6.0. This attribute must
# be set before creating the application.
#==========================================================================
if CONF.get('main', 'high_dpi_custom_scale_factor'):
factors = str(CONF.get('main', 'high_dpi_custom_scale_factors'))
f = list(filter(None, factors.split(';')))
if len(f) == 1:
os.environ['QT_SCALE_FACTOR'] = f[0]
else:
os.environ['QT_SCREEN_SCALE_FACTORS'] = factors
else:
os.environ['QT_SCALE_FACTOR'] = ''
os.environ['QT_SCREEN_SCALE_FACTORS'] = '' | start.py | spyder.spyder.app | false | true | [
"import os",
"import sys",
"import ctypes",
"import logging",
"import os.path as osp",
"import random",
"import socket",
"import time",
"import zmq",
"from spyder.app.cli_options import get_options",
"from spyder.config.base import (get_conf_path, reset_config_files,",
"from spyder.utils.conda import get_conda_root_prefix",
"from spyder.utils.external import lockfile",
"from spyder.py3compat import is_text_string",
"from spyder.config.manager import CONF",
"from spyder.config.manager import CONF",
"from locale import getlocale",
"from spyder.config.base import get_conf_paths",
"import shutil",
"from spyder.app import mainwindow",
"from spyder.app import mainwindow",
"from spyder.app import mainwindow"
] | 121 | 156 |
if sys.platform == 'darwin':
# Fixes launching issues with Big Sur (spyder-ide/spyder#14222)
os.environ['QT_MAC_WANTS_LAYER'] = '1'
# Prevent Spyder from crashing in macOS if locale is not defined
LANG = os.environ.get('LANG')
LC_ALL = os.environ.get('LC_ALL')
if bool(LANG) and not bool(LC_ALL):
LC_ALL = LANG
elif not bool(LANG) and bool(LC_ALL):
LANG = LC_ALL
else:
LANG = LC_ALL = 'en_US.UTF-8'
os.environ['LANG'] = LANG
os.environ['LC_ALL'] = LC_ALL
# Don't show useless warning in the terminal where Spyder
# was started.
# See spyder-ide/spyder#3730.
os.environ['EVENT_NOKQUEUE'] = '1'
else:
# Prevent our kernels to crash when Python fails to identify
# the system locale.
# Fixes spyder-ide/spyder#7051.
try:
from locale import getlocale
getlocale()
except ValueError:
# This can fail on Windows. See spyder-ide/spyder#6886.
try:
os.environ['LANG'] = 'C'
os.environ['LC_ALL'] = 'C'
except Exception:
pass
if options.debug_info:
levels = {'minimal': '2', 'verbose': '3'}
os.environ['SPYDER_DEBUG'] = levels[options.debug_info] | start.py | spyder.spyder.app | false | false | [
"import os",
"import sys",
"import ctypes",
"import logging",
"import os.path as osp",
"import random",
"import socket",
"import time",
"import zmq",
"from spyder.app.cli_options import get_options",
"from spyder.config.base import (get_conf_path, reset_config_files,",
"from spyder.utils.conda import get_conda_root_prefix",
"from spyder.utils.external import lockfile",
"from spyder.py3compat import is_text_string",
"from spyder.config.manager import CONF",
"from spyder.config.manager import CONF",
"from locale import getlocale",
"from spyder.config.base import get_conf_paths",
"import shutil",
"from spyder.app import mainwindow",
"from spyder.app import mainwindow",
"from spyder.app import mainwindow"
] | 158 | 195 |
if options.debug_info:
levels = {'minimal': '2', 'verbose': '3'}
os.environ['SPYDER_DEBUG'] = levels[options.debug_info]
_filename = 'spyder-debug.log'
if options.debug_output == 'file':
_filepath = osp.realpath(_filename)
else:
_filepath = get_conf_path(_filename)
os.environ['SPYDER_DEBUG_FILE'] = _filepath
if options.paths:
from spyder.config.base import get_conf_paths
sys.stdout.write('\nconfig:' + '\n')
for path in reversed(get_conf_paths()):
sys.stdout.write('\t' + path + '\n')
sys.stdout.write('\n' )
return
if (CONF.get('main', 'single_instance') and not options.new_instance
and not options.reset_config_files):
# Minimal delay (0.1-0.2 secs) to avoid that several
# instances started at the same time step in their
# own foots while trying to create the lock file
time.sleep(random.randrange(1000, 2000, 90)/10000.)
# Lock file creation
lock_file = get_conf_path('spyder.lock')
lock = lockfile.FilesystemLock(lock_file) | start.py | spyder.spyder.app | false | false | [
"import os",
"import sys",
"import ctypes",
"import logging",
"import os.path as osp",
"import random",
"import socket",
"import time",
"import zmq",
"from spyder.app.cli_options import get_options",
"from spyder.config.base import (get_conf_path, reset_config_files,",
"from spyder.utils.conda import get_conda_root_prefix",
"from spyder.utils.external import lockfile",
"from spyder.py3compat import is_text_string",
"from spyder.config.manager import CONF",
"from spyder.config.manager import CONF",
"from locale import getlocale",
"from spyder.config.base import get_conf_paths",
"import shutil",
"from spyder.app import mainwindow",
"from spyder.app import mainwindow",
"from spyder.app import mainwindow"
] | 193 | 221 |
# Lock file creation
lock_file = get_conf_path('spyder.lock')
lock = lockfile.FilesystemLock(lock_file)
# Try to lock spyder.lock. If it's *possible* to do it, then
# there is no previous instance running and we can start a
# new one. If *not*, then there is an instance already
# running, which is locking that file
try:
lock_created = lock.lock()
except:
# If locking fails because of errors in the lockfile
# module, try to remove a possibly stale spyder.lock.
# This is reported to solve all problems with lockfile.
# See spyder-ide/spyder#2363.
try:
if os.name == 'nt':
if osp.isdir(lock_file):
import shutil
shutil.rmtree(lock_file, ignore_errors=True)
else:
if osp.islink(lock_file):
os.unlink(lock_file)
except:
pass
# Then start Spyder as usual and *don't* continue
# executing this script because it doesn't make
# sense
from spyder.app import mainwindow
if running_under_pytest():
return mainwindow.main(options, args)
else:
mainwindow.main(options, args)
return | start.py | spyder.spyder.app | false | false | [
"import os",
"import sys",
"import ctypes",
"import logging",
"import os.path as osp",
"import random",
"import socket",
"import time",
"import zmq",
"from spyder.app.cli_options import get_options",
"from spyder.config.base import (get_conf_path, reset_config_files,",
"from spyder.utils.conda import get_conda_root_prefix",
"from spyder.utils.external import lockfile",
"from spyder.py3compat import is_text_string",
"from spyder.config.manager import CONF",
"from spyder.config.manager import CONF",
"from locale import getlocale",
"from spyder.config.base import get_conf_paths",
"import shutil",
"from spyder.app import mainwindow",
"from spyder.app import mainwindow",
"from spyder.app import mainwindow"
] | 219 | 253 |
if lock_created:
# Start a new instance
from spyder.app import mainwindow
if running_under_pytest():
return mainwindow.main(options, args)
else:
mainwindow.main(options, args)
else:
# Pass args to Spyder or print an informative
# message
if args:
send_args_to_spyder(args)
else:
print("Spyder is already running. If you want to open a new \n"
"instance, please use the --new-instance option")
else:
from spyder.app import mainwindow
if running_under_pytest():
return mainwindow.main(options, args)
else:
mainwindow.main(options, args)
if __name__ == "__main__":
main() | start.py | spyder.spyder.app | false | false | [
"import os",
"import sys",
"import ctypes",
"import logging",
"import os.path as osp",
"import random",
"import socket",
"import time",
"import zmq",
"from spyder.app.cli_options import get_options",
"from spyder.config.base import (get_conf_path, reset_config_files,",
"from spyder.utils.conda import get_conda_root_prefix",
"from spyder.utils.external import lockfile",
"from spyder.py3compat import is_text_string",
"from spyder.config.manager import CONF",
"from spyder.config.manager import CONF",
"from locale import getlocale",
"from spyder.config.base import get_conf_paths",
"import shutil",
"from spyder.app import mainwindow",
"from spyder.app import mainwindow",
"from spyder.app import mainwindow"
] | 255 | 279 |
# -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
# (see spyder/__init__.py for details)
"""
Restart Spyder
A helper script that allows to restart (and also reset) Spyder from within the
running application.
"""
# Standard library imports
import ast
import os
import os.path as osp
import subprocess
import sys
import time
# Third party imports
from qtpy.QtCore import Qt, QTimer
from qtpy.QtGui import QColor, QIcon
from qtpy.QtWidgets import QApplication, QMessageBox, QWidget
# Local imports
from spyder.app.utils import create_splash_screen
from spyder.config.base import _
from spyder.utils.image_path_manager import get_image_path
from spyder.utils.encoding import to_unicode
from spyder.utils.qthelpers import qapplication
from spyder.config.manager import CONF
IS_WINDOWS = os.name == 'nt'
SLEEP_TIME = 0.2 # Seconds for throttling control
CLOSE_ERROR, RESET_ERROR, RESTART_ERROR = [1, 2, 3] # Spyder error codes | restart.py | spyder.spyder.app | false | false | [
"import ast",
"import os",
"import os.path as osp",
"import subprocess",
"import sys",
"import time",
"from qtpy.QtCore import Qt, QTimer",
"from qtpy.QtGui import QColor, QIcon",
"from qtpy.QtWidgets import QApplication, QMessageBox, QWidget",
"from spyder.app.utils import create_splash_screen",
"from spyder.config.base import _",
"from spyder.utils.image_path_manager import get_image_path",
"from spyder.utils.encoding import to_unicode",
"from spyder.utils.qthelpers import qapplication",
"from spyder.config.manager import CONF"
] | 1 | 38 |
def _is_pid_running_on_windows(pid):
"""Check if a process is running on windows systems based on the pid."""
pid = str(pid)
# Hide flashing command prompt
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
process = subprocess.Popen(r'tasklist /fi "PID eq {0}"'.format(pid),
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
startupinfo=startupinfo)
stdoutdata, stderrdata = process.communicate()
stdoutdata = to_unicode(stdoutdata)
process.kill()
check = pid in stdoutdata
return check
def _is_pid_running_on_unix(pid):
"""Check if a process is running on unix systems based on the pid."""
try:
# On unix systems os.kill with a 0 as second argument only pokes the
# process (if it exists) and does not kill it
os.kill(pid, 0)
except OSError:
return False
else:
return True
def is_pid_running(pid):
"""Check if a process is running based on the pid."""
# Select the correct function depending on the OS
if os.name == 'nt':
return _is_pid_running_on_windows(pid)
else:
return _is_pid_running_on_unix(pid) | restart.py | spyder.spyder.app | false | true | [
"import ast",
"import os",
"import os.path as osp",
"import subprocess",
"import sys",
"import time",
"from qtpy.QtCore import Qt, QTimer",
"from qtpy.QtGui import QColor, QIcon",
"from qtpy.QtWidgets import QApplication, QMessageBox, QWidget",
"from spyder.app.utils import create_splash_screen",
"from spyder.config.base import _",
"from spyder.utils.image_path_manager import get_image_path",
"from spyder.utils.encoding import to_unicode",
"from spyder.utils.qthelpers import qapplication",
"from spyder.config.manager import CONF"
] | 41 | 79 |
class Restarter(QWidget):
"""Widget in charge of displaying the splash information screen and the
error messages.
"""
def __init__(self):
super(Restarter, self).__init__()
self.ellipsis = ['', '.', '..', '...', '..', '.']
# Widgets
self.timer_ellipsis = QTimer(self)
self.splash = create_splash_screen(use_previous_factor=True)
# Widget setup
self.setVisible(False)
self.splash.show()
self.timer_ellipsis.timeout.connect(self.animate_ellipsis)
def _show_message(self, text):
"""Show message on splash screen."""
self.splash.showMessage(text,
int(Qt.AlignBottom | Qt.AlignCenter |
Qt.AlignAbsolute),
QColor(Qt.white))
def animate_ellipsis(self):
"""Animate dots at the end of the splash screen message."""
ellipsis = self.ellipsis.pop(0)
text = ' ' * len(ellipsis) + self.splash_text + ellipsis
self.ellipsis.append(ellipsis)
self._show_message(text)
def set_splash_message(self, text):
"""Sets the text in the bottom of the Splash screen."""
self.splash_text = text
self._show_message(text)
self.timer_ellipsis.start(500) | restart.py | spyder.spyder.app | false | true | [
"import ast",
"import os",
"import os.path as osp",
"import subprocess",
"import sys",
"import time",
"from qtpy.QtCore import Qt, QTimer",
"from qtpy.QtGui import QColor, QIcon",
"from qtpy.QtWidgets import QApplication, QMessageBox, QWidget",
"from spyder.app.utils import create_splash_screen",
"from spyder.config.base import _",
"from spyder.utils.image_path_manager import get_image_path",
"from spyder.utils.encoding import to_unicode",
"from spyder.utils.qthelpers import qapplication",
"from spyder.config.manager import CONF"
] | 82 | 119 |
# Wait 1.2 seconds so we can give feedback to users that a
# restart is happening.
for __ in range(40):
time.sleep(0.03)
QApplication.processEvents()
def launch_error_message(self, error_type, error=None):
"""Launch a message box with a predefined error message.
Parameters
----------
error_type : int [CLOSE_ERROR, RESET_ERROR, RESTART_ERROR]
Possible error codes when restarting/resetting spyder.
error : Exception
Actual Python exception error caught.
"""
messages = {CLOSE_ERROR: _("It was not possible to close the previous "
"Spyder instance.\nRestart aborted."),
RESET_ERROR: _("Spyder could not reset to factory "
"defaults.\nRestart aborted."),
RESTART_ERROR: _("It was not possible to restart Spyder.\n"
"Operation aborted.")}
titles = {CLOSE_ERROR: _("Spyder exit error"),
RESET_ERROR: _("Spyder reset error"),
RESTART_ERROR: _("Spyder restart error")}
if error:
e = error.__repr__()
message = messages[error_type] + "\n\n{0}".format(e)
else:
message = messages[error_type] | restart.py | spyder.spyder.app | false | true | [
"import ast",
"import os",
"import os.path as osp",
"import subprocess",
"import sys",
"import time",
"from qtpy.QtCore import Qt, QTimer",
"from qtpy.QtGui import QColor, QIcon",
"from qtpy.QtWidgets import QApplication, QMessageBox, QWidget",
"from spyder.app.utils import create_splash_screen",
"from spyder.config.base import _",
"from spyder.utils.image_path_manager import get_image_path",
"from spyder.utils.encoding import to_unicode",
"from spyder.utils.qthelpers import qapplication",
"from spyder.config.manager import CONF"
] | 121 | 151 |
if error:
e = error.__repr__()
message = messages[error_type] + "\n\n{0}".format(e)
else:
message = messages[error_type]
title = titles[error_type]
self.splash.hide()
QMessageBox.warning(self, title, message, QMessageBox.Ok)
raise RuntimeError(message) | restart.py | spyder.spyder.app | false | false | [
"import ast",
"import os",
"import os.path as osp",
"import subprocess",
"import sys",
"import time",
"from qtpy.QtCore import Qt, QTimer",
"from qtpy.QtGui import QColor, QIcon",
"from qtpy.QtWidgets import QApplication, QMessageBox, QWidget",
"from spyder.app.utils import create_splash_screen",
"from spyder.config.base import _",
"from spyder.utils.image_path_manager import get_image_path",
"from spyder.utils.encoding import to_unicode",
"from spyder.utils.qthelpers import qapplication",
"from spyder.config.manager import CONF"
] | 147 | 156 |
def main():
#==========================================================================
# Proper high DPI scaling is available in Qt >= 5.6.0. This attribute must
# be set before creating the application.
#==========================================================================
env = os.environ.copy()
if CONF.get('main', 'high_dpi_custom_scale_factor'):
factors = str(CONF.get('main', 'high_dpi_custom_scale_factors'))
f = list(filter(None, factors.split(';')))
if len(f) == 1:
env['QT_SCALE_FACTOR'] = f[0]
else:
env['QT_SCREEN_SCALE_FACTORS'] = factors
else:
env['QT_SCALE_FACTOR'] = ''
env['QT_SCREEN_SCALE_FACTORS'] = ''
# Splash screen
# -------------------------------------------------------------------------
# Start Qt Splash to inform the user of the current status
app = qapplication()
app.set_font()
restarter = Restarter()
APP_ICON = QIcon(get_image_path("spyder"))
app.setWindowIcon(APP_ICON)
restarter.set_splash_message(_('Closing Spyder'))
# Get variables
spyder_args = env.pop('SPYDER_ARGS', None)
pid = env.pop('SPYDER_PID', None)
is_bootstrap = env.pop('SPYDER_IS_BOOTSTRAP', None)
reset = env.pop('SPYDER_RESET', 'False')
# Get the spyder base folder based on this file
spyder_dir = osp.dirname(osp.dirname(osp.dirname(osp.abspath(__file__)))) | restart.py | spyder.spyder.app | false | true | [
"import ast",
"import os",
"import os.path as osp",
"import subprocess",
"import sys",
"import time",
"from qtpy.QtCore import Qt, QTimer",
"from qtpy.QtGui import QColor, QIcon",
"from qtpy.QtWidgets import QApplication, QMessageBox, QWidget",
"from spyder.app.utils import create_splash_screen",
"from spyder.config.base import _",
"from spyder.utils.image_path_manager import get_image_path",
"from spyder.utils.encoding import to_unicode",
"from spyder.utils.qthelpers import qapplication",
"from spyder.config.manager import CONF"
] | 159 | 195 |
# Get the spyder base folder based on this file
spyder_dir = osp.dirname(osp.dirname(osp.dirname(osp.abspath(__file__))))
if not any([spyder_args, pid, is_bootstrap, reset]):
error = "This script can only be called from within a Spyder instance"
raise RuntimeError(error)
# Variables were stored as string literals in the environment, so to use
# them we need to parse them in a safe manner.
is_bootstrap = ast.literal_eval(is_bootstrap)
pid = ast.literal_eval(pid)
args = ast.literal_eval(spyder_args)
reset = ast.literal_eval(reset)
# SPYDER_DEBUG takes presedence over SPYDER_ARGS
if '--debug' in args:
args.remove('--debug')
for level in ['minimal', 'verbose']:
arg = f'--debug-info={level}'
if arg in args:
args.remove(arg)
# Enforce the --new-instance flag when running spyder
if '--new-instance' not in args:
if is_bootstrap and '--' not in args:
args = args + ['--', '--new-instance']
else:
args.append('--new-instance')
# Create the arguments needed for resetting
if '--' in args:
args_reset = ['--', '--reset']
else:
args_reset = ['--reset']
# Build the base command
if is_bootstrap:
script = osp.join(spyder_dir, 'bootstrap.py')
else:
script = osp.join(spyder_dir, 'spyder', 'app', 'start.py')
command = [f'"{sys.executable}"', f'"{script}"'] | restart.py | spyder.spyder.app | false | false | [
"import ast",
"import os",
"import os.path as osp",
"import subprocess",
"import sys",
"import time",
"from qtpy.QtCore import Qt, QTimer",
"from qtpy.QtGui import QColor, QIcon",
"from qtpy.QtWidgets import QApplication, QMessageBox, QWidget",
"from spyder.app.utils import create_splash_screen",
"from spyder.config.base import _",
"from spyder.utils.image_path_manager import get_image_path",
"from spyder.utils.encoding import to_unicode",
"from spyder.utils.qthelpers import qapplication",
"from spyder.config.manager import CONF"
] | 194 | 235 |
command = [f'"{sys.executable}"', f'"{script}"']
# Adjust the command and/or arguments to subprocess depending on the OS
shell = not IS_WINDOWS
# Before launching a new Spyder instance we need to make sure that the
# previous one has closed. We wait for a fixed and "reasonable" amount of
# time and check, otherwise an error is launched
wait_time = 90 if IS_WINDOWS else 30 # Seconds
for counter in range(int(wait_time / SLEEP_TIME)):
if not is_pid_running(pid):
break
time.sleep(SLEEP_TIME) # Throttling control
QApplication.processEvents() # Needed to refresh the splash
else:
# The old spyder instance took too long to close and restart aborts
restarter.launch_error_message(error_type=CLOSE_ERROR)
# Reset Spyder (if required)
# -------------------------------------------------------------------------
if reset:
restarter.set_splash_message(_('Resetting Spyder to defaults'))
try:
p = subprocess.Popen(' '.join(command + args_reset),
shell=shell, env=env)
except Exception as error:
restarter.launch_error_message(error_type=RESET_ERROR, error=error)
else:
p.communicate()
pid_reset = p.pid | restart.py | spyder.spyder.app | false | false | [
"import ast",
"import os",
"import os.path as osp",
"import subprocess",
"import sys",
"import time",
"from qtpy.QtCore import Qt, QTimer",
"from qtpy.QtGui import QColor, QIcon",
"from qtpy.QtWidgets import QApplication, QMessageBox, QWidget",
"from spyder.app.utils import create_splash_screen",
"from spyder.config.base import _",
"from spyder.utils.image_path_manager import get_image_path",
"from spyder.utils.encoding import to_unicode",
"from spyder.utils.qthelpers import qapplication",
"from spyder.config.manager import CONF"
] | 235 | 265 |
# Before launching a new Spyder instance we need to make sure that the
# reset subprocess has closed. We wait for a fixed and "reasonable"
# amount of time and check, otherwise an error is launched.
wait_time = 20 # Seconds
for counter in range(int(wait_time / SLEEP_TIME)):
if not is_pid_running(pid_reset):
break
time.sleep(SLEEP_TIME) # Throttling control
QApplication.processEvents() # Needed to refresh the splash
else:
# The reset subprocess took too long and it is killed
try:
p.kill()
except OSError as error:
restarter.launch_error_message(error_type=RESET_ERROR,
error=error)
else:
restarter.launch_error_message(error_type=RESET_ERROR)
# Restart
# -------------------------------------------------------------------------
restarter.set_splash_message(_('Restarting'))
try:
subprocess.Popen(' '.join(command + args), shell=shell, env=env)
except Exception as error:
restarter.launch_error_message(error_type=RESTART_ERROR, error=error)
if __name__ == '__main__':
main() | restart.py | spyder.spyder.app | false | false | [
"import ast",
"import os",
"import os.path as osp",
"import subprocess",
"import sys",
"import time",
"from qtpy.QtCore import Qt, QTimer",
"from qtpy.QtGui import QColor, QIcon",
"from qtpy.QtWidgets import QApplication, QMessageBox, QWidget",
"from spyder.app.utils import create_splash_screen",
"from spyder.config.base import _",
"from spyder.utils.image_path_manager import get_image_path",
"from spyder.utils.encoding import to_unicode",
"from spyder.utils.qthelpers import qapplication",
"from spyder.config.manager import CONF"
] | 267 | 296 |
# -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
# (see spyder/__init__.py for details)
"""
spyder.app
==========
Modules related to starting and restarting the Spyder application
""" | __init__.py | spyder.spyder.app | false | false | [] | 1 | 12 |
# -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
# (see spyder/__init__.py for details)
import argparse | cli_options.py | spyder.spyder.app | false | false | [
"import argparse"
] | 1 | 7 |
def get_options(argv=None):
"""
Convert options into commands.
Return commands, message
"""
parser = argparse.ArgumentParser(usage="spyder [options] files")
parser.add_argument(
'--new-instance',
action='store_true',
default=False,
help="Run a new instance of Spyder, even if the single "
"instance mode has been turned on (default)"
)
parser.add_argument(
'--defaults',
dest="reset_to_defaults",
action='store_true',
default=False,
help="Reset configuration settings to defaults"
)
parser.add_argument(
'--reset',
dest="reset_config_files",
action='store_true',
default=False,
help="Remove all configuration files!"
)
parser.add_argument(
'--optimize',
action='store_true',
default=False,
help="Optimize Spyder bytecode (this may require "
"administrative privileges)"
)
parser.add_argument(
'-w', '--workdir',
dest="working_directory",
default=None,
help="Default working directory"
)
parser.add_argument(
'--hide-console',
action='store_true',
default=False,
help="Hide parent console window (Windows)"
)
parser.add_argument(
'--show-console',
action='store_true',
default=False,
help="(Deprecated) Does nothing, now the default behavior " | cli_options.py | spyder.spyder.app | false | true | [
"import argparse"
] | 10 | 60 |
)
parser.add_argument(
'--show-console',
action='store_true',
default=False,
help="(Deprecated) Does nothing, now the default behavior "
"is to show the console"
)
parser.add_argument(
'--multithread',
dest="multithreaded",
action='store_true',
default=False,
help="Internal console is executed in another thread "
"(separate from main application thread)"
)
parser.add_argument(
'--profile',
action='store_true',
default=False,
help="Profile mode (internal test, not related "
"with Python profiling)"
)
parser.add_argument(
'--window-title',
type=str,
default=None,
help="String to show in the main window title"
)
parser.add_argument(
'-p', '--project',
default=None,
type=str,
dest="project",
help="Path that contains a Spyder project"
)
parser.add_argument(
'--opengl',
default=None,
dest="opengl_implementation",
choices=['software', 'desktop', 'gles'],
help="OpenGL implementation to pass to Qt"
)
parser.add_argument(
'--paths',
action='store_true',
default=False,
help="Show all Spyder configuration paths"
)
parser.add_argument(
'--debug-info',
default=None,
dest="debug_info", | cli_options.py | spyder.spyder.app | false | false | [
"import argparse"
] | 15 | 67 |
default=False,
help="Show all Spyder configuration paths"
)
parser.add_argument(
'--debug-info',
default=None,
dest="debug_info",
choices=['minimal', 'verbose'],
help=("Level of internal debugging info to give. "
"'minimal' only logs a small amount of "
"confirmation messages and 'verbose' logs a "
"lot of detailed information.")
)
parser.add_argument(
'--debug-output',
default='terminal',
dest="debug_output",
choices=['terminal', 'file'],
help=("Print internal debugging info to the terminal and a file in "
"the configuration directory or to the terminal and a file "
"called spyder-debug.log in the current working directory. "
"Default is 'terminal'.")
)
parser.add_argument(
'--filter-log',
default='',
help="Comma-separated module name hierarchies whose log "
"messages should be shown. e.g., "
"spyder.plugins.completion,spyder.plugins.editor"
)
parser.add_argument(
'--safe-mode',
dest="safe_mode",
action='store_true',
default=False,
help="Start Spyder with a clean configuration directory"
)
parser.add_argument(
'--no-web-widgets',
dest="no_web_widgets",
action='store_true',
default=False, | cli_options.py | spyder.spyder.app | false | false | [
"import argparse"
] | 101 | 142 |
)
parser.add_argument(
'--no-web-widgets',
dest="no_web_widgets",
action='store_true',
default=False,
help="Disable the usage of web widgets in Spyder (e.g. the Help and "
"Online help panes)."
)
parser.add_argument(
'--report-segfault',
dest="report_segfault",
action='store_true',
default=False,
help="Report segmentation fault to Github."
)
parser.add_argument(
'--conf-dir',
type=str,
dest="conf_dir",
default=None,
help="Choose a configuration directory to use for Spyder."
) | cli_options.py | spyder.spyder.app | false | false | [
"import argparse"
] | 15 | 37 |
parser.add_argument('files', nargs='*')
options = parser.parse_args(argv)
args = options.files
return options, args | cli_options.py | spyder.spyder.app | false | false | [
"import argparse"
] | 161 | 164 |
# -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
# (see spyder/__init__.py for details)
"""
Plugin dependency solver.
"""
import importlib
import logging
import traceback
import pkg_resources
from spyder.api.exceptions import SpyderAPIError
from spyder.api.plugins import Plugins
from spyder.api.utils import get_class_values
from spyder.config.base import STDERR
logger = logging.getLogger(__name__)
def find_internal_plugins():
"""
Find internal plugins based on setuptools entry points.
"""
internal_plugins = {}
entry_points = list(pkg_resources.iter_entry_points("spyder.plugins"))
internal_names = get_class_values(Plugins)
for entry_point in entry_points:
name = entry_point.name
if name not in internal_names:
continue
class_name = entry_point.attrs[0]
mod = importlib.import_module(entry_point.module_name)
plugin_class = getattr(mod, class_name, None)
internal_plugins[name] = plugin_class
# FIXME: This shouldn't be necessary but it's just to be sure
# plugins are sorted in alphabetical order. We need to remove it
# in a later version.
internal_plugins = {
key: value for key, value in sorted(internal_plugins.items())
}
return internal_plugins | find_plugins.py | spyder.spyder.app | false | true | [
"import importlib",
"import logging",
"import traceback",
"import pkg_resources",
"from spyder.api.exceptions import SpyderAPIError",
"from spyder.api.plugins import Plugins",
"from spyder.api.utils import get_class_values",
"from spyder.config.base import STDERR"
] | 1 | 51 |
def find_external_plugins():
"""
Find available external plugins based on setuptools entry points.
"""
internal_names = get_class_values(Plugins)
plugins = list(pkg_resources.iter_entry_points("spyder.plugins"))
external_plugins = {}
for entry_point in plugins:
name = entry_point.name
if name not in internal_names:
try:
class_name = entry_point.attrs[0]
mod = importlib.import_module(entry_point.module_name)
plugin_class = getattr(mod, class_name, None)
# To display in dependencies dialog.
plugin_class._spyder_module_name = entry_point.module_name
plugin_class._spyder_package_name = (
entry_point.dist.project_name)
plugin_class._spyder_version = entry_point.dist.version
external_plugins[name] = plugin_class
if name != plugin_class.NAME:
raise SpyderAPIError(
"Entry point name '{0}' and plugin.NAME '{1}' "
"do not match!".format(name, plugin_class.NAME)
)
except (ModuleNotFoundError, ImportError) as error:
print("%s: %s" % (name, str(error)), file=STDERR)
traceback.print_exc(file=STDERR)
return external_plugins | find_plugins.py | spyder.spyder.app | false | true | [
"import importlib",
"import logging",
"import traceback",
"import pkg_resources",
"from spyder.api.exceptions import SpyderAPIError",
"from spyder.api.plugins import Plugins",
"from spyder.api.utils import get_class_values",
"from spyder.config.base import STDERR"
] | 54 | 86 |
# -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
# (see spyder/__init__.py for details)
"""Utility functions for the Spyder application."""
# Standard library imports
import glob
import logging
import os
import os.path as osp
import re
import sys
# Third-party imports
import psutil
from qtpy.QtCore import QCoreApplication, Qt
from qtpy.QtGui import QColor, QIcon, QPalette, QPixmap, QPainter, QImage
from qtpy.QtWidgets import QApplication, QSplashScreen
from qtpy.QtSvg import QSvgRenderer
# Local imports
from spyder.config.base import (
DEV, get_conf_path, get_debug_level, is_conda_based_app,
running_under_pytest)
from spyder.config.manager import CONF
from spyder.utils.external.dafsa.dafsa import DAFSA
from spyder.utils.image_path_manager import get_image_path
from spyder.utils.installers import running_installer_test
from spyder.utils.palette import QStylePalette
from spyder.utils.qthelpers import file_uri, qapplication
# For spyder-ide/spyder#7447.
try:
from qtpy.QtQuick import QQuickWindow, QSGRendererInterface
except Exception:
QQuickWindow = QSGRendererInterface = None
root_logger = logging.getLogger()
FILTER_NAMES = os.environ.get('SPYDER_FILTER_LOG', "").split(',')
FILTER_NAMES = [f.strip() for f in FILTER_NAMES]
# Keeping a reference to the original sys.exit before patching it
ORIGINAL_SYS_EXIT = sys.exit | utils.py | spyder.spyder.app | false | false | [
"import glob",
"import logging",
"import os",
"import os.path as osp",
"import re",
"import sys",
"import psutil",
"from qtpy.QtCore import QCoreApplication, Qt",
"from qtpy.QtGui import QColor, QIcon, QPalette, QPixmap, QPainter, QImage",
"from qtpy.QtWidgets import QApplication, QSplashScreen",
"from qtpy.QtSvg import QSvgRenderer",
"from spyder.config.base import (",
"from spyder.config.manager import CONF",
"from spyder.utils.external.dafsa.dafsa import DAFSA",
"from spyder.utils.image_path_manager import get_image_path",
"from spyder.utils.installers import running_installer_test",
"from spyder.utils.palette import QStylePalette",
"from spyder.utils.qthelpers import file_uri, qapplication",
"from qtpy.QtQuick import QQuickWindow, QSGRendererInterface",
"from spyder.config.fonts import MEDIUM, MONOSPACE",
"from qtpy import QtWidgets"
] | 1 | 47 |
class Spy:
"""
This is used to inject a 'spy' object in the internal console
namespace to inspect Spyder internals.
Attributes:
app Reference to main QApplication object
window Reference to spyder.MainWindow widget
"""
def __init__(self, app, window):
self.app = app
self.window = window
def __dir__(self):
return (list(self.__dict__.keys()) +
[x for x in dir(self.__class__) if x[0] != '_'])
def get_python_doc_path():
"""
Return Python documentation path
(Windows: return the PythonXX.chm path if available)
"""
if os.name == 'nt':
doc_path = osp.join(sys.prefix, "Doc")
if not osp.isdir(doc_path):
return
python_chm = [path for path in os.listdir(doc_path)
if re.match(r"(?i)Python[0-9]{3,6}.chm", path)]
if python_chm:
return file_uri(osp.join(doc_path, python_chm[0]))
else:
vinf = sys.version_info
doc_path = '/usr/share/doc/python%d.%d/html' % (vinf[0], vinf[1])
python_doc = osp.join(doc_path, "index.html")
if osp.isfile(python_doc):
return file_uri(python_doc) | utils.py | spyder.spyder.app | true | true | [
"import glob",
"import logging",
"import os",
"import os.path as osp",
"import re",
"import sys",
"import psutil",
"from qtpy.QtCore import QCoreApplication, Qt",
"from qtpy.QtGui import QColor, QIcon, QPalette, QPixmap, QPainter, QImage",
"from qtpy.QtWidgets import QApplication, QSplashScreen",
"from qtpy.QtSvg import QSvgRenderer",
"from spyder.config.base import (",
"from spyder.config.manager import CONF",
"from spyder.utils.external.dafsa.dafsa import DAFSA",
"from spyder.utils.image_path_manager import get_image_path",
"from spyder.utils.installers import running_installer_test",
"from spyder.utils.palette import QStylePalette",
"from spyder.utils.qthelpers import file_uri, qapplication",
"from qtpy.QtQuick import QQuickWindow, QSGRendererInterface",
"from spyder.config.fonts import MEDIUM, MONOSPACE",
"from qtpy import QtWidgets"
] | 50 | 86 |
def set_opengl_implementation(option):
"""
Set the OpenGL implementation used by Spyder.
See spyder-ide/spyder#7447 for the details.
"""
if hasattr(QQuickWindow, "setGraphicsApi"):
set_api = QQuickWindow.setGraphicsApi # Qt 6
else:
set_api = QQuickWindow.setSceneGraphBackend # Qt 5
if option == 'software':
QCoreApplication.setAttribute(Qt.AA_UseSoftwareOpenGL)
if QQuickWindow is not None:
set_api(QSGRendererInterface.GraphicsApi.Software)
elif option == 'desktop':
QCoreApplication.setAttribute(Qt.AA_UseDesktopOpenGL)
if QQuickWindow is not None:
set_api(QSGRendererInterface.GraphicsApi.OpenGL)
elif option == 'gles':
QCoreApplication.setAttribute(Qt.AA_UseOpenGLES)
if QQuickWindow is not None:
set_api(QSGRendererInterface.GraphicsApi.OpenGL) | utils.py | spyder.spyder.app | false | true | [
"import glob",
"import logging",
"import os",
"import os.path as osp",
"import re",
"import sys",
"import psutil",
"from qtpy.QtCore import QCoreApplication, Qt",
"from qtpy.QtGui import QColor, QIcon, QPalette, QPixmap, QPainter, QImage",
"from qtpy.QtWidgets import QApplication, QSplashScreen",
"from qtpy.QtSvg import QSvgRenderer",
"from spyder.config.base import (",
"from spyder.config.manager import CONF",
"from spyder.utils.external.dafsa.dafsa import DAFSA",
"from spyder.utils.image_path_manager import get_image_path",
"from spyder.utils.installers import running_installer_test",
"from spyder.utils.palette import QStylePalette",
"from spyder.utils.qthelpers import file_uri, qapplication",
"from qtpy.QtQuick import QQuickWindow, QSGRendererInterface",
"from spyder.config.fonts import MEDIUM, MONOSPACE",
"from qtpy import QtWidgets"
] | 89 | 111 |
def setup_logging(cli_options):
"""Setup logging with cli options defined by the user."""
if cli_options.debug_info or get_debug_level() > 0:
levels = {2: logging.INFO, 3: logging.DEBUG}
log_level = levels[get_debug_level()]
log_format = '%(asctime)s [%(levelname)s] [%(name)s] -> %(message)s'
console_filters = cli_options.filter_log.split(',')
console_filters = [x.strip() for x in console_filters]
console_filters = console_filters + FILTER_NAMES
console_filters = [x for x in console_filters if x != '']
handlers = [logging.StreamHandler()]
filepath = os.environ['SPYDER_DEBUG_FILE']
handlers.append(
logging.FileHandler(filename=filepath, mode='w+')
)
match_func = lambda x: True
if console_filters != [''] and len(console_filters) > 0:
dafsa = DAFSA(console_filters)
match_func = lambda x: (dafsa.lookup(x, stop_on_prefix=True)
is not None)
formatter = logging.Formatter(log_format)
class ModuleFilter(logging.Filter):
"""Filter messages based on module name prefix."""
def filter(self, record):
return match_func(record.name) | utils.py | spyder.spyder.app | false | true | [
"import glob",
"import logging",
"import os",
"import os.path as osp",
"import re",
"import sys",
"import psutil",
"from qtpy.QtCore import QCoreApplication, Qt",
"from qtpy.QtGui import QColor, QIcon, QPalette, QPixmap, QPainter, QImage",
"from qtpy.QtWidgets import QApplication, QSplashScreen",
"from qtpy.QtSvg import QSvgRenderer",
"from spyder.config.base import (",
"from spyder.config.manager import CONF",
"from spyder.utils.external.dafsa.dafsa import DAFSA",
"from spyder.utils.image_path_manager import get_image_path",
"from spyder.utils.installers import running_installer_test",
"from spyder.utils.palette import QStylePalette",
"from spyder.utils.qthelpers import file_uri, qapplication",
"from qtpy.QtQuick import QQuickWindow, QSGRendererInterface",
"from spyder.config.fonts import MEDIUM, MONOSPACE",
"from qtpy import QtWidgets"
] | 114 | 144 |
class ModuleFilter(logging.Filter):
"""Filter messages based on module name prefix."""
def filter(self, record):
return match_func(record.name)
filter = ModuleFilter()
root_logger.setLevel(log_level)
for handler in handlers:
handler.addFilter(filter)
handler.setFormatter(formatter)
handler.setLevel(log_level)
root_logger.addHandler(handler) | utils.py | spyder.spyder.app | false | true | [
"import glob",
"import logging",
"import os",
"import os.path as osp",
"import re",
"import sys",
"import psutil",
"from qtpy.QtCore import QCoreApplication, Qt",
"from qtpy.QtGui import QColor, QIcon, QPalette, QPixmap, QPainter, QImage",
"from qtpy.QtWidgets import QApplication, QSplashScreen",
"from qtpy.QtSvg import QSvgRenderer",
"from spyder.config.base import (",
"from spyder.config.manager import CONF",
"from spyder.utils.external.dafsa.dafsa import DAFSA",
"from spyder.utils.image_path_manager import get_image_path",
"from spyder.utils.installers import running_installer_test",
"from spyder.utils.palette import QStylePalette",
"from spyder.utils.qthelpers import file_uri, qapplication",
"from qtpy.QtQuick import QQuickWindow, QSGRendererInterface",
"from spyder.config.fonts import MEDIUM, MONOSPACE",
"from qtpy import QtWidgets"
] | 140 | 152 |
def delete_debug_log_files():
"""Delete previous debug log files."""
regex = re.compile(r'.*_.*_(\d+)[.]log')
files = glob.glob(osp.join(get_conf_path('lsp_logs'), '*.log'))
for f in files:
match = regex.match(f)
if match is not None:
pid = int(match.group(1))
if not psutil.pid_exists(pid):
os.remove(f)
debug_file = os.environ['SPYDER_DEBUG_FILE']
if osp.exists(debug_file):
os.remove(debug_file)
def qt_message_handler(msg_type, msg_log_context, msg_string):
"""
Qt warning messages are intercepted by this handler.
On some operating systems, warning messages might be displayed
even if the actual message does not apply. This filter adds a
blacklist for messages that are being printed for no apparent
reason. Anything else will get printed in the internal console.
In DEV mode, all messages are printed.
"""
BLACKLIST = [
'QMainWidget::resizeDocks: all sizes need to be larger than 0',
]
if DEV or msg_string not in BLACKLIST:
print(msg_string) # spyder: test-skip | utils.py | spyder.spyder.app | false | true | [
"import glob",
"import logging",
"import os",
"import os.path as osp",
"import re",
"import sys",
"import psutil",
"from qtpy.QtCore import QCoreApplication, Qt",
"from qtpy.QtGui import QColor, QIcon, QPalette, QPixmap, QPainter, QImage",
"from qtpy.QtWidgets import QApplication, QSplashScreen",
"from qtpy.QtSvg import QSvgRenderer",
"from spyder.config.base import (",
"from spyder.config.manager import CONF",
"from spyder.utils.external.dafsa.dafsa import DAFSA",
"from spyder.utils.image_path_manager import get_image_path",
"from spyder.utils.installers import running_installer_test",
"from spyder.utils.palette import QStylePalette",
"from spyder.utils.qthelpers import file_uri, qapplication",
"from qtpy.QtQuick import QQuickWindow, QSGRendererInterface",
"from spyder.config.fonts import MEDIUM, MONOSPACE",
"from qtpy import QtWidgets"
] | 155 | 186 |
def create_splash_screen(use_previous_factor=False):
"""
Create splash screen.
Parameters
----------
use_previous_factor: bool, optional
Use previous scale factor when creating the splash screen. This is used
when restarting Spyder, so the screen looks as expected. Default is
False.
"""
if not running_under_pytest():
# This is a good size for the splash screen image at a scale factor of
# 1. It corresponds to 75 ppi and preserves its aspect ratio.
width = 526
height = 432
# This allows us to use the previous scale factor for the splash screen
# shown when Spyder is restarted. Otherwise, it appears pixelated.
previous_factor = float(
CONF.get('main', 'prev_high_dpi_custom_scale_factors', 1)
)
# We need to increase the image size according to the scale factor to
# be displayed correctly.
# See https://falsinsoft.blogspot.com/2016/04/
# qt-snippet-render-svg-to-qpixmap-for.html for details.
if CONF.get('main', 'high_dpi_custom_scale_factor'):
if not use_previous_factor:
factor = float(
CONF.get('main', 'high_dpi_custom_scale_factors')
)
else:
factor = previous_factor
else:
if not use_previous_factor:
factor = 1
else:
factor = previous_factor | utils.py | spyder.spyder.app | false | true | [
"import glob",
"import logging",
"import os",
"import os.path as osp",
"import re",
"import sys",
"import psutil",
"from qtpy.QtCore import QCoreApplication, Qt",
"from qtpy.QtGui import QColor, QIcon, QPalette, QPixmap, QPainter, QImage",
"from qtpy.QtWidgets import QApplication, QSplashScreen",
"from qtpy.QtSvg import QSvgRenderer",
"from spyder.config.base import (",
"from spyder.config.manager import CONF",
"from spyder.utils.external.dafsa.dafsa import DAFSA",
"from spyder.utils.image_path_manager import get_image_path",
"from spyder.utils.installers import running_installer_test",
"from spyder.utils.palette import QStylePalette",
"from spyder.utils.qthelpers import file_uri, qapplication",
"from qtpy.QtQuick import QQuickWindow, QSGRendererInterface",
"from spyder.config.fonts import MEDIUM, MONOSPACE",
"from qtpy import QtWidgets"
] | 189 | 227 |
# Save scale factor for restarts.
CONF.set('main', 'prev_high_dpi_custom_scale_factors', factor)
image = QImage(
int(width * factor), int(height * factor),
QImage.Format_ARGB32_Premultiplied
)
image.fill(0)
painter = QPainter(image)
renderer = QSvgRenderer(get_image_path('splash'))
renderer.render(painter)
painter.end()
# This is also necessary to make the image look good.
if factor > 1.0:
image.setDevicePixelRatio(factor)
pm = QPixmap.fromImage(image)
pm = pm.copy(0, 0, int(width * factor), int(height * factor))
splash = QSplashScreen(pm)
else:
splash = None
return splash | utils.py | spyder.spyder.app | false | false | [
"import glob",
"import logging",
"import os",
"import os.path as osp",
"import re",
"import sys",
"import psutil",
"from qtpy.QtCore import QCoreApplication, Qt",
"from qtpy.QtGui import QColor, QIcon, QPalette, QPixmap, QPainter, QImage",
"from qtpy.QtWidgets import QApplication, QSplashScreen",
"from qtpy.QtSvg import QSvgRenderer",
"from spyder.config.base import (",
"from spyder.config.manager import CONF",
"from spyder.utils.external.dafsa.dafsa import DAFSA",
"from spyder.utils.image_path_manager import get_image_path",
"from spyder.utils.installers import running_installer_test",
"from spyder.utils.palette import QStylePalette",
"from spyder.utils.qthelpers import file_uri, qapplication",
"from qtpy.QtQuick import QQuickWindow, QSGRendererInterface",
"from spyder.config.fonts import MEDIUM, MONOSPACE",
"from qtpy import QtWidgets"
] | 229 | 253 |
def set_links_color(app):
"""
Fix color for links.
This was taken from QDarkstyle, which is MIT licensed.
"""
color = QStylePalette.COLOR_ACCENT_4
qcolor = QColor(color)
app_palette = app.palette()
app_palette.setColor(QPalette.Normal, QPalette.Link, qcolor)
app.setPalette(app_palette) | utils.py | spyder.spyder.app | false | true | [
"import glob",
"import logging",
"import os",
"import os.path as osp",
"import re",
"import sys",
"import psutil",
"from qtpy.QtCore import QCoreApplication, Qt",
"from qtpy.QtGui import QColor, QIcon, QPalette, QPixmap, QPainter, QImage",
"from qtpy.QtWidgets import QApplication, QSplashScreen",
"from qtpy.QtSvg import QSvgRenderer",
"from spyder.config.base import (",
"from spyder.config.manager import CONF",
"from spyder.utils.external.dafsa.dafsa import DAFSA",
"from spyder.utils.image_path_manager import get_image_path",
"from spyder.utils.installers import running_installer_test",
"from spyder.utils.palette import QStylePalette",
"from spyder.utils.qthelpers import file_uri, qapplication",
"from qtpy.QtQuick import QQuickWindow, QSGRendererInterface",
"from spyder.config.fonts import MEDIUM, MONOSPACE",
"from qtpy import QtWidgets"
] | 256 | 267 |
def create_application():
"""Create application and patch sys.exit."""
# Our QApplication
app = qapplication()
# ---- Set icon
app_icon = QIcon(get_image_path("spyder"))
app.setWindowIcon(app_icon)
# ---- Set font
# The try/except is necessary to run the main window tests on their own.
try:
app.set_font()
except AttributeError as error:
if running_under_pytest():
# Set font options to avoid a ton of Qt warnings when running tests
app_family = app.font().family()
app_size = app.font().pointSize()
CONF.set('appearance', 'app_font/family', app_family)
CONF.set('appearance', 'app_font/size', app_size)
from spyder.config.fonts import MEDIUM, MONOSPACE
CONF.set('appearance', 'monospace_app_font/family', MONOSPACE[0])
CONF.set('appearance', 'monospace_app_font/size', MEDIUM)
else:
# Raise in case the error is valid
raise error
# Required for correct icon on GNOME/Wayland:
if hasattr(app, 'setDesktopFileName'):
app.setDesktopFileName('spyder')
# ---- Monkey patching QApplication
class FakeQApplication(QApplication):
"""Spyder's fake QApplication"""
def __init__(self, args):
self = app # analysis:ignore
@staticmethod
def exec_():
"""Do nothing because the Qt mainloop is already running"""
pass | utils.py | spyder.spyder.app | false | true | [
"import glob",
"import logging",
"import os",
"import os.path as osp",
"import re",
"import sys",
"import psutil",
"from qtpy.QtCore import QCoreApplication, Qt",
"from qtpy.QtGui import QColor, QIcon, QPalette, QPixmap, QPainter, QImage",
"from qtpy.QtWidgets import QApplication, QSplashScreen",
"from qtpy.QtSvg import QSvgRenderer",
"from spyder.config.base import (",
"from spyder.config.manager import CONF",
"from spyder.utils.external.dafsa.dafsa import DAFSA",
"from spyder.utils.image_path_manager import get_image_path",
"from spyder.utils.installers import running_installer_test",
"from spyder.utils.palette import QStylePalette",
"from spyder.utils.qthelpers import file_uri, qapplication",
"from qtpy.QtQuick import QQuickWindow, QSGRendererInterface",
"from spyder.config.fonts import MEDIUM, MONOSPACE",
"from qtpy import QtWidgets"
] | 270 | 311 |
@staticmethod
def exec_():
"""Do nothing because the Qt mainloop is already running"""
pass
from qtpy import QtWidgets
QtWidgets.QApplication = FakeQApplication
# ---- Monkey patching sys.exit
def fake_sys_exit(arg=[]):
pass
sys.exit = fake_sys_exit
# ---- Monkey patching sys.excepthook to avoid crashes in PyQt 5.5+
def spy_excepthook(type_, value, tback):
sys.__excepthook__(type_, value, tback)
if running_installer_test():
# This will exit Spyder with exit code 1 without invoking
# macOS system dialogue window.
raise SystemExit(1)
sys.excepthook = spy_excepthook
# Removing arguments from sys.argv as in standard Python interpreter
sys.argv = ['']
return app | utils.py | spyder.spyder.app | false | true | [
"import glob",
"import logging",
"import os",
"import os.path as osp",
"import re",
"import sys",
"import psutil",
"from qtpy.QtCore import QCoreApplication, Qt",
"from qtpy.QtGui import QColor, QIcon, QPalette, QPixmap, QPainter, QImage",
"from qtpy.QtWidgets import QApplication, QSplashScreen",
"from qtpy.QtSvg import QSvgRenderer",
"from spyder.config.base import (",
"from spyder.config.manager import CONF",
"from spyder.utils.external.dafsa.dafsa import DAFSA",
"from spyder.utils.image_path_manager import get_image_path",
"from spyder.utils.installers import running_installer_test",
"from spyder.utils.palette import QStylePalette",
"from spyder.utils.qthelpers import file_uri, qapplication",
"from qtpy.QtQuick import QQuickWindow, QSGRendererInterface",
"from spyder.config.fonts import MEDIUM, MONOSPACE",
"from qtpy import QtWidgets"
] | 308 | 333 |
def create_window(WindowClass, app, splash, options, args):
"""
Create and show Spyder's main window and start QApplication event loop.
Parameters
----------
WindowClass: QMainWindow
Subclass to instantiate the Window.
app: QApplication
Instance to start the application.
splash: QSplashScreen
Splash screen instamce.
options: argparse.Namespace
Command line options passed to Spyder
args: list
List of file names passed to the Spyder executable in the
command line.
"""
# Main window
main = WindowClass(splash, options)
try:
main.setup()
except BaseException:
if main.console is not None:
try:
main.console.exit_interpreter()
except BaseException:
pass
raise
main.pre_visible_setup()
main.show()
main.post_visible_setup()
if main.console:
main.console.start_interpreter(namespace={})
main.console.set_namespace_item('spy', Spy(app=app, window=main))
# Propagate current configurations to all configuration observers
CONF.notify_all_observers()
# Don't show icons in menus for Mac
if sys.platform == 'darwin':
QCoreApplication.setAttribute(Qt.AA_DontShowIconsInMenus, True) | utils.py | spyder.spyder.app | false | true | [
"import glob",
"import logging",
"import os",
"import os.path as osp",
"import re",
"import sys",
"import psutil",
"from qtpy.QtCore import QCoreApplication, Qt",
"from qtpy.QtGui import QColor, QIcon, QPalette, QPixmap, QPainter, QImage",
"from qtpy.QtWidgets import QApplication, QSplashScreen",
"from qtpy.QtSvg import QSvgRenderer",
"from spyder.config.base import (",
"from spyder.config.manager import CONF",
"from spyder.utils.external.dafsa.dafsa import DAFSA",
"from spyder.utils.image_path_manager import get_image_path",
"from spyder.utils.installers import running_installer_test",
"from spyder.utils.palette import QStylePalette",
"from spyder.utils.qthelpers import file_uri, qapplication",
"from qtpy.QtQuick import QQuickWindow, QSGRendererInterface",
"from spyder.config.fonts import MEDIUM, MONOSPACE",
"from qtpy import QtWidgets"
] | 336 | 379 |
# Don't show icons in menus for Mac
if sys.platform == 'darwin':
QCoreApplication.setAttribute(Qt.AA_DontShowIconsInMenus, True)
# Open external files with our Mac app
# ??? Do we need this?
if sys.platform == 'darwin' and is_conda_based_app():
app.sig_open_external_file.connect(main.open_external_file)
app._has_started = True
if hasattr(app, '_pending_file_open'):
if args:
args = app._pending_file_open + args
else:
args = app._pending_file_open
# Open external files passed as args
if args:
for a in args:
main.open_external_file(a)
# To give focus again to the last focused widget after restoring
# the window
app.focusChanged.connect(main.change_last_focused_widget)
if not running_under_pytest():
app.exec_()
return main | utils.py | spyder.spyder.app | false | false | [
"import glob",
"import logging",
"import os",
"import os.path as osp",
"import re",
"import sys",
"import psutil",
"from qtpy.QtCore import QCoreApplication, Qt",
"from qtpy.QtGui import QColor, QIcon, QPalette, QPixmap, QPainter, QImage",
"from qtpy.QtWidgets import QApplication, QSplashScreen",
"from qtpy.QtSvg import QSvgRenderer",
"from spyder.config.base import (",
"from spyder.config.manager import CONF",
"from spyder.utils.external.dafsa.dafsa import DAFSA",
"from spyder.utils.image_path_manager import get_image_path",
"from spyder.utils.installers import running_installer_test",
"from spyder.utils.palette import QStylePalette",
"from spyder.utils.qthelpers import file_uri, qapplication",
"from qtpy.QtQuick import QQuickWindow, QSGRendererInterface",
"from spyder.config.fonts import MEDIUM, MONOSPACE",
"from qtpy import QtWidgets"
] | 377 | 403 |
class MainWindow(
QMainWindow,
SpyderMainWindowMixin,
SpyderConfigurationAccessor
):
"""Spyder main window"""
CONF_SECTION = 'main'
DOCKOPTIONS = (
QMainWindow.AllowTabbedDocks | QMainWindow.AllowNestedDocks |
QMainWindow.AnimatedDocks
)
DEFAULT_LAYOUTS = 4
INITIAL_CWD = getcwd_or_home()
# Signals
restore_scrollbar_position = Signal()
sig_setup_finished = Signal()
sig_open_external_file = Signal(str)
sig_resized = Signal("QResizeEvent")
sig_moved = Signal("QMoveEvent")
sig_layout_setup_ready = Signal(object) # Related to default layouts
sig_window_state_changed = Signal(object)
"""
This signal is emitted when the window state has changed (for instance,
between maximized and minimized states).
Parameters
----------
window_state: Qt.WindowStates
The window state.
"""
def __init__(self, splash=None, options=None):
QMainWindow.__init__(self)
qapp = QApplication.instance()
if running_under_pytest():
self._proxy_style = None
else:
from spyder.utils.qthelpers import SpyderProxyStyle
# None is needed, see: https://bugreports.qt.io/browse/PYSIDE-922
self._proxy_style = SpyderProxyStyle(None) | mainwindow.py | spyder.spyder.app | false | true | [
"from collections import OrderedDict",
"import configparser as cp",
"from enum import Enum",
"import errno",
"import gc",
"import logging",
"import os",
"import os.path as osp",
"import shutil",
"import signal",
"import socket",
"import sys",
"import threading",
"import traceback",
"from spyder import requirements",
"from qtpy.QtCore import (QCoreApplication, Qt, QTimer, Signal, Slot,",
"from qtpy.QtGui import QColor, QKeySequence",
"from qtpy.QtWidgets import QApplication, QMainWindow, QMessageBox, QShortcut",
"from qtpy import QtSvg # analysis:ignore",
"from qtpy import QtWebEngineWidgets # analysis:ignore",
"from qtawesome.iconic_font import FontError",
"from spyder import __version__",
"from spyder.app.find_plugins import (",
"from spyder.app.utils import (",
"from spyder.api.plugin_registration.registry import PLUGIN_REGISTRY",
"from spyder.api.config.mixins import SpyderConfigurationAccessor",
"from spyder.api.widgets.mixins import SpyderMainWindowMixin",
"from spyder.config.base import (_, DEV, get_conf_path, get_debug_level,",
"from spyder.config.gui import is_dark_font_color",
"from spyder.config.main import OPEN_FILES_PORT",
"from spyder.config.manager import CONF",
"from spyder.config.utils import IMPORT_EXT",
"from spyder.py3compat import to_text_string",
"from spyder.utils import encoding, programs",
"from spyder.utils.icon_manager import ima",
"from spyder.utils.misc import select_port, getcwd_or_home",
"from spyder.utils.palette import QStylePalette",
"from spyder.utils.qthelpers import file_uri, qapplication, start_file",
"from spyder.utils.stylesheet import APP_STYLESHEET",
"from spyder.api.exceptions import SpyderAPIError",
"from spyder.api.plugins import (",
"from spyder.utils.windows import (set_attached_console_visible,",
"from spyder.utils.qthelpers import SpyderProxyStyle",
"import win32api",
"from spyder.plugins.help.utils.sphinxify import CSS_PATH, DARK_CSS_PATH",
"import spyder",
"import faulthandler"
] | 121 | 164 |
# Enabling scaling for high dpi. This is not required with Qt 6 where
# it is always enabled.
# See https://doc.qt.io/qt-6/portingguide.html#high-dpi
if hasattr(Qt, "AA_UseHighDpiPixmaps"):
qapp.setAttribute(Qt.AA_UseHighDpiPixmaps)
# Set Windows app icon to use .ico file
if os.name == "nt":
# Use resample kwarg to prevent a blurry icon on Windows
# See spyder-ide/spyder#18283
qapp.setWindowIcon(ima.get_icon("windows_app_icon", resample=True))
# Set default style
self.default_style = str(qapp.style().objectName())
# Save command line options for plugins to access them
self._cli_options = options
logger.info("Start of MainWindow constructor")
def signal_handler(signum, frame=None):
"""Handler for signals."""
sys.stdout.write('Handling signal: %s\n' % signum)
sys.stdout.flush()
QApplication.quit() | mainwindow.py | spyder.spyder.app | false | true | [
"from collections import OrderedDict",
"import configparser as cp",
"from enum import Enum",
"import errno",
"import gc",
"import logging",
"import os",
"import os.path as osp",
"import shutil",
"import signal",
"import socket",
"import sys",
"import threading",
"import traceback",
"from spyder import requirements",
"from qtpy.QtCore import (QCoreApplication, Qt, QTimer, Signal, Slot,",
"from qtpy.QtGui import QColor, QKeySequence",
"from qtpy.QtWidgets import QApplication, QMainWindow, QMessageBox, QShortcut",
"from qtpy import QtSvg # analysis:ignore",
"from qtpy import QtWebEngineWidgets # analysis:ignore",
"from qtawesome.iconic_font import FontError",
"from spyder import __version__",
"from spyder.app.find_plugins import (",
"from spyder.app.utils import (",
"from spyder.api.plugin_registration.registry import PLUGIN_REGISTRY",
"from spyder.api.config.mixins import SpyderConfigurationAccessor",
"from spyder.api.widgets.mixins import SpyderMainWindowMixin",
"from spyder.config.base import (_, DEV, get_conf_path, get_debug_level,",
"from spyder.config.gui import is_dark_font_color",
"from spyder.config.main import OPEN_FILES_PORT",
"from spyder.config.manager import CONF",
"from spyder.config.utils import IMPORT_EXT",
"from spyder.py3compat import to_text_string",
"from spyder.utils import encoding, programs",
"from spyder.utils.icon_manager import ima",
"from spyder.utils.misc import select_port, getcwd_or_home",
"from spyder.utils.palette import QStylePalette",
"from spyder.utils.qthelpers import file_uri, qapplication, start_file",
"from spyder.utils.stylesheet import APP_STYLESHEET",
"from spyder.api.exceptions import SpyderAPIError",
"from spyder.api.plugins import (",
"from spyder.utils.windows import (set_attached_console_visible,",
"from spyder.utils.qthelpers import SpyderProxyStyle",
"import win32api",
"from spyder.plugins.help.utils.sphinxify import CSS_PATH, DARK_CSS_PATH",
"import spyder",
"import faulthandler"
] | 166 | 190 |
if os.name == "nt":
try:
import win32api
win32api.SetConsoleCtrlHandler(signal_handler, True)
except ImportError:
pass
else:
signal.signal(signal.SIGTERM, signal_handler)
if not DEV:
# Make spyder quit when presing ctrl+C in the console
# In DEV Ctrl+C doesn't quit, because it helps to
# capture the traceback when spyder freezes
signal.signal(signal.SIGINT, signal_handler)
# Shortcut management data
self.shortcut_data = []
self.shortcut_queue = [] | mainwindow.py | spyder.spyder.app | false | false | [
"from collections import OrderedDict",
"import configparser as cp",
"from enum import Enum",
"import errno",
"import gc",
"import logging",
"import os",
"import os.path as osp",
"import shutil",
"import signal",
"import socket",
"import sys",
"import threading",
"import traceback",
"from spyder import requirements",
"from qtpy.QtCore import (QCoreApplication, Qt, QTimer, Signal, Slot,",
"from qtpy.QtGui import QColor, QKeySequence",
"from qtpy.QtWidgets import QApplication, QMainWindow, QMessageBox, QShortcut",
"from qtpy import QtSvg # analysis:ignore",
"from qtpy import QtWebEngineWidgets # analysis:ignore",
"from qtawesome.iconic_font import FontError",
"from spyder import __version__",
"from spyder.app.find_plugins import (",
"from spyder.app.utils import (",
"from spyder.api.plugin_registration.registry import PLUGIN_REGISTRY",
"from spyder.api.config.mixins import SpyderConfigurationAccessor",
"from spyder.api.widgets.mixins import SpyderMainWindowMixin",
"from spyder.config.base import (_, DEV, get_conf_path, get_debug_level,",
"from spyder.config.gui import is_dark_font_color",
"from spyder.config.main import OPEN_FILES_PORT",
"from spyder.config.manager import CONF",
"from spyder.config.utils import IMPORT_EXT",
"from spyder.py3compat import to_text_string",
"from spyder.utils import encoding, programs",
"from spyder.utils.icon_manager import ima",
"from spyder.utils.misc import select_port, getcwd_or_home",
"from spyder.utils.palette import QStylePalette",
"from spyder.utils.qthelpers import file_uri, qapplication, start_file",
"from spyder.utils.stylesheet import APP_STYLESHEET",
"from spyder.api.exceptions import SpyderAPIError",
"from spyder.api.plugins import (",
"from spyder.utils.windows import (set_attached_console_visible,",
"from spyder.utils.qthelpers import SpyderProxyStyle",
"import win32api",
"from spyder.plugins.help.utils.sphinxify import CSS_PATH, DARK_CSS_PATH",
"import spyder",
"import faulthandler"
] | 192 | 208 |
# Shortcut management data
self.shortcut_data = []
self.shortcut_queue = []
# New API
self._APPLICATION_TOOLBARS = OrderedDict()
self._STATUS_WIDGETS = OrderedDict()
# Mapping of new plugin identifiers vs old attributtes
# names given for plugins or to prevent collisions with other
# attributes, i.e layout (Qt) vs layout (SpyderPluginV2)
self._INTERNAL_PLUGINS_MAPPING = {
'console': Plugins.Console,
'maininterpreter': Plugins.MainInterpreter,
'outlineexplorer': Plugins.OutlineExplorer,
'variableexplorer': Plugins.VariableExplorer,
'debugger': Plugins.Debugger,
'ipyconsole': Plugins.IPythonConsole,
'workingdirectory': Plugins.WorkingDirectory,
'projects': Plugins.Projects,
'findinfiles': Plugins.Find,
'layouts': Plugins.Layout,
'switcher': Plugins.Switcher,
}
self.thirdparty_plugins = []
# Preferences
self.prefs_dialog_instance = None
# Actions
self.undo_action = None
self.redo_action = None
self.copy_action = None
self.cut_action = None
self.paste_action = None
self.selectall_action = None
# TODO: Move to corresponding Plugins
self.file_toolbar = None
self.file_toolbar_actions = []
self.menus = [] | mainwindow.py | spyder.spyder.app | false | false | [
"from collections import OrderedDict",
"import configparser as cp",
"from enum import Enum",
"import errno",
"import gc",
"import logging",
"import os",
"import os.path as osp",
"import shutil",
"import signal",
"import socket",
"import sys",
"import threading",
"import traceback",
"from spyder import requirements",
"from qtpy.QtCore import (QCoreApplication, Qt, QTimer, Signal, Slot,",
"from qtpy.QtGui import QColor, QKeySequence",
"from qtpy.QtWidgets import QApplication, QMainWindow, QMessageBox, QShortcut",
"from qtpy import QtSvg # analysis:ignore",
"from qtpy import QtWebEngineWidgets # analysis:ignore",
"from qtawesome.iconic_font import FontError",
"from spyder import __version__",
"from spyder.app.find_plugins import (",
"from spyder.app.utils import (",
"from spyder.api.plugin_registration.registry import PLUGIN_REGISTRY",
"from spyder.api.config.mixins import SpyderConfigurationAccessor",
"from spyder.api.widgets.mixins import SpyderMainWindowMixin",
"from spyder.config.base import (_, DEV, get_conf_path, get_debug_level,",
"from spyder.config.gui import is_dark_font_color",
"from spyder.config.main import OPEN_FILES_PORT",
"from spyder.config.manager import CONF",
"from spyder.config.utils import IMPORT_EXT",
"from spyder.py3compat import to_text_string",
"from spyder.utils import encoding, programs",
"from spyder.utils.icon_manager import ima",
"from spyder.utils.misc import select_port, getcwd_or_home",
"from spyder.utils.palette import QStylePalette",
"from spyder.utils.qthelpers import file_uri, qapplication, start_file",
"from spyder.utils.stylesheet import APP_STYLESHEET",
"from spyder.api.exceptions import SpyderAPIError",
"from spyder.api.plugins import (",
"from spyder.utils.windows import (set_attached_console_visible,",
"from spyder.utils.qthelpers import SpyderProxyStyle",
"import win32api",
"from spyder.plugins.help.utils.sphinxify import CSS_PATH, DARK_CSS_PATH",
"import spyder",
"import faulthandler"
] | 206 | 247 |
# TODO: Move to corresponding Plugins
self.file_toolbar = None
self.file_toolbar_actions = []
self.menus = []
if running_under_pytest():
# Show errors in internal console when testing.
self.set_conf('show_internal_errors', False)
self.CURSORBLINK_OSDEFAULT = QApplication.cursorFlashTime()
if set_windows_appusermodelid is not None:
res = set_windows_appusermodelid()
logger.info("appusermodelid: %s", res)
# Setting QTimer if running in travis
test_app = os.environ.get('TEST_CI_APP')
if test_app is not None:
app = qapplication()
timer_shutdown_time = 30000
self.timer_shutdown = QTimer(self)
self.timer_shutdown.timeout.connect(app.quit)
self.timer_shutdown.start(timer_shutdown_time)
# Showing splash screen
self.splash = splash
if self.get_conf('current_version', default='') != __version__:
self.set_conf('current_version', __version__)
# Execute here the actions to be performed only once after
# each update (there is nothing there for now, but it could
# be useful some day...)
# List of satellite widgets (registered in add_dockwidget):
self.widgetlist = [] | mainwindow.py | spyder.spyder.app | false | false | [
"from collections import OrderedDict",
"import configparser as cp",
"from enum import Enum",
"import errno",
"import gc",
"import logging",
"import os",
"import os.path as osp",
"import shutil",
"import signal",
"import socket",
"import sys",
"import threading",
"import traceback",
"from spyder import requirements",
"from qtpy.QtCore import (QCoreApplication, Qt, QTimer, Signal, Slot,",
"from qtpy.QtGui import QColor, QKeySequence",
"from qtpy.QtWidgets import QApplication, QMainWindow, QMessageBox, QShortcut",
"from qtpy import QtSvg # analysis:ignore",
"from qtpy import QtWebEngineWidgets # analysis:ignore",
"from qtawesome.iconic_font import FontError",
"from spyder import __version__",
"from spyder.app.find_plugins import (",
"from spyder.app.utils import (",
"from spyder.api.plugin_registration.registry import PLUGIN_REGISTRY",
"from spyder.api.config.mixins import SpyderConfigurationAccessor",
"from spyder.api.widgets.mixins import SpyderMainWindowMixin",
"from spyder.config.base import (_, DEV, get_conf_path, get_debug_level,",
"from spyder.config.gui import is_dark_font_color",
"from spyder.config.main import OPEN_FILES_PORT",
"from spyder.config.manager import CONF",
"from spyder.config.utils import IMPORT_EXT",
"from spyder.py3compat import to_text_string",
"from spyder.utils import encoding, programs",
"from spyder.utils.icon_manager import ima",
"from spyder.utils.misc import select_port, getcwd_or_home",
"from spyder.utils.palette import QStylePalette",
"from spyder.utils.qthelpers import file_uri, qapplication, start_file",
"from spyder.utils.stylesheet import APP_STYLESHEET",
"from spyder.api.exceptions import SpyderAPIError",
"from spyder.api.plugins import (",
"from spyder.utils.windows import (set_attached_console_visible,",
"from spyder.utils.qthelpers import SpyderProxyStyle",
"import win32api",
"from spyder.plugins.help.utils.sphinxify import CSS_PATH, DARK_CSS_PATH",
"import spyder",
"import faulthandler"
] | 243 | 277 |
# List of satellite widgets (registered in add_dockwidget):
self.widgetlist = []
# Flags used if closing() is called by the exit() shell command
self.already_closed = False
self.is_starting_up = True
self.is_setting_up = True
self.window_size = None
self.window_position = None
# To keep track of the last focused widget
self.last_focused_widget = None
self.previous_focused_widget = None | mainwindow.py | spyder.spyder.app | false | false | [
"from collections import OrderedDict",
"import configparser as cp",
"from enum import Enum",
"import errno",
"import gc",
"import logging",
"import os",
"import os.path as osp",
"import shutil",
"import signal",
"import socket",
"import sys",
"import threading",
"import traceback",
"from spyder import requirements",
"from qtpy.QtCore import (QCoreApplication, Qt, QTimer, Signal, Slot,",
"from qtpy.QtGui import QColor, QKeySequence",
"from qtpy.QtWidgets import QApplication, QMainWindow, QMessageBox, QShortcut",
"from qtpy import QtSvg # analysis:ignore",
"from qtpy import QtWebEngineWidgets # analysis:ignore",
"from qtawesome.iconic_font import FontError",
"from spyder import __version__",
"from spyder.app.find_plugins import (",
"from spyder.app.utils import (",
"from spyder.api.plugin_registration.registry import PLUGIN_REGISTRY",
"from spyder.api.config.mixins import SpyderConfigurationAccessor",
"from spyder.api.widgets.mixins import SpyderMainWindowMixin",
"from spyder.config.base import (_, DEV, get_conf_path, get_debug_level,",
"from spyder.config.gui import is_dark_font_color",
"from spyder.config.main import OPEN_FILES_PORT",
"from spyder.config.manager import CONF",
"from spyder.config.utils import IMPORT_EXT",
"from spyder.py3compat import to_text_string",
"from spyder.utils import encoding, programs",
"from spyder.utils.icon_manager import ima",
"from spyder.utils.misc import select_port, getcwd_or_home",
"from spyder.utils.palette import QStylePalette",
"from spyder.utils.qthelpers import file_uri, qapplication, start_file",
"from spyder.utils.stylesheet import APP_STYLESHEET",
"from spyder.api.exceptions import SpyderAPIError",
"from spyder.api.plugins import (",
"from spyder.utils.windows import (set_attached_console_visible,",
"from spyder.utils.qthelpers import SpyderProxyStyle",
"import win32api",
"from spyder.plugins.help.utils.sphinxify import CSS_PATH, DARK_CSS_PATH",
"import spyder",
"import faulthandler"
] | 276 | 289 |
# To keep track of the last focused widget
self.last_focused_widget = None
self.previous_focused_widget = None
# Server to open external files on a single instance
# This is needed in order to handle socket creation problems.
# See spyder-ide/spyder#4132.
if os.name == 'nt':
try:
self.open_files_server = socket.socket(socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_TCP)
except OSError:
self.open_files_server = None
QMessageBox.warning(
None,
"Spyder",
_("An error occurred while creating a socket needed "
"by Spyder. Please, try to run as an Administrator "
"from cmd.exe the following command and then "
"restart your computer: <br><br><span "
"style=\'color: {color}\'><b>netsh winsock reset "
"</b></span><br>").format(
color=QStylePalette.COLOR_BACKGROUND_4)
)
else:
self.open_files_server = socket.socket(socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_TCP) | mainwindow.py | spyder.spyder.app | false | false | [
"from collections import OrderedDict",
"import configparser as cp",
"from enum import Enum",
"import errno",
"import gc",
"import logging",
"import os",
"import os.path as osp",
"import shutil",
"import signal",
"import socket",
"import sys",
"import threading",
"import traceback",
"from spyder import requirements",
"from qtpy.QtCore import (QCoreApplication, Qt, QTimer, Signal, Slot,",
"from qtpy.QtGui import QColor, QKeySequence",
"from qtpy.QtWidgets import QApplication, QMainWindow, QMessageBox, QShortcut",
"from qtpy import QtSvg # analysis:ignore",
"from qtpy import QtWebEngineWidgets # analysis:ignore",
"from qtawesome.iconic_font import FontError",
"from spyder import __version__",
"from spyder.app.find_plugins import (",
"from spyder.app.utils import (",
"from spyder.api.plugin_registration.registry import PLUGIN_REGISTRY",
"from spyder.api.config.mixins import SpyderConfigurationAccessor",
"from spyder.api.widgets.mixins import SpyderMainWindowMixin",
"from spyder.config.base import (_, DEV, get_conf_path, get_debug_level,",
"from spyder.config.gui import is_dark_font_color",
"from spyder.config.main import OPEN_FILES_PORT",
"from spyder.config.manager import CONF",
"from spyder.config.utils import IMPORT_EXT",
"from spyder.py3compat import to_text_string",
"from spyder.utils import encoding, programs",
"from spyder.utils.icon_manager import ima",
"from spyder.utils.misc import select_port, getcwd_or_home",
"from spyder.utils.palette import QStylePalette",
"from spyder.utils.qthelpers import file_uri, qapplication, start_file",
"from spyder.utils.stylesheet import APP_STYLESHEET",
"from spyder.api.exceptions import SpyderAPIError",
"from spyder.api.plugins import (",
"from spyder.utils.windows import (set_attached_console_visible,",
"from spyder.utils.qthelpers import SpyderProxyStyle",
"import win32api",
"from spyder.plugins.help.utils.sphinxify import CSS_PATH, DARK_CSS_PATH",
"import spyder",
"import faulthandler"
] | 287 | 315 |
# Apply main window settings
self.apply_settings()
# To set all dockwidgets tabs to be on top (in case we want to do it
# in the future)
# self.setTabPosition(Qt.AllDockWidgetAreas, QTabWidget.North)
logger.info("End of MainWindow constructor")
# ---- Plugin handling methods
# -------------------------------------------------------------------------
def get_plugin(self, plugin_name, error=True):
"""
Return a plugin instance by providing the plugin class.
"""
if plugin_name in PLUGIN_REGISTRY:
return PLUGIN_REGISTRY.get_plugin(plugin_name)
if error:
raise SpyderAPIError(f'Plugin "{plugin_name}" not found!')
return None
def get_dockable_plugins(self):
"""Get a list of all dockable plugins."""
dockable_plugins = []
for plugin_name in PLUGIN_REGISTRY:
plugin = PLUGIN_REGISTRY.get_plugin(plugin_name)
if isinstance(plugin, (SpyderDockablePlugin, SpyderPluginWidget)):
dockable_plugins.append((plugin_name, plugin))
return dockable_plugins
def is_plugin_enabled(self, plugin_name):
"""Determine if a given plugin is going to be loaded."""
return PLUGIN_REGISTRY.is_plugin_enabled(plugin_name) | mainwindow.py | spyder.spyder.app | false | true | [
"from collections import OrderedDict",
"import configparser as cp",
"from enum import Enum",
"import errno",
"import gc",
"import logging",
"import os",
"import os.path as osp",
"import shutil",
"import signal",
"import socket",
"import sys",
"import threading",
"import traceback",
"from spyder import requirements",
"from qtpy.QtCore import (QCoreApplication, Qt, QTimer, Signal, Slot,",
"from qtpy.QtGui import QColor, QKeySequence",
"from qtpy.QtWidgets import QApplication, QMainWindow, QMessageBox, QShortcut",
"from qtpy import QtSvg # analysis:ignore",
"from qtpy import QtWebEngineWidgets # analysis:ignore",
"from qtawesome.iconic_font import FontError",
"from spyder import __version__",
"from spyder.app.find_plugins import (",
"from spyder.app.utils import (",
"from spyder.api.plugin_registration.registry import PLUGIN_REGISTRY",
"from spyder.api.config.mixins import SpyderConfigurationAccessor",
"from spyder.api.widgets.mixins import SpyderMainWindowMixin",
"from spyder.config.base import (_, DEV, get_conf_path, get_debug_level,",
"from spyder.config.gui import is_dark_font_color",
"from spyder.config.main import OPEN_FILES_PORT",
"from spyder.config.manager import CONF",
"from spyder.config.utils import IMPORT_EXT",
"from spyder.py3compat import to_text_string",
"from spyder.utils import encoding, programs",
"from spyder.utils.icon_manager import ima",
"from spyder.utils.misc import select_port, getcwd_or_home",
"from spyder.utils.palette import QStylePalette",
"from spyder.utils.qthelpers import file_uri, qapplication, start_file",
"from spyder.utils.stylesheet import APP_STYLESHEET",
"from spyder.api.exceptions import SpyderAPIError",
"from spyder.api.plugins import (",
"from spyder.utils.windows import (set_attached_console_visible,",
"from spyder.utils.qthelpers import SpyderProxyStyle",
"import win32api",
"from spyder.plugins.help.utils.sphinxify import CSS_PATH, DARK_CSS_PATH",
"import spyder",
"import faulthandler"
] | 317 | 351 |
def is_plugin_enabled(self, plugin_name):
"""Determine if a given plugin is going to be loaded."""
return PLUGIN_REGISTRY.is_plugin_enabled(plugin_name)
def is_plugin_available(self, plugin_name):
"""Determine if a given plugin is available."""
return PLUGIN_REGISTRY.is_plugin_available(plugin_name)
def show_status_message(self, message, timeout):
"""
Show a status message in Spyder Main Window.
"""
status_bar = self.statusBar()
if status_bar.isVisible():
status_bar.showMessage(message, timeout)
def show_plugin_compatibility_message(self, plugin_name, message):
"""
Show a compatibility message.
"""
messageBox = QMessageBox(self)
# Set attributes
messageBox.setWindowModality(Qt.NonModal)
messageBox.setAttribute(Qt.WA_DeleteOnClose)
messageBox.setWindowTitle(_('Plugin compatibility check'))
messageBox.setText(
_("It was not possible to load the {} plugin. The problem "
"was:<br><br>{}").format(plugin_name, message)
)
messageBox.setStandardButtons(QMessageBox.Ok)
# Show message.
# Note: All adjustments that require graphical properties of the widget
# need to be done after this point.
messageBox.show() | mainwindow.py | spyder.spyder.app | false | true | [
"from collections import OrderedDict",
"import configparser as cp",
"from enum import Enum",
"import errno",
"import gc",
"import logging",
"import os",
"import os.path as osp",
"import shutil",
"import signal",
"import socket",
"import sys",
"import threading",
"import traceback",
"from spyder import requirements",
"from qtpy.QtCore import (QCoreApplication, Qt, QTimer, Signal, Slot,",
"from qtpy.QtGui import QColor, QKeySequence",
"from qtpy.QtWidgets import QApplication, QMainWindow, QMessageBox, QShortcut",
"from qtpy import QtSvg # analysis:ignore",
"from qtpy import QtWebEngineWidgets # analysis:ignore",
"from qtawesome.iconic_font import FontError",
"from spyder import __version__",
"from spyder.app.find_plugins import (",
"from spyder.app.utils import (",
"from spyder.api.plugin_registration.registry import PLUGIN_REGISTRY",
"from spyder.api.config.mixins import SpyderConfigurationAccessor",
"from spyder.api.widgets.mixins import SpyderMainWindowMixin",
"from spyder.config.base import (_, DEV, get_conf_path, get_debug_level,",
"from spyder.config.gui import is_dark_font_color",
"from spyder.config.main import OPEN_FILES_PORT",
"from spyder.config.manager import CONF",
"from spyder.config.utils import IMPORT_EXT",
"from spyder.py3compat import to_text_string",
"from spyder.utils import encoding, programs",
"from spyder.utils.icon_manager import ima",
"from spyder.utils.misc import select_port, getcwd_or_home",
"from spyder.utils.palette import QStylePalette",
"from spyder.utils.qthelpers import file_uri, qapplication, start_file",
"from spyder.utils.stylesheet import APP_STYLESHEET",
"from spyder.api.exceptions import SpyderAPIError",
"from spyder.api.plugins import (",
"from spyder.utils.windows import (set_attached_console_visible,",
"from spyder.utils.qthelpers import SpyderProxyStyle",
"import win32api",
"from spyder.plugins.help.utils.sphinxify import CSS_PATH, DARK_CSS_PATH",
"import spyder",
"import faulthandler"
] | 349 | 384 |
# Show message.
# Note: All adjustments that require graphical properties of the widget
# need to be done after this point.
messageBox.show()
# Center message
screen_geometry = self.screen().geometry()
x = (screen_geometry.width() - messageBox.width()) / 2
y = (screen_geometry.height() - messageBox.height()) / 2
messageBox.move(x, y)
def register_plugin(self, plugin_name, external=False, omit_conf=False):
"""
Register a plugin in Spyder Main Window.
"""
plugin = PLUGIN_REGISTRY.get_plugin(plugin_name)
self.set_splash(_("Loading {}...").format(plugin.get_name()))
logger.info("Loading {}...".format(plugin.NAME))
# Check plugin compatibility
is_compatible, message = plugin.check_compatibility()
plugin.is_compatible = is_compatible
plugin.get_description()
if not is_compatible:
self.show_plugin_compatibility_message(plugin.get_name(), message)
return | mainwindow.py | spyder.spyder.app | false | true | [
"from collections import OrderedDict",
"import configparser as cp",
"from enum import Enum",
"import errno",
"import gc",
"import logging",
"import os",
"import os.path as osp",
"import shutil",
"import signal",
"import socket",
"import sys",
"import threading",
"import traceback",
"from spyder import requirements",
"from qtpy.QtCore import (QCoreApplication, Qt, QTimer, Signal, Slot,",
"from qtpy.QtGui import QColor, QKeySequence",
"from qtpy.QtWidgets import QApplication, QMainWindow, QMessageBox, QShortcut",
"from qtpy import QtSvg # analysis:ignore",
"from qtpy import QtWebEngineWidgets # analysis:ignore",
"from qtawesome.iconic_font import FontError",
"from spyder import __version__",
"from spyder.app.find_plugins import (",
"from spyder.app.utils import (",
"from spyder.api.plugin_registration.registry import PLUGIN_REGISTRY",
"from spyder.api.config.mixins import SpyderConfigurationAccessor",
"from spyder.api.widgets.mixins import SpyderMainWindowMixin",
"from spyder.config.base import (_, DEV, get_conf_path, get_debug_level,",
"from spyder.config.gui import is_dark_font_color",
"from spyder.config.main import OPEN_FILES_PORT",
"from spyder.config.manager import CONF",
"from spyder.config.utils import IMPORT_EXT",
"from spyder.py3compat import to_text_string",
"from spyder.utils import encoding, programs",
"from spyder.utils.icon_manager import ima",
"from spyder.utils.misc import select_port, getcwd_or_home",
"from spyder.utils.palette import QStylePalette",
"from spyder.utils.qthelpers import file_uri, qapplication, start_file",
"from spyder.utils.stylesheet import APP_STYLESHEET",
"from spyder.api.exceptions import SpyderAPIError",
"from spyder.api.plugins import (",
"from spyder.utils.windows import (set_attached_console_visible,",
"from spyder.utils.qthelpers import SpyderProxyStyle",
"import win32api",
"from spyder.plugins.help.utils.sphinxify import CSS_PATH, DARK_CSS_PATH",
"import spyder",
"import faulthandler"
] | 381 | 408 |
if not is_compatible:
self.show_plugin_compatibility_message(plugin.get_name(), message)
return
# Connect plugin signals to main window methods
plugin.sig_exception_occurred.connect(self.handle_exception)
plugin.sig_free_memory_requested.connect(self.free_memory)
plugin.sig_quit_requested.connect(self.close)
plugin.sig_restart_requested.connect(self.restart)
plugin.sig_redirect_stdio_requested.connect(
self.redirect_internalshell_stdio)
plugin.sig_status_message_requested.connect(self.show_status_message)
plugin.sig_unmaximize_plugin_requested.connect(self.unmaximize_plugin)
plugin.sig_unmaximize_plugin_requested[object].connect(
self.unmaximize_plugin)
if isinstance(plugin, SpyderDockablePlugin):
plugin.sig_switch_to_plugin_requested.connect(
self.switch_to_plugin)
plugin.sig_update_ancestor_requested.connect(
lambda: plugin.set_ancestor(self))
# Connect Main window Signals to plugin signals
self.sig_moved.connect(plugin.sig_mainwindow_moved)
self.sig_resized.connect(plugin.sig_mainwindow_resized)
self.sig_window_state_changed.connect(
plugin.sig_mainwindow_state_changed)
# Register plugin
plugin._register(omit_conf=omit_conf) | mainwindow.py | spyder.spyder.app | false | false | [
"from collections import OrderedDict",
"import configparser as cp",
"from enum import Enum",
"import errno",
"import gc",
"import logging",
"import os",
"import os.path as osp",
"import shutil",
"import signal",
"import socket",
"import sys",
"import threading",
"import traceback",
"from spyder import requirements",
"from qtpy.QtCore import (QCoreApplication, Qt, QTimer, Signal, Slot,",
"from qtpy.QtGui import QColor, QKeySequence",
"from qtpy.QtWidgets import QApplication, QMainWindow, QMessageBox, QShortcut",
"from qtpy import QtSvg # analysis:ignore",
"from qtpy import QtWebEngineWidgets # analysis:ignore",
"from qtawesome.iconic_font import FontError",
"from spyder import __version__",
"from spyder.app.find_plugins import (",
"from spyder.app.utils import (",
"from spyder.api.plugin_registration.registry import PLUGIN_REGISTRY",
"from spyder.api.config.mixins import SpyderConfigurationAccessor",
"from spyder.api.widgets.mixins import SpyderMainWindowMixin",
"from spyder.config.base import (_, DEV, get_conf_path, get_debug_level,",
"from spyder.config.gui import is_dark_font_color",
"from spyder.config.main import OPEN_FILES_PORT",
"from spyder.config.manager import CONF",
"from spyder.config.utils import IMPORT_EXT",
"from spyder.py3compat import to_text_string",
"from spyder.utils import encoding, programs",
"from spyder.utils.icon_manager import ima",
"from spyder.utils.misc import select_port, getcwd_or_home",
"from spyder.utils.palette import QStylePalette",
"from spyder.utils.qthelpers import file_uri, qapplication, start_file",
"from spyder.utils.stylesheet import APP_STYLESHEET",
"from spyder.api.exceptions import SpyderAPIError",
"from spyder.api.plugins import (",
"from spyder.utils.windows import (set_attached_console_visible,",
"from spyder.utils.qthelpers import SpyderProxyStyle",
"import win32api",
"from spyder.plugins.help.utils.sphinxify import CSS_PATH, DARK_CSS_PATH",
"import spyder",
"import faulthandler"
] | 406 | 435 |
# Register plugin
plugin._register(omit_conf=omit_conf)
if isinstance(plugin, SpyderDockablePlugin):
# Add dockwidget
self.add_dockwidget(plugin)
# Update margins
margin = 0
if self.get_conf('use_custom_margin'):
margin = self.get_conf('custom_margin')
plugin.update_margins(margin)
if plugin_name == Plugins.Shortcuts:
for action, context, action_name in self.shortcut_queue:
self.register_shortcut(action, context, action_name)
self.shortcut_queue = []
logger.info("Registering shortcuts for {}...".format(plugin.NAME))
for action_name, action in plugin.get_actions().items():
context = (getattr(action, 'shortcut_context', plugin.NAME)
or plugin.NAME)
if getattr(action, 'register_shortcut', True):
if isinstance(action_name, Enum):
action_name = action_name.value
if Plugins.Shortcuts in PLUGIN_REGISTRY:
self.register_shortcut(action, context, action_name)
else:
self.shortcut_queue.append((action, context, action_name)) | mainwindow.py | spyder.spyder.app | false | false | [
"from collections import OrderedDict",
"import configparser as cp",
"from enum import Enum",
"import errno",
"import gc",
"import logging",
"import os",
"import os.path as osp",
"import shutil",
"import signal",
"import socket",
"import sys",
"import threading",
"import traceback",
"from spyder import requirements",
"from qtpy.QtCore import (QCoreApplication, Qt, QTimer, Signal, Slot,",
"from qtpy.QtGui import QColor, QKeySequence",
"from qtpy.QtWidgets import QApplication, QMainWindow, QMessageBox, QShortcut",
"from qtpy import QtSvg # analysis:ignore",
"from qtpy import QtWebEngineWidgets # analysis:ignore",
"from qtawesome.iconic_font import FontError",
"from spyder import __version__",
"from spyder.app.find_plugins import (",
"from spyder.app.utils import (",
"from spyder.api.plugin_registration.registry import PLUGIN_REGISTRY",
"from spyder.api.config.mixins import SpyderConfigurationAccessor",
"from spyder.api.widgets.mixins import SpyderMainWindowMixin",
"from spyder.config.base import (_, DEV, get_conf_path, get_debug_level,",
"from spyder.config.gui import is_dark_font_color",
"from spyder.config.main import OPEN_FILES_PORT",
"from spyder.config.manager import CONF",
"from spyder.config.utils import IMPORT_EXT",
"from spyder.py3compat import to_text_string",
"from spyder.utils import encoding, programs",
"from spyder.utils.icon_manager import ima",
"from spyder.utils.misc import select_port, getcwd_or_home",
"from spyder.utils.palette import QStylePalette",
"from spyder.utils.qthelpers import file_uri, qapplication, start_file",
"from spyder.utils.stylesheet import APP_STYLESHEET",
"from spyder.api.exceptions import SpyderAPIError",
"from spyder.api.plugins import (",
"from spyder.utils.windows import (set_attached_console_visible,",
"from spyder.utils.qthelpers import SpyderProxyStyle",
"import win32api",
"from spyder.plugins.help.utils.sphinxify import CSS_PATH, DARK_CSS_PATH",
"import spyder",
"import faulthandler"
] | 434 | 463 |
if isinstance(plugin, SpyderDockablePlugin):
try:
context = '_'
name = 'switch to {}'.format(plugin.CONF_SECTION)
except (cp.NoSectionError, cp.NoOptionError):
pass
sc = QShortcut(QKeySequence(), self,
lambda: self.switch_to_plugin(plugin))
sc.setContext(Qt.ApplicationShortcut)
plugin._shortcut = sc
if Plugins.Shortcuts in PLUGIN_REGISTRY:
self.register_shortcut(sc, context, name)
self.register_shortcut(
plugin.toggle_view_action, context, name)
else:
self.shortcut_queue.append((sc, context, name))
self.shortcut_queue.append(
(plugin.toggle_view_action, context, name))
def unregister_plugin(self, plugin):
"""
Unregister a plugin from the Spyder Main Window.
"""
logger.info("Unloading {}...".format(plugin.NAME))
# Disconnect all slots
signals = [
plugin.sig_quit_requested,
plugin.sig_redirect_stdio_requested,
plugin.sig_status_message_requested,
]
for sig in signals:
try:
sig.disconnect()
except TypeError:
pass | mainwindow.py | spyder.spyder.app | false | true | [
"from collections import OrderedDict",
"import configparser as cp",
"from enum import Enum",
"import errno",
"import gc",
"import logging",
"import os",
"import os.path as osp",
"import shutil",
"import signal",
"import socket",
"import sys",
"import threading",
"import traceback",
"from spyder import requirements",
"from qtpy.QtCore import (QCoreApplication, Qt, QTimer, Signal, Slot,",
"from qtpy.QtGui import QColor, QKeySequence",
"from qtpy.QtWidgets import QApplication, QMainWindow, QMessageBox, QShortcut",
"from qtpy import QtSvg # analysis:ignore",
"from qtpy import QtWebEngineWidgets # analysis:ignore",
"from qtawesome.iconic_font import FontError",
"from spyder import __version__",
"from spyder.app.find_plugins import (",
"from spyder.app.utils import (",
"from spyder.api.plugin_registration.registry import PLUGIN_REGISTRY",
"from spyder.api.config.mixins import SpyderConfigurationAccessor",
"from spyder.api.widgets.mixins import SpyderMainWindowMixin",
"from spyder.config.base import (_, DEV, get_conf_path, get_debug_level,",
"from spyder.config.gui import is_dark_font_color",
"from spyder.config.main import OPEN_FILES_PORT",
"from spyder.config.manager import CONF",
"from spyder.config.utils import IMPORT_EXT",
"from spyder.py3compat import to_text_string",
"from spyder.utils import encoding, programs",
"from spyder.utils.icon_manager import ima",
"from spyder.utils.misc import select_port, getcwd_or_home",
"from spyder.utils.palette import QStylePalette",
"from spyder.utils.qthelpers import file_uri, qapplication, start_file",
"from spyder.utils.stylesheet import APP_STYLESHEET",
"from spyder.api.exceptions import SpyderAPIError",
"from spyder.api.plugins import (",
"from spyder.utils.windows import (set_attached_console_visible,",
"from spyder.utils.qthelpers import SpyderProxyStyle",
"import win32api",
"from spyder.plugins.help.utils.sphinxify import CSS_PATH, DARK_CSS_PATH",
"import spyder",
"import faulthandler"
] | 465 | 503 |
for sig in signals:
try:
sig.disconnect()
except TypeError:
pass
# Unregister shortcuts for actions
logger.info("Unregistering shortcuts for {}...".format(plugin.NAME))
for action_name, action in plugin.get_actions().items():
context = (getattr(action, 'shortcut_context', plugin.NAME)
or plugin.NAME)
self.shortcuts.unregister_shortcut(action, context, action_name)
# Unregister switch to shortcut
shortcut = None
try:
context = '_'
name = 'switch to {}'.format(plugin.CONF_SECTION)
shortcut = self.get_shortcut(
name,
context,
plugin_name=plugin.CONF_SECTION
)
except Exception:
pass
if shortcut is not None:
self.shortcuts.unregister_shortcut(
plugin._shortcut,
context,
"Switch to {}".format(plugin.CONF_SECTION),
)
# Remove dockwidget
logger.info("Removing {} dockwidget...".format(plugin.NAME))
self.remove_dockwidget(plugin)
plugin._unregister() | mainwindow.py | spyder.spyder.app | false | false | [
"from collections import OrderedDict",
"import configparser as cp",
"from enum import Enum",
"import errno",
"import gc",
"import logging",
"import os",
"import os.path as osp",
"import shutil",
"import signal",
"import socket",
"import sys",
"import threading",
"import traceback",
"from spyder import requirements",
"from qtpy.QtCore import (QCoreApplication, Qt, QTimer, Signal, Slot,",
"from qtpy.QtGui import QColor, QKeySequence",
"from qtpy.QtWidgets import QApplication, QMainWindow, QMessageBox, QShortcut",
"from qtpy import QtSvg # analysis:ignore",
"from qtpy import QtWebEngineWidgets # analysis:ignore",
"from qtawesome.iconic_font import FontError",
"from spyder import __version__",
"from spyder.app.find_plugins import (",
"from spyder.app.utils import (",
"from spyder.api.plugin_registration.registry import PLUGIN_REGISTRY",
"from spyder.api.config.mixins import SpyderConfigurationAccessor",
"from spyder.api.widgets.mixins import SpyderMainWindowMixin",
"from spyder.config.base import (_, DEV, get_conf_path, get_debug_level,",
"from spyder.config.gui import is_dark_font_color",
"from spyder.config.main import OPEN_FILES_PORT",
"from spyder.config.manager import CONF",
"from spyder.config.utils import IMPORT_EXT",
"from spyder.py3compat import to_text_string",
"from spyder.utils import encoding, programs",
"from spyder.utils.icon_manager import ima",
"from spyder.utils.misc import select_port, getcwd_or_home",
"from spyder.utils.palette import QStylePalette",
"from spyder.utils.qthelpers import file_uri, qapplication, start_file",
"from spyder.utils.stylesheet import APP_STYLESHEET",
"from spyder.api.exceptions import SpyderAPIError",
"from spyder.api.plugins import (",
"from spyder.utils.windows import (set_attached_console_visible,",
"from spyder.utils.qthelpers import SpyderProxyStyle",
"import win32api",
"from spyder.plugins.help.utils.sphinxify import CSS_PATH, DARK_CSS_PATH",
"import spyder",
"import faulthandler"
] | 499 | 536 |
# Remove dockwidget
logger.info("Removing {} dockwidget...".format(plugin.NAME))
self.remove_dockwidget(plugin)
plugin._unregister()
def create_plugin_conf_widget(self, plugin):
"""
Create configuration dialog box page widget.
"""
config_dialog = self.prefs_dialog_instance
if plugin.CONF_WIDGET_CLASS is not None and config_dialog is not None:
conf_widget = plugin.CONF_WIDGET_CLASS(plugin, config_dialog)
conf_widget.initialize()
return conf_widget
def switch_to_plugin(self, plugin, force_focus=None):
"""
Switch to `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).
"""
self.layouts.switch_to_plugin(plugin, force_focus=force_focus)
def unmaximize_plugin(self, not_this_plugin=None):
"""
Unmaximize currently maximized plugin, if any.
Parameters
----------
not_this_plugin: SpyderDockablePlugin, optional
Unmaximize plugin if the maximized one is `not_this_plugin`.
"""
if not_this_plugin is None:
self.layouts.unmaximize_dockwidget()
else:
self.layouts.unmaximize_other_dockwidget(
plugin_instance=not_this_plugin) | mainwindow.py | spyder.spyder.app | false | true | [
"from collections import OrderedDict",
"import configparser as cp",
"from enum import Enum",
"import errno",
"import gc",
"import logging",
"import os",
"import os.path as osp",
"import shutil",
"import signal",
"import socket",
"import sys",
"import threading",
"import traceback",
"from spyder import requirements",
"from qtpy.QtCore import (QCoreApplication, Qt, QTimer, Signal, Slot,",
"from qtpy.QtGui import QColor, QKeySequence",
"from qtpy.QtWidgets import QApplication, QMainWindow, QMessageBox, QShortcut",
"from qtpy import QtSvg # analysis:ignore",
"from qtpy import QtWebEngineWidgets # analysis:ignore",
"from qtawesome.iconic_font import FontError",
"from spyder import __version__",
"from spyder.app.find_plugins import (",
"from spyder.app.utils import (",
"from spyder.api.plugin_registration.registry import PLUGIN_REGISTRY",
"from spyder.api.config.mixins import SpyderConfigurationAccessor",
"from spyder.api.widgets.mixins import SpyderMainWindowMixin",
"from spyder.config.base import (_, DEV, get_conf_path, get_debug_level,",
"from spyder.config.gui import is_dark_font_color",
"from spyder.config.main import OPEN_FILES_PORT",
"from spyder.config.manager import CONF",
"from spyder.config.utils import IMPORT_EXT",
"from spyder.py3compat import to_text_string",
"from spyder.utils import encoding, programs",
"from spyder.utils.icon_manager import ima",
"from spyder.utils.misc import select_port, getcwd_or_home",
"from spyder.utils.palette import QStylePalette",
"from spyder.utils.qthelpers import file_uri, qapplication, start_file",
"from spyder.utils.stylesheet import APP_STYLESHEET",
"from spyder.api.exceptions import SpyderAPIError",
"from spyder.api.plugins import (",
"from spyder.utils.windows import (set_attached_console_visible,",
"from spyder.utils.qthelpers import SpyderProxyStyle",
"import win32api",
"from spyder.plugins.help.utils.sphinxify import CSS_PATH, DARK_CSS_PATH",
"import spyder",
"import faulthandler"
] | 532 | 573 |
def remove_dockwidget(self, plugin):
"""
Remove a plugin QDockWidget from the main window.
"""
self.removeDockWidget(plugin.dockwidget)
try:
self.widgetlist.remove(plugin)
except ValueError:
pass
def handle_exception(self, error_data):
"""
This method will call the handle exception method of the Console
plugin. It is provided as a signal on the Plugin API for convenience,
so that plugin do not need to explicitly call the Console 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.
"""
console = self.get_plugin(Plugins.Console, error=False)
if console:
console.handle_exception(error_data) | mainwindow.py | spyder.spyder.app | false | true | [
"from collections import OrderedDict",
"import configparser as cp",
"from enum import Enum",
"import errno",
"import gc",
"import logging",
"import os",
"import os.path as osp",
"import shutil",
"import signal",
"import socket",
"import sys",
"import threading",
"import traceback",
"from spyder import requirements",
"from qtpy.QtCore import (QCoreApplication, Qt, QTimer, Signal, Slot,",
"from qtpy.QtGui import QColor, QKeySequence",
"from qtpy.QtWidgets import QApplication, QMainWindow, QMessageBox, QShortcut",
"from qtpy import QtSvg # analysis:ignore",
"from qtpy import QtWebEngineWidgets # analysis:ignore",
"from qtawesome.iconic_font import FontError",
"from spyder import __version__",
"from spyder.app.find_plugins import (",
"from spyder.app.utils import (",
"from spyder.api.plugin_registration.registry import PLUGIN_REGISTRY",
"from spyder.api.config.mixins import SpyderConfigurationAccessor",
"from spyder.api.widgets.mixins import SpyderMainWindowMixin",
"from spyder.config.base import (_, DEV, get_conf_path, get_debug_level,",
"from spyder.config.gui import is_dark_font_color",
"from spyder.config.main import OPEN_FILES_PORT",
"from spyder.config.manager import CONF",
"from spyder.config.utils import IMPORT_EXT",
"from spyder.py3compat import to_text_string",
"from spyder.utils import encoding, programs",
"from spyder.utils.icon_manager import ima",
"from spyder.utils.misc import select_port, getcwd_or_home",
"from spyder.utils.palette import QStylePalette",
"from spyder.utils.qthelpers import file_uri, qapplication, start_file",
"from spyder.utils.stylesheet import APP_STYLESHEET",
"from spyder.api.exceptions import SpyderAPIError",
"from spyder.api.plugins import (",
"from spyder.utils.windows import (set_attached_console_visible,",
"from spyder.utils.qthelpers import SpyderProxyStyle",
"import win32api",
"from spyder.plugins.help.utils.sphinxify import CSS_PATH, DARK_CSS_PATH",
"import spyder",
"import faulthandler"
] | 575 | 617 |
# ---- Window setup
# -------------------------------------------------------------------------
def _update_shortcuts_in_panes_menu(self, show=True):
"""
Display the shortcut for the "Switch to plugin..." on the toggle view
action of the plugins displayed in the Help/Panes menu.
Notes
-----
SpyderDockablePlugins provide two actions that function as a single
action. The `Switch to Plugin...` action has an assignable shortcut
via the shortcut preferences. The `Plugin toggle View` in the `View`
application menu, uses a custom `Toggle view action` that displays the
shortcut assigned to the `Switch to Plugin...` action, but is not
triggered by that shortcut.
"""
for plugin_name in PLUGIN_REGISTRY:
plugin = PLUGIN_REGISTRY.get_plugin(plugin_name)
if isinstance(plugin, SpyderDockablePlugin):
try:
# New API
action = plugin.toggle_view_action
except AttributeError:
# Old API
action = plugin._toggle_view_action | mainwindow.py | spyder.spyder.app | false | true | [
"from collections import OrderedDict",
"import configparser as cp",
"from enum import Enum",
"import errno",
"import gc",
"import logging",
"import os",
"import os.path as osp",
"import shutil",
"import signal",
"import socket",
"import sys",
"import threading",
"import traceback",
"from spyder import requirements",
"from qtpy.QtCore import (QCoreApplication, Qt, QTimer, Signal, Slot,",
"from qtpy.QtGui import QColor, QKeySequence",
"from qtpy.QtWidgets import QApplication, QMainWindow, QMessageBox, QShortcut",
"from qtpy import QtSvg # analysis:ignore",
"from qtpy import QtWebEngineWidgets # analysis:ignore",
"from qtawesome.iconic_font import FontError",
"from spyder import __version__",
"from spyder.app.find_plugins import (",
"from spyder.app.utils import (",
"from spyder.api.plugin_registration.registry import PLUGIN_REGISTRY",
"from spyder.api.config.mixins import SpyderConfigurationAccessor",
"from spyder.api.widgets.mixins import SpyderMainWindowMixin",
"from spyder.config.base import (_, DEV, get_conf_path, get_debug_level,",
"from spyder.config.gui import is_dark_font_color",
"from spyder.config.main import OPEN_FILES_PORT",
"from spyder.config.manager import CONF",
"from spyder.config.utils import IMPORT_EXT",
"from spyder.py3compat import to_text_string",
"from spyder.utils import encoding, programs",
"from spyder.utils.icon_manager import ima",
"from spyder.utils.misc import select_port, getcwd_or_home",
"from spyder.utils.palette import QStylePalette",
"from spyder.utils.qthelpers import file_uri, qapplication, start_file",
"from spyder.utils.stylesheet import APP_STYLESHEET",
"from spyder.api.exceptions import SpyderAPIError",
"from spyder.api.plugins import (",
"from spyder.utils.windows import (set_attached_console_visible,",
"from spyder.utils.qthelpers import SpyderProxyStyle",
"import win32api",
"from spyder.plugins.help.utils.sphinxify import CSS_PATH, DARK_CSS_PATH",
"import spyder",
"import faulthandler"
] | 619 | 643 |
if show:
section = plugin.CONF_SECTION
try:
context = '_'
name = 'switch to {}'.format(section)
shortcut = self.get_shortcut(
name, context, plugin_name=section)
except (cp.NoSectionError, cp.NoOptionError):
shortcut = QKeySequence()
else:
shortcut = QKeySequence()
action.setShortcut(shortcut)
def setup(self):
"""Setup main window."""
PLUGIN_REGISTRY.sig_plugin_ready.connect(
lambda plugin_name, omit_conf: self.register_plugin(
plugin_name, omit_conf=omit_conf))
PLUGIN_REGISTRY.set_main(self)
# TODO: Remove circular dependency between help and ipython console
# and remove this import. Help plugin should take care of it
from spyder.plugins.help.utils.sphinxify import CSS_PATH, DARK_CSS_PATH
logger.info("*** Start of MainWindow setup ***")
logger.info("Applying theme configuration...")
ui_theme = self.get_conf('ui_theme', section='appearance')
color_scheme = self.get_conf('selected', section='appearance')
qapp = QApplication.instance() | mainwindow.py | spyder.spyder.app | false | true | [
"from collections import OrderedDict",
"import configparser as cp",
"from enum import Enum",
"import errno",
"import gc",
"import logging",
"import os",
"import os.path as osp",
"import shutil",
"import signal",
"import socket",
"import sys",
"import threading",
"import traceback",
"from spyder import requirements",
"from qtpy.QtCore import (QCoreApplication, Qt, QTimer, Signal, Slot,",
"from qtpy.QtGui import QColor, QKeySequence",
"from qtpy.QtWidgets import QApplication, QMainWindow, QMessageBox, QShortcut",
"from qtpy import QtSvg # analysis:ignore",
"from qtpy import QtWebEngineWidgets # analysis:ignore",
"from qtawesome.iconic_font import FontError",
"from spyder import __version__",
"from spyder.app.find_plugins import (",
"from spyder.app.utils import (",
"from spyder.api.plugin_registration.registry import PLUGIN_REGISTRY",
"from spyder.api.config.mixins import SpyderConfigurationAccessor",
"from spyder.api.widgets.mixins import SpyderMainWindowMixin",
"from spyder.config.base import (_, DEV, get_conf_path, get_debug_level,",
"from spyder.config.gui import is_dark_font_color",
"from spyder.config.main import OPEN_FILES_PORT",
"from spyder.config.manager import CONF",
"from spyder.config.utils import IMPORT_EXT",
"from spyder.py3compat import to_text_string",
"from spyder.utils import encoding, programs",
"from spyder.utils.icon_manager import ima",
"from spyder.utils.misc import select_port, getcwd_or_home",
"from spyder.utils.palette import QStylePalette",
"from spyder.utils.qthelpers import file_uri, qapplication, start_file",
"from spyder.utils.stylesheet import APP_STYLESHEET",
"from spyder.api.exceptions import SpyderAPIError",
"from spyder.api.plugins import (",
"from spyder.utils.windows import (set_attached_console_visible,",
"from spyder.utils.qthelpers import SpyderProxyStyle",
"import win32api",
"from spyder.plugins.help.utils.sphinxify import CSS_PATH, DARK_CSS_PATH",
"import spyder",
"import faulthandler"
] | 645 | 675 |
if ui_theme == 'dark':
if not running_under_pytest():
# Set style proxy to fix combobox popup on mac and qdark
qapp.setStyle(self._proxy_style)
dark_qss = str(APP_STYLESHEET)
self.setStyleSheet(dark_qss)
self.statusBar().setStyleSheet(dark_qss)
css_path = DARK_CSS_PATH
elif ui_theme == 'light':
if not running_under_pytest():
# Set style proxy to fix combobox popup on mac and qdark
qapp.setStyle(self._proxy_style)
light_qss = str(APP_STYLESHEET)
self.setStyleSheet(light_qss)
self.statusBar().setStyleSheet(light_qss)
css_path = CSS_PATH
elif ui_theme == 'automatic':
if not is_dark_font_color(color_scheme):
if not running_under_pytest():
# Set style proxy to fix combobox popup on mac and qdark
qapp.setStyle(self._proxy_style)
dark_qss = str(APP_STYLESHEET)
self.setStyleSheet(dark_qss)
self.statusBar().setStyleSheet(dark_qss)
css_path = DARK_CSS_PATH
else:
light_qss = str(APP_STYLESHEET)
self.setStyleSheet(light_qss)
self.statusBar().setStyleSheet(light_qss)
css_path = CSS_PATH | mainwindow.py | spyder.spyder.app | false | false | [
"from collections import OrderedDict",
"import configparser as cp",
"from enum import Enum",
"import errno",
"import gc",
"import logging",
"import os",
"import os.path as osp",
"import shutil",
"import signal",
"import socket",
"import sys",
"import threading",
"import traceback",
"from spyder import requirements",
"from qtpy.QtCore import (QCoreApplication, Qt, QTimer, Signal, Slot,",
"from qtpy.QtGui import QColor, QKeySequence",
"from qtpy.QtWidgets import QApplication, QMainWindow, QMessageBox, QShortcut",
"from qtpy import QtSvg # analysis:ignore",
"from qtpy import QtWebEngineWidgets # analysis:ignore",
"from qtawesome.iconic_font import FontError",
"from spyder import __version__",
"from spyder.app.find_plugins import (",
"from spyder.app.utils import (",
"from spyder.api.plugin_registration.registry import PLUGIN_REGISTRY",
"from spyder.api.config.mixins import SpyderConfigurationAccessor",
"from spyder.api.widgets.mixins import SpyderMainWindowMixin",
"from spyder.config.base import (_, DEV, get_conf_path, get_debug_level,",
"from spyder.config.gui import is_dark_font_color",
"from spyder.config.main import OPEN_FILES_PORT",
"from spyder.config.manager import CONF",
"from spyder.config.utils import IMPORT_EXT",
"from spyder.py3compat import to_text_string",
"from spyder.utils import encoding, programs",
"from spyder.utils.icon_manager import ima",
"from spyder.utils.misc import select_port, getcwd_or_home",
"from spyder.utils.palette import QStylePalette",
"from spyder.utils.qthelpers import file_uri, qapplication, start_file",
"from spyder.utils.stylesheet import APP_STYLESHEET",
"from spyder.api.exceptions import SpyderAPIError",
"from spyder.api.plugins import (",
"from spyder.utils.windows import (set_attached_console_visible,",
"from spyder.utils.qthelpers import SpyderProxyStyle",
"import win32api",
"from spyder.plugins.help.utils.sphinxify import CSS_PATH, DARK_CSS_PATH",
"import spyder",
"import faulthandler"
] | 677 | 708 |
# This needs to done after applying the stylesheet to the window
logger.info("Set color for links in Qt widgets")
set_links_color(qapp)
# Set css_path as a configuration to be used by the plugins
self.set_conf('css_path', css_path, section='appearance')
# Status bar
status = self.statusBar()
status.setObjectName("StatusBar")
status.showMessage(_("Welcome to Spyder!"), 5000)
# Load and register internal and external plugins
external_plugins = find_external_plugins()
internal_plugins = find_internal_plugins()
all_plugins = external_plugins.copy()
all_plugins.update(internal_plugins.copy())
# Determine 'enable' config for plugins that have it.
enabled_plugins = {}
registry_internal_plugins = {}
registry_external_plugins = {}
for plugin in all_plugins.values():
plugin_name = plugin.NAME
# Disable plugins that use web widgets (currently Help and Online
# Help) if the user asks for it.
# See spyder-ide/spyder#16518
if self._cli_options.no_web_widgets:
if "help" in plugin_name:
continue
plugin_main_attribute_name = (
self._INTERNAL_PLUGINS_MAPPING[plugin_name]
if plugin_name in self._INTERNAL_PLUGINS_MAPPING
else plugin_name) | mainwindow.py | spyder.spyder.app | false | false | [
"from collections import OrderedDict",
"import configparser as cp",
"from enum import Enum",
"import errno",
"import gc",
"import logging",
"import os",
"import os.path as osp",
"import shutil",
"import signal",
"import socket",
"import sys",
"import threading",
"import traceback",
"from spyder import requirements",
"from qtpy.QtCore import (QCoreApplication, Qt, QTimer, Signal, Slot,",
"from qtpy.QtGui import QColor, QKeySequence",
"from qtpy.QtWidgets import QApplication, QMainWindow, QMessageBox, QShortcut",
"from qtpy import QtSvg # analysis:ignore",
"from qtpy import QtWebEngineWidgets # analysis:ignore",
"from qtawesome.iconic_font import FontError",
"from spyder import __version__",
"from spyder.app.find_plugins import (",
"from spyder.app.utils import (",
"from spyder.api.plugin_registration.registry import PLUGIN_REGISTRY",
"from spyder.api.config.mixins import SpyderConfigurationAccessor",
"from spyder.api.widgets.mixins import SpyderMainWindowMixin",
"from spyder.config.base import (_, DEV, get_conf_path, get_debug_level,",
"from spyder.config.gui import is_dark_font_color",
"from spyder.config.main import OPEN_FILES_PORT",
"from spyder.config.manager import CONF",
"from spyder.config.utils import IMPORT_EXT",
"from spyder.py3compat import to_text_string",
"from spyder.utils import encoding, programs",
"from spyder.utils.icon_manager import ima",
"from spyder.utils.misc import select_port, getcwd_or_home",
"from spyder.utils.palette import QStylePalette",
"from spyder.utils.qthelpers import file_uri, qapplication, start_file",
"from spyder.utils.stylesheet import APP_STYLESHEET",
"from spyder.api.exceptions import SpyderAPIError",
"from spyder.api.plugins import (",
"from spyder.utils.windows import (set_attached_console_visible,",
"from spyder.utils.qthelpers import SpyderProxyStyle",
"import win32api",
"from spyder.plugins.help.utils.sphinxify import CSS_PATH, DARK_CSS_PATH",
"import spyder",
"import faulthandler"
] | 710 | 745 |
if plugin_name in internal_plugins:
registry_internal_plugins[plugin_name] = (
plugin_main_attribute_name, plugin)
enable_option = "enable"
enable_section = plugin_main_attribute_name
else:
registry_external_plugins[plugin_name] = (
plugin_main_attribute_name, plugin)
# This is a workaround to allow disabling external plugins.
# Because of the way the current config implementation works,
# an external plugin config option (e.g. 'enable') can only be
# read after the plugin is loaded. But here we're trying to
# decide if the plugin should be loaded if it's enabled. So,
# for now we read (and save, see the config page associated to
# PLUGIN_REGISTRY) that option in our internal config options.
# See spyder-ide/spyder#17464 for more details.
enable_option = f"{plugin_main_attribute_name}/enable"
enable_section = PLUGIN_REGISTRY._external_plugins_conf_section | mainwindow.py | spyder.spyder.app | false | false | [
"from collections import OrderedDict",
"import configparser as cp",
"from enum import Enum",
"import errno",
"import gc",
"import logging",
"import os",
"import os.path as osp",
"import shutil",
"import signal",
"import socket",
"import sys",
"import threading",
"import traceback",
"from spyder import requirements",
"from qtpy.QtCore import (QCoreApplication, Qt, QTimer, Signal, Slot,",
"from qtpy.QtGui import QColor, QKeySequence",
"from qtpy.QtWidgets import QApplication, QMainWindow, QMessageBox, QShortcut",
"from qtpy import QtSvg # analysis:ignore",
"from qtpy import QtWebEngineWidgets # analysis:ignore",
"from qtawesome.iconic_font import FontError",
"from spyder import __version__",
"from spyder.app.find_plugins import (",
"from spyder.app.utils import (",
"from spyder.api.plugin_registration.registry import PLUGIN_REGISTRY",
"from spyder.api.config.mixins import SpyderConfigurationAccessor",
"from spyder.api.widgets.mixins import SpyderMainWindowMixin",
"from spyder.config.base import (_, DEV, get_conf_path, get_debug_level,",
"from spyder.config.gui import is_dark_font_color",
"from spyder.config.main import OPEN_FILES_PORT",
"from spyder.config.manager import CONF",
"from spyder.config.utils import IMPORT_EXT",
"from spyder.py3compat import to_text_string",
"from spyder.utils import encoding, programs",
"from spyder.utils.icon_manager import ima",
"from spyder.utils.misc import select_port, getcwd_or_home",
"from spyder.utils.palette import QStylePalette",
"from spyder.utils.qthelpers import file_uri, qapplication, start_file",
"from spyder.utils.stylesheet import APP_STYLESHEET",
"from spyder.api.exceptions import SpyderAPIError",
"from spyder.api.plugins import (",
"from spyder.utils.windows import (set_attached_console_visible,",
"from spyder.utils.qthelpers import SpyderProxyStyle",
"import win32api",
"from spyder.plugins.help.utils.sphinxify import CSS_PATH, DARK_CSS_PATH",
"import spyder",
"import faulthandler"
] | 747 | 765 |
try:
if self.get_conf(enable_option, section=enable_section):
enabled_plugins[plugin_name] = plugin
PLUGIN_REGISTRY.set_plugin_enabled(plugin_name)
except (cp.NoOptionError, cp.NoSectionError):
enabled_plugins[plugin_name] = plugin
PLUGIN_REGISTRY.set_plugin_enabled(plugin_name)
PLUGIN_REGISTRY.set_all_internal_plugins(registry_internal_plugins)
PLUGIN_REGISTRY.set_all_external_plugins(registry_external_plugins)
# Instantiate internal Spyder 5 plugins
for plugin_name in internal_plugins:
if plugin_name in enabled_plugins:
PluginClass = internal_plugins[plugin_name]
if issubclass(PluginClass, SpyderPluginV2):
PLUGIN_REGISTRY.register_plugin(self, PluginClass,
external=False)
# Instantiate internal Spyder 4 plugins
for plugin_name in internal_plugins:
if plugin_name in enabled_plugins:
PluginClass = internal_plugins[plugin_name]
if issubclass(PluginClass, SpyderPlugin):
plugin_instance = PLUGIN_REGISTRY.register_plugin(
self, PluginClass, external=False)
self.preferences.register_plugin_preferences(
plugin_instance) | mainwindow.py | spyder.spyder.app | false | false | [
"from collections import OrderedDict",
"import configparser as cp",
"from enum import Enum",
"import errno",
"import gc",
"import logging",
"import os",
"import os.path as osp",
"import shutil",
"import signal",
"import socket",
"import sys",
"import threading",
"import traceback",
"from spyder import requirements",
"from qtpy.QtCore import (QCoreApplication, Qt, QTimer, Signal, Slot,",
"from qtpy.QtGui import QColor, QKeySequence",
"from qtpy.QtWidgets import QApplication, QMainWindow, QMessageBox, QShortcut",
"from qtpy import QtSvg # analysis:ignore",
"from qtpy import QtWebEngineWidgets # analysis:ignore",
"from qtawesome.iconic_font import FontError",
"from spyder import __version__",
"from spyder.app.find_plugins import (",
"from spyder.app.utils import (",
"from spyder.api.plugin_registration.registry import PLUGIN_REGISTRY",
"from spyder.api.config.mixins import SpyderConfigurationAccessor",
"from spyder.api.widgets.mixins import SpyderMainWindowMixin",
"from spyder.config.base import (_, DEV, get_conf_path, get_debug_level,",
"from spyder.config.gui import is_dark_font_color",
"from spyder.config.main import OPEN_FILES_PORT",
"from spyder.config.manager import CONF",
"from spyder.config.utils import IMPORT_EXT",
"from spyder.py3compat import to_text_string",
"from spyder.utils import encoding, programs",
"from spyder.utils.icon_manager import ima",
"from spyder.utils.misc import select_port, getcwd_or_home",
"from spyder.utils.palette import QStylePalette",
"from spyder.utils.qthelpers import file_uri, qapplication, start_file",
"from spyder.utils.stylesheet import APP_STYLESHEET",
"from spyder.api.exceptions import SpyderAPIError",
"from spyder.api.plugins import (",
"from spyder.utils.windows import (set_attached_console_visible,",
"from spyder.utils.qthelpers import SpyderProxyStyle",
"import win32api",
"from spyder.plugins.help.utils.sphinxify import CSS_PATH, DARK_CSS_PATH",
"import spyder",
"import faulthandler"
] | 767 | 794 |
# Instantiate external Spyder 5 plugins
for plugin_name in external_plugins:
if plugin_name in enabled_plugins:
PluginClass = external_plugins[plugin_name]
try:
plugin_instance = PLUGIN_REGISTRY.register_plugin(
self, PluginClass, external=True)
except Exception as error:
print("%s: %s" % (PluginClass, str(error)), file=STDERR)
traceback.print_exc(file=STDERR)
# Set window title
self.set_window_title()
self.set_splash("")
# Toolbars
# TODO: Remove after finishing the migration
logger.info("Creating toolbars...")
toolbar = self.toolbar
self.file_toolbar = toolbar.get_application_toolbar("file_toolbar")
self.set_splash(_("Setting up main window..."))
def __getattr__(self, attr):
"""
Redefinition of __getattr__ to enable access to plugins. | mainwindow.py | spyder.spyder.app | false | true | [
"from collections import OrderedDict",
"import configparser as cp",
"from enum import Enum",
"import errno",
"import gc",
"import logging",
"import os",
"import os.path as osp",
"import shutil",
"import signal",
"import socket",
"import sys",
"import threading",
"import traceback",
"from spyder import requirements",
"from qtpy.QtCore import (QCoreApplication, Qt, QTimer, Signal, Slot,",
"from qtpy.QtGui import QColor, QKeySequence",
"from qtpy.QtWidgets import QApplication, QMainWindow, QMessageBox, QShortcut",
"from qtpy import QtSvg # analysis:ignore",
"from qtpy import QtWebEngineWidgets # analysis:ignore",
"from qtawesome.iconic_font import FontError",
"from spyder import __version__",
"from spyder.app.find_plugins import (",
"from spyder.app.utils import (",
"from spyder.api.plugin_registration.registry import PLUGIN_REGISTRY",
"from spyder.api.config.mixins import SpyderConfigurationAccessor",
"from spyder.api.widgets.mixins import SpyderMainWindowMixin",
"from spyder.config.base import (_, DEV, get_conf_path, get_debug_level,",
"from spyder.config.gui import is_dark_font_color",
"from spyder.config.main import OPEN_FILES_PORT",
"from spyder.config.manager import CONF",
"from spyder.config.utils import IMPORT_EXT",
"from spyder.py3compat import to_text_string",
"from spyder.utils import encoding, programs",
"from spyder.utils.icon_manager import ima",
"from spyder.utils.misc import select_port, getcwd_or_home",
"from spyder.utils.palette import QStylePalette",
"from spyder.utils.qthelpers import file_uri, qapplication, start_file",
"from spyder.utils.stylesheet import APP_STYLESHEET",
"from spyder.api.exceptions import SpyderAPIError",
"from spyder.api.plugins import (",
"from spyder.utils.windows import (set_attached_console_visible,",
"from spyder.utils.qthelpers import SpyderProxyStyle",
"import win32api",
"from spyder.plugins.help.utils.sphinxify import CSS_PATH, DARK_CSS_PATH",
"import spyder",
"import faulthandler"
] | 796 | 821 |
self.set_splash(_("Setting up main window..."))
def __getattr__(self, attr):
"""
Redefinition of __getattr__ to enable access to plugins.
Loaded plugins can be accessed as attributes of the mainwindow
as before, e.g self.console or self.main.console, preserving the
same accessor as before.
"""
# Mapping of new plugin identifiers vs old attributtes
# names given for plugins
try:
if attr in self._INTERNAL_PLUGINS_MAPPING.keys():
return self.get_plugin(
self._INTERNAL_PLUGINS_MAPPING[attr], error=False)
return self.get_plugin(attr)
except SpyderAPIError:
pass
return super().__getattr__(attr)
def pre_visible_setup(self):
"""
Actions to be performed before the main window is visible.
The actions here are related with setting up the main window.
"""
logger.info("Setting up window...")
if self.get_conf('vertical_tabs'):
self.DOCKOPTIONS = self.DOCKOPTIONS | QMainWindow.VerticalTabs
self.setDockOptions(self.DOCKOPTIONS)
for plugin_name in PLUGIN_REGISTRY:
plugin_instance = PLUGIN_REGISTRY.get_plugin(plugin_name)
try:
plugin_instance.before_mainwindow_visible()
except AttributeError:
pass
if self.splash is not None:
self.splash.hide() | mainwindow.py | spyder.spyder.app | false | true | [
"from collections import OrderedDict",
"import configparser as cp",
"from enum import Enum",
"import errno",
"import gc",
"import logging",
"import os",
"import os.path as osp",
"import shutil",
"import signal",
"import socket",
"import sys",
"import threading",
"import traceback",
"from spyder import requirements",
"from qtpy.QtCore import (QCoreApplication, Qt, QTimer, Signal, Slot,",
"from qtpy.QtGui import QColor, QKeySequence",
"from qtpy.QtWidgets import QApplication, QMainWindow, QMessageBox, QShortcut",
"from qtpy import QtSvg # analysis:ignore",
"from qtpy import QtWebEngineWidgets # analysis:ignore",
"from qtawesome.iconic_font import FontError",
"from spyder import __version__",
"from spyder.app.find_plugins import (",
"from spyder.app.utils import (",
"from spyder.api.plugin_registration.registry import PLUGIN_REGISTRY",
"from spyder.api.config.mixins import SpyderConfigurationAccessor",
"from spyder.api.widgets.mixins import SpyderMainWindowMixin",
"from spyder.config.base import (_, DEV, get_conf_path, get_debug_level,",
"from spyder.config.gui import is_dark_font_color",
"from spyder.config.main import OPEN_FILES_PORT",
"from spyder.config.manager import CONF",
"from spyder.config.utils import IMPORT_EXT",
"from spyder.py3compat import to_text_string",
"from spyder.utils import encoding, programs",
"from spyder.utils.icon_manager import ima",
"from spyder.utils.misc import select_port, getcwd_or_home",
"from spyder.utils.palette import QStylePalette",
"from spyder.utils.qthelpers import file_uri, qapplication, start_file",
"from spyder.utils.stylesheet import APP_STYLESHEET",
"from spyder.api.exceptions import SpyderAPIError",
"from spyder.api.plugins import (",
"from spyder.utils.windows import (set_attached_console_visible,",
"from spyder.utils.qthelpers import SpyderProxyStyle",
"import win32api",
"from spyder.plugins.help.utils.sphinxify import CSS_PATH, DARK_CSS_PATH",
"import spyder",
"import faulthandler"
] | 817 | 858 |
if self.splash is not None:
self.splash.hide()
# Register custom layouts
if self.layouts is not None:
self.layouts.register_custom_layouts()
# Needed to ensure dockwidgets/panes layout size distribution
# when a layout state is already present.
# See spyder-ide/spyder#17945
if (
self.layouts is not None
and self.get_conf('window/state', default=None)
):
self.layouts.before_mainwindow_visible()
# Tabify new plugins which were installed or created after Spyder ran
# for the first time.
# NOTE: **DO NOT** make layout changes after this point or new plugins
# won't be tabified correctly.
if self.layouts is not None:
self.layouts.tabify_new_plugins()
logger.info("*** End of MainWindow setup ***")
self.is_starting_up = False
def post_visible_setup(self):
"""
Actions to be performed only after the main window's `show` method
is triggered.
"""
# This must be run before the main window is shown.
# Fixes spyder-ide/spyder#12104
self.layouts.on_mainwindow_visible()
# Process pending events and hide splash screen before moving forward.
QApplication.processEvents()
if self.splash is not None:
self.splash.hide() | mainwindow.py | spyder.spyder.app | false | true | [
"from collections import OrderedDict",
"import configparser as cp",
"from enum import Enum",
"import errno",
"import gc",
"import logging",
"import os",
"import os.path as osp",
"import shutil",
"import signal",
"import socket",
"import sys",
"import threading",
"import traceback",
"from spyder import requirements",
"from qtpy.QtCore import (QCoreApplication, Qt, QTimer, Signal, Slot,",
"from qtpy.QtGui import QColor, QKeySequence",
"from qtpy.QtWidgets import QApplication, QMainWindow, QMessageBox, QShortcut",
"from qtpy import QtSvg # analysis:ignore",
"from qtpy import QtWebEngineWidgets # analysis:ignore",
"from qtawesome.iconic_font import FontError",
"from spyder import __version__",
"from spyder.app.find_plugins import (",
"from spyder.app.utils import (",
"from spyder.api.plugin_registration.registry import PLUGIN_REGISTRY",
"from spyder.api.config.mixins import SpyderConfigurationAccessor",
"from spyder.api.widgets.mixins import SpyderMainWindowMixin",
"from spyder.config.base import (_, DEV, get_conf_path, get_debug_level,",
"from spyder.config.gui import is_dark_font_color",
"from spyder.config.main import OPEN_FILES_PORT",
"from spyder.config.manager import CONF",
"from spyder.config.utils import IMPORT_EXT",
"from spyder.py3compat import to_text_string",
"from spyder.utils import encoding, programs",
"from spyder.utils.icon_manager import ima",
"from spyder.utils.misc import select_port, getcwd_or_home",
"from spyder.utils.palette import QStylePalette",
"from spyder.utils.qthelpers import file_uri, qapplication, start_file",
"from spyder.utils.stylesheet import APP_STYLESHEET",
"from spyder.api.exceptions import SpyderAPIError",
"from spyder.api.plugins import (",
"from spyder.utils.windows import (set_attached_console_visible,",
"from spyder.utils.qthelpers import SpyderProxyStyle",
"import win32api",
"from spyder.plugins.help.utils.sphinxify import CSS_PATH, DARK_CSS_PATH",
"import spyder",
"import faulthandler"
] | 857 | 895 |
# Process pending events and hide splash screen before moving forward.
QApplication.processEvents()
if self.splash is not None:
self.splash.hide()
# Move the window to the primary screen if the previous location is not
# visible to the user.
self.move_to_primary_screen()
# To avoid regressions. We shouldn't have loaded the modules below at
# this point.
if DEV is not None:
assert 'pandas' not in sys.modules
assert 'matplotlib' not in sys.modules
# Call on_mainwindow_visible for all plugins, except Layout because it
# needs to be called first (see above).
for plugin_name in PLUGIN_REGISTRY:
if plugin_name != Plugins.Layout:
plugin = PLUGIN_REGISTRY.get_plugin(plugin_name)
try:
plugin.on_mainwindow_visible()
QApplication.processEvents()
except AttributeError:
pass
self.restore_scrollbar_position.emit() | mainwindow.py | spyder.spyder.app | false | false | [
"from collections import OrderedDict",
"import configparser as cp",
"from enum import Enum",
"import errno",
"import gc",
"import logging",
"import os",
"import os.path as osp",
"import shutil",
"import signal",
"import socket",
"import sys",
"import threading",
"import traceback",
"from spyder import requirements",
"from qtpy.QtCore import (QCoreApplication, Qt, QTimer, Signal, Slot,",
"from qtpy.QtGui import QColor, QKeySequence",
"from qtpy.QtWidgets import QApplication, QMainWindow, QMessageBox, QShortcut",
"from qtpy import QtSvg # analysis:ignore",
"from qtpy import QtWebEngineWidgets # analysis:ignore",
"from qtawesome.iconic_font import FontError",
"from spyder import __version__",
"from spyder.app.find_plugins import (",
"from spyder.app.utils import (",
"from spyder.api.plugin_registration.registry import PLUGIN_REGISTRY",
"from spyder.api.config.mixins import SpyderConfigurationAccessor",
"from spyder.api.widgets.mixins import SpyderMainWindowMixin",
"from spyder.config.base import (_, DEV, get_conf_path, get_debug_level,",
"from spyder.config.gui import is_dark_font_color",
"from spyder.config.main import OPEN_FILES_PORT",
"from spyder.config.manager import CONF",
"from spyder.config.utils import IMPORT_EXT",
"from spyder.py3compat import to_text_string",
"from spyder.utils import encoding, programs",
"from spyder.utils.icon_manager import ima",
"from spyder.utils.misc import select_port, getcwd_or_home",
"from spyder.utils.palette import QStylePalette",
"from spyder.utils.qthelpers import file_uri, qapplication, start_file",
"from spyder.utils.stylesheet import APP_STYLESHEET",
"from spyder.api.exceptions import SpyderAPIError",
"from spyder.api.plugins import (",
"from spyder.utils.windows import (set_attached_console_visible,",
"from spyder.utils.qthelpers import SpyderProxyStyle",
"import win32api",
"from spyder.plugins.help.utils.sphinxify import CSS_PATH, DARK_CSS_PATH",
"import spyder",
"import faulthandler"
] | 892 | 918 |
self.restore_scrollbar_position.emit()
# Server to maintain just one Spyder instance and open files in it if
# the user tries to start other instances with
# $ spyder foo.py
if (
self.get_conf('single_instance') and
not self._cli_options.new_instance and
self.open_files_server
):
t = threading.Thread(target=self.start_open_files_server)
t.daemon = True
t.start()
# Connect the window to the signal emitted by the previous server
# when it gets a client connected to it
self.sig_open_external_file.connect(self.open_external_file)
# Update plugins toggle actions to show the "Switch to" plugin shortcut
self._update_shortcuts_in_panes_menu()
# Reopen last session if no project is active
# NOTE: This needs to be after the calls to on_mainwindow_visible
self.reopen_last_session()
# Raise the menuBar to the top of the main window widget's stack
# Fixes spyder-ide/spyder#3887.
self.menuBar().raise_()
# Restore undocked plugins
self.restore_undocked_plugins()
# Notify that the setup of the mainwindow was finished
self.is_setting_up = False
self.sig_setup_finished.emit()
def reopen_last_session(self):
"""
Reopen last session if no project is active. | mainwindow.py | spyder.spyder.app | false | true | [
"from collections import OrderedDict",
"import configparser as cp",
"from enum import Enum",
"import errno",
"import gc",
"import logging",
"import os",
"import os.path as osp",
"import shutil",
"import signal",
"import socket",
"import sys",
"import threading",
"import traceback",
"from spyder import requirements",
"from qtpy.QtCore import (QCoreApplication, Qt, QTimer, Signal, Slot,",
"from qtpy.QtGui import QColor, QKeySequence",
"from qtpy.QtWidgets import QApplication, QMainWindow, QMessageBox, QShortcut",
"from qtpy import QtSvg # analysis:ignore",
"from qtpy import QtWebEngineWidgets # analysis:ignore",
"from qtawesome.iconic_font import FontError",
"from spyder import __version__",
"from spyder.app.find_plugins import (",
"from spyder.app.utils import (",
"from spyder.api.plugin_registration.registry import PLUGIN_REGISTRY",
"from spyder.api.config.mixins import SpyderConfigurationAccessor",
"from spyder.api.widgets.mixins import SpyderMainWindowMixin",
"from spyder.config.base import (_, DEV, get_conf_path, get_debug_level,",
"from spyder.config.gui import is_dark_font_color",
"from spyder.config.main import OPEN_FILES_PORT",
"from spyder.config.manager import CONF",
"from spyder.config.utils import IMPORT_EXT",
"from spyder.py3compat import to_text_string",
"from spyder.utils import encoding, programs",
"from spyder.utils.icon_manager import ima",
"from spyder.utils.misc import select_port, getcwd_or_home",
"from spyder.utils.palette import QStylePalette",
"from spyder.utils.qthelpers import file_uri, qapplication, start_file",
"from spyder.utils.stylesheet import APP_STYLESHEET",
"from spyder.api.exceptions import SpyderAPIError",
"from spyder.api.plugins import (",
"from spyder.utils.windows import (set_attached_console_visible,",
"from spyder.utils.qthelpers import SpyderProxyStyle",
"import win32api",
"from spyder.plugins.help.utils.sphinxify import CSS_PATH, DARK_CSS_PATH",
"import spyder",
"import faulthandler"
] | 918 | 956 |
def reopen_last_session(self):
"""
Reopen last session if no project is active.
This can't be moved to on_mainwindow_visible in the editor because we
need to let the same method on Projects run first.
"""
projects = self.get_plugin(Plugins.Projects, error=False)
editor = self.get_plugin(Plugins.Editor, error=False)
reopen_last_session = False
if projects:
if projects.get_active_project() is None:
reopen_last_session = True
else:
reopen_last_session = True
if editor and reopen_last_session:
logger.info("Restoring opened files from the previous session")
editor.setup_open_files(close_previous_files=False)
def restore_undocked_plugins(self):
"""Restore plugins that were undocked in the previous session."""
logger.info("Restoring undocked plugins from the previous session")
for plugin_name in PLUGIN_REGISTRY:
plugin = PLUGIN_REGISTRY.get_plugin(plugin_name)
if isinstance(plugin, SpyderDockablePlugin):
if plugin.get_conf('undocked_on_window_close', default=False):
plugin.create_window()
elif isinstance(plugin, SpyderPluginWidget):
if plugin.get_option('undocked_on_window_close',
default=False):
plugin._create_window() | mainwindow.py | spyder.spyder.app | false | true | [
"from collections import OrderedDict",
"import configparser as cp",
"from enum import Enum",
"import errno",
"import gc",
"import logging",
"import os",
"import os.path as osp",
"import shutil",
"import signal",
"import socket",
"import sys",
"import threading",
"import traceback",
"from spyder import requirements",
"from qtpy.QtCore import (QCoreApplication, Qt, QTimer, Signal, Slot,",
"from qtpy.QtGui import QColor, QKeySequence",
"from qtpy.QtWidgets import QApplication, QMainWindow, QMessageBox, QShortcut",
"from qtpy import QtSvg # analysis:ignore",
"from qtpy import QtWebEngineWidgets # analysis:ignore",
"from qtawesome.iconic_font import FontError",
"from spyder import __version__",
"from spyder.app.find_plugins import (",
"from spyder.app.utils import (",
"from spyder.api.plugin_registration.registry import PLUGIN_REGISTRY",
"from spyder.api.config.mixins import SpyderConfigurationAccessor",
"from spyder.api.widgets.mixins import SpyderMainWindowMixin",
"from spyder.config.base import (_, DEV, get_conf_path, get_debug_level,",
"from spyder.config.gui import is_dark_font_color",
"from spyder.config.main import OPEN_FILES_PORT",
"from spyder.config.manager import CONF",
"from spyder.config.utils import IMPORT_EXT",
"from spyder.py3compat import to_text_string",
"from spyder.utils import encoding, programs",
"from spyder.utils.icon_manager import ima",
"from spyder.utils.misc import select_port, getcwd_or_home",
"from spyder.utils.palette import QStylePalette",
"from spyder.utils.qthelpers import file_uri, qapplication, start_file",
"from spyder.utils.stylesheet import APP_STYLESHEET",
"from spyder.api.exceptions import SpyderAPIError",
"from spyder.api.plugins import (",
"from spyder.utils.windows import (set_attached_console_visible,",
"from spyder.utils.qthelpers import SpyderProxyStyle",
"import win32api",
"from spyder.plugins.help.utils.sphinxify import CSS_PATH, DARK_CSS_PATH",
"import spyder",
"import faulthandler"
] | 954 | 987 |
def set_window_title(self):
"""Set window title."""
if DEV is not None:
title = u"Spyder %s (Python %s.%s)" % (__version__,
sys.version_info[0],
sys.version_info[1])
elif is_conda_based_app():
title = "Spyder"
else:
title = u"Spyder (Python %s.%s)" % (sys.version_info[0],
sys.version_info[1])
if get_debug_level():
title += u" [DEBUG MODE %d]" % get_debug_level()
window_title = self._cli_options.window_title
if window_title is not None:
title += u' -- ' + to_text_string(window_title)
# TODO: Remove self.projects reference once there's an API for setting
# window title.
projects = self.get_plugin(Plugins.Projects, error=False)
if projects:
path = projects.get_active_project_path()
if path:
path = path.replace(get_home_dir(), u'~')
title = u'{0} - {1}'.format(path, title)
self.base_title = title
self.setWindowTitle(self.base_title) | mainwindow.py | spyder.spyder.app | false | true | [
"from collections import OrderedDict",
"import configparser as cp",
"from enum import Enum",
"import errno",
"import gc",
"import logging",
"import os",
"import os.path as osp",
"import shutil",
"import signal",
"import socket",
"import sys",
"import threading",
"import traceback",
"from spyder import requirements",
"from qtpy.QtCore import (QCoreApplication, Qt, QTimer, Signal, Slot,",
"from qtpy.QtGui import QColor, QKeySequence",
"from qtpy.QtWidgets import QApplication, QMainWindow, QMessageBox, QShortcut",
"from qtpy import QtSvg # analysis:ignore",
"from qtpy import QtWebEngineWidgets # analysis:ignore",
"from qtawesome.iconic_font import FontError",
"from spyder import __version__",
"from spyder.app.find_plugins import (",
"from spyder.app.utils import (",
"from spyder.api.plugin_registration.registry import PLUGIN_REGISTRY",
"from spyder.api.config.mixins import SpyderConfigurationAccessor",
"from spyder.api.widgets.mixins import SpyderMainWindowMixin",
"from spyder.config.base import (_, DEV, get_conf_path, get_debug_level,",
"from spyder.config.gui import is_dark_font_color",
"from spyder.config.main import OPEN_FILES_PORT",
"from spyder.config.manager import CONF",
"from spyder.config.utils import IMPORT_EXT",
"from spyder.py3compat import to_text_string",
"from spyder.utils import encoding, programs",
"from spyder.utils.icon_manager import ima",
"from spyder.utils.misc import select_port, getcwd_or_home",
"from spyder.utils.palette import QStylePalette",
"from spyder.utils.qthelpers import file_uri, qapplication, start_file",
"from spyder.utils.stylesheet import APP_STYLESHEET",
"from spyder.api.exceptions import SpyderAPIError",
"from spyder.api.plugins import (",
"from spyder.utils.windows import (set_attached_console_visible,",
"from spyder.utils.qthelpers import SpyderProxyStyle",
"import win32api",
"from spyder.plugins.help.utils.sphinxify import CSS_PATH, DARK_CSS_PATH",
"import spyder",
"import faulthandler"
] | 989 | 1,018 |
self.base_title = title
self.setWindowTitle(self.base_title)
# TODO: To be removed after all actions are moved to their corresponding
# plugins
def register_shortcut(self, qaction_or_qshortcut, context, name,
add_shortcut_to_tip=True, plugin_name=None):
shortcuts = self.get_plugin(Plugins.Shortcuts, error=False)
if shortcuts:
shortcuts.register_shortcut(
qaction_or_qshortcut,
context,
name,
add_shortcut_to_tip=add_shortcut_to_tip,
plugin_name=plugin_name,
)
def unregister_shortcut(self, qaction_or_qshortcut, context, name,
add_shortcut_to_tip=True, plugin_name=None):
shortcuts = self.get_plugin(Plugins.Shortcuts, error=False)
if shortcuts:
shortcuts.unregister_shortcut(
qaction_or_qshortcut,
context,
name,
add_shortcut_to_tip=add_shortcut_to_tip,
plugin_name=plugin_name,
)
# ---- Qt methods
# -------------------------------------------------------------------------
def createPopupMenu(self):
return self.application.get_application_context_menu(parent=self)
def closeEvent(self, event):
"""closeEvent reimplementation"""
if self.closing(True):
event.accept()
else:
event.ignore() | mainwindow.py | spyder.spyder.app | false | true | [
"from collections import OrderedDict",
"import configparser as cp",
"from enum import Enum",
"import errno",
"import gc",
"import logging",
"import os",
"import os.path as osp",
"import shutil",
"import signal",
"import socket",
"import sys",
"import threading",
"import traceback",
"from spyder import requirements",
"from qtpy.QtCore import (QCoreApplication, Qt, QTimer, Signal, Slot,",
"from qtpy.QtGui import QColor, QKeySequence",
"from qtpy.QtWidgets import QApplication, QMainWindow, QMessageBox, QShortcut",
"from qtpy import QtSvg # analysis:ignore",
"from qtpy import QtWebEngineWidgets # analysis:ignore",
"from qtawesome.iconic_font import FontError",
"from spyder import __version__",
"from spyder.app.find_plugins import (",
"from spyder.app.utils import (",
"from spyder.api.plugin_registration.registry import PLUGIN_REGISTRY",
"from spyder.api.config.mixins import SpyderConfigurationAccessor",
"from spyder.api.widgets.mixins import SpyderMainWindowMixin",
"from spyder.config.base import (_, DEV, get_conf_path, get_debug_level,",
"from spyder.config.gui import is_dark_font_color",
"from spyder.config.main import OPEN_FILES_PORT",
"from spyder.config.manager import CONF",
"from spyder.config.utils import IMPORT_EXT",
"from spyder.py3compat import to_text_string",
"from spyder.utils import encoding, programs",
"from spyder.utils.icon_manager import ima",
"from spyder.utils.misc import select_port, getcwd_or_home",
"from spyder.utils.palette import QStylePalette",
"from spyder.utils.qthelpers import file_uri, qapplication, start_file",
"from spyder.utils.stylesheet import APP_STYLESHEET",
"from spyder.api.exceptions import SpyderAPIError",
"from spyder.api.plugins import (",
"from spyder.utils.windows import (set_attached_console_visible,",
"from spyder.utils.qthelpers import SpyderProxyStyle",
"import win32api",
"from spyder.plugins.help.utils.sphinxify import CSS_PATH, DARK_CSS_PATH",
"import spyder",
"import faulthandler"
] | 1,017 | 1,056 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.