/
console_widget.py
1808 lines (1542 loc) · 71.5 KB
/
console_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
""" An abstract base class for console-type widgets.
"""
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
# Standard library imports
from os.path import commonprefix
import re
import sys
from textwrap import dedent
# System library imports
from PyQt4 import QtCore, QtGui
# Local imports
from IPython.config.configurable import Configurable
from IPython.frontend.qt.util import MetaQObjectHasTraits, get_font
from IPython.utils.traitlets import Bool, Enum, Int
from ansi_code_processor import QtAnsiCodeProcessor
from completion_widget import CompletionWidget
#-----------------------------------------------------------------------------
# Classes
#-----------------------------------------------------------------------------
class ConsoleWidget(Configurable, QtGui.QWidget):
""" An abstract base class for console-type widgets. This class has
functionality for:
* Maintaining a prompt and editing region
* Providing the traditional Unix-style console keyboard shortcuts
* Performing tab completion
* Paging text
* Handling ANSI escape codes
ConsoleWidget also provides a number of utility methods that will be
convenient to implementors of a console-style widget.
"""
__metaclass__ = MetaQObjectHasTraits
#------ Configuration ------------------------------------------------------
# Whether to process ANSI escape codes.
ansi_codes = Bool(True, config=True)
# The maximum number of lines of text before truncation. Specifying a
# non-positive number disables text truncation (not recommended).
buffer_size = Int(500, config=True)
# Whether to use a list widget or plain text output for tab completion.
gui_completion = Bool(False, config=True)
# The type of underlying text widget to use. Valid values are 'plain', which
# specifies a QPlainTextEdit, and 'rich', which specifies a QTextEdit.
# NOTE: this value can only be specified during initialization.
kind = Enum(['plain', 'rich'], default_value='plain', config=True)
# The type of paging to use. Valid values are:
# 'inside' : The widget pages like a traditional terminal.
# 'hsplit' : When paging is requested, the widget is split
# horizontally. The top pane contains the console, and the
# bottom pane contains the paged text.
# 'vsplit' : Similar to 'hsplit', except that a vertical splitter used.
# 'custom' : No action is taken by the widget beyond emitting a
# 'custom_page_requested(str)' signal.
# 'none' : The text is written directly to the console.
# NOTE: this value can only be specified during initialization.
paging = Enum(['inside', 'hsplit', 'vsplit', 'custom', 'none'],
default_value='inside', config=True)
# Whether to override ShortcutEvents for the keybindings defined by this
# widget (Ctrl+n, Ctrl+a, etc). Enable this if you want this widget to take
# priority (when it has focus) over, e.g., window-level menu shortcuts.
override_shortcuts = Bool(False)
#------ Signals ------------------------------------------------------------
# Signals that indicate ConsoleWidget state.
copy_available = QtCore.pyqtSignal(bool)
redo_available = QtCore.pyqtSignal(bool)
undo_available = QtCore.pyqtSignal(bool)
# Signal emitted when paging is needed and the paging style has been
# specified as 'custom'.
custom_page_requested = QtCore.pyqtSignal(object)
# Signal emitted when the font is changed.
font_changed = QtCore.pyqtSignal(QtGui.QFont)
#------ Protected class variables ------------------------------------------
_ctrl_down_remap = { QtCore.Qt.Key_B : QtCore.Qt.Key_Left,
QtCore.Qt.Key_F : QtCore.Qt.Key_Right,
QtCore.Qt.Key_A : QtCore.Qt.Key_Home,
QtCore.Qt.Key_E : QtCore.Qt.Key_End,
QtCore.Qt.Key_P : QtCore.Qt.Key_Up,
QtCore.Qt.Key_N : QtCore.Qt.Key_Down,
QtCore.Qt.Key_D : QtCore.Qt.Key_Delete, }
_shortcuts = set(_ctrl_down_remap.keys() +
[ QtCore.Qt.Key_C, QtCore.Qt.Key_G, QtCore.Qt.Key_O,
QtCore.Qt.Key_V ])
#---------------------------------------------------------------------------
# 'QObject' interface
#---------------------------------------------------------------------------
def __init__(self, parent=None, **kw):
""" Create a ConsoleWidget.
Parameters:
-----------
parent : QWidget, optional [default None]
The parent for this widget.
"""
QtGui.QWidget.__init__(self, parent)
Configurable.__init__(self, **kw)
# Create the layout and underlying text widget.
layout = QtGui.QStackedLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
self._control = self._create_control()
self._page_control = None
self._splitter = None
if self.paging in ('hsplit', 'vsplit'):
self._splitter = QtGui.QSplitter()
if self.paging == 'hsplit':
self._splitter.setOrientation(QtCore.Qt.Horizontal)
else:
self._splitter.setOrientation(QtCore.Qt.Vertical)
self._splitter.addWidget(self._control)
layout.addWidget(self._splitter)
else:
layout.addWidget(self._control)
# Create the paging widget, if necessary.
if self.paging in ('inside', 'hsplit', 'vsplit'):
self._page_control = self._create_page_control()
if self._splitter:
self._page_control.hide()
self._splitter.addWidget(self._page_control)
else:
layout.addWidget(self._page_control)
# Initialize protected variables. Some variables contain useful state
# information for subclasses; they should be considered read-only.
self._ansi_processor = QtAnsiCodeProcessor()
self._completion_widget = CompletionWidget(self._control)
self._continuation_prompt = '> '
self._continuation_prompt_html = None
self._executing = False
self._filter_drag = False
self._filter_resize = False
self._prompt = ''
self._prompt_html = None
self._prompt_pos = 0
self._prompt_sep = ''
self._reading = False
self._reading_callback = None
self._tab_width = 8
self._text_completing_pos = 0
# Set a monospaced font.
self.reset_font()
def eventFilter(self, obj, event):
""" Reimplemented to ensure a console-like behavior in the underlying
text widgets.
"""
etype = event.type()
if etype == QtCore.QEvent.KeyPress:
# Re-map keys for all filtered widgets.
key = event.key()
if self._control_key_down(event.modifiers()) and \
key in self._ctrl_down_remap:
new_event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress,
self._ctrl_down_remap[key],
QtCore.Qt.NoModifier)
QtGui.qApp.sendEvent(obj, new_event)
return True
elif obj == self._control:
return self._event_filter_console_keypress(event)
elif obj == self._page_control:
return self._event_filter_page_keypress(event)
# Make middle-click paste safe.
elif etype == QtCore.QEvent.MouseButtonRelease and \
event.button() == QtCore.Qt.MidButton and \
obj == self._control.viewport():
cursor = self._control.cursorForPosition(event.pos())
self._control.setTextCursor(cursor)
self.paste(QtGui.QClipboard.Selection)
return True
# Manually adjust the scrollbars *after* a resize event is dispatched.
elif etype == QtCore.QEvent.Resize and not self._filter_resize:
self._filter_resize = True
QtGui.qApp.sendEvent(obj, event)
self._adjust_scrollbars()
self._filter_resize = False
return True
# Override shortcuts for all filtered widgets.
elif etype == QtCore.QEvent.ShortcutOverride and \
self.override_shortcuts and \
self._control_key_down(event.modifiers()) and \
event.key() in self._shortcuts:
event.accept()
# Ensure that drags are safe. The problem is that the drag starting
# logic, which determines whether the drag is a Copy or Move, is locked
# down in QTextControl. If the widget is editable, which it must be if
# we're not executing, the drag will be a Move. The following hack
# prevents QTextControl from deleting the text by clearing the selection
# when a drag leave event originating from this widget is dispatched.
# The fact that we have to clear the user's selection is unfortunate,
# but the alternative--trying to prevent Qt from using its hardwired
# drag logic and writing our own--is worse.
elif etype == QtCore.QEvent.DragEnter and \
obj == self._control.viewport() and \
event.source() == self._control.viewport():
self._filter_drag = True
elif etype == QtCore.QEvent.DragLeave and \
obj == self._control.viewport() and \
self._filter_drag:
cursor = self._control.textCursor()
cursor.clearSelection()
self._control.setTextCursor(cursor)
self._filter_drag = False
# Ensure that drops are safe.
elif etype == QtCore.QEvent.Drop and obj == self._control.viewport():
cursor = self._control.cursorForPosition(event.pos())
if self._in_buffer(cursor.position()):
text = unicode(event.mimeData().text())
self._insert_plain_text_into_buffer(cursor, text)
# Qt is expecting to get something here--drag and drop occurs in its
# own event loop. Send a DragLeave event to end it.
QtGui.qApp.sendEvent(obj, QtGui.QDragLeaveEvent())
return True
return super(ConsoleWidget, self).eventFilter(obj, event)
#---------------------------------------------------------------------------
# 'QWidget' interface
#---------------------------------------------------------------------------
def sizeHint(self):
""" Reimplemented to suggest a size that is 80 characters wide and
25 lines high.
"""
font_metrics = QtGui.QFontMetrics(self.font)
margin = (self._control.frameWidth() +
self._control.document().documentMargin()) * 2
style = self.style()
splitwidth = style.pixelMetric(QtGui.QStyle.PM_SplitterWidth)
# Note 1: Despite my best efforts to take the various margins into
# account, the width is still coming out a bit too small, so we include
# a fudge factor of one character here.
# Note 2: QFontMetrics.maxWidth is not used here or anywhere else due
# to a Qt bug on certain Mac OS systems where it returns 0.
width = font_metrics.width(' ') * 81 + margin
width += style.pixelMetric(QtGui.QStyle.PM_ScrollBarExtent)
if self.paging == 'hsplit':
width = width * 2 + splitwidth
height = font_metrics.height() * 25 + margin
if self.paging == 'vsplit':
height = height * 2 + splitwidth
return QtCore.QSize(width, height)
#---------------------------------------------------------------------------
# 'ConsoleWidget' public interface
#---------------------------------------------------------------------------
def can_copy(self):
""" Returns whether text can be copied to the clipboard.
"""
return self._control.textCursor().hasSelection()
def can_cut(self):
""" Returns whether text can be cut to the clipboard.
"""
cursor = self._control.textCursor()
return (cursor.hasSelection() and
self._in_buffer(cursor.anchor()) and
self._in_buffer(cursor.position()))
def can_paste(self):
""" Returns whether text can be pasted from the clipboard.
"""
if self._control.textInteractionFlags() & QtCore.Qt.TextEditable:
return not QtGui.QApplication.clipboard().text().isEmpty()
return False
def clear(self, keep_input=True):
""" Clear the console.
Parameters:
-----------
keep_input : bool, optional (default True)
If set, restores the old input buffer if a new prompt is written.
"""
if self._executing:
self._control.clear()
else:
if keep_input:
input_buffer = self.input_buffer
self._control.clear()
self._show_prompt()
if keep_input:
self.input_buffer = input_buffer
def copy(self):
""" Copy the currently selected text to the clipboard.
"""
self._control.copy()
def cut(self):
""" Copy the currently selected text to the clipboard and delete it
if it's inside the input buffer.
"""
self.copy()
if self.can_cut():
self._control.textCursor().removeSelectedText()
def execute(self, source=None, hidden=False, interactive=False):
""" Executes source or the input buffer, possibly prompting for more
input.
Parameters:
-----------
source : str, optional
The source to execute. If not specified, the input buffer will be
used. If specified and 'hidden' is False, the input buffer will be
replaced with the source before execution.
hidden : bool, optional (default False)
If set, no output will be shown and the prompt will not be modified.
In other words, it will be completely invisible to the user that
an execution has occurred.
interactive : bool, optional (default False)
Whether the console is to treat the source as having been manually
entered by the user. The effect of this parameter depends on the
subclass implementation.
Raises:
-------
RuntimeError
If incomplete input is given and 'hidden' is True. In this case,
it is not possible to prompt for more input.
Returns:
--------
A boolean indicating whether the source was executed.
"""
# WARNING: The order in which things happen here is very particular, in
# large part because our syntax highlighting is fragile. If you change
# something, test carefully!
# Decide what to execute.
if source is None:
source = self.input_buffer
if not hidden:
# A newline is appended later, but it should be considered part
# of the input buffer.
source += '\n'
elif not hidden:
self.input_buffer = source
# Execute the source or show a continuation prompt if it is incomplete.
complete = self._is_complete(source, interactive)
if hidden:
if complete:
self._execute(source, hidden)
else:
error = 'Incomplete noninteractive input: "%s"'
raise RuntimeError(error % source)
else:
if complete:
self._append_plain_text('\n')
self._executing_input_buffer = self.input_buffer
self._executing = True
self._prompt_finished()
# The maximum block count is only in effect during execution.
# This ensures that _prompt_pos does not become invalid due to
# text truncation.
self._control.document().setMaximumBlockCount(self.buffer_size)
# Setting a positive maximum block count will automatically
# disable the undo/redo history, but just to be safe:
self._control.setUndoRedoEnabled(False)
# Perform actual execution.
self._execute(source, hidden)
else:
# Do this inside an edit block so continuation prompts are
# removed seamlessly via undo/redo.
cursor = self._get_end_cursor()
cursor.beginEditBlock()
cursor.insertText('\n')
self._insert_continuation_prompt(cursor)
cursor.endEditBlock()
# Do not do this inside the edit block. It works as expected
# when using a QPlainTextEdit control, but does not have an
# effect when using a QTextEdit. I believe this is a Qt bug.
self._control.moveCursor(QtGui.QTextCursor.End)
return complete
def _get_input_buffer(self):
""" The text that the user has entered entered at the current prompt.
"""
# If we're executing, the input buffer may not even exist anymore due to
# the limit imposed by 'buffer_size'. Therefore, we store it.
if self._executing:
return self._executing_input_buffer
cursor = self._get_end_cursor()
cursor.setPosition(self._prompt_pos, QtGui.QTextCursor.KeepAnchor)
input_buffer = unicode(cursor.selection().toPlainText())
# Strip out continuation prompts.
return input_buffer.replace('\n' + self._continuation_prompt, '\n')
def _set_input_buffer(self, string):
""" Replaces the text in the input buffer with 'string'.
"""
# For now, it is an error to modify the input buffer during execution.
if self._executing:
raise RuntimeError("Cannot change input buffer during execution.")
# Remove old text.
cursor = self._get_end_cursor()
cursor.beginEditBlock()
cursor.setPosition(self._prompt_pos, QtGui.QTextCursor.KeepAnchor)
cursor.removeSelectedText()
# Insert new text with continuation prompts.
self._insert_plain_text_into_buffer(self._get_prompt_cursor(), string)
cursor.endEditBlock()
self._control.moveCursor(QtGui.QTextCursor.End)
input_buffer = property(_get_input_buffer, _set_input_buffer)
def _get_font(self):
""" The base font being used by the ConsoleWidget.
"""
return self._control.document().defaultFont()
def _set_font(self, font):
""" Sets the base font for the ConsoleWidget to the specified QFont.
"""
font_metrics = QtGui.QFontMetrics(font)
self._control.setTabStopWidth(self.tab_width * font_metrics.width(' '))
self._completion_widget.setFont(font)
self._control.document().setDefaultFont(font)
if self._page_control:
self._page_control.document().setDefaultFont(font)
self.font_changed.emit(font)
font = property(_get_font, _set_font)
def paste(self, mode=QtGui.QClipboard.Clipboard):
""" Paste the contents of the clipboard into the input region.
Parameters:
-----------
mode : QClipboard::Mode, optional [default QClipboard::Clipboard]
Controls which part of the system clipboard is used. This can be
used to access the selection clipboard in X11 and the Find buffer
in Mac OS. By default, the regular clipboard is used.
"""
if self._control.textInteractionFlags() & QtCore.Qt.TextEditable:
# Make sure the paste is safe.
self._keep_cursor_in_buffer()
cursor = self._control.textCursor()
# Remove any trailing newline, which confuses the GUI and forces the
# user to backspace.
text = unicode(QtGui.QApplication.clipboard().text(mode)).rstrip()
self._insert_plain_text_into_buffer(cursor, dedent(text))
def print_(self, printer = None):
""" Print the contents of the ConsoleWidget to the specified QPrinter.
"""
if(printer is None):
printer = QtGui.QPrinter()
if(QtGui.QPrintDialog(printer).exec_() != QtGui.QDialog.Accepted):
return
self._control.print_(printer)
def export_html_inline(self, parent = None):
""" Export the contents of the ConsoleWidget as HTML with inline PNGs.
"""
self.export_html(parent, inline = True)
def export_html(self, parent = None, inline = False):
""" Export the contents of the ConsoleWidget as HTML.
Parameters:
-----------
inline : bool, optional [default True]
If True, include images as inline PNGs. Otherwise,
include them as links to external PNG files, mimicking
Firefox's "Web Page, complete" behavior.
"""
dialog = QtGui.QFileDialog(parent, 'Save HTML Document')
dialog.setAcceptMode(QtGui.QFileDialog.AcceptSave)
dialog.setDefaultSuffix('htm')
dialog.setNameFilter('HTML document (*.htm)')
if dialog.exec_():
filename = str(dialog.selectedFiles()[0])
if(inline):
path = None
else:
offset = filename.rfind(".")
if(offset > 0):
path = filename[:offset]+"_files"
else:
path = filename+"_files"
import os
try:
os.mkdir(path)
except OSError:
# TODO: check that this is an "already exists" error
pass
f = open(filename, 'w')
try:
# N.B. this is overly restrictive, but Qt's output is
# predictable...
img_re = re.compile(r'<img src="(?P<name>[\d]+)" />')
html = self.fix_html_encoding(
str(self._control.toHtml().toUtf8()))
f.write(img_re.sub(
lambda x: self.image_tag(x, path = path, format = "png"),
html))
finally:
f.close()
return filename
return None
def export_xhtml(self, parent = None):
""" Export the contents of the ConsoleWidget as XHTML with inline SVGs.
"""
dialog = QtGui.QFileDialog(parent, 'Save XHTML Document')
dialog.setAcceptMode(QtGui.QFileDialog.AcceptSave)
dialog.setDefaultSuffix('xml')
dialog.setNameFilter('XHTML document (*.xml)')
if dialog.exec_():
filename = str(dialog.selectedFiles()[0])
f = open(filename, 'w')
try:
# N.B. this is overly restrictive, but Qt's output is
# predictable...
img_re = re.compile(r'<img src="(?P<name>[\d]+)" />')
html = str(self._control.toHtml().toUtf8())
# Hack to make xhtml header -- note that we are not doing
# any check for valid xml
offset = html.find("<html>")
assert(offset > -1)
html = ('<html xmlns="http://www.w3.org/1999/xhtml">\n'+
html[offset+6:])
# And now declare UTF-8 encoding
html = self.fix_html_encoding(html)
f.write(img_re.sub(
lambda x: self.image_tag(x, path = None, format = "svg"),
html))
finally:
f.close()
return filename
return None
def fix_html_encoding(self, html):
""" Return html string, with a UTF-8 declaration added to <HEAD>.
Assumes that html is Qt generated and has already been UTF-8 encoded
and coerced to a python string. If the expected head element is
not found, the given object is returned unmodified.
This patching is needed for proper rendering of some characters
(e.g., indented commands) when viewing exported HTML on a local
system (i.e., without seeing an encoding declaration in an HTTP
header).
C.f. http://www.w3.org/International/O-charset for details.
"""
offset = html.find("<head>")
if(offset > -1):
html = (html[:offset+6]+
'\n<meta http-equiv="Content-Type" '+
'content="text/html; charset=utf-8" />\n'+
html[offset+6:])
return html
def image_tag(self, match, path = None, format = "png"):
""" Return (X)HTML mark-up for the image-tag given by match.
Parameters
----------
match : re.SRE_Match
A match to an HTML image tag as exported by Qt, with
match.group("Name") containing the matched image ID.
path : string|None, optional [default None]
If not None, specifies a path to which supporting files
may be written (e.g., for linked images).
If None, all images are to be included inline.
format : "png"|"svg", optional [default "png"]
Format for returned or referenced images.
Subclasses supporting image display should override this
method.
"""
# Default case -- not enough information to generate tag
return ""
def prompt_to_top(self):
""" Moves the prompt to the top of the viewport.
"""
if not self._executing:
prompt_cursor = self._get_prompt_cursor()
if self._get_cursor().blockNumber() < prompt_cursor.blockNumber():
self._set_cursor(prompt_cursor)
self._set_top_cursor(prompt_cursor)
def redo(self):
""" Redo the last operation. If there is no operation to redo, nothing
happens.
"""
self._control.redo()
def reset_font(self):
""" Sets the font to the default fixed-width font for this platform.
"""
if sys.platform == 'win32':
# Consolas ships with Vista/Win7, fallback to Courier if needed
family, fallback = 'Consolas', 'Courier'
elif sys.platform == 'darwin':
# OSX always has Monaco, no need for a fallback
family, fallback = 'Monaco', None
else:
# FIXME: remove Consolas as a default on Linux once our font
# selections are configurable by the user.
family, fallback = 'Consolas', 'Monospace'
font = get_font(family, fallback)
font.setPointSize(QtGui.qApp.font().pointSize())
font.setStyleHint(QtGui.QFont.TypeWriter)
self._set_font(font)
def change_font_size(self, delta):
"""Change the font size by the specified amount (in points).
"""
font = self.font
font.setPointSize(font.pointSize() + delta)
self._set_font(font)
def select_all(self):
""" Selects all the text in the buffer.
"""
self._control.selectAll()
def _get_tab_width(self):
""" The width (in terms of space characters) for tab characters.
"""
return self._tab_width
def _set_tab_width(self, tab_width):
""" Sets the width (in terms of space characters) for tab characters.
"""
font_metrics = QtGui.QFontMetrics(self.font)
self._control.setTabStopWidth(tab_width * font_metrics.width(' '))
self._tab_width = tab_width
tab_width = property(_get_tab_width, _set_tab_width)
def undo(self):
""" Undo the last operation. If there is no operation to undo, nothing
happens.
"""
self._control.undo()
#---------------------------------------------------------------------------
# 'ConsoleWidget' abstract interface
#---------------------------------------------------------------------------
def _is_complete(self, source, interactive):
""" Returns whether 'source' can be executed. When triggered by an
Enter/Return key press, 'interactive' is True; otherwise, it is
False.
"""
raise NotImplementedError
def _execute(self, source, hidden):
""" Execute 'source'. If 'hidden', do not show any output.
"""
raise NotImplementedError
def _prompt_started_hook(self):
""" Called immediately after a new prompt is displayed.
"""
pass
def _prompt_finished_hook(self):
""" Called immediately after a prompt is finished, i.e. when some input
will be processed and a new prompt displayed.
"""
pass
def _up_pressed(self):
""" Called when the up key is pressed. Returns whether to continue
processing the event.
"""
return True
def _down_pressed(self):
""" Called when the down key is pressed. Returns whether to continue
processing the event.
"""
return True
def _tab_pressed(self):
""" Called when the tab key is pressed. Returns whether to continue
processing the event.
"""
return False
#--------------------------------------------------------------------------
# 'ConsoleWidget' protected interface
#--------------------------------------------------------------------------
def _append_html(self, html):
""" Appends html at the end of the console buffer.
"""
cursor = self._get_end_cursor()
self._insert_html(cursor, html)
def _append_html_fetching_plain_text(self, html):
""" Appends 'html', then returns the plain text version of it.
"""
cursor = self._get_end_cursor()
return self._insert_html_fetching_plain_text(cursor, html)
def _append_plain_text(self, text):
""" Appends plain text at the end of the console buffer, processing
ANSI codes if enabled.
"""
cursor = self._get_end_cursor()
self._insert_plain_text(cursor, text)
def _append_plain_text_keeping_prompt(self, text):
""" Writes 'text' after the current prompt, then restores the old prompt
with its old input buffer.
"""
input_buffer = self.input_buffer
self._append_plain_text('\n')
self._prompt_finished()
self._append_plain_text(text)
self._show_prompt()
self.input_buffer = input_buffer
def _cancel_text_completion(self):
""" If text completion is progress, cancel it.
"""
if self._text_completing_pos:
self._clear_temporary_buffer()
self._text_completing_pos = 0
def _clear_temporary_buffer(self):
""" Clears the "temporary text" buffer, i.e. all the text following
the prompt region.
"""
# Select and remove all text below the input buffer.
cursor = self._get_prompt_cursor()
prompt = self._continuation_prompt.lstrip()
while cursor.movePosition(QtGui.QTextCursor.NextBlock):
temp_cursor = QtGui.QTextCursor(cursor)
temp_cursor.select(QtGui.QTextCursor.BlockUnderCursor)
text = unicode(temp_cursor.selection().toPlainText()).lstrip()
if not text.startswith(prompt):
break
else:
# We've reached the end of the input buffer and no text follows.
return
cursor.movePosition(QtGui.QTextCursor.Left) # Grab the newline.
cursor.movePosition(QtGui.QTextCursor.End,
QtGui.QTextCursor.KeepAnchor)
cursor.removeSelectedText()
# After doing this, we have no choice but to clear the undo/redo
# history. Otherwise, the text is not "temporary" at all, because it
# can be recalled with undo/redo. Unfortunately, Qt does not expose
# fine-grained control to the undo/redo system.
if self._control.isUndoRedoEnabled():
self._control.setUndoRedoEnabled(False)
self._control.setUndoRedoEnabled(True)
def _complete_with_items(self, cursor, items):
""" Performs completion with 'items' at the specified cursor location.
"""
self._cancel_text_completion()
if len(items) == 1:
cursor.setPosition(self._control.textCursor().position(),
QtGui.QTextCursor.KeepAnchor)
cursor.insertText(items[0])
elif len(items) > 1:
current_pos = self._control.textCursor().position()
prefix = commonprefix(items)
if prefix:
cursor.setPosition(current_pos, QtGui.QTextCursor.KeepAnchor)
cursor.insertText(prefix)
current_pos = cursor.position()
if self.gui_completion:
cursor.movePosition(QtGui.QTextCursor.Left, n=len(prefix))
self._completion_widget.show_items(cursor, items)
else:
cursor.beginEditBlock()
self._append_plain_text('\n')
self._page(self._format_as_columns(items))
cursor.endEditBlock()
cursor.setPosition(current_pos)
self._control.moveCursor(QtGui.QTextCursor.End)
self._control.setTextCursor(cursor)
self._text_completing_pos = current_pos
def _context_menu_make(self, pos):
""" Creates a context menu for the given QPoint (in widget coordinates).
"""
menu = QtGui.QMenu()
cut_action = menu.addAction('Cut', self.cut)
cut_action.setEnabled(self.can_cut())
cut_action.setShortcut(QtGui.QKeySequence.Cut)
copy_action = menu.addAction('Copy', self.copy)
copy_action.setEnabled(self.can_copy())
copy_action.setShortcut(QtGui.QKeySequence.Copy)
paste_action = menu.addAction('Paste', self.paste)
paste_action.setEnabled(self.can_paste())
paste_action.setShortcut(QtGui.QKeySequence.Paste)
menu.addSeparator()
menu.addAction('Select All', self.select_all)
menu.addSeparator()
print_action = menu.addAction('Print', self.print_)
print_action.setEnabled(True)
html_action = menu.addAction('Export HTML (external PNGs)',
self.export_html)
html_action.setEnabled(True)
html_inline_action = menu.addAction('Export HTML (inline PNGs)',
self.export_html_inline)
html_inline_action.setEnabled(True)
xhtml_action = menu.addAction('Export XHTML (inline SVGs)',
self.export_xhtml)
xhtml_action.setEnabled(True)
return menu
def _control_key_down(self, modifiers, include_command=True):
""" Given a KeyboardModifiers flags object, return whether the Control
key is down.
Parameters:
-----------
include_command : bool, optional (default True)
Whether to treat the Command key as a (mutually exclusive) synonym
for Control when in Mac OS.
"""
# Note that on Mac OS, ControlModifier corresponds to the Command key
# while MetaModifier corresponds to the Control key.
if sys.platform == 'darwin':
down = include_command and (modifiers & QtCore.Qt.ControlModifier)
return bool(down) ^ bool(modifiers & QtCore.Qt.MetaModifier)
else:
return bool(modifiers & QtCore.Qt.ControlModifier)
def _create_control(self):
""" Creates and connects the underlying text widget.
"""
# Create the underlying control.
if self.kind == 'plain':
control = QtGui.QPlainTextEdit()
elif self.kind == 'rich':
control = QtGui.QTextEdit()
control.setAcceptRichText(False)
# Install event filters. The filter on the viewport is needed for
# mouse events and drag events.
control.installEventFilter(self)
control.viewport().installEventFilter(self)
# Connect signals.
control.cursorPositionChanged.connect(self._cursor_position_changed)
control.customContextMenuRequested.connect(
self._custom_context_menu_requested)
control.copyAvailable.connect(self.copy_available)
control.redoAvailable.connect(self.redo_available)
control.undoAvailable.connect(self.undo_available)
# Hijack the document size change signal to prevent Qt from adjusting
# the viewport's scrollbar. We are relying on an implementation detail
# of Q(Plain)TextEdit here, which is potentially dangerous, but without
# this functionality we cannot create a nice terminal interface.
layout = control.document().documentLayout()
layout.documentSizeChanged.disconnect()
layout.documentSizeChanged.connect(self._adjust_scrollbars)
# Configure the control.
control.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
control.setReadOnly(True)
control.setUndoRedoEnabled(False)
control.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
return control
def _create_page_control(self):
""" Creates and connects the underlying paging widget.
"""
if self.kind == 'plain':
control = QtGui.QPlainTextEdit()
elif self.kind == 'rich':
control = QtGui.QTextEdit()
control.installEventFilter(self)
control.setReadOnly(True)
control.setUndoRedoEnabled(False)
control.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
return control
def _event_filter_console_keypress(self, event):
""" Filter key events for the underlying text widget to create a
console-like interface.
"""
intercepted = False
cursor = self._control.textCursor()
position = cursor.position()
key = event.key()
ctrl_down = self._control_key_down(event.modifiers())
alt_down = event.modifiers() & QtCore.Qt.AltModifier
shift_down = event.modifiers() & QtCore.Qt.ShiftModifier
#------ Special sequences ----------------------------------------------
if event.matches(QtGui.QKeySequence.Copy):
self.copy()
intercepted = True
elif event.matches(QtGui.QKeySequence.Cut):
self.cut()
intercepted = True
elif event.matches(QtGui.QKeySequence.Paste):
self.paste()
intercepted = True
#------ Special modifier logic -----------------------------------------
elif key in (QtCore.Qt.Key_Return, QtCore.Qt.Key_Enter):
intercepted = True
# Special handling when tab completing in text mode.
self._cancel_text_completion()
if self._in_buffer(position):
if self._reading:
self._append_plain_text('\n')
self._reading = False
if self._reading_callback:
self._reading_callback()
# If the input buffer is a single line or there is only
# whitespace after the cursor, execute. Otherwise, split the
# line with a continuation prompt.