-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
main_widget.py
2223 lines (1913 loc) · 79.2 KB
/
main_widget.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
# (see spyder/__init__.py for details)
"""
IPython Console main widget based on QtConsole.
"""
# Standard library imports
import logging
import os
import os.path as osp
import shlex
import sys
# Third-party imports
from jupyter_client.connect import find_connection_file
from jupyter_core.paths import jupyter_config_dir
import qstylizer.style
from qtpy.QtCore import Signal, Slot
from qtpy.QtGui import QColor
from qtpy.QtWebEngineWidgets import WEBENGINE
from qtpy.QtWidgets import (
QApplication, QHBoxLayout, QLabel, QMessageBox, QVBoxLayout, QWidget)
from traitlets.config.loader import Config, load_pyconfig_files
# Local imports
from spyder.api.config.decorators import on_conf_change
from spyder.api.translations import _
from spyder.api.widgets.main_widget import PluginMainWidget
from spyder.api.widgets.menus import MENU_SEPARATOR
from spyder.config.base import (
get_home_dir, running_under_pytest)
from spyder.plugins.ipythonconsole.utils.kernel_handler import KernelHandler
from spyder.plugins.ipythonconsole.utils.kernelspec import SpyderKernelSpec
from spyder.plugins.ipythonconsole.utils.style import create_qss_style
from spyder.plugins.ipythonconsole.widgets import (
ClientWidget, ConsoleRestartDialog, COMPLETION_WIDGET_TYPE,
KernelConnectionDialog, PageControlWidget, MatplotlibStatus)
from spyder.plugins.ipythonconsole.widgets.mixins import CachedKernelMixin
from spyder.utils import encoding, programs, sourcecode
from spyder.utils.envs import get_list_envs
from spyder.utils.misc import get_error_match, remove_backslashes
from spyder.utils.palette import QStylePalette
from spyder.utils.workers import WorkerManager
from spyder.widgets.browser import FrameWebView
from spyder.widgets.findreplace import FindReplace
from spyder.widgets.tabs import Tabs
# Logging
logger = logging.getLogger(__name__)
# =============================================================================
# ---- Constants
# =============================================================================
MAIN_BG_COLOR = QStylePalette.COLOR_BACKGROUND_1
class IPythonConsoleWidgetActions:
# Clients creation
CreateNewClient = 'new tab'
CreateCythonClient = 'create cython client'
CreateSymPyClient = 'create cympy client'
CreatePyLabClient = 'create pylab client'
CreateNewClientEnvironment = 'create environment client'
# Current console actions
ClearConsole = 'Clear shell'
ClearLine = 'clear line'
ConnectToKernel = 'connect to kernel'
Interrupt = 'interrupt kernel'
InspectObject = 'Inspect current object'
Restart = 'Restart kernel'
ResetNamespace = 'reset namespace'
ShowEnvironmentVariables = 'Show environment variables'
ShowSystemPath = 'show system path'
ToggleElapsedTime = 'toggle elapsed time'
Quit = 'exit'
# Tabs
RenameTab = 'rename tab'
# Variables display
ArrayInline = 'enter array inline'
ArrayTable = 'enter array table'
# Documentation and help
IPythonDocumentation = 'ipython documentation'
ConsoleHelp = 'console help'
QuickReference = 'quick reference'
# Navigation
GoRight = "go to next console"
GoLeft = "go to previous console"
class IPythonConsoleWidgetOptionsMenus:
SpecialConsoles = 'special_consoles_submenu'
Documentation = 'documentation_submenu'
EnvironmentConsoles = 'environment_consoles_submenu'
class IPythonConsoleWidgetOptionsMenuSections:
Consoles = 'consoles_section'
Edit = 'edit_section'
View = 'view_section'
class IPythonConsoleWidgetMenus:
TabsContextMenu = 'tabs_context_menu'
class IPythonConsoleWidgetTabsContextMenuSections:
Consoles = 'tabs_consoles_section'
Edit = 'tabs_edit_section'
# --- Widgets
# ----------------------------------------------------------------------------
class IPythonConsoleWidget(PluginMainWidget, CachedKernelMixin):
"""
IPython Console plugin
This is a widget with tabs where each one is a ClientWidget.
"""
# Signals
sig_append_to_history_requested = Signal(str, str)
"""
This signal is emitted when the plugin requires to add commands to a
history file.
Parameters
----------
filename: str
History file filename.
text: str
Text to append to the history file.
"""
sig_history_requested = Signal(str)
"""
This signal is emitted when the plugin wants a specific history file
to be shown.
Parameters
----------
path: str
Path to history file.
"""
sig_focus_changed = Signal()
"""
This signal is emitted when the plugin focus changes.
"""
sig_switch_to_plugin_requested = Signal()
"""
This signal will request to change the focus to the plugin.
"""
sig_edit_goto_requested = Signal(str, int, str)
"""
This signal will request to open a file in a given row and column
using a code editor.
Parameters
----------
path: str
Path to file.
row: int
Cursor starting row position.
word: str
Word to select on given row.
"""
sig_edit_new = Signal(str)
"""
This signal will request to create a new file in a code editor.
Parameters
----------
path: str
Path to file.
"""
sig_shellwidget_created = Signal(object)
"""
This signal is emitted when a shellwidget is created.
Parameters
----------
shellwidget: spyder.plugins.ipyconsole.widgets.shell.ShellWidget
The shellwigdet.
"""
sig_shellwidget_deleted = Signal(object)
"""
This signal is emitted when a shellwidget is deleted/removed.
Parameters
----------
shellwidget: spyder.plugins.ipyconsole.widgets.shell.ShellWidget
The shellwigdet.
"""
sig_shellwidget_changed = Signal(object)
"""
This signal is emitted when the current shellwidget changes.
Parameters
----------
shellwidget: spyder.plugins.ipyconsole.widgets.shell.ShellWidget
The shellwigdet.
"""
sig_render_plain_text_requested = Signal(str)
"""
This signal is emitted to request a plain text help render.
Parameters
----------
plain_text: str
The plain text to render.
"""
sig_render_rich_text_requested = Signal(str, bool)
"""
This signal is emitted to request a rich text help render.
Parameters
----------
rich_text: str
The rich text.
collapse: bool
If the text contains collapsed sections, show them closed (True) or
open (False).
"""
sig_help_requested = Signal(dict)
"""
This signal is emitted to request help on a given object `name`.
Parameters
----------
help_data: dict
Example `{'name': str, 'ignore_unknown': bool}`.
"""
sig_current_directory_changed = Signal(str)
"""
This signal is emitted when the current directory of the active shell
widget has changed.
Parameters
----------
working_directory: str
The new working directory path.
"""
def __init__(self, name=None, plugin=None, parent=None):
super().__init__(name, plugin, parent)
self.menu_actions = None
self.master_clients = 0
self.clients = []
self.filenames = []
self.mainwindow_close = False
self.active_project_path = None
self.create_new_client_if_empty = True
self.run_cell_filename = None
self.interrupt_action = None
self.initial_conf_options = self.get_conf_options()
self.registered_spyder_kernel_handlers = {}
self.envs = {}
self.default_interpreter = sys.executable
# Disable infowidget if requested by the user
self.enable_infowidget = True
if plugin:
cli_options = plugin.get_command_line_options()
if cli_options.no_web_widgets:
self.enable_infowidget = False
# Attrs for testing
self._testing = bool(os.environ.get('IPYCONSOLE_TESTING'))
layout = QVBoxLayout()
layout.setSpacing(0)
self.tabwidget = Tabs(self, rename_tabs=True, split_char='/',
split_index=0)
if (hasattr(self.tabwidget, 'setDocumentMode')
and not sys.platform == 'darwin'):
# Don't set document mode to true on OSX because it generates
# a crash when the console is detached from the main window
# Fixes spyder-ide/spyder#561.
self.tabwidget.setDocumentMode(True)
self.tabwidget.currentChanged.connect(
lambda idx: self.refresh_container(give_focus=True))
self.tabwidget.tabBar().tabMoved.connect(self.move_tab)
self.tabwidget.tabBar().sig_name_changed.connect(
self.rename_tabs_after_change)
self.tabwidget.set_close_function(self.close_client)
if sys.platform == 'darwin':
tab_container = QWidget()
tab_container.setObjectName('tab-container')
tab_layout = QHBoxLayout(tab_container)
tab_layout.setContentsMargins(0, 0, 0, 0)
tab_layout.addWidget(self.tabwidget)
layout.addWidget(tab_container)
else:
layout.addWidget(self.tabwidget)
# Info widget
if self.enable_infowidget:
self.infowidget = FrameWebView(self)
if WEBENGINE:
self.infowidget.page().setBackgroundColor(
QColor(MAIN_BG_COLOR))
else:
self.infowidget.setStyleSheet(
"background:{}".format(MAIN_BG_COLOR))
layout.addWidget(self.infowidget)
else:
self.infowidget = None
# Label to inform users how to get out of the pager
self.pager_label = QLabel(_("Press <b>Q</b> to exit pager"), self)
pager_label_css = qstylizer.style.StyleSheet()
pager_label_css.setValues(**{
'background-color': f'{QStylePalette.COLOR_ACCENT_2}',
'color': f'{QStylePalette.COLOR_TEXT_1}',
'margin': '0px 1px 4px 1px',
'padding': '5px',
'qproperty-alignment': 'AlignCenter'
})
self.pager_label.setStyleSheet(pager_label_css.toString())
self.pager_label.hide()
layout.addWidget(self.pager_label)
# Find/replace widget
self.find_widget = FindReplace(self)
self.find_widget.hide()
layout.addWidget(self.find_widget)
self.setLayout(layout)
# Accepting drops
self.setAcceptDrops(True)
# Needed to start Spyder in Windows with Python 3.8
# See spyder-ide/spyder#11880
self._init_asyncio_patch()
# Create MatplotlibStatus
self.matplotlib_status = MatplotlibStatus(self)
# Initial value for the current working directory
self._current_working_directory = get_home_dir()
# Worker to compute envs in a thread
self._worker_manager = WorkerManager(max_threads=1)
# Update the list of envs at startup
self.get_envs()
def on_close(self):
self.mainwindow_close = True
self.close_all_clients()
# ---- PluginMainWidget API and settings handling
# ------------------------------------------------------------------------
def get_title(self):
return _('IPython Console')
def get_focus_widget(self):
client = self.tabwidget.currentWidget()
if client is not None:
return client.get_control()
def setup(self):
# --- Options menu actions
self.create_client_action = self.create_action(
IPythonConsoleWidgetActions.CreateNewClient,
text=_("New console (default settings)"),
icon=self.create_icon('ipython_console'),
triggered=self.create_new_client,
register_shortcut=True
)
self.restart_action = self.create_action(
IPythonConsoleWidgetActions.Restart,
text=_("Restart kernel"),
icon=self.create_icon('restart'),
triggered=self.restart_kernel,
register_shortcut=True
)
self.reset_action = self.create_action(
IPythonConsoleWidgetActions.ResetNamespace,
text=_("Remove all variables"),
icon=self.create_icon('editdelete'),
triggered=self.reset_namespace,
register_shortcut=True
)
self.interrupt_action = self.create_action(
IPythonConsoleWidgetActions.Interrupt,
text=_("Interrupt kernel"),
icon=self.create_icon('stop'),
triggered=self.interrupt_kernel,
)
self.connect_to_kernel_action = self.create_action(
IPythonConsoleWidgetActions.ConnectToKernel,
text=_("Connect to an existing kernel"),
tip=_("Open a new IPython console connected to an existing "
"kernel"),
triggered=self._create_client_for_kernel,
)
self.rename_tab_action = self.create_action(
IPythonConsoleWidgetActions.RenameTab,
text=_("Rename tab"),
icon=self.create_icon('rename'),
triggered=self.tab_name_editor,
)
self.create_action(
IPythonConsoleWidgetActions.GoRight,
text=_("Go to the next console"),
icon=self.create_icon('Next'),
triggered=lambda: self.tabs.tab_navigate(+1),
register_shortcut=True
)
self.create_action(
IPythonConsoleWidgetActions.GoLeft,
text=_("Go to the previous console"),
icon=self.create_icon('Previous'),
triggered=lambda: self.tabs.tab_navigate(-1),
register_shortcut=True
)
# --- For the client
self.env_action = self.create_action(
IPythonConsoleWidgetActions.ShowEnvironmentVariables,
text=_("Show environment variables"),
icon=self.create_icon('environ'),
triggered=lambda:
self.get_current_shellwidget().request_env()
if self.get_current_shellwidget() else None,
)
self.syspath_action = self.create_action(
IPythonConsoleWidgetActions.ShowSystemPath,
text=_("Show sys.path contents"),
icon=self.create_icon('syspath'),
triggered=lambda:
self.get_current_shellwidget().request_syspath()
if self.get_current_shellwidget() else None,
)
self.show_time_action = self.create_action(
IPythonConsoleWidgetActions.ToggleElapsedTime,
text=_("Show elapsed time"),
toggled=self.set_show_elapsed_time_current_client,
initial=self.get_conf('show_elapsed_time')
)
# --- Context menu actions
# TODO: Shortcut registration not working
self.inspect_action = self.create_action(
IPythonConsoleWidgetActions.InspectObject,
text=_("Inspect current object"),
icon=self.create_icon('MessageBoxInformation'),
triggered=self.current_client_inspect_object,
register_shortcut=True)
self.clear_line_action = self.create_action(
IPythonConsoleWidgetActions.ClearLine,
text=_("Clear line or block"),
triggered=self.current_client_clear_line,
register_shortcut=True)
self.clear_console_action = self.create_action(
IPythonConsoleWidgetActions.ClearConsole,
text=_("Clear console"),
triggered=self.current_client_clear_console,
register_shortcut=True)
self.quit_action = self.create_action(
IPythonConsoleWidgetActions.Quit,
_("&Quit"),
icon=self.create_icon('exit'),
triggered=self.current_client_quit)
# --- Other actions with shortcuts
self.array_table_action = self.create_action(
IPythonConsoleWidgetActions.ArrayTable,
text=_("Enter array table"),
triggered=self.current_client_enter_array_table,
register_shortcut=True)
self.array_inline_action = self.create_action(
IPythonConsoleWidgetActions.ArrayInline,
text=_("Enter array inline"),
triggered=self.current_client_enter_array_inline,
register_shortcut=True)
self.context_menu_actions = (
MENU_SEPARATOR,
self.inspect_action,
self.clear_line_action,
self.clear_console_action,
self.reset_action,
self.array_table_action,
self.array_inline_action,
MENU_SEPARATOR,
self.quit_action
)
# --- Setting options menu
options_menu = self.get_options_menu()
self.console_environment_menu = self.create_menu(
IPythonConsoleWidgetOptionsMenus.EnvironmentConsoles,
_('New console in environment')
)
stylesheet = qstylizer.style.StyleSheet()
stylesheet["QMenu"]["menu-scrollable"].setValue("1")
self.console_environment_menu.setStyleSheet(stylesheet.toString())
self.special_console_menu = self.create_menu(
IPythonConsoleWidgetOptionsMenus.SpecialConsoles,
_('New special console'))
for item in [
self.create_client_action,
self.console_environment_menu,
self.special_console_menu,
self.connect_to_kernel_action]:
self.add_item_to_menu(
item,
menu=options_menu,
section=IPythonConsoleWidgetOptionsMenuSections.Consoles,
)
for item in [
self.interrupt_action,
self.restart_action,
self.reset_action,
self.rename_tab_action]:
self.add_item_to_menu(
item,
menu=options_menu,
section=IPythonConsoleWidgetOptionsMenuSections.Edit,
)
for item in [
self.env_action,
self.syspath_action,
self.show_time_action]:
self.add_item_to_menu(
item,
menu=options_menu,
section=IPythonConsoleWidgetOptionsMenuSections.View,
)
create_pylab_action = self.create_action(
IPythonConsoleWidgetActions.CreatePyLabClient,
text=_("New Pylab console (data plotting)"),
icon=self.create_icon('ipython_console'),
triggered=self.create_pylab_client,
)
create_sympy_action = self.create_action(
IPythonConsoleWidgetActions.CreateSymPyClient,
text=_("New SymPy console (symbolic math)"),
icon=self.create_icon('ipython_console'),
triggered=self.create_sympy_client,
)
create_cython_action = self.create_action(
IPythonConsoleWidgetActions.CreateCythonClient,
_("New Cython console (Python with C extensions)"),
icon=self.create_icon('ipython_console'),
triggered=self.create_cython_client,
)
self.console_environment_menu.aboutToShow.connect(
self.update_environment_menu)
for item in [
create_pylab_action,
create_sympy_action,
create_cython_action]:
self.add_item_to_menu(
item,
menu=self.special_console_menu
)
# --- Widgets for the tab corner
self.reset_button = self.create_toolbutton(
'reset',
text=_("Remove all variables"),
tip=_("Remove all variables from kernel namespace"),
icon=self.create_icon("editdelete"),
triggered=self.reset_namespace,
)
self.stop_button = self.create_toolbutton(
'interrupt',
text=_("Interrupt kernel"),
tip=_("Interrupt kernel"),
icon=self.create_icon('stop'),
triggered=self.interrupt_kernel,
)
self.time_label = QLabel("")
# --- Add tab corner widgets.
self.add_corner_widget('timer', self.time_label)
self.add_corner_widget('reset', self.reset_button)
self.add_corner_widget('start_interrupt', self.stop_button)
# --- Tabs context menu
tabs_context_menu = self.create_menu(
IPythonConsoleWidgetMenus.TabsContextMenu)
for item in [
self.create_client_action,
self.console_environment_menu,
self.special_console_menu,
self.connect_to_kernel_action]:
self.add_item_to_menu(
item,
menu=tabs_context_menu,
section=IPythonConsoleWidgetTabsContextMenuSections.Consoles,
)
for item in [
self.interrupt_action,
self.restart_action,
self.reset_action,
self.rename_tab_action]:
self.add_item_to_menu(
item,
menu=tabs_context_menu,
section=IPythonConsoleWidgetTabsContextMenuSections.Edit,
)
self.tabwidget.menu = tabs_context_menu
# --- Create IPython documentation menu
self.ipython_menu = self.create_menu(
menu_id=IPythonConsoleWidgetOptionsMenus.Documentation,
title=_("IPython documentation"))
intro_action = self.create_action(
IPythonConsoleWidgetActions.IPythonDocumentation,
text=_("Intro to IPython"),
triggered=self.show_intro
)
quickref_action = self.create_action(
IPythonConsoleWidgetActions.QuickReference,
text=_("Quick reference"),
triggered=self.show_quickref
)
guiref_action = self.create_action(
IPythonConsoleWidgetActions.ConsoleHelp,
text=_("Console help"),
triggered=self.show_guiref
)
for help_action in [
intro_action, guiref_action, quickref_action]:
self.ipython_menu.add_action(help_action)
def set_show_elapsed_time_current_client(self, state):
if self.get_current_client():
client = self.get_current_client()
client.set_show_elapsed_time(state)
self.refresh_container()
def update_actions(self):
client = self.get_current_client()
if client is not None:
# Executing state
executing = client.is_client_executing()
self.interrupt_action.setEnabled(executing)
self.stop_button.setEnabled(executing)
# Client is loading or showing a kernel error
if (
client.infowidget is not None
and client.info_page is not None
):
error_or_loading = client.info_page != client.blank_page
self.restart_action.setEnabled(not error_or_loading)
self.reset_action.setEnabled(not error_or_loading)
self.env_action.setEnabled(not error_or_loading)
self.syspath_action.setEnabled(not error_or_loading)
self.show_time_action.setEnabled(not error_or_loading)
def get_envs(self):
"""
Get the list of environments/interpreters in a worker.
"""
self._worker_manager.terminate_all()
worker = self._worker_manager.create_python_worker(get_list_envs)
worker.sig_finished.connect(self.update_envs)
worker.start()
def update_envs(self, worker, output, error):
"""Update the list of environments in the system."""
if output is not None:
self.envs.update(**output)
def update_environment_menu(self):
"""
Update context menu submenu with entries for available interpreters.
"""
self.get_envs()
self.console_environment_menu.clear_actions()
for env_key, env_info in self.envs.items():
env_name = env_key.split()[-1]
path_to_interpreter, python_version = env_info
action = self.create_action(
name=env_key,
text=f'{env_key} ({python_version})',
icon=self.create_icon('ipython_console'),
triggered=(
lambda checked, env_name=env_name,
path_to_interpreter=path_to_interpreter:
self.create_environment_client(
env_name,
path_to_interpreter
)
),
overwrite=True
)
self.add_item_to_menu(
action,
menu=self.console_environment_menu
)
self.console_environment_menu._render()
# ---- GUI options
@on_conf_change(section='help', option='connect/ipython_console')
def change_clients_help_connection(self, value):
for idx, client in enumerate(self.clients):
self._change_client_conf(
client,
client.get_control().set_help_enabled,
value)
@on_conf_change(section='appearance', option=['selected', 'ui_theme'])
def change_clients_color_scheme(self, option, value):
if option == 'ui_theme':
value = self.get_conf('selected', section='appearance')
for idx, client in enumerate(self.clients):
self._change_client_conf(
client,
client.set_color_scheme,
value)
@on_conf_change(option='show_elapsed_time')
def change_clients_show_elapsed_time(self, value):
for idx, client in enumerate(self.clients):
self._change_client_conf(
client,
client.set_show_elapsed_time,
value)
if self.get_current_client():
self.refresh_container()
@on_conf_change(option='show_reset_namespace_warning')
def change_clients_show_reset_namespace_warning(self, value):
for idx, client in enumerate(self.clients):
def change_client_reset_warning(value=value):
client.reset_warning = value
self._change_client_conf(
client,
change_client_reset_warning,
value)
@on_conf_change(option='show_calltips')
def change_clients_show_calltips(self, value):
for idx, client in enumerate(self.clients):
self._change_client_conf(
client,
client.shellwidget.set_show_calltips,
value)
@on_conf_change(option='buffer_size')
def change_clients_buffer_size(self, value):
for idx, client in enumerate(self.clients):
self._change_client_conf(
client,
client.shellwidget.set_buffer_size,
value)
@on_conf_change(option='completion_type')
def change_clients_completion_type(self, value):
for idx, client in enumerate(self.clients):
self._change_client_conf(
client,
client.shellwidget._set_completion_widget,
COMPLETION_WIDGET_TYPE[value])
# ---- Advanced GUI options
@on_conf_change(option='in_prompt')
def change_clients_in_prompt(self, value):
if bool(value):
for idx, client in enumerate(self.clients):
self._change_client_conf(
client,
client.shellwidget.set_in_prompt,
value)
@on_conf_change(option='out_prompt')
def change_clients_out_prompt(self, value):
if bool(value):
for idx, client in enumerate(self.clients):
self._change_client_conf(
client,
client.shellwidget.set_out_prompt,
value)
# ---- Advanced options
@on_conf_change(option='greedy_completer')
def change_clients_greedy_completer(self, value):
for idx, client in enumerate(self.clients):
self._change_client_conf(
client,
client.shellwidget.set_greedy_completer,
value)
@on_conf_change(option='jedi_completer')
def change_clients_jedi_completer(self, value):
for idx, client in enumerate(self.clients):
self._change_client_conf(
client,
client.shellwidget.set_jedi_completer,
value)
@on_conf_change(option='autocall')
def change_clients_autocall(self, value):
for idx, client in enumerate(self.clients):
self._change_client_conf(
client,
client.shellwidget.set_autocall,
value)
@on_conf_change(option=[
'symbolic_math', 'hide_cmd_windows',
'startup/run_lines', 'startup/use_run_file', 'startup/run_file',
'pylab', 'pylab/backend', 'pylab/autoload',
'pylab/inline/figure_format', 'pylab/inline/resolution',
'pylab/inline/width', 'pylab/inline/height',
'pylab/inline/bbox_inches'])
def change_possible_restart_and_mpl_conf(self, option, value):
"""
Apply options that possibly require a kernel restart or related to
Matplotlib inline backend options.
"""
# Check that we are not triggering validations in the initial
# notification sent when Spyder is starting or when another option
# already required a restart and the restart dialog was shown
if not self._testing:
if option in self.initial_conf_options:
self.initial_conf_options.remove(option)
return
restart_needed = False
restart_options = []
# Startup options (needs a restart)
run_lines_n = 'startup/run_lines'
use_run_file_n = 'startup/use_run_file'
run_file_n = 'startup/run_file'
# Graphic options
pylab_n = 'pylab'
pylab_o = self.get_conf(pylab_n)
pylab_backend_n = 'pylab/backend'
# Advanced options (needs a restart)
symbolic_math_n = 'symbolic_math'
hide_cmd_windows_n = 'hide_cmd_windows'
restart_options += [run_lines_n, use_run_file_n, run_file_n,
symbolic_math_n, hide_cmd_windows_n]
restart_needed = option in restart_options
inline_backend = 0
pylab_restart = False
clients_backend_require_restart = [False] * len(self.clients)
current_client = self.get_current_client()
current_client_backend_require_restart = False
if pylab_o and pylab_backend_n == option and current_client:
pylab_backend_o = self.get_conf(pylab_backend_n)
# Check if clients require a restart due to a change in
# interactive backend.
clients_backend_require_restart = []
for client in self.clients:
interactive_backend = (
client.shellwidget.get_mpl_interactive_backend())
if (
# No restart is needed if the new backend is inline
pylab_backend_o != inline_backend and
# There was an error getting the interactive backend in
# the kernel, so we can't proceed.
interactive_backend is not None and
# There has to be an interactive backend (i.e. different
# from inline) set in the kernel before. Else, a restart
# is not necessary.
interactive_backend != inline_backend and
# The interactive backend to switch to has to be different
# from the current one
interactive_backend != pylab_backend_o
):
clients_backend_require_restart.append(True)
# Detect if current client requires restart
if id(client) == id(current_client):
current_client_backend_require_restart = True
# For testing
if self._testing:
os.environ['BACKEND_REQUIRE_RESTART'] = 'true'
else:
clients_backend_require_restart.append(False)
pylab_restart = any(clients_backend_require_restart)
if (restart_needed or pylab_restart) and not running_under_pytest():
self.initial_conf_options = self.get_conf_options()
self.initial_conf_options.remove(option)
restart_dialog = ConsoleRestartDialog(self)
restart_dialog.exec_()
(restart_all, restart_current,
no_restart) = restart_dialog.get_action_value()
else:
restart_all = False
restart_current = False
no_restart = True
# Apply settings
options = {option: value}
for idx, client in enumerate(self.clients):
restart = (
(pylab_restart and clients_backend_require_restart[idx]) or
restart_needed
)
if not (restart and restart_all) or no_restart:
sw = client.shellwidget
if sw.is_debugging() and sw._executing:
# Apply conf when the next Pdb prompt is available
def change_client_mpl_conf(o=options, c=client):
self._change_client_mpl_conf(o, c)
sw.sig_pdb_prompt_ready.disconnect(
change_client_mpl_conf)
sw.sig_pdb_prompt_ready.connect(change_client_mpl_conf)
else:
self._change_client_mpl_conf(options, client)
elif restart and restart_all:
self.restart_kernel(client, ask_before_restart=False)
if (
(
(pylab_restart and current_client_backend_require_restart)
or restart_needed
)
and restart_current
and current_client
):
self.restart_kernel(current_client, ask_before_restart=False)
# ---- Private methods
# -------------------------------------------------------------------------
def _change_client_conf(self, client, client_conf_func, value):
"""
Change a client configuration option, taking into account if it is
in a debugging session.
Parameters
----------
client : ClientWidget
Client to update configuration.
client_conf_func : Callable
Client method to use to change the configuration.
value : any
New value for the client configuration.
Returns
-------
None.
"""