/
plugin.py
1896 lines (1644 loc) · 76.1 KB
/
plugin.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 plugin based on QtConsole.
"""
# pylint: disable=C0103
# pylint: disable=R0903
# pylint: disable=R0911
# pylint: disable=R0201
# Standard library imports
import os
import os.path as osp
import sys
import traceback
import uuid
# Third party imports
from jupyter_client.connect import find_connection_file
from jupyter_core.paths import jupyter_config_dir, jupyter_runtime_dir
from qtconsole.client import QtKernelClient
from qtpy.QtCore import Qt, Signal, Slot
from qtpy.QtGui import QColor
from qtpy.QtWebEngineWidgets import WEBENGINE
from qtpy.QtWidgets import (QActionGroup, QApplication, QHBoxLayout, QLabel,
QMenu, QMessageBox, QVBoxLayout, QWidget)
from traitlets.config.loader import Config, load_pyconfig_files
from zmq.ssh import tunnel as zmqtunnel
# Local imports
from spyder.api.plugins import SpyderPluginWidget
from spyder.config.base import (_, get_conf_path, get_home_dir,
running_under_pytest)
from spyder.config.gui import get_font, is_dark_interface
from spyder.config.manager import CONF
from spyder.plugins.ipythonconsole.confpage import IPythonConsoleConfigPage
from spyder.plugins.ipythonconsole.utils.kernelspec import SpyderKernelSpec
from spyder.plugins.ipythonconsole.utils.manager import SpyderKernelManager
from spyder.plugins.ipythonconsole.utils.ssh import openssh_tunnel
from spyder.plugins.ipythonconsole.utils.style import create_qss_style
from spyder.plugins.ipythonconsole.widgets import (
ClientWidget, ConsoleRestartDialog, KernelConnectionDialog,
PageControlWidget)
from spyder.py3compat import is_string, to_text_string, PY2, PY38_OR_MORE
from spyder.utils import encoding
from spyder.utils import icon_manager as ima
from spyder.utils import programs, sourcecode
from spyder.utils.misc import get_error_match, remove_backslashes
from spyder.utils.programs import get_temp_dir
from spyder.utils.qthelpers import MENU_SEPARATOR, add_actions, create_action
from spyder.widgets.browser import WebView
from spyder.widgets.findreplace import FindReplace
from spyder.widgets.tabs import Tabs
if is_dark_interface():
MAIN_BG_COLOR = '#19232D'
else:
MAIN_BG_COLOR = 'white'
class IPythonConsole(SpyderPluginWidget):
"""
IPython Console plugin
This is a widget with tabs where each one is a ClientWidget
"""
CONF_SECTION = 'ipython_console'
CONFIGWIDGET_CLASS = IPythonConsoleConfigPage
CONF_FILE = False
DISABLE_ACTIONS_WHEN_HIDDEN = False
# Signals
focus_changed = Signal()
edit_goto = Signal((str, int, str), (str, int, str, bool))
sig_pdb_state = Signal(bool, dict)
sig_shellwidget_process_started = Signal(object)
"""
This signal is emitted when a shellwidget process starts.
Parameters
----------
shellwidget: spyder.plugins.ipyconsole.widgets.shell.ShellWidget
The shellwigdet.
"""
sig_shellwidget_process_finished = Signal(object)
"""
This signal is emitted when a shellwidget process finishes.
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.
"""
# Error messages
permission_error_msg = _("The directory {} is not writable and it is "
"required to create IPython consoles. Please "
"make it writable.")
def __init__(self, parent, testing=False, test_dir=None,
test_no_stderr=False, css_path=None):
"""Ipython Console constructor."""
SpyderPluginWidget.__init__(self, parent)
self.tabwidget = None
self.menu_actions = None
self.master_clients = 0
self.clients = []
self.filenames = []
self.mainwindow_close = False
self.create_new_client_if_empty = True
self.css_path = css_path
self.run_cell_filename = None
self.interrupt_action = None
# Attrs for testing
self.testing = testing
self.test_dir = test_dir
self.test_no_stderr = test_no_stderr
# Create temp dir on testing to save kernel errors
if self.test_dir is not None:
if not osp.isdir(osp.join(test_dir)):
os.makedirs(osp.join(test_dir))
layout = QVBoxLayout()
layout.setSpacing(0)
self.tabwidget = Tabs(self, menu=self._options_menu,
actions=self.menu_actions,
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(self.refresh_plugin)
self.tabwidget.tabBar().tabMoved.connect(self.move_tab)
self.tabwidget.tabBar().sig_change_name.connect(
self.rename_tabs_after_change)
self.tabwidget.set_close_function(self.close_client)
self.main.editor.sig_file_debug_message_requested.connect(
self.print_debug_file_msg)
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
self.infowidget = WebView(self)
if WEBENGINE:
self.infowidget.page().setBackgroundColor(QColor(MAIN_BG_COLOR))
else:
self.infowidget.setStyleSheet(
"background:{}".format(MAIN_BG_COLOR))
self.set_infowidget_font()
layout.addWidget(self.infowidget)
# Label to inform users how to get out of the pager
self.pager_label = QLabel(_("Press <b>Q</b> to exit pager"), self)
self.pager_label.setStyleSheet(
"background-color: #3775A9;"
"color: white;"
"margin: 0px 4px 4px 4px;"
"padding: 5px;"
"qproperty-alignment: AlignCenter;"
)
self.pager_label.hide()
layout.addWidget(self.pager_label)
# Find/replace widget
self.find_widget = FindReplace(self)
self.find_widget.hide()
self.register_widget_shortcuts(self.find_widget)
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()
#------ SpyderPluginMixin API ---------------------------------------------
def update_font(self):
"""Update font from Preferences"""
font = self.get_font()
for client in self.clients:
client.set_font(font)
def _apply_gui_plugin_settings(self, options, client):
"""Apply GUI related configurations to a client."""
# GUI options
font_n = 'plugin_font'
help_n = 'connect_to_oi'
color_scheme_n = 'color_scheme_name'
show_time_n = 'show_elapsed_time'
reset_namespace_n = 'show_reset_namespace_warning'
ask_before_restart_n = 'ask_before_restart'
ask_before_closing_n = 'ask_before_closing'
show_calltips_n = 'show_calltips'
buffer_size_n = 'buffer_size'
completion_type_n = 'completion_type'
# Advanced GUI options
in_prompt_n = 'in_prompt'
out_prompt_n = 'out_prompt'
# Client widgets
control = client.get_control()
sw = client.shellwidget
if font_n in options:
font_o = self.get_font()
client.set_font(font_o)
if help_n in options and control is not None:
help_o = CONF.get('help', 'connect/ipython_console')
control.set_help_enabled(help_o)
if color_scheme_n in options:
color_scheme_o = CONF.get('appearance', 'selected')
client.set_color_scheme(color_scheme_o)
if show_time_n in options:
show_time_o = self.get_option(show_time_n)
client.show_time_action.setChecked(show_time_o)
client.set_elapsed_time_visible(show_time_o)
if reset_namespace_n in options:
reset_namespace_o = self.get_option(reset_namespace_n)
client.reset_warning = reset_namespace_o
if ask_before_restart_n in options:
ask_before_restart_o = self.get_option(ask_before_restart_n)
client.ask_before_restart = ask_before_restart_o
if ask_before_closing_n in options:
ask_before_closing_o = self.get_option(ask_before_closing_n)
client.ask_before_closing = ask_before_closing_o
if show_calltips_n in options:
show_calltips_o = self.get_option(show_calltips_n)
sw.set_show_calltips(show_calltips_o)
if buffer_size_n in options:
buffer_size_o = self.get_option(buffer_size_n)
sw.set_buffer_size(buffer_size_o)
if completion_type_n in options:
completion_type_o = self.get_option(completion_type_n)
completions = {0: "droplist", 1: "ncurses", 2: "plain"}
sw._set_completion_widget(completions[completion_type_o])
# Advanced GUI options
if in_prompt_n in options:
in_prompt_o = self.get_option(in_prompt_n)
sw.set_in_prompt(in_prompt_o)
if out_prompt_n in options:
out_prompt_o = self.get_option(out_prompt_n)
sw.set_out_prompt(out_prompt_o)
def _apply_mpl_plugin_settings(self, options, client):
"""Apply Matplotlib related configurations to a client."""
# Matplotlib options
pylab_n = 'pylab'
pylab_o = self.get_option(pylab_n)
pylab_autoload_n = 'pylab/autoload'
pylab_backend_n = 'pylab/backend'
inline_backend_figure_format_n = 'pylab/inline/figure_format'
inline_backend_resolution_n = 'pylab/inline/resolution'
inline_backend_width_n = 'pylab/inline/width'
inline_backend_height_n = 'pylab/inline/height'
inline_backend_bbox_inches_n = 'pylab/inline/bbox_inches'
# Client widgets
sw = client.shellwidget
if pylab_o:
if pylab_backend_n in options or pylab_autoload_n in options:
pylab_autoload_o = self.get_option(pylab_autoload_n)
pylab_backend_o = self.get_option(pylab_backend_n)
sw.set_matplotlib_backend(pylab_backend_o, pylab_autoload_o)
if inline_backend_figure_format_n in options:
inline_backend_figure_format_o = self.get_option(
inline_backend_figure_format_n)
sw.set_mpl_inline_figure_format(inline_backend_figure_format_o)
if inline_backend_resolution_n in options:
inline_backend_resolution_o = self.get_option(
inline_backend_resolution_n)
sw.set_mpl_inline_resolution(inline_backend_resolution_o)
if (inline_backend_width_n in options or
inline_backend_height_n in options):
inline_backend_width_o = self.get_option(
inline_backend_width_n)
inline_backend_height_o = self.get_option(
inline_backend_height_n)
sw.set_mpl_inline_figure_size(
inline_backend_width_o, inline_backend_height_o)
if inline_backend_bbox_inches_n in options:
inline_backend_bbox_inches_o = self.get_option(
inline_backend_bbox_inches_n)
sw.set_mpl_inline_bbox_inches(inline_backend_bbox_inches_o)
def _apply_advanced_plugin_settings(self, options, client):
"""Apply advanced configurations to a client."""
# Advanced options
greedy_completer_n = 'greedy_completer'
jedi_completer_n = 'jedi_completer'
autocall_n = 'autocall'
# Client widget
sw = client.shellwidget
if greedy_completer_n in options:
greedy_completer_o = self.get_option(greedy_completer_n)
sw.set_greedy_completer(greedy_completer_o)
if jedi_completer_n in options:
jedi_completer_o = self.get_option(jedi_completer_n)
sw.set_jedi_completer(jedi_completer_o)
if autocall_n in options:
autocall_o = self.get_option(autocall_n)
sw.set_autocall(autocall_o)
def _apply_pdb_plugin_settings(self, options, client):
"""Apply debugging configurations to a client."""
# Debugging options
pdb_ignore_lib_n = 'pdb_ignore_lib'
pdb_execute_events_n = 'pdb_execute_events'
pdb_use_exclamation_mark_n = 'pdb_use_exclamation_mark'
# Client widget
sw = client.shellwidget
if pdb_ignore_lib_n in options:
pdb_ignore_lib_o = self.get_option(pdb_ignore_lib_n)
sw.set_pdb_ignore_lib(pdb_ignore_lib_o)
if pdb_execute_events_n in options:
pdb_execute_events_o = self.get_option(pdb_execute_events_n)
sw.set_pdb_execute_events(pdb_execute_events_o)
if pdb_use_exclamation_mark_n in options:
pdb_use_exclamation_mark_o = self.get_option(
pdb_use_exclamation_mark_n)
sw.set_pdb_use_exclamation_mark(pdb_use_exclamation_mark_o)
def apply_plugin_settings_to_client(
self, options, client, disconnect_ready_signal=False):
"""Apply given plugin settings to the given client."""
# GUI options
self._apply_gui_plugin_settings(options, client)
# Matplotlib options
self._apply_mpl_plugin_settings(options, client)
# Advanced options
self._apply_advanced_plugin_settings(options, client)
# Debugging options
self._apply_pdb_plugin_settings(options, client)
if disconnect_ready_signal:
client.shellwidget.sig_pdb_prompt_ready.disconnect()
def apply_plugin_settings(self, options):
"""Apply configuration file's plugin settings."""
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_option(pylab_n)
pylab_backend_n = 'pylab/backend'
inline_backend = 0
pylab_restart = False
client_backend_not_inline = [False] * len(self.clients)
if pylab_o and pylab_backend_n in options:
pylab_backend_o = self.get_option(pylab_backend_n)
client_backend_not_inline = [
client.shellwidget.get_matplotlib_backend() != inline_backend
for client in self.clients]
current_client_backend_not_inline = (
self.get_current_client().shellwidget.get_matplotlib_backend()
!= inline_backend)
pylab_restart = (
any(client_backend_not_inline) and
pylab_backend_o != inline_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 = any([restart_option in options
for restart_option in restart_options])
if (restart_needed or pylab_restart) and not running_under_pytest():
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
for idx, client in enumerate(self.clients):
restart = ((pylab_restart and client_backend_not_inline[idx]) or
restart_needed)
if not (restart and restart_all) or no_restart:
sw = client.shellwidget
if sw.is_debugging() and sw._executing:
# Apply settings when the next Pdb prompt is available
sw.sig_pdb_prompt_ready.connect(
lambda o=options, c=client:
self.apply_plugin_settings_to_client(
o, c, disconnect_ready_signal=True)
)
else:
self.apply_plugin_settings_to_client(options, client)
elif restart and restart_all:
client.ask_before_restart = False
client.restart_kernel()
if (((pylab_restart and current_client_backend_not_inline)
or restart_needed) and restart_current):
current_client = self.get_current_client()
current_client.ask_before_restart = False
current_client.restart_kernel()
def toggle_view(self, checked):
"""Toggle view"""
if checked:
self.dockwidget.show()
self.dockwidget.raise_()
# Start a client in case there are none shown
if not self.clients:
if self.main.is_setting_up:
self.create_new_client(give_focus=False)
else:
self.create_new_client(give_focus=True)
else:
self.dockwidget.hide()
#------ SpyderPluginWidget API --------------------------------------------
def get_plugin_title(self):
"""Return widget title"""
return _('IPython console')
def get_plugin_icon(self):
"""Return widget icon"""
return ima.icon('ipython_console')
def get_focus_widget(self):
"""
Return the widget to give focus to when
this plugin's dockwidget is raised on top-level
"""
client = self.tabwidget.currentWidget()
if client is not None:
return client.get_control()
def closing_plugin(self, cancelable=False):
"""Perform actions before parent main window is closed"""
self.mainwindow_close = True
for client in self.clients:
client.shutdown()
client.remove_stderr_file()
client.dialog_manager.close_all()
client.close()
return True
def refresh_plugin(self):
"""Refresh tabwidget"""
client = None
if self.tabwidget.count():
client = self.tabwidget.currentWidget()
# Decide what to show for each client
if client.info_page != client.blank_page:
# Show info_page if it has content
client.set_info_page()
client.shellwidget.hide()
client.layout.addWidget(self.infowidget)
self.infowidget.show()
else:
self.infowidget.hide()
client.shellwidget.show()
# Give focus to the control widget of the selected tab
control = client.get_control()
control.setFocus()
if isinstance(control, PageControlWidget):
self.pager_label.show()
else:
self.pager_label.hide()
# Create corner widgets
buttons = [[b, -7] for b in client.get_toolbar_buttons()]
buttons = sum(buttons, [])[:-1]
widgets = [client.create_time_label()] + buttons
else:
control = None
widgets = []
self.find_widget.set_editor(control)
self.tabwidget.set_corner_widgets({Qt.TopRightCorner: widgets})
if client:
sw = client.shellwidget
self.main.variableexplorer.set_shellwidget_from_id(id(sw))
self.sig_pdb_state.emit(
sw.is_waiting_pdb_input(), sw.get_pdb_last_step())
self.sig_shellwidget_changed.emit(sw)
self.update_tabs_text()
self.sig_update_plugin_title.emit()
def get_plugin_actions(self):
"""Return a list of actions related to plugin."""
create_client_action = create_action(
self,
_("New console (default settings)"),
icon=ima.icon('ipython_console'),
triggered=self.create_new_client,
context=Qt.WidgetWithChildrenShortcut)
self.register_shortcut(create_client_action, context="ipython_console",
name="New tab")
create_pylab_action = create_action(
self,
_("New Pylab console (data plotting)"),
icon=ima.icon('ipython_console'),
triggered=self.create_pylab_client,
context=Qt.WidgetWithChildrenShortcut)
create_sympy_action = create_action(
self,
_("New SymPy console (symbolic math)"),
icon=ima.icon('ipython_console'),
triggered=self.create_sympy_client,
context=Qt.WidgetWithChildrenShortcut)
create_cython_action = create_action(
self,
_("New Cython console (Python with "
"C extensions)"),
icon=ima.icon('ipython_console'),
triggered=self.create_cython_client,
context=Qt.WidgetWithChildrenShortcut)
special_console_action_group = QActionGroup(self)
special_console_actions = (create_pylab_action, create_sympy_action,
create_cython_action)
add_actions(special_console_action_group, special_console_actions)
special_console_menu = QMenu(_("New special console"), self)
add_actions(special_console_menu, special_console_actions)
restart_action = create_action(self, _("Restart kernel"),
icon=ima.icon('restart'),
triggered=self.restart_kernel,
context=Qt.WidgetWithChildrenShortcut)
reset_action = create_action(self, _("Remove all variables"),
icon=ima.icon('editdelete'),
triggered=self.reset_kernel,
context=Qt.WidgetWithChildrenShortcut)
self.register_shortcut(reset_action, context="ipython_console",
name="Reset namespace")
if self.interrupt_action is None:
self.interrupt_action = create_action(
self, _("Interrupt kernel"),
icon=ima.icon('stop'),
triggered=self.interrupt_kernel,
context=Qt.WidgetWithChildrenShortcut)
self.register_shortcut(restart_action, context="ipython_console",
name="Restart kernel")
connect_to_kernel_action = create_action(self,
_("Connect to an existing kernel"), None, None,
_("Open a new IPython console connected to an existing kernel"),
triggered=self.create_client_for_kernel)
rename_tab_action = create_action(self, _("Rename tab"),
icon=ima.icon('rename'),
triggered=self.tab_name_editor)
# Add the action to the 'Consoles' menu on the main window
main_consoles_menu = self.main.consoles_menu_actions
main_consoles_menu.insert(0, create_client_action)
main_consoles_menu += [special_console_menu, connect_to_kernel_action,
MENU_SEPARATOR,
self.interrupt_action, restart_action,
reset_action]
# Plugin actions
self.menu_actions = [create_client_action, special_console_menu,
connect_to_kernel_action,
MENU_SEPARATOR,
self.interrupt_action,
restart_action, reset_action, rename_tab_action]
self.update_execution_state_kernel()
# Check for a current client. Since it manages more actions.
client = self.get_current_client()
if client:
return client.get_options_menu()
return self.menu_actions
def register_plugin(self):
"""Register plugin in Spyder's main window"""
self.add_dockwidget()
self.focus_changed.connect(self.main.plugin_focus_changed)
self.edit_goto.connect(self.main.editor.load)
self.edit_goto[str, int, str, bool].connect(
lambda fname, lineno, word, processevents:
self.main.editor.load(fname, lineno, word,
processevents=processevents))
self.main.editor.breakpoints_saved.connect(self.set_spyder_breakpoints)
self.main.editor.run_in_current_ipyclient.connect(self.run_script)
self.main.editor.run_cell_in_ipyclient.connect(self.run_cell)
self.main.editor.debug_cell_in_ipyclient.connect(self.debug_cell)
self.tabwidget.currentChanged.connect(self.update_working_directory)
self.tabwidget.currentChanged.connect(self.check_pdb_state)
self._remove_old_stderr_files()
# Update kernels if python path is changed
self.main.sig_pythonpath_changed.connect(self.update_path)
#------ Public API (for clients) ------------------------------------------
def get_clients(self):
"""Return clients list"""
return [cl for cl in self.clients if isinstance(cl, ClientWidget)]
def get_focus_client(self):
"""Return current client with focus, if any"""
widget = QApplication.focusWidget()
for client in self.get_clients():
if widget is client or widget is client.get_control():
return client
def get_current_client(self):
"""Return the currently selected client"""
client = self.tabwidget.currentWidget()
if client is not None:
return client
def get_current_shellwidget(self):
"""Return the shellwidget of the current client"""
client = self.get_current_client()
if client is not None:
return client.shellwidget
def run_script(self, filename, wdir, args, debug, post_mortem,
current_client, clear_variables, console_namespace):
"""Run script in current or dedicated client"""
norm = lambda text: remove_backslashes(to_text_string(text))
# Run Cython files in a dedicated console
is_cython = osp.splitext(filename)[1] == '.pyx'
if is_cython:
current_client = False
# Select client to execute code on it
is_new_client = False
if current_client:
client = self.get_current_client()
else:
client = self.get_client_for_file(filename)
if client is None:
self.create_client_for_file(filename, is_cython=is_cython)
client = self.get_current_client()
is_new_client = True
if client is not None:
# If spyder-kernels, use runfile
if client.shellwidget.is_spyder_kernel():
line = "%s('%s'" % ('debugfile' if debug else 'runfile',
norm(filename))
if args:
line += ", args='%s'" % norm(args)
if wdir:
line += ", wdir='%s'" % norm(wdir)
if post_mortem:
line += ", post_mortem=True"
if console_namespace:
line += ", current_namespace=True"
line += ")"
else: # External, non spyder-kernels, use %run
line = "%run "
if debug:
line += "-d "
line += "\"%s\"" % to_text_string(filename)
if args:
line += " %s" % norm(args)
try:
if client.shellwidget._executing:
# Don't allow multiple executions when there's
# still an execution taking place
# Fixes spyder-ide/spyder#7293.
pass
elif current_client:
self.execute_code(line, current_client, clear_variables)
else:
if is_new_client:
client.shellwidget.silent_execute('%clear')
else:
client.shellwidget.execute('%clear')
client.shellwidget.sig_prompt_ready.connect(
lambda: self.execute_code(line, current_client,
clear_variables))
except AttributeError:
pass
self.switch_to_plugin()
else:
#XXX: not sure it can really happen
QMessageBox.warning(self, _('Warning'),
_("No IPython console is currently available to run <b>%s</b>."
"<br><br>Please open a new one and try again."
) % osp.basename(filename), QMessageBox.Ok)
def run_cell(self, code, cell_name, filename, run_cell_copy,
function='runcell'):
"""Run cell in current or dedicated client."""
def norm(text):
return remove_backslashes(to_text_string(text))
self.run_cell_filename = filename
# Select client to execute code on it
client = self.get_client_for_file(filename)
if client is None:
client = self.get_current_client()
if client is not None:
# Internal kernels, use runcell
if client.get_kernel() is not None and not run_cell_copy:
line = (to_text_string(
"{}({}, '{}')").format(
to_text_string(function),
repr(cell_name),
norm(filename).replace("'", r"\'")))
# External kernels and run_cell_copy, just execute the code
else:
line = code.strip()
try:
self.execute_code(line)
except AttributeError:
pass
self._visibility_changed(True)
self.raise_()
else:
# XXX: not sure it can really happen
QMessageBox.warning(self, _('Warning'),
_("No IPython console is currently available "
"to run <b>{}</b>.<br><br>Please open a new "
"one and try again."
).format(osp.basename(filename)),
QMessageBox.Ok)
def debug_cell(self, code, cell_name, filename, run_cell_copy):
"""Debug current cell."""
self.run_cell(code, cell_name, filename, run_cell_copy, 'debugcell')
def set_current_client_working_directory(self, directory):
"""Set current client working directory."""
shellwidget = self.get_current_shellwidget()
if shellwidget is not None:
shellwidget.set_cwd(directory)
def set_working_directory(self, dirname):
"""Set current working directory.
In the workingdirectory and explorer plugins.
"""
if osp.isdir(dirname):
self.sig_current_directory_changed.emit(dirname)
def update_working_directory(self):
"""Update working directory to console cwd."""
shellwidget = self.get_current_shellwidget()
if shellwidget is not None:
shellwidget.update_cwd()
def update_path(self, path_dict, new_path_dict):
"""Update path on consoles."""
for client in self.get_clients():
shell = client.shellwidget
if shell is not None:
self.main.get_spyder_pythonpath()
shell.update_syspath(path_dict, new_path_dict)
def execute_code(self, lines, current_client=True, clear_variables=False):
"""Execute code instructions."""
sw = self.get_current_shellwidget()
if sw is not None:
if not current_client:
# Clear console and reset namespace for
# dedicated clients.
# See spyder-ide/spyder#5748.
try:
sw.sig_prompt_ready.disconnect()
except TypeError:
pass
sw.reset_namespace(warning=False)
elif current_client and clear_variables:
sw.reset_namespace(warning=False)
# Needed to handle an error when kernel_client is none.
# See spyder-ide/spyder#6308.
try:
sw.execute(to_text_string(lines))
except AttributeError:
pass
self.activateWindow()
self.get_current_client().get_control().setFocus()
def pdb_execute_command(self, command):
"""
Send command to the pdb kernel if possible.
"""
sw = self.get_current_shellwidget()
if sw is not None:
# Needed to handle an error when kernel_client is None.
# See spyder-ide/spyder#7578.
try:
sw.pdb_execute_command(command)
except AttributeError:
pass
def stop_debugging(self):
"""Stop debugging"""
sw = self.get_current_shellwidget()
if sw is not None:
sw.stop_debugging()
def get_pdb_state(self):
"""Get debugging state of the current console."""
sw = self.get_current_shellwidget()
if sw is not None:
return sw.is_waiting_pdb_input()
return False
def get_pdb_last_step(self):
"""Get last pdb step of the current console."""
sw = self.get_current_shellwidget()
if sw is not None:
return sw.get_pdb_last_step()
return {}
def check_pdb_state(self):
"""
Check if actions need to be taken checking the last pdb state.
"""
pdb_state = self.get_pdb_state()
if pdb_state:
pdb_last_step = self.get_pdb_last_step()
sw = self.get_current_shellwidget()
if 'fname' in pdb_last_step and sw is not None:
fname = pdb_last_step['fname']
line = pdb_last_step['lineno']
self.pdb_has_stopped(fname, line, sw)
@Slot()
@Slot(bool)
@Slot(str)
@Slot(bool, str)
@Slot(bool, bool)
@Slot(bool, str, bool)
def create_new_client(self, give_focus=True, filename='', is_cython=False,
is_pylab=False, is_sympy=False, given_name=None):
"""Create a new client"""
self.master_clients += 1
client_id = dict(int_id=to_text_string(self.master_clients),
str_id='A')
cf = self._new_connection_file()
show_elapsed_time = self.get_option('show_elapsed_time')
reset_warning = self.get_option('show_reset_namespace_warning')
ask_before_restart = self.get_option('ask_before_restart')
ask_before_closing = self.get_option('ask_before_closing')
client = ClientWidget(self, id_=client_id,
history_filename=get_conf_path('history.py'),
config_options=self.config_options(),
additional_options=self.additional_options(
is_pylab=is_pylab,
is_sympy=is_sympy),
interpreter_versions=self.interpreter_versions(),
connection_file=cf,
menu_actions=self.menu_actions,
options_button=self.options_button,
show_elapsed_time=show_elapsed_time,
reset_warning=reset_warning,
given_name=given_name,
ask_before_restart=ask_before_restart,
ask_before_closing=ask_before_closing,
css_path=self.css_path)
# Change stderr_dir if requested
if self.test_dir is not None:
client.stderr_dir = self.test_dir
self.add_tab(client, name=client.get_name(), filename=filename)
if cf is None:
error_msg = self.permission_error_msg.format(jupyter_runtime_dir())
client.show_kernel_error(error_msg)
return
# Check if ipykernel is present in the external interpreter.
# Else we won't be able to create a client
if not CONF.get('main_interpreter', 'default'):
pyexec = CONF.get('main_interpreter', 'executable')
has_spyder_kernels = programs.is_module_installed(
'spyder_kernels',
interpreter=pyexec,
version='>=1.10.0;<1.11.0')
if not has_spyder_kernels and not running_under_pytest():
client.show_kernel_error(
_("Your Python environment or installation doesn't have "
"the <tt>spyder-kernels</tt> module or the right "
"version of it installed (>= 1.10.0 and < 1.11.0). "
"Without this module is not possible for Spyder to "
"create a console for you.<br><br>"
"You can install it by running in a system terminal:"
"<br><br>"
"<tt>conda install spyder-kernels</tt>"
"<br><br>or<br><br>"