feat: refactoring terminal file

This commit is contained in:
Jose Augusto 2020-12-28 21:28:38 -03:00
parent 24757a6922
commit ed54a0d683

View File

@ -844,7 +844,7 @@ class Terminal(Gtk.VBox):
def get_window_title(self):
"""Return the window title"""
return(self.vte.get_window_title() or str(self.command))
return self.vte.get_window_title() or str(self.command)
def on_group_button_press(self, widget, event):
"""Handler for the group button"""
@ -864,10 +864,10 @@ class Terminal(Gtk.VBox):
focused=self.get_toplevel().get_focussed_terminal()
if focused in targets: targets.remove(focused)
if self != focused:
if self.group==focused.group:
new_group=None
if self.group == focused.group:
new_group = None
else:
new_group=focused.group
new_group = focused.group
[term.set_group(None, new_group) for term in targets]
[term.titlebar.update(focused) for term in targets]
return True
@ -885,13 +885,13 @@ class Terminal(Gtk.VBox):
return True
else:
dbg('on_group_button_press: unknown group button interaction')
return(False)
return False
def on_keypress(self, widget, event):
"""Handler for keyboard events"""
if not event:
dbg('Terminal::on_keypress: Called on %s with no event' % widget)
return(False)
return False
# FIXME: Does keybindings really want to live in Terminator()?
mapping = self.terminator.keybindings.lookup(event)
@ -908,10 +908,10 @@ class Terminal(Gtk.VBox):
if isinstance(child, Terminal):
# not a Notebook instance => a single tab is used
# .get_n_pages() can not be used
return(False)
return False
if mapping == "hide_window":
return(False)
return False
if mapping and mapping not in ['close_window',
'full_screen']:
@ -920,14 +920,14 @@ class Terminal(Gtk.VBox):
# 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 ():
if self.vte.get_has_selection():
getattr(self, "key_" + mapping)()
return(True)
return True
elif not self.config['smart_copy']:
return(True)
return True
else:
getattr(self, "key_" + mapping)()
return(True)
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?
@ -937,11 +937,11 @@ class Terminal(Gtk.VBox):
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)
event)
if groupsend == groupsend_type['all']:
self.terminator.all_emit(self, 'key-press-event', event)
return(False)
return False
def on_buttonpress(self, widget, event):
"""Handler for mouse events"""
@ -959,11 +959,11 @@ class Terminal(Gtk.VBox):
middle_click = [self.paste_clipboard, (True, )]
right_click = [self.popup_menu, (widget, event)]
### Ctrl-click event here.
# Ctrl-click event here.
if event.button == self.MOUSEBUTTON_LEFT:
# Ctrl+leftclick on a URL should open it
if event.get_state() & Gdk.ModifierType.CONTROL_MASK == Gdk.ModifierType.CONTROL_MASK:
## Check new OSC-8 method first
# Check new OSC-8 method first
url = self.vte.hyperlink_check_event(event)
dbg('url: %s' % url)
if url:
@ -986,9 +986,8 @@ class Terminal(Gtk.VBox):
gtk_settings.set_property('gtk-enable-primary-paste', primary_state)
else:
middle_click[0](*middle_click[1])
return(True)
return True
return Vte.Terminal.do_button_press_event(self.vte, event)
#return(True)
elif event.button == self.MOUSEBUTTON_RIGHT:
# rightclick should display a context menu if Ctrl is not pressed,
# plus either the app is not interested in mouse events or Shift is pressed
@ -998,9 +997,8 @@ class Terminal(Gtk.VBox):
right_click[0](*right_click[1])
else:
right_click[0](*right_click[1])
return(True)
return(False)
return True
return False
def on_mousewheel(self, widget, event):
"""Handler for modifier + mouse wheel scroll events"""
@ -1009,31 +1007,31 @@ class Terminal(Gtk.VBox):
if event.state & Gdk.ModifierType.CONTROL_MASK == Gdk.ModifierType.CONTROL_MASK:
# Zoom the terminal(s) in or out if not disabled in config
if self.config["disable_mousewheel_zoom"] is True:
return (False)
return False
# Choice of target terminals depends on Shift and Super modifiers
if event.state & Gdk.ModifierType.MOD4_MASK == Gdk.ModifierType.MOD4_MASK:
targets=self.terminator.terminals
targets = self.terminator.terminals
elif event.state & Gdk.ModifierType.SHIFT_MASK == Gdk.ModifierType.SHIFT_MASK:
targets=self.terminator.get_target_terms(self)
targets = self.terminator.get_target_terms(self)
else:
targets=[self]
targets = [self]
if event.direction == Gdk.ScrollDirection.UP or SMOOTH_SCROLL_UP:
for target in targets:
target.zoom_in()
return (True)
return True
elif event.direction == Gdk.ScrollDirection.DOWN or SMOOTH_SCROLL_DOWN:
for target in targets:
target.zoom_out()
return (True)
return True
if event.state & Gdk.ModifierType.SHIFT_MASK == Gdk.ModifierType.SHIFT_MASK:
# Shift + mouse wheel up/down
if event.direction == Gdk.ScrollDirection.UP or SMOOTH_SCROLL_UP:
self.scroll_by_page(-1)
return (True)
return True
elif event.direction == Gdk.ScrollDirection.DOWN or SMOOTH_SCROLL_DOWN:
self.scroll_by_page(1)
return (True)
return(False)
return True
return False
def popup_menu(self, widget, event=None):
"""Display the context menu"""
@ -1066,15 +1064,16 @@ class Terminal(Gtk.VBox):
Gtk.drag_set_icon_pixbuf(drag_context, util.widget_pixbuf(self, 512), 0, 0)
def on_drag_data_get(self, _widget, _drag_context, selection_data, info,
_time, data):
_time, data):
"""I have no idea what this does, drag and drop is a mystery. sorry."""
selection_data.set(Gdk.atom_intern('vte', False), info,
bytes(str(data.terminator.terminals.index(self)), 'utf-8'))
bytes(str(data.terminator.terminals.index(self)),
'utf-8'))
def on_drag_motion(self, widget, drag_context, x, y, _time, _data):
"""*shrug*"""
if not drag_context.list_targets() == [Gdk.atom_intern('vte', False)] and \
(Gtk.targets_include_text(drag_context.list_targets()) or \
(Gtk.targets_include_text(drag_context.list_targets()) or
Gtk.targets_include_uri(drag_context.list_targets())):
# copy text from another widget
return
@ -1101,7 +1100,7 @@ class Terminal(Gtk.VBox):
bottommiddle = (alloc.width/2, alloc.height)
middleleft = (0, alloc.height/2)
middleright = (alloc.width, alloc.height/2)
#print "%f %f %d %d" %(coef1, coef2, b1,b2)
coord = ()
if pos == "right":
coord = (topright, topmiddle, bottommiddle, bottomright)
@ -1112,21 +1111,20 @@ class Terminal(Gtk.VBox):
elif pos == "bottom":
coord = (bottomleft, bottomright, middleright , middleleft)
#here, we define some widget internal values
# here, we define some widget internal values
widget._draw_data = { 'color': color, 'coord' : coord }
#redraw by forcing an event
# redraw by forcing an event
connec = widget.connect_after('draw', self.on_draw)
widget.queue_draw_area(0, 0, alloc.width, alloc.height)
widget.get_window().process_updates(True)
#finaly reset the values
# finaly reset the values
widget.disconnect(connec)
widget._draw_data = None
def background_draw(self, widget, cr):
if not self.config['background_type'] == 'image' or not self.background_image:
return(False)
#if not self.background_image:
# return(False)
return False
rect = self.vte.get_allocation()
xratio = float(rect.width) / float(self.background_image.get_width())
yratio = float(rect.height) / float(self.background_image.get_height())
@ -1140,25 +1138,25 @@ class Terminal(Gtk.VBox):
def on_draw(self, widget, context):
if not widget._draw_data:
return(False)
return False
color = widget._draw_data['color']
coord = widget._draw_data['coord']
context.set_source_rgba(color.red, color.green, color.blue, 0.5)
if len(coord) > 0 :
if len(coord) > 0:
context.move_to(coord[len(coord)-1][0], coord[len(coord)-1][1])
for i in coord:
context.line_to(i[0], i[1])
context.fill()
return(False)
return False
def on_drag_data_received(self, widget, drag_context, x, y, selection_data,
info, _time, data):
"""Something has been dragged into the terminal. Handle it as either a
URL or another terminal."""
### FIXME this code is a mess that I don't quite understand how it works.
# FIXME this code is a mess that I don't quite understand how it works.
dbg('drag data received of type: %s' % (selection_data.get_data_type()))
# print(selection_data.get_urls())
if Gtk.targets_include_text(drag_context.list_targets()) or \
@ -1168,7 +1166,7 @@ class Terminal(Gtk.VBox):
# https://bugs.launchpad.net/terminator/+bug/1518705
if info == self.TARGET_TYPE_MOZ:
txt = txt.decode('utf-16')
### KDE ends it's text/x-moz-url text with CRLF, :shrug:
# KDE ends it's text/x-moz-url text with CRLF, :shrug:
if not txt.endswith('\r\n'):
txt = txt.split('\n')[0]
else:
@ -1186,10 +1184,10 @@ class Terminal(Gtk.VBox):
str=''
for fname in txt_lines[:-1]:
fname = "'%s'" % urlunquote(fname[7:].replace("'",
'\'\\\'\''))
'\'\\\'\''))
str += fname + ' '
txt=str
### Never send a CRLF to the terminal from here
txt = str
# Never send a CRLF to the terminal from here
txt = txt.rstrip('\r\n')
for term in self.terminator.get_target_terms(self):
term.feed(txt.encode())
@ -1197,7 +1195,7 @@ class Terminal(Gtk.VBox):
widgetsrc = data.terminator.terminals[int(selection_data.get_data())]
srcvte = Gtk.drag_get_source_widget(drag_context)
#check if computation requireds
# check if computation requireds
if (isinstance(srcvte, Gtk.EventBox) and
srcvte == self.titlebar) or srcvte == widget:
return
@ -1231,7 +1229,7 @@ class Terminal(Gtk.VBox):
def get_location(self, term, x, y):
"""Get our location within the terminal"""
pos = ''
#get the diagonales function for the receiving widget
# get the diagonales function for the receiving widget
term_alloc = term.get_allocation()
coef1 = float(term_alloc.height)/float(term_alloc.width)
coef2 = -float(term_alloc.height)/float(term_alloc.width)
@ -1246,13 +1244,13 @@ class Terminal(Gtk.VBox):
#| / \ |
#|/ \|
#--------
if (x*coef1 + b1 > y ) and (x*coef2 + b2 < y ):
pos = "right"
if (x*coef1 + b1 > y ) and (x*coef2 + b2 > y ):
if (x*coef1 + b1 > y) and (x*coef2 + b2 < y):
pos = "right"
if (x*coef1 + b1 > y) and (x*coef2 + b2 > y):
pos = "top"
if (x*coef1 + b1 < y ) and (x*coef2 + b2 > y ):
if (x*coef1 + b1 < y) and (x*coef2 + b2 > y):
pos = "left"
if (x*coef1 + b1 < y ) and (x*coef2 + b2 < y ):
if (x*coef1 + b1 < y) and (x*coef2 + b2 < y):
pos = "bottom"
return pos
@ -1327,7 +1325,7 @@ class Terminal(Gtk.VBox):
def deferred_on_vte_size_allocate(self, widget, allocation):
# widget & allocation are not used in on_vte_size_allocate, so we
# can use the on_vte_size_allocate instead of duplicating the code
if self.pending_on_vte_size_allocate == True:
if self.pending_on_vte_size_allocate:
return
self.pending_on_vte_size_allocate = True
GObject.idle_add(self.do_deferred_on_vte_size_allocate, widget, allocation)
@ -1351,22 +1349,21 @@ class Terminal(Gtk.VBox):
sloppy = self.config.get_system_focus() in ['sloppy', 'mouse']
elif self.config['focus'] in ['sloppy', 'mouse']:
sloppy = True
if sloppy == True and self.titlebar.editing() == False:
if sloppy and self.titlebar.editing() == False:
term.grab_focus()
return(False)
return False
def get_zoom_data(self):
"""Return a dict of information for Window"""
data = {}
data['old_font'] = self.vte.get_font().copy()
data['old_char_height'] = self.vte.get_char_height()
data['old_char_width'] = self.vte.get_char_width()
data['old_allocation'] = self.vte.get_allocation()
data['old_columns'] = self.vte.get_column_count()
data['old_rows'] = self.vte.get_row_count()
data['old_parent'] = self.get_parent()
data = {'old_font': self.vte.get_font().copy(),
'old_char_height': self.vte.get_char_height(),
'old_char_width': self.vte.get_char_width(),
'old_allocation': self.vte.get_allocation(),
'old_columns': self.vte.get_column_count(),
'old_rows': self.vte.get_row_count(),
'old_parent': self.get_parent()}
return(data)
return data
def zoom_scale(self, widget, allocation, old_data):
"""Scale our font correctly based on how big we are not vs before"""
@ -1410,7 +1407,7 @@ class Terminal(Gtk.VBox):
except TypeError:
prop = False
return(prop)
return prop
def zoom(self, widget=None):
"""Zoom ourself to fill the window"""
@ -1434,11 +1431,11 @@ class Terminal(Gtk.VBox):
shell = None
command = None
if self.terminator.doing_layout == True:
if self.terminator.doing_layout:
dbg('still laying out, refusing to spawn a child')
return
if respawn == False:
if respawn is False:
self.vte.grab_focus()
options = self.config.options_get()
@ -1463,7 +1460,7 @@ class Terminal(Gtk.VBox):
self.set_cwd(self.directory)
# working directory given as argument
elif options and options.working_directory and \
options.working_directory != '':
options.working_directory != '':
self.set_cwd(options.working_directory)
options.working_directory = ''
@ -1483,18 +1480,16 @@ class Terminal(Gtk.VBox):
if shell is None:
self.vte.feed(_('Unable to find a shell'))
return(-1)
return -1
try:
os.putenv('WINDOWID', '%s' % self.vte.get_parent_window().xid)
except AttributeError:
pass
envv = []
envv.append('TERM=%s' % self.config['term'])
envv.append('COLORTERM=%s' % self.config['colorterm'])
envv.append('PWD=%s' % self.cwd)
envv.append('TERMINATOR_UUID=%s' % self.uuid.urn)
envv = ['TERM=%s' % self.config['term'],
'COLORTERM=%s' % self.config['colorterm'], 'PWD=%s' % self.cwd,
'TERMINATOR_UUID=%s' % self.uuid.urn]
if self.terminator.dbus_name:
envv.append('TERMINATOR_DBUS_NAME=%s' % self.terminator.dbus_name)
if self.terminator.dbus_path:
@ -1503,20 +1498,20 @@ class Terminal(Gtk.VBox):
dbg('Forking shell: "%s" with args: %s' % (shell, args))
args.insert(0, shell)
result, self.pid = self.vte.spawn_sync(Vte.PtyFlags.DEFAULT,
self.cwd,
args,
envv,
GLib.SpawnFlags.FILE_AND_ARGV_ZERO,
None,
None,
None)
self.cwd,
args,
envv,
GLib.SpawnFlags.FILE_AND_ARGV_ZERO,
None,
None,
None)
self.command = shell
self.titlebar.update()
if self.pid == -1:
self.vte.feed(_('Unable to start shell:') + shell)
return(-1)
return -1
def prepare_url(self, urlmatch):
"""Prepare a URL from a VTE match"""
@ -1547,11 +1542,11 @@ class Terminal(Gtk.VBox):
except Exception as ex:
err('Exception occurred preparing URL: %s' % ex)
return(url)
return url
def open_url(self, url, prepare=False):
"""Open a given URL, conditionally unpacking it from a VTE match"""
if prepare == True:
if prepare:
url = self.prepare_url(url)
dbg('open_url: URL: %s (prepared: %s)' % (url, prepare))
@ -1614,7 +1609,7 @@ class Terminal(Gtk.VBox):
def zoom_orig(self):
"""Restore original font size"""
if self.config['use_system_font'] == True:
if self.config['use_system_font']:
font = self.config.get_system_mono_font()
else:
font = self.config['font']
@ -1632,25 +1627,25 @@ class Terminal(Gtk.VBox):
col, row = self.vte.get_cursor_position()
width = self.vte.get_char_width()
height = self.vte.get_char_height()
return((col * width, row * height))
return col * width, row * height
def get_font_size(self):
"""Return the width/height of our font"""
return((self.vte.get_char_width(), self.vte.get_char_height()))
return self.vte.get_char_width(), self.vte.get_char_height()
def get_size(self):
"""Return the column/rows of the terminal"""
return((self.vte.get_column_count(), self.vte.get_row_count()))
return self.vte.get_column_count(), self.vte.get_row_count()
def on_bell(self, widget):
"""Set the urgency hint/icon/flash for our window"""
if self.config['urgent_bell'] == True:
if self.config['urgent_bell']:
window = self.get_toplevel()
if window.is_toplevel():
window.set_urgency_hint(True)
if self.config['icon_bell'] == True:
if self.config['icon_bell']:
self.titlebar.icon_bell()
if self.config['visible_bell'] == True:
if self.config['visible_bell']:
# Repurposed the code used for drag and drop overlay to provide a visual terminal flash
alloc = widget.get_allocation()
@ -1660,15 +1655,15 @@ class Terminal(Gtk.VBox):
color = Gdk.RGBA()
color.parse(self.config['foreground_color']) # VERIFY FOR GTK3
coord = ( (0, 0), (alloc.width, 0), (alloc.width, alloc.height), (0, alloc.height))
coord = ((0, 0), (alloc.width, 0), (alloc.width, alloc.height), (0, alloc.height))
#here, we define some widget internal values
# here, we define some widget internal values
widget._draw_data = { 'color': color, 'coord' : coord }
#redraw by forcing an event
# redraw by forcing an event
connec = widget.connect_after('draw', self.on_draw)
widget.queue_draw_area(0, 0, alloc.width, alloc.height)
widget.get_window().process_updates(True)
#finaly reset the values
# finaly reset the values
widget.disconnect(connec)
widget._draw_data = None
@ -1676,17 +1671,14 @@ class Terminal(Gtk.VBox):
GObject.timeout_add(100, self.on_bell_cleanup, widget, alloc)
def on_bell_cleanup(self, widget, alloc):
'''Queue a redraw to clear the visual flash overlay'''
"""Queue a redraw to clear the visual flash overlay"""
widget.queue_draw_area(0, 0, alloc.width, alloc.height)
widget.get_window().process_updates(True)
return False
def describe_layout(self, count, parent, global_layout, child_order):
"""Describe our layout"""
layout = {}
layout['type'] = 'Terminal'
layout['parent'] = parent
layout['order'] = child_order
layout = {'type': 'Terminal', 'parent': parent, 'order': child_order}
if self.group:
layout['group'] = self.group
profile = self.get_profile()
@ -1700,7 +1692,7 @@ class Terminal(Gtk.VBox):
name = 'terminal%d' % count
count = count + 1
global_layout[name] = layout
return(count)
return count
def create_layout(self, layout):
"""Apply our layout"""
@ -1739,7 +1731,8 @@ class Terminal(Gtk.VBox):
adjustment.set_value(min(value, bottom))
def get_allocation(self):
"""Get a real allocation which includes the bloody x and y coordinates (grumble, grumble)"""
"""Get a real allocation which includes the bloody x and y coordinates
(grumble, grumble) """
alloc = super(Terminal, self).get_allocation()
rv = self.translate_coordinates(self.get_toplevel(), 0, 0)
if rv:
@ -1942,9 +1935,9 @@ class Terminal(Gtk.VBox):
def key_edit_window_title(self):
window = self.get_toplevel()
dialog = Gtk.Dialog(_('Rename Window'), window,
Gtk.DialogFlags.MODAL,
( Gtk.STOCK_CANCEL, Gtk.ResponseType.REJECT,
Gtk.STOCK_OK, Gtk.ResponseType.ACCEPT ))
Gtk.DialogFlags.MODAL,
(Gtk.STOCK_CANCEL, Gtk.ResponseType.REJECT,
Gtk.STOCK_OK, Gtk.ResponseType.ACCEPT))
dialog.set_default_response(Gtk.ResponseType.ACCEPT)
dialog.set_resizable(False)
dialog.set_border_width(8)
@ -2014,5 +2007,6 @@ class Terminal(Gtk.VBox):
# End key events
GObject.type_register(Terminal)
# vim: set expandtab ts=4 sw=4: