-
Notifications
You must be signed in to change notification settings - Fork 259
/
terminal.py
2174 lines (1810 loc) · 81.9 KB
/
terminal.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
# Terminator by Chris Jones <[email protected]>
# GPL v2 only
"""terminal.py - classes necessary to provide Terminal widgets"""
import os
import signal
import gi
from gi.repository import GLib, GObject, Pango, Gtk, Gdk, GdkPixbuf, cairo
gi.require_version('Vte', '2.91') # vte-0.38 (gnome-3.14)
from gi.repository import Vte
import subprocess
try:
from urllib.parse import unquote as urlunquote
except ImportError:
from urllib import unquote as urlunquote
from .util import dbg, err, spawn_new_terminator, make_uuid, manual_lookup
from . import util
from .config import Config
from .cwd import get_pid_cwd
from .factory import Factory
from .terminator import Terminator
from .titlebar import Titlebar
from .terminal_popup_menu import TerminalPopupMenu
from .prefseditor import PrefsEditor
from .searchbar import Searchbar
from .translation import _
from .signalman import Signalman
from . import plugin
from terminatorlib.layoutlauncher import LayoutLauncher
from . import regex
# pylint: disable-msg=R0904
class Terminal(Gtk.VBox):
"""Class implementing the VTE widget and its wrappings"""
__gsignals__ = {
'pre-close-term': (GObject.SignalFlags.RUN_LAST, None, ()),
'close-term': (GObject.SignalFlags.RUN_LAST, None, ()),
'title-change': (GObject.SignalFlags.RUN_LAST, None,
(GObject.TYPE_STRING,)),
'insert-term-name': (GObject.SignalFlags.RUN_LAST, None, ()),
'enumerate': (GObject.SignalFlags.RUN_LAST, None,
(GObject.TYPE_INT,)),
'group-tab': (GObject.SignalFlags.RUN_LAST, None, ()),
'group-tab-toggle': (GObject.SignalFlags.RUN_LAST, None, ()),
'ungroup-tab': (GObject.SignalFlags.RUN_LAST, None, ()),
'ungroup-all': (GObject.SignalFlags.RUN_LAST, None, ()),
'split-auto': (GObject.SignalFlags.RUN_LAST, None,
(GObject.TYPE_STRING,)),
'split-horiz': (GObject.SignalFlags.RUN_LAST, None,
(GObject.TYPE_STRING,)),
'split-vert': (GObject.SignalFlags.RUN_LAST, None,
(GObject.TYPE_STRING,)),
'rotate-cw': (GObject.SignalFlags.RUN_LAST, None, ()),
'rotate-ccw': (GObject.SignalFlags.RUN_LAST, None, ()),
'tab-new': (GObject.SignalFlags.RUN_LAST, None,
(GObject.TYPE_BOOLEAN, GObject.TYPE_OBJECT)),
'tab-top-new': (GObject.SignalFlags.RUN_LAST, None, ()),
'focus-in': (GObject.SignalFlags.RUN_LAST, None, ()),
'focus-out': (GObject.SignalFlags.RUN_LAST, None, ()),
'zoom': (GObject.SignalFlags.RUN_LAST, None, ()),
'maximise': (GObject.SignalFlags.RUN_LAST, None, ()),
'unzoom': (GObject.SignalFlags.RUN_LAST, None, ()),
'resize-term': (GObject.SignalFlags.RUN_LAST, None,
(GObject.TYPE_STRING,)),
'navigate': (GObject.SignalFlags.RUN_LAST, None,
(GObject.TYPE_STRING,)),
'tab-change': (GObject.SignalFlags.RUN_LAST, None,
(GObject.TYPE_INT,)),
'group-all': (GObject.SignalFlags.RUN_LAST, None, ()),
'group-all-toggle': (GObject.SignalFlags.RUN_LAST, None, ()),
'move-tab': (GObject.SignalFlags.RUN_LAST, None,
(GObject.TYPE_STRING,)),
'group-win': (GObject.SignalFlags.RUN_LAST, None, ()),
'group-win-toggle': (GObject.SignalFlags.RUN_LAST, None, ()),
'ungroup-win': (GObject.SignalFlags.RUN_LAST, None, ()),
}
TARGET_TYPE_VTE = 8
TARGET_TYPE_MOZ = 9
MOUSEBUTTON_LEFT = 1
MOUSEBUTTON_MIDDLE = 2
MOUSEBUTTON_RIGHT = 3
terminator = None
vte = None
terminalbox = None
scrollbar = None
titlebar = None
searchbar = None
group = None
cwd = None
origcwd = None
command = None
clipboard = None
pid = None
matches = None
regex_flags = None
config = None
custom_font_size = None
layout_command = None
relaunch_command = None
directory = None
is_held_open = False
fgcolor_active = None
fgcolor_inactive = None
bgcolor = None
bgcolor_inactive = None
palette_active = None
palette_inactive = None
composite_support = None
cnxids = None
targets_for_new_group = None
def __init__(self):
"""Class initialiser"""
GObject.GObject.__init__(self)
self.terminator = Terminator()
self.terminator.register_terminal(self)
# FIXME: Surely these should happen in Terminator::register_terminal()?
self.connect('enumerate', self.terminator.do_enumerate)
self.connect('insert-term-name', self.terminator.do_insert_term_name)
self.connect('focus-in', self.terminator.focus_changed)
self.connect('focus-out', self.terminator.focus_left)
self.matches = {}
self.cnxids = Signalman()
self.config = Config()
self.cwd = get_pid_cwd()
self.origcwd = self.terminator.origcwd
self.clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
self.pending_on_vte_size_allocate = False
self.vte = Vte.Terminal()
self.vte.set_allow_hyperlink(True)
self.vte._draw_data = None
if not hasattr(self.vte, "set_opacity") or \
not hasattr(self.vte, "is_composited"):
self.composite_support = False
else:
self.composite_support = True
dbg('composite_support: %s' % self.composite_support)
if hasattr(self.vte, "set_enable_sixel"):
self.vte.set_enable_sixel(True)
self.vte.show()
#force to load for new window/terminal use case loading plugin
#and connecting signals, note the line update_url_matches also
#calls load_plugins, but it won't reload since already loaded
self.load_plugins(force = True)
self.update_url_matches()
self.terminalbox = self.create_terminalbox()
self.titlebar = Titlebar(self)
self.titlebar.connect_icon(self.on_group_button_press)
self.titlebar.connect('edit-done', self.on_edit_done)
self.connect('title-change', self.titlebar.set_terminal_title)
self.titlebar.connect('create-group', self.really_create_group)
self.titlebar.update('window-focus-out')
self.titlebar.show_all()
self.searchbar = Searchbar()
self.searchbar.connect('end-search', self.on_search_done)
self.show()
if self.config['title_at_bottom']:
self.pack_start(self.terminalbox, True, True, 0)
self.pack_start(self.titlebar, False, True, 0)
else:
self.pack_start(self.titlebar, False, True, 0)
self.pack_start(self.terminalbox, True, True, 0)
self.pack_end(self.searchbar, True, True, 0)
self.connect_signals()
os.putenv('TERM', self.config['term'])
os.putenv('COLORTERM', self.config['colorterm'])
env_proxy = os.getenv('http_proxy')
if not env_proxy:
if self.config['http_proxy'] and self.config['http_proxy'] != '':
os.putenv('http_proxy', self.config['http_proxy'])
self.reconfigure()
self.vte.set_size(80, 24)
def set_background_image(self,image):
try:
bg_pixbuf = GdkPixbuf.Pixbuf.new_from_file(image)
self.background_image = Gdk.cairo_surface_create_from_pixbuf(bg_pixbuf, 1, None)
self.vte.set_clear_background(False)
self.vte.connect("draw", self.background_draw)
except Exception as e:
self.background_image = None
self.vte.set_clear_background(True)
err('error loading background image: %s, %s' % (type(e).__name__,e))
def get_vte(self):
"""This simply returns the vte widget we are using"""
return(self.vte)
def force_set_profile(self, widget, profile):
"""Forcibly set our profile"""
self.set_profile(widget, profile, True)
def set_profile(self, _widget, profile, force=False):
"""Set our profile"""
if profile != self.config.get_profile():
self.config.set_profile(profile, force)
self.reconfigure()
def get_profile(self):
"""Return our profile name"""
return(self.config.profile)
def switch_to_next_profile(self):
profilelist = self.config.list_profiles()
list_length = len(profilelist)
if list_length > 1:
if profilelist.index(self.get_profile()) + 1 == list_length:
self.force_set_profile(False, profilelist[0])
else:
self.force_set_profile(False, profilelist[profilelist.index(self.get_profile()) + 1])
def switch_to_previous_profile(self):
profilelist = self.config.list_profiles()
list_length = len(profilelist)
if list_length > 1:
if profilelist.index(self.get_profile()) == 0:
self.force_set_profile(False, profilelist[list_length - 1])
else:
self.force_set_profile(False, profilelist[profilelist.index(self.get_profile()) - 1])
def get_cwd(self):
"""Return our cwd"""
vte_cwd = self.vte.get_current_directory_uri()
if vte_cwd:
# OSC7 pwd gives an answer
return(GLib.filename_from_uri(vte_cwd)[0])
else:
# Fall back to old gtk2 method
dbg('calling get_pid_cwd')
return(get_pid_cwd(self.pid))
def close(self):
"""Close ourselves"""
dbg('close: called')
self.cnxids.remove_widget(self.vte)
self.emit('close-term')
if self.pid is not None:
try:
dbg('close: killing %d' % self.pid)
os.kill(self.pid, signal.SIGHUP)
except Exception as ex:
# We really don't want to care if this failed. Deep OS voodoo is
# not what we should be doing.
dbg('os.kill failed: %s' % ex)
pass
if self.vte:
self.terminalbox.remove(self.vte)
del(self.vte)
def create_terminalbox(self):
"""Create a GtkHBox containing the terminal and a scrollbar"""
terminalbox = Gtk.Box.new(Gtk.Orientation.HORIZONTAL, 0)
self.scrollbar = Gtk.Scrollbar.new(Gtk.Orientation.VERTICAL, adjustment=self.vte.get_vadjustment())
self.scrollbar.set_no_show_all(True)
terminalbox.pack_start(self.vte, True, True, 0)
terminalbox.pack_start(self.scrollbar, False, True, 0)
terminalbox.show_all()
return(terminalbox)
def load_plugins(self, force = False):
registry = plugin.PluginRegistry()
registry.load_plugins(force)
def _add_regex(self, name, re):
dbg(f"adding regex: {re}")
match = -1
if regex.FLAGS_PCRE2:
try:
reg = Vte.Regex.new_for_match(re, len(re), self.regex_flags or regex.FLAGS_PCRE2)
match = self.vte.match_add_regex(reg, 0)
except GLib.Error:
# happens when PCRE2 support is not builtin (Ubuntu < 19.10)
pass
# try the "old" glib regex
if match < 0:
reg = GLib.Regex.new(re, self.regex_flags or regex.FLAGS_GLIB, 0)
match = self.vte.match_add_gregex(reg, 0)
self.matches[name] = match
self.vte.match_set_cursor_name(self.matches[name], 'pointer')
def update_url_matches(self):
"""Update the regexps used to match URLs"""
userchars = "-A-Za-z0-9"
passchars = "-A-Za-z0-9,?;.:/!%$^*&~\"#'"
hostchars = r"-A-Za-z0-9:\[\]"
pathchars = "-A-Za-z0-9_$.+!*(),;:@&=?/~#%'"
schemes = "(news:|telnet:|nntp:|https?:|ftps?:|webcal:|ssh:)"
user = "[" + userchars + "]+(:[" + passchars + "]+)?"
urlpath = "/[" + pathchars + "]*[^]'.}>) \t\r\n,\\\"]"
lboundry = "\\b"
rboundry = "\\b"
re = (lboundry + "file:/" + "//?(:[0-9]+)?(" + urlpath + ")" +
rboundry + "/?")
self._add_regex('file', re)
re = (lboundry + schemes +
"//(" + user + "@)?[" + hostchars +".]+(:[0-9]+)?(" +
urlpath + ")?" + rboundry + "/?")
self._add_regex('full_uri', re)
if self.matches['full_uri'] == -1 or self.matches['file'] == -1:
err ('Terminal::update_url_matches: Failed adding URL matches')
else:
re = (lboundry +
'(callto:|h323:|sip:)' + "[" + userchars + "+][" +
userchars + ".]*(:[0-9]+)?@?[" + pathchars + "]+" +
rboundry)
self._add_regex('voip', re)
re = (lboundry +
"(www|ftp)[" + hostchars + r"]*\.[" + hostchars +
".]+(:[0-9]+)?(" + urlpath + ")?" + rboundry + "/?")
self._add_regex('addr_only', re)
re = (lboundry +
"(mailto:)?[a-zA-Z0-9][a-zA-Z0-9.+-]*@[a-zA-Z0-9]" +
r"[a-zA-Z0-9-]*\.[a-zA-Z0-9][a-zA-Z0-9-]+" +
"[.a-zA-Z0-9-]*" + rboundry)
self._add_regex('email', re)
re = (lboundry +
r"""news:[-A-Z\^_a-z{|}~!"#$%&'()*+,./0-9;:=?`]+@""" +
"[-A-Za-z0-9.]+(:[0-9]+)?" + rboundry)
self._add_regex('nntp', re)
# Now add any matches from plugins
try:
registry = plugin.PluginRegistry()
registry.load_plugins()
plugins = registry.get_plugins_by_capability('url_handler')
for urlplugin in plugins:
name = urlplugin.handler_name
match = urlplugin.match
if name in self.matches:
dbg('refusing to add duplicate match %s' % name)
continue
self._add_regex(name, match)
dbg('added plugin URL handler for %s (%s) as %d' %
(name, urlplugin.__class__.__name__,
self.matches[name]))
except Exception as ex:
err('Exception occurred adding plugin URL match: %s, %s' % (type(ex).__name__, ex))
def match_add(self, name, match):
"""Register a URL match"""
if name in self.matches:
err('Terminal::match_add: Refusing to create duplicate match %s' % name)
return
self._add_regex(name, match)
def match_remove(self, name):
"""Remove a previously registered URL match"""
if name not in self.matches:
err('Terminal::match_remove: Unable to remove non-existent match %s' % name)
return
self.vte.match_remove(self.matches[name])
del(self.matches[name])
def maybe_copy_clipboard(self):
if self.config['copy_on_selection'] and self.vte.get_has_selection():
self.vte.copy_clipboard()
def connect_signals(self):
"""Connect all the gtk signals and drag-n-drop mechanics"""
self.scrollbar.connect('button-press-event', self.on_buttonpress)
self.cnxids.new(self.vte, 'key-press-event', self.on_keypress)
self.cnxids.new(self.vte, 'button-press-event', self.on_buttonpress)
self.cnxids.new(self.vte, 'scroll-event', self.on_mousewheel)
self.cnxids.new(self.vte, 'popup-menu', self.popup_menu)
srcvtetargets = [("vte", Gtk.TargetFlags.SAME_APP, self.TARGET_TYPE_VTE)]
dsttargets = [("vte", Gtk.TargetFlags.SAME_APP, self.TARGET_TYPE_VTE),
('text/x-moz-url', 0, self.TARGET_TYPE_MOZ),
('_NETSCAPE_URL', 0, 0)]
'''
The following should work, but on my system it corrupts the returned
TargetEntry's in the newdstargets with binary crap, causing "Segmentation
fault (core dumped)" when the later drag_dest_set gets called.
dsttargetlist = Gtk.TargetList.new([])
dsttargetlist.add_text_targets(0)
dsttargetlist.add_uri_targets(0)
dsttargetlist.add_table(dsttargets)
newdsttargets = Gtk.target_table_new_from_list(dsttargetlist)
'''
# FIXME: Temporary workaround for the problems with the correct way of doing things
dsttargets.extend([('text/plain', 0, 0),
('text/plain;charset=utf-8', 0, 0),
('TEXT', 0, 0),
('STRING', 0, 0),
('UTF8_STRING', 0, 0),
('COMPOUND_TEXT', 0, 0),
('text/uri-list', 0, 0)])
# Convert to target entries
srcvtetargets = [Gtk.TargetEntry.new(*tgt) for tgt in srcvtetargets]
dsttargets = [Gtk.TargetEntry.new(*tgt) for tgt in dsttargets]
dbg('Finalised drag targets: %s' % dsttargets)
for (widget, mask) in [
(self.vte, Gdk.ModifierType.CONTROL_MASK | Gdk.ModifierType.BUTTON3_MASK),
(self.titlebar, Gdk.ModifierType.BUTTON1_MASK)]:
widget.drag_source_set(mask, srcvtetargets, Gdk.DragAction.MOVE)
self.vte.drag_dest_set(Gtk.DestDefaults.MOTION |
Gtk.DestDefaults.HIGHLIGHT | Gtk.DestDefaults.DROP,
dsttargets, Gdk.DragAction.COPY | Gdk.DragAction.MOVE)
for widget in [self.vte, self.titlebar]:
self.cnxids.new(widget, 'drag-begin', self.on_drag_begin, self)
self.cnxids.new(widget, 'drag-data-get', self.on_drag_data_get,
self)
self.cnxids.new(self.vte, 'drag-motion', self.on_drag_motion, self)
self.cnxids.new(self.vte, 'drag-data-received',
self.on_drag_data_received, self)
self.cnxids.new(self.vte, 'selection-changed',
lambda widget: self.maybe_copy_clipboard())
if self.composite_support:
self.cnxids.new(self.vte, 'composited-changed', self.reconfigure)
self.cnxids.new(self.vte, 'window-title-changed', lambda x:
self.emit('title-change', self.get_window_title()))
self.cnxids.new(self.vte, 'grab-focus', self.on_vte_focus)
self.cnxids.new(self.vte, 'focus-in-event', self.on_vte_focus_in)
self.cnxids.new(self.vte, 'focus-out-event', self.on_vte_focus_out)
self.cnxids.new(self.vte, 'size-allocate', self.deferred_on_vte_size_allocate)
self.vte.add_events(Gdk.EventMask.ENTER_NOTIFY_MASK)
self.cnxids.new(self.vte, 'enter_notify_event',
self.on_vte_notify_enter)
self.cnxids.new(self.vte, 'realize', self.reconfigure)
def create_popup_group_menu(self, widget, event = None):
"""Pop up a menu for the group widget"""
if event:
button = event.button
time = event.time
else:
button = 0
time = 0
menu = self.populate_group_menu()
menu.show_all()
menu.popup_at_widget(widget,Gdk.Gravity.SOUTH_WEST,Gdk.Gravity.NORTH_WEST,None)
return(True)
def populate_group_menu(self):
"""Fill out a group menu"""
menu = Gtk.Menu()
self.group_menu = menu
groupitems = []
item = Gtk.MenuItem.new_with_mnemonic(_('N_ew group...'))
item.connect('activate', self.create_group)
menu.append(item)
if len(self.terminator.groups) > 0:
cnxs = []
item = Gtk.RadioMenuItem.new_with_mnemonic(groupitems, _('_None'))
groupitems = item.get_group()
item.set_active(self.group == None)
cnxs.append([item, 'toggled', self.set_group, None])
menu.append(item)
for group in self.terminator.groups:
item = Gtk.RadioMenuItem.new_with_label(groupitems, group)
groupitems = item.get_group()
item.set_active(self.group == group)
cnxs.append([item, 'toggled', self.set_group, group])
menu.append(item)
for cnx in cnxs:
cnx[0].connect(cnx[1], cnx[2], cnx[3])
if self.group != None or len(self.terminator.groups) > 0:
menu.append(Gtk.SeparatorMenuItem())
if self.group != None:
item = Gtk.MenuItem(_('Remove group %s') % self.group)
item.connect('activate', self.ungroup, self.group)
menu.append(item)
if util.has_ancestor(self, Gtk.Window):
item = Gtk.MenuItem.new_with_mnemonic(_('G_roup all in window'))
item.connect('activate', lambda x: self.emit('group_win'))
menu.append(item)
if len(self.terminator.groups) > 0:
item = Gtk.MenuItem.new_with_mnemonic(_('Ungro_up all in window'))
item.connect('activate', lambda x: self.emit('ungroup_win'))
menu.append(item)
if util.has_ancestor(self, Gtk.Notebook):
item = Gtk.MenuItem.new_with_mnemonic(_('G_roup all in tab'))
item.connect('activate', lambda x: self.emit('group_tab'))
menu.append(item)
if len(self.terminator.groups) > 0:
item = Gtk.MenuItem.new_with_mnemonic(_('Ungro_up all in tab'))
item.connect('activate', lambda x: self.emit('ungroup_tab'))
menu.append(item)
if len(self.terminator.groups) > 0:
item = Gtk.MenuItem(_('Remove all groups'))
item.connect('activate', lambda x: self.emit('ungroup-all'))
menu.append(item)
if self.group != None:
menu.append(Gtk.SeparatorMenuItem())
item = Gtk.MenuItem(_('Close group %s') % self.group)
item.connect('activate', lambda x:
self.terminator.closegroupedterms(self.group))
menu.append(item)
menu.append(Gtk.SeparatorMenuItem())
groupitems = []
cnxs = []
for key, value in list({_('Broadcast _all'):'all',
_('Broadcast _group'):'group',
_('Broadcast _off'):'off'}.items()):
item = Gtk.RadioMenuItem.new_with_mnemonic(groupitems, key)
groupitems = item.get_group()
dbg('%s active: %s' %
(key, self.terminator.groupsend ==
self.terminator.groupsend_type[value]))
item.set_active(self.terminator.groupsend ==
self.terminator.groupsend_type[value])
cnxs.append([item, 'activate', self.set_groupsend, self.terminator.groupsend_type[value]])
menu.append(item)
for cnx in cnxs:
cnx[0].connect(cnx[1], cnx[2], cnx[3])
menu.append(Gtk.SeparatorMenuItem())
item = Gtk.CheckMenuItem.new_with_mnemonic(_('_Split to this group'))
item.set_active(self.config['split_to_group'])
item.connect('toggled', lambda x: self.do_splittogroup_toggle())
menu.append(item)
item = Gtk.CheckMenuItem.new_with_mnemonic(_('Auto_clean groups'))
item.set_active(self.config['autoclean_groups'])
item.connect('toggled', lambda x: self.do_autocleangroups_toggle())
menu.append(item)
menu.append(Gtk.SeparatorMenuItem())
item = Gtk.MenuItem.new_with_mnemonic(_('_Insert terminal number'))
item.connect('activate', lambda x: self.emit('enumerate', False))
menu.append(item)
item = Gtk.MenuItem.new_with_mnemonic(_('Insert zero _padded terminal number'))
item.connect('activate', lambda x: self.emit('enumerate', True))
menu.append(item)
item = Gtk.MenuItem.new_with_mnemonic(_('Insert terminal _name'))
item.connect('activate', lambda x: self.emit('insert-term-name'))
menu.append(item)
return(menu)
def set_group(self, _item, name):
"""Set a particular group"""
if self.group == name:
# already in this group, no action needed
return
dbg('Setting group to %s' % name)
self.group = name
self.titlebar.set_group_label(name)
self.terminator.group_hoover()
def create_group(self, _item):
"""Trigger the creation of a group via the titlebar (because popup
windows are really lame)"""
self.titlebar.create_group()
def really_create_group(self, _widget, groupname):
"""The titlebar has spoken, let a group be created"""
self.terminator.create_group(groupname)
self.set_group(None, groupname)
def ungroup(self, _widget, data):
"""Remove a group"""
# FIXME: Could we emit and have Terminator do this?
for term in self.terminator.terminals:
if term.group == data:
term.set_group(None, None)
self.terminator.group_hoover()
def set_groupsend(self, _widget, value):
"""Set the groupsend mode"""
# FIXME: Can we think of a smarter way of doing this than poking?
if value in list(self.terminator.groupsend_type.values()):
dbg('setting groupsend to %s' % value)
self.terminator.groupsend = value
def do_splittogroup_toggle(self):
"""Toggle the splittogroup mode"""
self.config['split_to_group'] = not self.config['split_to_group']
def do_autocleangroups_toggle(self):
"""Toggle the autocleangroups mode"""
self.config['autoclean_groups'] = not self.config['autoclean_groups']
def reconfigure(self, _widget=None):
"""Reconfigure our settings"""
dbg('Terminal::reconfigure')
self.cnxids.remove_signal(self.vte, 'realize')
# Handle child command exiting
self.cnxids.remove_signal(self.vte, 'child-exited')
if self.config['exit_action'] == 'restart':
self.cnxids.new(self.vte, 'child-exited', self.spawn_child, True)
elif self.config['exit_action'] == 'hold':
self.cnxids.new(self.vte, 'child-exited', self.held_open, True)
elif self.config['exit_action'] in ('close', 'left'):
self.cnxids.new(self.vte, 'child-exited',
lambda x, y: self.emit('close-term'))
# Word char support was missing from vte 0.38, silently skip this setting
if hasattr(self.vte, 'set_word_char_exceptions'):
self.vte.set_word_char_exceptions(self.config['word_chars'])
self.vte.set_mouse_autohide(self.config['mouse_autohide'])
backspace = self.config['backspace_binding']
delete = self.config['delete_binding']
try:
if backspace == 'ascii-del':
backbind = Vte.ERASE_ASCII_DELETE
elif backspace == 'control-h':
backbind = Vte.ERASE_ASCII_BACKSPACE
elif backspace == 'escape-sequence':
backbind = Vte.ERASE_DELETE_SEQUENCE
else:
backbind = Vte.ERASE_AUTO
except AttributeError:
if backspace == 'ascii-del':
backbind = 2
elif backspace == 'control-h':
backbind = 1
elif backspace == 'escape-sequence':
backbind = 3
else:
backbind = 0
try:
if delete == 'ascii-del':
delbind = Vte.ERASE_ASCII_DELETE
elif delete == 'control-h':
delbind = Vte.ERASE_ASCII_BACKSPACE
elif delete == 'escape-sequence':
delbind = Vte.ERASE_DELETE_SEQUENCE
else:
delbind = Vte.ERASE_AUTO
except AttributeError:
if delete == 'ascii-del':
delbind = 2
elif delete == 'control-h':
delbind = 1
elif delete == 'escape-sequence':
delbind = 3
else:
delbind = 0
self.vte.set_backspace_binding(backbind)
self.vte.set_delete_binding(delbind)
if not self.custom_font_size:
try:
if self.config['use_system_font'] == True:
font = self.config.get_system_mono_font()
else:
font = self.config['font']
self.set_font(Pango.FontDescription(font))
except:
pass
self.vte.set_allow_bold(self.config['allow_bold'])
if hasattr(self.vte,'set_cell_height_scale'):
self.vte.set_cell_height_scale(self.config['cell_height'])
if hasattr(self.vte,'set_cell_width_scale'):
self.vte.set_cell_width_scale(self.config['cell_width'])
if hasattr(self.vte, 'set_bold_is_bright'):
self.vte.set_bold_is_bright(self.config['bold_is_bright'])
if self.config['use_theme_colors']:
self.fgcolor_active = self.vte.get_style_context().get_color(Gtk.StateType.NORMAL) # VERIFY FOR GTK3: do these really take the theme colors?
self.bgcolor = self.vte.get_style_context().get_background_color(Gtk.StateType.NORMAL)
else:
self.fgcolor_active = Gdk.RGBA()
self.fgcolor_active.parse(self.config['foreground_color'])
self.bgcolor = Gdk.RGBA()
self.bgcolor.parse(self.config['background_color'])
if self.config['background_type'] in ('transparent', 'image'):
self.bgcolor.alpha = self.config['background_darkness']
else:
self.bgcolor.alpha = 1
if self.config['background_type'] == 'image' and self.config['background_image'] != '':
self.set_background_image(self.config['background_image'])
else:
self.background_image = None
factor = self.config['inactive_color_offset']
if factor > 1.0:
factor = 1.0
self.fgcolor_inactive = self.fgcolor_active.copy()
dbg(("fgcolor_inactive set to: RGB(%s,%s,%s)", getattr(self.fgcolor_inactive, "red"),
getattr(self.fgcolor_inactive, "green"),
getattr(self.fgcolor_inactive, "blue")))
for bit in ['red', 'green', 'blue']:
setattr(self.fgcolor_inactive, bit,
getattr(self.fgcolor_inactive, bit) * factor)
dbg(("fgcolor_inactive set to: RGB(%s,%s,%s)", getattr(self.fgcolor_inactive, "red"),
getattr(self.fgcolor_inactive, "green"),
getattr(self.fgcolor_inactive, "blue")))
bg_factor = self.config['inactive_bg_color_offset']
if bg_factor > 1.0:
bg_factor = 1.0
self.bgcolor_inactive = self.bgcolor.copy()
dbg(("bgcolor_inactive set to: RGB(%s,%s,%s)", getattr(self.bgcolor_inactive, "red"),
getattr(self.bgcolor_inactive, "green"),
getattr(self.bgcolor_inactive, "blue")))
for bit in ['red', 'green', 'blue']:
setattr(self.bgcolor_inactive, bit,
getattr(self.bgcolor_inactive, bit) * bg_factor)
dbg(("bgcolor_inactive set to: RGB(%s,%s,%s)", getattr(self.bgcolor_inactive, "red"),
getattr(self.bgcolor_inactive, "green"),
getattr(self.bgcolor_inactive, "blue")))
colors = self.config['palette'].split(':')
self.palette_active = []
for color in colors:
if color:
newcolor = Gdk.RGBA()
newcolor.parse(color)
self.palette_active.append(newcolor)
if len(colors) == 16:
# RGB values for indices 16..255 copied from vte source in order to dim them
shades = [0, 95, 135, 175, 215, 255]
for r in range(0, 6):
for g in range(0, 6):
for b in range(0, 6):
newcolor = Gdk.RGBA()
setattr(newcolor, "red", shades[r] / 255.0)
setattr(newcolor, "green", shades[g] / 255.0)
setattr(newcolor, "blue", shades[b] / 255.0)
self.palette_active.append(newcolor)
for y in range(8, 248, 10):
newcolor = Gdk.RGBA()
setattr(newcolor, "red", y / 255.0)
setattr(newcolor, "green", y / 255.0)
setattr(newcolor, "blue", y / 255.0)
self.palette_active.append(newcolor)
self.palette_inactive = []
for color in self.palette_active:
newcolor = Gdk.RGBA()
for bit in ['red', 'green', 'blue']:
setattr(newcolor, bit,
getattr(color, bit) * factor)
self.palette_inactive.append(newcolor)
if self.terminator.last_focused_term == self:
self.vte.set_colors(self.fgcolor_active, self.bgcolor,
self.palette_active)
else:
self.vte.set_colors(self.fgcolor_inactive, self.bgcolor_inactive,
self.palette_inactive)
profiles = self.config.base.profiles
terminal_box_style_context = self.terminalbox.get_style_context()
for profile in list(profiles.keys()):
munged_profile = "terminator-profile-%s" % (
"".join([c if c.isalnum() else "-" for c in profile]))
if terminal_box_style_context.has_class(munged_profile):
terminal_box_style_context.remove_class(munged_profile)
munged_profile = "".join([c if c.isalnum() else "-" for c in self.get_profile()])
css_class_name = "terminator-profile-%s" % (munged_profile)
terminal_box_style_context.add_class(css_class_name)
self.set_cursor_color()
self.vte.set_cursor_shape(getattr(Vte.CursorShape,
self.config['cursor_shape'].upper()));
if self.config['cursor_blink'] == True:
self.vte.set_cursor_blink_mode(Vte.CursorBlinkMode.ON)
else:
self.vte.set_cursor_blink_mode(Vte.CursorBlinkMode.OFF)
if self.config['force_no_bell'] == True:
self.vte.set_audible_bell(False)
self.cnxids.remove_signal(self.vte, 'bell')
else:
self.vte.set_audible_bell(self.config['audible_bell'])
self.cnxids.remove_signal(self.vte, 'bell')
if self.config['urgent_bell'] == True or \
self.config['icon_bell'] == True or \
self.config['visible_bell'] == True:
try:
self.cnxids.new(self.vte, 'bell', self.on_bell)
except TypeError:
err('bell signal unavailable with this version of VTE')
if self.config['scrollback_infinite'] == True:
scrollback_lines = -1
else:
scrollback_lines = self.config['scrollback_lines']
self.vte.set_scrollback_lines(scrollback_lines)
self.vte.set_scroll_on_keystroke(self.config['scroll_on_keystroke'])
self.vte.set_scroll_on_output(self.config['scroll_on_output'])
if self.config['scrollbar_position'] in ['disabled', 'hidden']:
self.scrollbar.hide()
else:
self.scrollbar.show()
if self.config['scrollbar_position'] == 'left':
self.terminalbox.reorder_child(self.scrollbar, 0)
elif self.config['scrollbar_position'] == 'right':
self.terminalbox.reorder_child(self.vte, 0)
self.titlebar.update()
self.vte.queue_draw()
def set_cursor_color(self):
"""Set the cursor color appropriately"""
if self.config['cursor_color_default']:
self.vte.set_color_cursor(None)
self.vte.set_color_cursor_foreground(None)
else:
# foreground
cursor_fg_color = Gdk.RGBA()
if self.config['cursor_fg_color'] == '':
cursor_fg_color.parse(self.config['background_color'])
else:
cursor_fg_color.parse(self.config['cursor_fg_color'])
self.vte.set_color_cursor_foreground(cursor_fg_color)
# background
cursor_bg_color = Gdk.RGBA()
if self.config['cursor_bg_color'] == '':
cursor_bg_color.parse(self.config['foreground_color'])
else:
cursor_bg_color.parse(self.config['cursor_bg_color'])
self.vte.set_color_cursor(cursor_bg_color)
def get_window_title(self):
"""Return the window title"""
return self.vte.get_window_title() or str(self.command)
def on_group_button_press(self, widget, event):
"""Handler for the group button"""
if event.button == 1:
if event.type == Gdk.EventType._2BUTTON_PRESS or \
event.type == Gdk.EventType._3BUTTON_PRESS:
# Ignore these, or they make the interaction bad
return True
# Super key applies interaction to all terms in group
include_siblings=event.get_state() & Gdk.ModifierType.MOD4_MASK == Gdk.ModifierType.MOD4_MASK
if include_siblings:
targets=self.terminator.get_sibling_terms(self)
else:
targets=[self]
if event.get_state() & Gdk.ModifierType.CONTROL_MASK == Gdk.ModifierType.CONTROL_MASK:
dbg('on_group_button_press: toggle terminal to focused terminals group')
focused=self.get_toplevel().get_focussed_terminal()
if focused in targets: targets.remove(focused)
if self != focused:
if focused.group is None and self.group is None:
# Create a new group and assign currently focused
# terminal to this group
new_group = self.terminator.new_random_group()
focused.set_group(None, new_group)
focused.titlebar.update()
elif self.group == focused.group:
new_group = None
else:
new_group = focused.group
[term.set_group(None, new_group) for term in targets]
[term.titlebar.update(focused) for term in targets]
return True
elif event.get_state() & Gdk.ModifierType.SHIFT_MASK == Gdk.ModifierType.SHIFT_MASK:
dbg('on_group_button_press: rename of terminals group')
self.targets_for_new_group = targets
self.titlebar.create_group()
return True
elif event.type == Gdk.EventType.BUTTON_PRESS:
# Single Click gives popup
dbg('on_group_button_press: group menu popup')
window = self.get_toplevel()
window.preventHide = True
self.create_popup_group_menu(widget, event)
return True
else:
dbg('on_group_button_press: unknown group button interaction')
return False
def on_keypress(self, widget, event):
"""Handler for keyboard events"""
if not event:
dbg('Called on %s with no event' % widget)
return False
# FIXME: Does keybindings really want to live in Terminator()?
mapping = self.terminator.keybindings.lookup(event)
if mapping == "hide_window":
return False
if mapping and mapping not in ['close_window',
'full_screen']:
dbg('lookup found: %r' % mapping)
# handle the case where user has re-bound copy to ctrl+<key>
# we only copy if there is a selection otherwise let it fall through
# to ^<key>
if (mapping == "copy" and event.get_state() & Gdk.ModifierType.CONTROL_MASK):
if self.vte.get_has_selection():
getattr(self, "key_" + mapping)()
return True
elif not self.config['smart_copy']:
return True
else:
getattr(self, "key_" + mapping)()
return True
# FIXME: This is all clearly wrong. We should be doing this better
# maybe we can emit the key event and let Terminator() care?
groupsend = self.terminator.groupsend
groupsend_type = self.terminator.groupsend_type
window_focussed = self.vte.get_toplevel().get_property('has-toplevel-focus')
if groupsend != groupsend_type['off'] and window_focussed and self.vte.is_focus():
if self.group and groupsend == groupsend_type['group']:
self.terminator.group_emit(self, self.group, 'key-press-event',
event)
if groupsend == groupsend_type['all']:
self.terminator.all_emit(self, 'key-press-event', event)
return False
def on_buttonpress(self, widget, event):
"""Handler for mouse events"""
# Any button event should grab focus
widget.grab_focus()