id
int64
0
458k
file_name
stringlengths
4
119
file_path
stringlengths
14
227
content
stringlengths
24
9.96M
size
int64
24
9.96M
language
stringclasses
1 value
extension
stringclasses
14 values
total_lines
int64
1
219k
avg_line_length
float64
2.52
4.63M
max_line_length
int64
5
9.91M
alphanum_fraction
float64
0
1
repo_name
stringlengths
7
101
repo_stars
int64
100
139k
repo_forks
int64
0
26.4k
repo_open_issues
int64
0
2.27k
repo_license
stringclasses
12 values
repo_extraction_date
stringclasses
433 values
18,800
buildwebhelp.py
GNOME_meld/help/C/buildwebhelp.py
#! /usr/bin/python3 import glob import os import subprocess import sys from bs4 import BeautifulSoup JEKYLL_HEADER = """--- layout: help title: Meld - Help --- """ SCSS_HEADER = """ #help-content { border-left: solid 1px #e0e0df; border-right: solid 1px #e0e0df; background-color: #ffffff; } #help-content div.body { border: none !important; } #help-content div.headbar { margin: 10px !important; } #help-content div.footbar { margin: 10px !important; } #help-content { .title { line-height: 1em; } h1 { font-family: sans-serif; font-weight: bold; text-shadow: none; color: black; } h2 { font-family: sans-serif; text-shadow: none; color: black; } """ SCSS_FOOTER = """ } """ def munge_html(filename): if not os.path.exists(filename): print("File not found: " + filename, file=sys.stderr) sys.exit(1) with open(filename) as f: contents = f.read() soup = BeautifulSoup(contents, "lxml") body = "".join([str(tag) for tag in soup.body]) body = JEKYLL_HEADER + body print("Rewriting " + filename) with open(filename, "w") as f: f.write(body) def munge_css(filename): if not os.path.exists(filename): print("File not found: " + filename, file=sys.stderr) sys.exit(1) with open(filename) as f: contents = f.read() contents = SCSS_HEADER + contents + SCSS_FOOTER new_css = sassify(contents) print("Rewriting " + filename) with open(filename, 'w') as f: f.write(new_css) def sassify(scss_string): scss = subprocess.Popen( ['scss', '-s'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, universal_newlines=True, ) stdout, stderr = scss.communicate(scss_string) return stdout if __name__ == "__main__": if os.path.exists('html'): print("Refusing to overwrite existing html/ folder", file=sys.stderr) sys.exit(1) print("Generating CSS with gnome-doc-tool...", file=sys.stderr) subprocess.check_call(['gnome-doc-tool', 'css']) print("Generating HTML with gnome-doc-tool...", file=sys.stderr) subprocess.check_call(['gnome-doc-tool', 'html', '-c', 'index.css', '--copy-graphics', '*.page']) os.mkdir('html') for filename in glob.glob('*.html'): munge_html(filename) os.rename(filename, os.path.join('html', filename)) munge_css('index.css') os.rename('index.css', os.path.join('html', 'index.css')) print("Embeddable documentation written to html/", file=sys.stderr)
2,577
Python
.py
92
23.48913
77
0.647227
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,801
filters.py
GNOME_meld/meld/filters.py
# Copyright (C) 2011-2013 Kai Willadsen <kai.willadsen@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or (at # your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import logging import re log = logging.getLogger(__name__) def try_compile(regex, flags=0): try: compiled = re.compile(regex, flags) except re.error: log.warning( 'Error compiling regex {!r} with flags {!r}'.format(regex, flags)) compiled = None return compiled class FilterEntry: __slots__ = ("label", "active", "filter", "byte_filter", "filter_string") REGEX, SHELL = 0, 1 def __init__(self, label, active, filter, byte_filter, filter_string): self.label = label self.active = active self.filter = filter self.byte_filter = byte_filter self.filter_string = filter_string @classmethod def compile_regex(cls, regex, byte_regex=False): if byte_regex and not isinstance(regex, bytes): # TODO: Register a custom error handling function to replace # encoding errors with '.'? regex = regex.encode('utf8', 'replace') return try_compile(regex, re.M) @classmethod def compile_shell_pattern(cls, pattern): bits = pattern.split() if not bits: # An empty pattern would match everything, so skip it return None elif len(bits) > 1: regexes = [shell_to_regex(b)[:-1] for b in bits] regex = "(%s)$" % "|".join(regexes) else: regex = shell_to_regex(bits[0]) return try_compile(regex) @classmethod def new_from_gsetting(cls, elements, filter_type): name, active, filter_string = elements if filter_type == cls.REGEX: str_re = cls.compile_regex(filter_string) bytes_re = cls.compile_regex(filter_string, byte_regex=True) elif filter_type == cls.SHELL: str_re = cls.compile_shell_pattern(filter_string) bytes_re = None else: raise ValueError("Unknown filter type") active = active and bool(str_re) return cls(name, active, str_re, bytes_re, filter_string) @classmethod def check_filter(cls, filter_string, filter_type): if filter_type == cls.REGEX: compiled = cls.compile_regex(filter_string) elif filter_type == cls.SHELL: compiled = cls.compile_shell_pattern(filter_string) return compiled is not None def __copy__(self): new = type(self)( self.label, self.active, None, None, self.filter_string) if self.filter is not None: new.filter = re.compile(self.filter.pattern, self.filter.flags) if self.byte_filter is not None: new.byte_filter = re.compile( self.byte_filter.pattern, self.byte_filter.flags) return new def shell_to_regex(pat): """Translate a shell PATTERN to a regular expression. Based on fnmatch.translate(). We also handle {a,b,c} where fnmatch does not. """ i, n = 0, len(pat) res = '' while i < n: c = pat[i] i += 1 if c == '\\': try: c = pat[i] except IndexError: pass else: i += 1 res += re.escape(c) elif c == '*': res += '.*' elif c == '?': res += '.' elif c == '[': try: j = pat.index(']', i) except ValueError: res += r'\[' else: stuff = pat[i:j] i = j + 1 if stuff[0] == '!': stuff = '^%s' % stuff[1:] elif stuff[0] == '^': stuff = r'\^%s' % stuff[1:] res += '[%s]' % stuff elif c == '{': try: j = pat.index('}', i) except ValueError: res += '\\{' else: stuff = pat[i:j] i = j + 1 res += '(%s)' % "|".join( [shell_to_regex(p)[:-1] for p in stuff.split(",")] ) else: res += re.escape(c) return res + "$"
4,831
Python
.py
131
27.335878
78
0.553087
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,802
undo.py
GNOME_meld/meld/undo.py
# Copyright (C) 2002-2006 Stephen Kennedy <stevek@gnome.org> # Copyright (C) 2010-2011 Kai Willadsen <kai.willadsen@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or (at # your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """Module to help implement undo functionality. Usage: t = TextWidget() s = UndoSequence() def on_textwidget_text_inserted(): s.begin_group() if not t.is_modified(): s.add_action( TextWidgetModifiedAction() ) s.add_action( InsertionAction() ) s.end_group() def on_undo_button_pressed(): s.undo() """ import logging import weakref from gi.repository import GObject log = logging.getLogger(__name__) class GroupAction: """A group action combines several actions into one logical action. """ def __init__(self, seq): self.seq = seq # TODO: If a GroupAction affects more than one sequence, our logic # breaks. Currently, this isn't a problem. self.buffer = seq.actions[0].buffer def undo(self): actions = [] while self.seq.can_undo(): actions.extend(self.seq.undo()) return actions def redo(self): actions = [] while self.seq.can_redo(): actions.extend(self.seq.redo()) return actions class UndoSequence(GObject.GObject): """A manager class for operations which can be undone/redone. """ __gsignals__ = { 'can-undo': ( GObject.SignalFlags.RUN_FIRST, None, (GObject.TYPE_BOOLEAN,) ), 'can-redo': ( GObject.SignalFlags.RUN_FIRST, None, (GObject.TYPE_BOOLEAN,) ), 'checkpointed': ( GObject.SignalFlags.RUN_FIRST, None, (GObject.TYPE_OBJECT, GObject.TYPE_BOOLEAN,) ), } def __init__(self, buffers): """Create an empty UndoSequence An undo sequence is tied to a collection of GtkTextBuffers, and expects to maintain undo checkpoints for the same set of buffers for the lifetime of the UndoSequence. """ super().__init__() self.buffer_refs = [weakref.ref(buf) for buf in buffers] self.clear() def clear(self): """Remove all undo and redo actions from this sequence If the sequence was previously able to undo and/or redo, the 'can-undo' and 'can-redo' signals are emitted. """ if self.can_undo(): self.emit('can-undo', 0) if self.can_redo(): self.emit('can-redo', 0) self.actions = [] self.next_redo = 0 self.checkpoints = { # Each buffer's checkpoint starts at zero and has no end ref(): [0, None] for ref in self.buffer_refs } self.group = None self.busy = False def can_undo(self): """Return whether an undo is possible.""" return getattr(self, 'next_redo', 0) > 0 def can_redo(self): """Return whether a redo is possible.""" next_redo = getattr(self, 'next_redo', 0) return next_redo < len(getattr(self, 'actions', [])) def add_action(self, action): """Add an action to the undo list. Arguments: action -- A class with two callable attributes: 'undo' and 'redo' which are called by this sequence during an undo or redo. """ if self.busy: return if self.group is None: if self.checkpointed(action.buffer): self.checkpoints[action.buffer][1] = self.next_redo self.emit('checkpointed', action.buffer, False) else: # If we go back in the undo stack before the checkpoint starts, # and then modify the buffer, we lose the checkpoint altogether start, end = self.checkpoints.get(action.buffer, (None, None)) if start is not None and start > self.next_redo: self.checkpoints[action.buffer] = (None, None) could_undo = self.can_undo() could_redo = self.can_redo() self.actions[self.next_redo:] = [] self.actions.append(action) self.next_redo += 1 if not could_undo: self.emit('can-undo', 1) if could_redo: self.emit('can-redo', 0) else: self.group.add_action(action) def undo(self): """Undo an action. Raises an AssertionError if the sequence is not undoable. """ assert self.next_redo > 0 self.busy = True buf = self.actions[self.next_redo - 1].buffer if self.checkpointed(buf): self.emit('checkpointed', buf, False) could_redo = self.can_redo() self.next_redo -= 1 actions = self.actions[self.next_redo].undo() self.busy = False if not self.can_undo(): self.emit('can-undo', 0) if not could_redo: self.emit('can-redo', 1) if self.checkpointed(buf): self.emit('checkpointed', buf, True) return actions def redo(self): """Redo an action. Raises and AssertionError if the sequence is not undoable. """ assert self.next_redo < len(self.actions) self.busy = True buf = self.actions[self.next_redo].buffer if self.checkpointed(buf): self.emit('checkpointed', buf, False) could_undo = self.can_undo() a = self.actions[self.next_redo] self.next_redo += 1 actions = a.redo() self.busy = False if not could_undo: self.emit('can-undo', 1) if not self.can_redo(): self.emit('can-redo', 0) if self.checkpointed(buf): self.emit('checkpointed', buf, True) return actions def checkpoint(self, buf): start = self.next_redo while start > 0 and self.actions[start - 1].buffer != buf: start -= 1 end = self.next_redo while (end < len(self.actions) - 1 and self.actions[end + 1].buffer != buf): end += 1 if end == len(self.actions): end = None self.checkpoints[buf] = [start, end] self.emit('checkpointed', buf, True) def checkpointed(self, buf): # While the main undo sequence should always have checkpoints # recorded, grouped subsequences won't. start, end = self.checkpoints.get(buf, (None, None)) if start is None: return False if end is None: end = len(self.actions) return start <= self.next_redo <= end def begin_group(self): """Group several actions into a single logical action. When you wrap several calls to add_action() inside begin_group() and end_group(), all the intervening actions are considered one logical action. For instance a 'replace' action may be implemented as a pair of 'delete' and 'create' actions, but undoing should undo both of them. """ if self.busy: return if self.group: self.group.begin_group() else: buffers = [ref() for ref in self.buffer_refs] self.group = UndoSequence(buffers) def end_group(self): """End a logical group action This must always be paired with a begin_group() call. However, we don't complain if this is not the case because we rely on external libraries (i.e., GTK+ and GtkSourceView) also pairing these correctly. See also begin_group(). """ if self.busy: return if self.group is None: log.warning('Tried to end a non-existent group') return if self.group.group is not None: self.group.end_group() else: group = self.group self.group = None # Collapse single action groups if len(group.actions) == 1: self.add_action(group.actions[0]) elif len(group.actions) > 1: self.add_action(GroupAction(group)) def abort_group(self): """Clear the currently grouped actions This discards all actions since the last begin_group() was called. Note that it does not actually undo the actions themselves. """ if self.busy: return if self.group is None: log.warning('Tried to abort a non-existent group') return if self.group.group is not None: self.group.abort_group() else: self.group = None def in_grouped_action(self): return self.group is not None
9,330
Python
.py
246
28.780488
79
0.59562
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,803
meldwindow.py
GNOME_meld/meld/meldwindow.py
# Copyright (C) 2002-2006 Stephen Kennedy <stevek@gnome.org> # Copyright (C) 2010-2013 Kai Willadsen <kai.willadsen@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or (at # your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import logging import os from typing import Any, Dict, Optional, Sequence from gi.repository import Gdk, Gio, GLib, Gtk # Import support module to get all builder-constructed widgets in the namespace import meld.ui.gladesupport # noqa: F401 import meld.ui.util from meld.conf import PROFILE, _ from meld.const import ( FILE_FILTER_ACTION_FORMAT, TEXT_FILTER_ACTION_FORMAT, FileComparisonMode, ) from meld.dirdiff import DirDiff from meld.filediff import FileDiff from meld.imagediff import ImageDiff, files_are_images from meld.melddoc import ComparisonState, MeldDoc from meld.menuhelpers import replace_menu_section from meld.misc import guess_if_remote_x11 from meld.newdifftab import NewDiffTab from meld.recent import RecentType, recent_comparisons from meld.settings import get_meld_settings from meld.task import LifoScheduler from meld.ui.notebooklabel import NotebookLabel from meld.vcview import VcView from meld.windowstate import SavedWindowState log = logging.getLogger(__name__) @Gtk.Template(resource_path='/org/gnome/meld/ui/appwindow.ui') class MeldWindow(Gtk.ApplicationWindow): __gtype_name__ = 'MeldWindow' appvbox = Gtk.Template.Child() folder_filter_button = Gtk.Template.Child() text_filter_button = Gtk.Template.Child() gear_menu_button = Gtk.Template.Child() next_conflict_button = Gtk.Template.Child() notebook = Gtk.Template.Child() previous_conflict_button = Gtk.Template.Child() spinner = Gtk.Template.Child() vc_filter_button = Gtk.Template.Child() view_toolbar = Gtk.Template.Child() def __init__(self): super().__init__() # Manually handle GAction additions actions = ( ("close", self.action_close), ("new-tab", self.action_new_tab), ("stop", self.action_stop), ) for name, callback in actions: action = Gio.SimpleAction.new(name, None) action.connect('activate', callback) self.add_action(action) state_actions = ( ( "fullscreen", self.action_fullscreen_change, GLib.Variant.new_boolean(False), ), ( "gear-menu", None, GLib.Variant.new_boolean(False), ), ) for (name, callback, state) in state_actions: action = Gio.SimpleAction.new_stateful(name, None, state) if callback: action.connect('change-state', callback) self.add_action(action) # Initialise sensitivity for important actions self.lookup_action('stop').set_enabled(False) # Fake out the spinner on Windows or X11 forwarding. See Gitlab # issues #133 and #507. if os.name == "nt" or guess_if_remote_x11(): for attr in ('stop', 'hide', 'show', 'start'): setattr(self.spinner, attr, lambda *args: True) self.drag_dest_set( Gtk.DestDefaults.MOTION | Gtk.DestDefaults.HIGHLIGHT | Gtk.DestDefaults.DROP, None, Gdk.DragAction.COPY) self.drag_dest_add_uri_targets() self.connect( "drag_data_received", self.on_widget_drag_data_received) self.window_state = SavedWindowState() self.window_state.bind(self) self.should_close = False self.idle_hooked = 0 self.scheduler = LifoScheduler() self.scheduler.connect("runnable", self.on_scheduler_runnable) if PROFILE != '': style_context = self.get_style_context() style_context.add_class("devel") def do_realize(self): Gtk.ApplicationWindow.do_realize(self) app = self.get_application() menu = app.get_menu_by_id("gear-menu") self.gear_menu_button.set_popover( Gtk.Popover.new_from_model(self.gear_menu_button, menu)) filter_model = app.get_menu_by_id("text-filter-menu") self.text_filter_button.set_popover( Gtk.Popover.new_from_model(self.text_filter_button, filter_model)) filter_menu = app.get_menu_by_id("folder-status-filter-menu") self.folder_filter_button.set_popover( Gtk.Popover.new_from_model(self.folder_filter_button, filter_menu)) vc_filter_model = app.get_menu_by_id('vc-status-filter-menu') self.vc_filter_button.set_popover( Gtk.Popover.new_from_model(self.vc_filter_button, vc_filter_model)) meld_settings = get_meld_settings() self.update_text_filters(meld_settings) self.update_filename_filters(meld_settings) self.settings_handlers = [ meld_settings.connect( "text-filters-changed", self.update_text_filters), meld_settings.connect( "file-filters-changed", self.update_filename_filters), ] meld.ui.util.extract_accels_from_menu(menu, self.get_application()) def update_filename_filters(self, settings): filter_items_model = Gio.Menu() for i, filt in enumerate(settings.file_filters): name = FILE_FILTER_ACTION_FORMAT.format(i) filter_items_model.append( label=filt.label, detailed_action=f'view.{name}') section = Gio.MenuItem.new_section(_("Filename"), filter_items_model) section.set_attribute([("id", "s", "custom-filter-section")]) app = self.get_application() filter_model = app.get_menu_by_id("folder-status-filter-menu") replace_menu_section(filter_model, section) def update_text_filters(self, settings): filter_items_model = Gio.Menu() for i, filt in enumerate(settings.text_filters): name = TEXT_FILTER_ACTION_FORMAT.format(i) filter_items_model.append( label=filt.label, detailed_action=f'view.{name}') section = Gio.MenuItem.new_section(None, filter_items_model) section.set_attribute([("id", "s", "custom-filter-section")]) app = self.get_application() filter_model = app.get_menu_by_id("text-filter-menu") replace_menu_section(filter_model, section) def on_widget_drag_data_received( self, wid, context, x, y, selection_data, info, time): uris = selection_data.get_uris() if uris: self.open_paths([Gio.File.new_for_uri(uri) for uri in uris]) return True def on_idle(self): ret = self.scheduler.iteration() if ret and isinstance(ret, str): self.spinner.set_tooltip_text(ret) pending = self.scheduler.tasks_pending() if not pending: self.spinner.stop() self.spinner.hide() self.spinner.set_tooltip_text("") self.idle_hooked = None # On window close, this idle loop races widget destruction, # and so actions may already be gone at this point. stop_action = self.lookup_action('stop') if stop_action: stop_action.set_enabled(False) return pending def on_scheduler_runnable(self, sched): if not self.idle_hooked: self.spinner.show() self.spinner.start() self.lookup_action('stop').set_enabled(True) self.idle_hooked = GLib.idle_add(self.on_idle) @Gtk.Template.Callback() def on_delete_event(self, *extra): # Delete pages from right-to-left. This ensures that if a version # control page is open in the far left page, it will be closed last. responses = [] for page in reversed(self.notebook.get_children()): self.notebook.set_current_page(self.notebook.page_num(page)) responses.append(page.on_delete_event()) have_cancelled_tabs = any(r == Gtk.ResponseType.CANCEL for r in responses) have_saving_tabs = any(r == Gtk.ResponseType.APPLY for r in responses) # If we have tabs that are not straight OK responses, we cancel the # close. Either something has cancelled the close, or we temporarily # cancel the close while async saving is happening. cancel_delete = have_cancelled_tabs or have_saving_tabs or self.has_pages() # If we have only saving and no cancelled tabs, we record that we # should close once the other tabs have closed (assuming the state) # doesn't otherwise change. self.should_close = have_saving_tabs and not have_cancelled_tabs return cancel_delete def has_pages(self): return self.notebook.get_n_pages() > 0 def handle_current_doc_switch(self, page): page.on_container_switch_out_event(self) @Gtk.Template.Callback() def on_switch_page(self, notebook, page, which): oldidx = notebook.get_current_page() if oldidx >= 0: olddoc = notebook.get_nth_page(oldidx) self.handle_current_doc_switch(olddoc) newdoc = notebook.get_nth_page(which) if which >= 0 else None self.lookup_action('close').set_enabled(bool(newdoc)) if hasattr(newdoc, 'scheduler'): self.scheduler.add_task(newdoc.scheduler) self.view_toolbar.foreach(self.view_toolbar.remove) if hasattr(newdoc, 'toolbar_actions'): self.view_toolbar.add(newdoc.toolbar_actions) @Gtk.Template.Callback() def after_switch_page(self, notebook, page, which): newdoc = notebook.get_nth_page(which) newdoc.on_container_switch_in_event(self) def action_new_tab(self, action, parameter): self.append_new_comparison() def action_close(self, *extra): i = self.notebook.get_current_page() if i >= 0: page = self.notebook.get_nth_page(i) page.on_delete_event() def action_fullscreen_change(self, action, state): window_state = self.get_window().get_state() is_full = window_state & Gdk.WindowState.FULLSCREEN action.set_state(state) if state and not is_full: self.fullscreen() elif is_full: self.unfullscreen() def action_stop(self, *args): # TODO: This is the only window-level action we have that still # works on the "current" document like this. self.current_doc().action_stop() def page_removed(self, page, status): if hasattr(page, 'scheduler'): self.scheduler.remove_scheduler(page.scheduler) page_num = self.notebook.page_num(page) if self.notebook.get_current_page() == page_num: self.handle_current_doc_switch(page) self.notebook.remove_page(page_num) # Normal switch-page handlers don't get run for removing the # last page from a notebook. if not self.has_pages(): self.on_switch_page(self.notebook, page, -1) if self.should_close: cancelled = self.emit( 'delete-event', Gdk.Event.new(Gdk.EventType.DELETE)) if not cancelled: self.destroy() def on_page_state_changed(self, page, old_state, new_state): if self.should_close and old_state == ComparisonState.Closing: # Cancel closing if one of our tabs does self.should_close = False def on_file_changed(self, srcpage, filename): for page in self.notebook.get_children(): if page != srcpage: page.on_file_changed(filename) @Gtk.Template.Callback() def on_open_recent(self, recent_selector, uri): try: self.append_recent(uri) except (IOError, ValueError): # FIXME: Need error handling, but no sensible display location log.exception(f'Error opening recent file {uri}') def _append_page(self, page): nbl = NotebookLabel(page=page) self.notebook.append_page(page, nbl) self.notebook.child_set_property(page, 'tab-expand', True) # Change focus to the newly created page only if the user is on a # DirDiff or VcView page, or if it's a new tab page. This prevents # cycling through X pages when X diffs are initiated. if isinstance(self.current_doc(), DirDiff) or \ isinstance(self.current_doc(), VcView) or \ isinstance(page, NewDiffTab): self.notebook.set_current_page(self.notebook.page_num(page)) if hasattr(page, 'scheduler'): self.scheduler.add_scheduler(page.scheduler) if isinstance(page, MeldDoc): page.file_changed_signal.connect(self.on_file_changed) page.create_diff_signal.connect( lambda obj, arg, kwargs: self.append_diff(arg, **kwargs)) page.tab_state_changed.connect(self.on_page_state_changed) page.close_signal.connect(self.page_removed) self.notebook.set_tab_reorderable(page, True) def append_new_comparison(self): doc = NewDiffTab(self) self._append_page(doc) self.notebook.on_label_changed(doc, _("New comparison"), None) def diff_created_cb(doc, newdoc): doc.on_delete_event() idx = self.notebook.page_num(newdoc) self.notebook.set_current_page(idx) doc.connect("diff-created", diff_created_cb) return doc def append_dirdiff( self, gfiles: Sequence[Optional[Gio.File]], auto_compare: bool = False, ) -> DirDiff: assert len(gfiles) in (1, 2, 3) doc = DirDiff(len(gfiles)) self._append_page(doc) gfiles = [f or Gio.File.new_for_path("") for f in gfiles] doc.folders = gfiles doc.set_locations() if auto_compare: doc.scheduler.add_task(doc.auto_compare) return doc def append_filediff( self, gfiles, *, encodings=None, merge_output=None, meta=None): assert len(gfiles) in (1, 2, 3) # Check whether to show image window or not. if files_are_images(gfiles): doc = ImageDiff(len(gfiles)) else: doc = FileDiff(len(gfiles)) self._append_page(doc) doc.set_files(gfiles, encodings) if merge_output is not None: doc.set_merge_output_file(merge_output) if meta is not None: doc.set_meta(meta) return doc def append_filemerge(self, gfiles, merge_output=None): if len(gfiles) != 3: raise ValueError( _("Need three files to auto-merge, got: %r") % [f.get_parse_name() for f in gfiles]) doc = FileDiff( len(gfiles), comparison_mode=FileComparisonMode.AutoMerge) self._append_page(doc) doc.set_files(gfiles) if merge_output is not None: doc.set_merge_output_file(merge_output) return doc def append_diff( self, gfiles: Sequence[Optional[Gio.File]], auto_compare: bool = False, auto_merge: bool = False, merge_output: Optional[Gio.File] = None, meta: Optional[Dict[str, Any]] = None, ): have_directories = False have_files = False for f in gfiles: if not f: continue file_type = f.query_file_type(Gio.FileQueryInfoFlags.NONE, None) if file_type == Gio.FileType.DIRECTORY: have_directories = True else: have_files = True if have_directories and have_files: raise ValueError( _("Cannot compare a mixture of files and directories")) elif have_directories: return self.append_dirdiff(gfiles, auto_compare) elif auto_merge: return self.append_filemerge(gfiles, merge_output=merge_output) else: return self.append_filediff( gfiles, merge_output=merge_output, meta=meta) def append_vcview(self, location, auto_compare=False): doc = VcView() self._append_page(doc) if isinstance(location, (list, tuple)): location = location[0] if location: doc.set_location(location.get_path()) if auto_compare: doc.scheduler.add_task(doc.auto_compare) return doc def append_recent(self, uri): comparison_type, gfiles = recent_comparisons.read(uri) comparison_method = { RecentType.File: self.append_filediff, RecentType.Folder: self.append_dirdiff, RecentType.Merge: self.append_filemerge, RecentType.VersionControl: self.append_vcview, } tab = comparison_method[comparison_type](gfiles) self.notebook.set_current_page(self.notebook.page_num(tab)) recent_comparisons.add(tab) return tab def _single_file_open(self, gfile): doc = VcView() def cleanup(): self.scheduler.remove_scheduler(doc.scheduler) self.scheduler.add_task(cleanup) self.scheduler.add_scheduler(doc.scheduler) path = gfile.get_path() doc.set_location(path) doc.create_diff_signal.connect( lambda obj, arg, kwargs: self.append_diff(arg, **kwargs)) doc.run_diff(path) def open_paths(self, gfiles, auto_compare=False, auto_merge=False, focus=False): tab = None if len(gfiles) == 1: gfile = gfiles[0] if not gfile or ( gfile.query_file_type(Gio.FileQueryInfoFlags.NONE, None) == Gio.FileType.DIRECTORY ): tab = self.append_vcview(gfile, auto_compare) else: self._single_file_open(gfile) elif len(gfiles) in (2, 3): tab = self.append_diff(gfiles, auto_compare=auto_compare, auto_merge=auto_merge) if tab: recent_comparisons.add(tab) if focus: self.notebook.set_current_page(self.notebook.page_num(tab)) return tab def current_doc(self): "Get the current doc or a dummy object if there is no current" index = self.notebook.get_current_page() if index >= 0: page = self.notebook.get_nth_page(index) if isinstance(page, MeldDoc): return page class DummyDoc: def __getattr__(self, a): return lambda *x: None return DummyDoc()
19,232
Python
.py
432
34.881944
83
0.630654
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,804
treehelpers.py
GNOME_meld/meld/treehelpers.py
# Copyright (C) 2002-2006 Stephen Kennedy <stevek@gnome.org> # Copyright (C) 2011-2016 Kai Willadsen <kai.willadsen@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or (at # your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from gi.repository import Gtk def tree_path_as_tuple(path): """Get the path indices as a tuple This helper only exists because we often want to use tree paths as set members or dictionary keys, and this is a convenient option. """ return tuple(path.get_indices()) def tree_path_prev(path): if not path or path[-1] == 0: return None return path[:-1] + [path[-1] - 1] def tree_path_up(path): if not path: return None return path[:-1] def valid_path(model, path): try: model.get_iter(path) return True except ValueError: return False def refocus_deleted_path(model, path): # Since the passed path has been deleted, either the path is now a # valid successor, or there are no successors. If valid, return it. # If not, and the path has a predecessor sibling (immediate or # otherwise), then return that. If there are no siblings, traverse # parents until we get a valid path, and return that. if valid_path(model, path): return path new_path = tree_path_prev(path) while new_path: if valid_path(model, new_path): return new_path new_path = tree_path_prev(new_path) new_path = tree_path_up(path) while new_path: if valid_path(model, new_path): return new_path new_path = tree_path_up(new_path) class SearchableTreeStore(Gtk.TreeStore): def inorder_search_down(self, it): while it: child = self.iter_children(it) if child: it = child else: next_it = self.iter_next(it) if next_it: it = next_it else: while True: it = self.iter_parent(it) if not it: return next_it = self.iter_next(it) if next_it: it = next_it break yield it def inorder_search_up(self, it): while it: path = self.get_path(it) if path[-1]: path = path[:-1] + [path[-1] - 1] it = self.get_iter(path) while 1: nc = self.iter_n_children(it) if nc: it = self.iter_nth_child(it, nc - 1) else: break else: up = self.iter_parent(it) if up: it = up else: return yield it def get_previous_next_paths(self, path, match_func): prev_path, next_path = None, None try: start_iter = self.get_iter(path) except ValueError: # Invalid tree path return None, None for it in self.inorder_search_up(start_iter): if match_func(it): prev_path = self.get_path(it) break for it in self.inorder_search_down(start_iter): if match_func(it): next_path = self.get_path(it) break return prev_path, next_path
4,035
Python
.py
109
26.522936
71
0.565206
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,805
newdifftab.py
GNOME_meld/meld/newdifftab.py
# Copyright (C) 2011-2013 Kai Willadsen <kai.willadsen@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or (at # your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import enum from gi.repository import Gio, GLib, GObject, Gtk from meld.conf import _ from meld.melddoc import LabeledObjectMixin, MeldDoc from meld.recent import recent_comparisons from meld.ui.util import map_widgets_into_lists class DiffType(enum.IntEnum): # TODO: This should probably live in MeldWindow Unselected = -1 File = 0 Folder = 1 Version = 2 def supports_blank(self): return self in (self.File, self.Folder) @Gtk.Template(resource_path='/org/gnome/meld/ui/new-diff-tab.ui') class NewDiffTab(Gtk.Alignment, LabeledObjectMixin): __gtype_name__ = "NewDiffTab" __gsignals__ = { 'diff-created': (GObject.SignalFlags.RUN_FIRST, None, (object,)), } close_signal = MeldDoc.close_signal label_changed_signal = LabeledObjectMixin.label_changed label_text = _("New comparison") button_compare = Gtk.Template.Child() button_new_blank = Gtk.Template.Child() button_type_dir = Gtk.Template.Child() button_type_file = Gtk.Template.Child() button_type_vc = Gtk.Template.Child() choosers_notebook = Gtk.Template.Child() dir_chooser0 = Gtk.Template.Child() dir_chooser1 = Gtk.Template.Child() dir_chooser2 = Gtk.Template.Child() dir_three_way_checkbutton = Gtk.Template.Child() file_chooser0 = Gtk.Template.Child() file_chooser1 = Gtk.Template.Child() file_chooser2 = Gtk.Template.Child() file_three_way_checkbutton = Gtk.Template.Child() vc_chooser0 = Gtk.Template.Child() def __init__(self, parentapp): super().__init__() map_widgets_into_lists( self, ["file_chooser", "dir_chooser", "vc_chooser"] ) self.button_types = [ self.button_type_file, self.button_type_dir, self.button_type_vc, ] self.diff_methods = { DiffType.File: parentapp.append_filediff, DiffType.Folder: parentapp.append_dirdiff, DiffType.Version: parentapp.append_vcview, } self.diff_type = DiffType.Unselected default_path = GLib.get_home_dir() for chooser in self.file_chooser: chooser.set_current_folder(default_path) self.show() @Gtk.Template.Callback() def on_button_type_toggled(self, button, *args): if not button.get_active(): if not any([b.get_active() for b in self.button_types]): button.set_active(True) return for b in self.button_types: if b is not button: b.set_active(False) self.diff_type = DiffType(self.button_types.index(button)) self.choosers_notebook.set_current_page(self.diff_type + 1) # FIXME: Add support for new blank for VcView self.button_new_blank.set_sensitive( self.diff_type.supports_blank()) self.button_compare.set_sensitive(True) @Gtk.Template.Callback() def on_three_way_checkbutton_toggled(self, button, *args): if button is self.file_three_way_checkbutton: self.file_chooser2.set_sensitive(button.get_active()) else: # button is self.dir_three_way_checkbutton self.dir_chooser2.set_sensitive(button.get_active()) @Gtk.Template.Callback() def on_file_set(self, filechooser, *args): gfile = filechooser.get_file() if not gfile: return parent = gfile.get_parent() if not parent: return if parent.query_file_type( Gio.FileQueryInfoFlags.NONE, None) == Gio.FileType.DIRECTORY: for chooser in self.file_chooser: if not chooser.get_file(): chooser.set_current_folder_file(parent) # TODO: We could do checks here to prevent errors: check to see if # we've got binary files; check for null file selections; sniff text # encodings; check file permissions. def _get_num_paths(self): if self.diff_type in (DiffType.File, DiffType.Folder): three_way_buttons = ( self.file_three_way_checkbutton, self.dir_three_way_checkbutton, ) three_way = three_way_buttons[self.diff_type].get_active() num_paths = 3 if three_way else 2 else: # DiffType.Version num_paths = 1 return num_paths @Gtk.Template.Callback() def on_button_compare_clicked(self, *args): type_choosers = (self.file_chooser, self.dir_chooser, self.vc_chooser) choosers = type_choosers[self.diff_type][:self._get_num_paths()] compare_gfiles = [chooser.get_file() for chooser in choosers] compare_kwargs = {} tab = self.diff_methods[self.diff_type]( compare_gfiles, **compare_kwargs) recent_comparisons.add(tab) self.emit('diff-created', tab) @Gtk.Template.Callback() def on_button_new_blank_clicked(self, *args): # TODO: This doesn't work the way I'd like for DirDiff and VCView. # It should do something similar to FileDiff; give a tab with empty # file entries and no comparison done. # File comparison wants None for its paths here. Folder mode # needs an actual directory. if self.diff_type == DiffType.File: gfiles = [None] * self._get_num_paths() else: gfiles = [Gio.File.new_for_path("")] * self._get_num_paths() tab = self.diff_methods[self.diff_type](gfiles) self.emit('diff-created', tab) def on_container_switch_in_event(self, window): self.label_changed.emit(self.label_text, self.tooltip_text) window.text_filter_button.set_visible(False) window.folder_filter_button.set_visible(False) window.vc_filter_button.set_visible(False) window.next_conflict_button.set_visible(False) window.previous_conflict_button.set_visible(False) def on_container_switch_out_event(self, *args): pass def on_delete_event(self, *args): self.close_signal.emit(0) return Gtk.ResponseType.OK
6,827
Python
.py
156
35.75
78
0.656019
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,806
meldapp.py
GNOME_meld/meld/meldapp.py
# Copyright (C) 2002-2006 Stephen Kennedy <stevek@gnome.org> # Copyright (C) 2010-2013 Kai Willadsen <kai.willadsen@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or (at # your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import io import logging import optparse import os from gi.repository import Gdk, Gio, GLib, Gtk import meld.accelerators import meld.conf from meld.conf import _ from meld.filediff import FileDiff from meld.meldwindow import MeldWindow from meld.preferences import PreferencesDialog log = logging.getLogger(__name__) # Monkeypatching optparse like this is obviously awful, but this is to # handle Unicode translated strings within optparse itself that will # otherwise crash badly. This just makes optparse use our ugettext # import of _, rather than the non-unicode gettext. optparse._ = _ class MeldApp(Gtk.Application): def __init__(self): super().__init__( application_id=meld.conf.APPLICATION_ID, flags=Gio.ApplicationFlags.HANDLES_COMMAND_LINE, ) GLib.set_application_name(meld.conf.APPLICATION_NAME) GLib.set_prgname(meld.conf.APPLICATION_ID) Gtk.Window.set_default_icon_name(meld.conf.APPLICATION_ID) self.set_resource_base_path(meld.conf.RESOURCE_BASE) provider = Gtk.CssProvider() provider.load_from_resource(self.make_resource_path('meld.css')) Gtk.StyleContext.add_provider_for_screen( Gdk.Screen.get_default(), provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION) def make_resource_path(self, resource_path: str) -> str: return f'{self.props.resource_base_path}/{resource_path}' def do_startup(self): Gtk.Application.do_startup(self) meld.accelerators.register_accels(self) actions = ( ("preferences", self.preferences_callback), ("help", self.help_callback), ("about", self.about_callback), ("quit", self.quit_callback), ) for (name, callback) in actions: action = Gio.SimpleAction.new(name, None) action.connect('activate', callback) self.add_action(action) # Keep clipboard contents after application exit clip = Gtk.Clipboard.get_default(Gdk.Display.get_default()) clip.set_can_store(None) self.new_window() def do_activate(self): self.get_active_window().present() def do_command_line(self, command_line): tab = self.parse_args(command_line) if isinstance(tab, int): return tab elif tab: def done(tab, status): self.release() tab.command_line.set_exit_status(status) tab.command_line = None self.hold() tab.command_line = command_line tab.close_signal.connect(done) window = self.get_active_window() if not window.has_pages(): window.append_new_comparison() self.activate() return 0 def do_window_removed(self, widget): Gtk.Application.do_window_removed(self, widget) if not len(self.get_windows()): self.quit() # We can't override do_local_command_line because it has no introspection # annotations: https://bugzilla.gnome.org/show_bug.cgi?id=687912 # def do_local_command_line(self, command_line): # return False def preferences_callback(self, action, parameter): parent = self.get_active_window() dialog = PreferencesDialog(transient_for=parent) dialog.present() def help_callback(self, action, parameter): if meld.conf.DATADIR_IS_UNINSTALLED: uri = "https://meld.app/help/" else: uri = "help:meld" Gtk.show_uri( Gdk.Screen.get_default(), uri, Gtk.get_current_event_time()) def about_callback(self, action, parameter): builder = Gtk.Builder.new_from_resource( '/org/gnome/meld/ui/about-dialog.ui') dialog = builder.get_object('about-dialog') dialog.set_version(meld.conf.__version__) dialog.set_logo_icon_name(meld.conf.APPLICATION_ID) dialog.set_transient_for(self.get_active_window()) dialog.run() dialog.destroy() def quit_callback(self, action, parameter): for window in self.get_windows(): cancelled = window.emit( "delete-event", Gdk.Event.new(Gdk.EventType.DELETE)) if cancelled: return window.destroy() self.quit() def new_window(self): window = MeldWindow() self.add_window(window) return window def open_files( self, gfiles, *, window=None, close_on_error=False, **kwargs): """Open a comparison between files in a Meld window :param gfiles: list of Gio.File to be compared :param window: window in which to open comparison tabs; if None, the current window is used :param close_on_error: if true, close window if an error occurs """ window = window or self.get_active_window() try: return window.open_paths(gfiles, **kwargs) except ValueError: if close_on_error: self.remove_window(window) raise def diff_files_callback(self, option, opt_str, value, parser): """Gather --diff arguments and append to a list""" assert value is None diff_files_args = [] while parser.rargs: # Stop if we find a short- or long-form arg, or a '--' # Note that this doesn't handle negative numbers. arg = parser.rargs[0] if arg[:2] == "--" or (arg[:1] == "-" and len(arg) > 1): break else: diff_files_args.append(arg) del parser.rargs[0] if len(diff_files_args) not in (1, 2, 3): raise optparse.OptionValueError( _("wrong number of arguments supplied to --diff")) parser.values.diff.append(diff_files_args) def parse_args(self, command_line): usages = [ ("", _("Start with an empty window")), ("<%s|%s>" % (_("file"), _("folder")), _("Start a version control comparison")), ("<%s> <%s> [<%s>]" % ((_("file"),) * 3), _("Start a 2- or 3-way file comparison")), ("<%s> <%s> [<%s>]" % ((_("folder"),) * 3), _("Start a 2- or 3-way folder comparison")), ] pad_args_fmt = "%-" + str(max([len(s[0]) for s in usages])) + "s %s" usage_lines = [" %prog " + pad_args_fmt % u for u in usages] usage = "\n" + "\n".join(usage_lines) usage += _( "\n" "\n" "For file comparisons, the special argument @blank may be used " "instead of\n" "a <file> argument to create a blank pane." ) class GLibFriendlyOptionParser(optparse.OptionParser): def __init__(self, command_line, *args, **kwargs): self.command_line = command_line self.should_exit = False self.output = io.StringIO() self.exit_status = 0 super().__init__(*args, **kwargs) def exit(self, status=0, msg=None): self.should_exit = True # FIXME: This is... let's say... an unsupported method. Let's # be circumspect about the likelihood of this working. try: self.command_line.do_print_literal( self.command_line, self.output.getvalue()) except Exception: print(self.output.getvalue()) self.exit_status = status def print_usage(self, file=None): if self.usage: print(self.get_usage(), file=self.output) def print_version(self, file=None): if self.version: print(self.get_version(), file=self.output) def print_help(self, file=None): print(self.format_help(), file=self.output) def error(self, msg): self.local_error(msg) raise ValueError() def local_error(self, msg): self.print_usage() error_string = _("Error: %s\n") % msg print(error_string, file=self.output) self.exit(2) parser = GLibFriendlyOptionParser( command_line=command_line, usage=usage, description=_("Meld is a file and directory comparison tool."), version="%prog " + meld.conf.__version__) parser.add_option( "-L", "--label", action="append", default=[], help=_("Set label to use instead of file name")) parser.add_option( "-n", "--newtab", action="store_true", default=False, help=_("Open a new tab in an already running instance")) parser.add_option( "-a", "--auto-compare", action="store_true", default=False, help=_("Automatically compare all differing files on startup")) parser.add_option( "-u", "--unified", action="store_true", help=_("Ignored for compatibility")) parser.add_option( "-o", "--output", action="store", type="string", dest="outfile", default=None, help=_("Set the target file for saving a merge result")) parser.add_option( "--auto-merge", None, action="store_true", default=False, help=_("Automatically merge files")) parser.add_option( "", "--comparison-file", action="store", type="string", dest="comparison_file", default=None, help=_("Load a saved comparison from a Meld comparison file")) parser.add_option( "", "--diff", action="callback", callback=self.diff_files_callback, dest="diff", default=[], help=_("Create a diff tab for the supplied files or folders")) def cleanup(): if not command_line.get_is_remote(): self.quit() parser.command_line = None rawargs = command_line.get_arguments()[1:] try: options, args = parser.parse_args(rawargs) except ValueError: # Thrown to avert further parsing when we've hit an error, because # of our weird when-to-exit issues. pass if parser.should_exit: cleanup() return parser.exit_status if len(args) > 3: parser.local_error(_("too many arguments (wanted 0-3, got %d)") % len(args)) elif options.auto_merge and len(args) < 3: parser.local_error(_("can’t auto-merge less than 3 files")) elif options.auto_merge and any([os.path.isdir(f) for f in args]): parser.local_error(_("can’t auto-merge directories")) if parser.should_exit: cleanup() return parser.exit_status if options.comparison_file or (len(args) == 1 and args[0].endswith(".meldcmp")): path = options.comparison_file or args[0] comparison_file_path = os.path.expanduser(path) gio_file = Gio.File.new_for_path(comparison_file_path) try: tab = self.get_active_window().append_recent( gio_file.get_uri()) except (IOError, ValueError): parser.local_error(_("Error reading saved comparison file")) if parser.should_exit: cleanup() return parser.exit_status return tab def make_file_from_command_line(arg): f = command_line.create_file_for_arg(arg) if not f.query_exists(cancellable=None): # May be a relative path with ':', misinterpreted as a URI cwd = Gio.File.new_for_path(command_line.get_cwd()) relative = Gio.File.resolve_relative_path(cwd, arg) if relative.query_exists(cancellable=None): return relative # We have special handling for not-a-file arguments: # * @blank is just a new blank tab # # The intention was to support @clipboard here as well, which # would have started with a pasted clipboard, but Wayland's # clipboard security makes this borderline impossible for us. if arg == "@blank": return None # Otherwise we fall through and return the original arg for # a better error message if f.get_uri() is None: raise ValueError(_("invalid path or URI “%s”") % arg) # TODO: support for directories specified by URIs file_type = f.query_file_type(Gio.FileQueryInfoFlags.NONE, None) if not f.is_native() and file_type == Gio.FileType.DIRECTORY: if f.get_path() is None: raise ValueError( _("remote folder “{}” not supported").format(arg)) return f tab = None error = None comparisons = [c for c in [args] + options.diff if c] # Every Meld invocation creates at most one window. If there is # no existing application, a window is created in do_startup(). # If there is an existing application, then this is a remote # invocation, in which case we'll create a window if and only # if the new-tab flag is not provided. # # In all cases, all tabs newly created here are attached to the # same window, either implicitly by using the most-recently- # focused window, or explicitly as below. window = None close_on_error = False if command_line.get_is_remote() and not options.newtab: window = self.new_window() close_on_error = True for i, paths in enumerate(comparisons): auto_merge = options.auto_merge and i == 0 try: files = [make_file_from_command_line(p) for p in paths] tab = self.open_files( files, window=window, close_on_error=close_on_error, auto_compare=options.auto_compare, auto_merge=auto_merge, focus=i == 0, ) except ValueError as err: error = err log.debug("Couldn't open comparison: %s", error, exc_info=True) else: if i > 0: continue if options.label: tab.set_labels(options.label) if options.outfile and isinstance(tab, FileDiff): outfile = make_file_from_command_line(options.outfile) tab.set_merge_output_file(outfile) if error: if not tab: parser.local_error(error) else: print(error) # Delete the error here; otherwise we keep the local app # alive in a reference cycle, and the command line hangs. del error if parser.should_exit: cleanup() return parser.exit_status parser.command_line = None return tab if len(comparisons) == 1 else None
16,257
Python
.py
360
33.394444
79
0.576123
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,807
linkmap.py
GNOME_meld/meld/linkmap.py
# Copyright (C) 2002-2006 Stephen Kennedy <stevek@gnome.org> # Copyright (C) 2009-2013 Kai Willadsen <kai.willadsen@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or (at # your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import math from gi.repository import Gdk, Gtk from meld.settings import get_meld_settings from meld.style import get_common_theme # Rounded rectangle corner radius for culled changes display RADIUS = 3 class LinkMap(Gtk.DrawingArea): __gtype_name__ = "LinkMap" def __init__(self): self.filediff = None self.views = [] def associate(self, filediff, left_view, right_view): self.filediff = filediff self.views = [left_view, right_view] if self.get_direction() == Gtk.TextDirection.RTL: self.views.reverse() self.view_indices = [filediff.textview.index(t) for t in self.views] meld_settings = get_meld_settings() self.on_setting_changed(meld_settings, 'style-scheme') meld_settings.connect('changed', self.on_setting_changed) def on_setting_changed(self, settings, key): if key == 'style-scheme': self.fill_colors, self.line_colors = get_common_theme() def do_draw(self, context): if not self.views: return pix_start = [t.get_visible_rect().y for t in self.views] y_offset = [ t.translate_coordinates(self, 0, 0)[1] + 1 for t in self.views] clip_y = min(y_offset) - 1 clip_height = max(t.get_visible_rect().height for t in self.views) + 2 allocation = self.get_allocation() stylecontext = self.get_style_context() Gtk.render_background( stylecontext, context, 0, clip_y, allocation.width, clip_height) context.set_line_width(1.0) height = allocation.height visible = [ self.views[0].get_line_num_for_y(pix_start[0]), self.views[0].get_line_num_for_y(pix_start[0] + height), self.views[1].get_line_num_for_y(pix_start[1]), self.views[1].get_line_num_for_y(pix_start[1] + height), ] # For bezier control points x_steps = [-0.5, allocation.width / 2, allocation.width + 0.5] q_rad = math.pi / 2 left, right = self.view_indices def view_offset_line(view_idx, line_num): line_start = self.views[view_idx].get_y_for_line_num(line_num) return line_start - pix_start[view_idx] + y_offset[view_idx] for c in self.filediff.linediffer.pair_changes(left, right, visible): # f and t are short for "from" and "to" f0, f1 = [view_offset_line(0, line) for line in c[1:3]] t0, t1 = [view_offset_line(1, line) for line in c[3:5]] # We want the last pixel of the previous line f1 = f1 if f1 == f0 else f1 - 1 t1 = t1 if t1 == t0 else t1 - 1 # If either endpoint is completely off-screen, we cull for clarity if (t0 < 0 and t1 < 0) or (t0 > height and t1 > height): if f0 == f1: continue context.arc( x_steps[0], f0 - 0.5 + RADIUS, RADIUS, q_rad * 3, 0) context.arc(x_steps[0], f1 - 0.5 - RADIUS, RADIUS, 0, q_rad) context.close_path() elif (f0 < 0 and f1 < 0) or (f0 > height and f1 > height): if t0 == t1: continue context.arc_negative(x_steps[2], t0 - 0.5 + RADIUS, RADIUS, q_rad * 3, q_rad * 2) context.arc_negative(x_steps[2], t1 - 0.5 - RADIUS, RADIUS, q_rad * 2, q_rad) context.close_path() else: context.move_to(x_steps[0], f0 - 0.5) context.curve_to(x_steps[1], f0 - 0.5, x_steps[1], t0 - 0.5, x_steps[2], t0 - 0.5) context.line_to(x_steps[2], t1 - 0.5) context.curve_to(x_steps[1], t1 - 0.5, x_steps[1], f1 - 0.5, x_steps[0], f1 - 0.5) context.close_path() Gdk.cairo_set_source_rgba(context, self.fill_colors[c[0]]) context.fill_preserve() chunk_idx = self.filediff.linediffer.locate_chunk(left, c[1])[0] if chunk_idx == self.filediff.cursor.chunk: highlight = self.fill_colors['current-chunk-highlight'] Gdk.cairo_set_source_rgba(context, highlight) context.fill_preserve() Gdk.cairo_set_source_rgba(context, self.line_colors[c[0]]) context.stroke() LinkMap.set_css_name("link-map") class ScrollLinkMap(Gtk.DrawingArea): __gtype_name__ = "ScrollLinkMap"
5,430
Python
.py
110
38.145455
78
0.582042
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,808
tree.py
GNOME_meld/meld/tree.py
# Copyright (C) 2002-2006 Stephen Kennedy <stevek@gnome.org> # Copyright (C) 2011-2015 Kai Willadsen <kai.willadsen@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or (at # your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import os from gi.module import get_introspection_module from gi.repository import Gdk, GLib, GObject, Pango from meld.style import colour_lookup_with_fallback from meld.treehelpers import SearchableTreeStore from meld.vc._vc import ( # noqa: F401 CONFLICT_BASE, CONFLICT_LOCAL, CONFLICT_MERGED, CONFLICT_OTHER, CONFLICT_REMOTE, CONFLICT_THIS, STATE_CONFLICT, STATE_EMPTY, STATE_ERROR, STATE_IGNORED, STATE_MAX, STATE_MISSING, STATE_MODIFIED, STATE_NEW, STATE_NOCHANGE, STATE_NONE, STATE_NONEXIST, STATE_NORMAL, STATE_REMOVED, STATE_SPINNER, ) _GIGtk = None try: _GIGtk = get_introspection_module('Gtk') except Exception: pass COL_PATH, COL_STATE, COL_TEXT, COL_ICON, COL_TINT, COL_FG, COL_STYLE, \ COL_WEIGHT, COL_STRIKE, COL_END = list(range(10)) COL_TYPES = (str, str, str, str, Gdk.RGBA, Gdk.RGBA, Pango.Style, Pango.Weight, bool) class DiffTreeStore(SearchableTreeStore): def __init__(self, ntree, types): full_types = [] for col_type in (COL_TYPES + tuple(types)): full_types.extend([col_type] * ntree) super().__init__(*full_types) self._none_of_cols = { col_num: GObject.Value(col_type, None) for col_num, col_type in enumerate(full_types) } self.ntree = ntree self._setup_default_styles() def _setup_default_styles(self, style=None): roman, italic = Pango.Style.NORMAL, Pango.Style.ITALIC normal, bold = Pango.Weight.NORMAL, Pango.Weight.BOLD lookup = colour_lookup_with_fallback unk_fg = lookup("meld:unknown-text", "foreground") new_fg = lookup("meld:insert", "foreground") mod_fg = lookup("meld:replace", "foreground") del_fg = lookup("meld:delete", "foreground") err_fg = lookup("meld:error", "foreground") con_fg = lookup("meld:conflict", "foreground") self.text_attributes = [ # foreground, style, weight, strikethrough (unk_fg, roman, normal, None), # STATE_IGNORED (unk_fg, roman, normal, None), # STATE_NONE (None, roman, normal, None), # STATE_NORMAL (None, italic, normal, None), # STATE_NOCHANGE (err_fg, roman, bold, None), # STATE_ERROR (unk_fg, italic, normal, None), # STATE_EMPTY (new_fg, roman, bold, None), # STATE_NEW (mod_fg, roman, bold, None), # STATE_MODIFIED (mod_fg, roman, normal, None), # STATE_RENAMED (con_fg, roman, bold, None), # STATE_CONFLICT (del_fg, roman, bold, True), # STATE_REMOVED (del_fg, roman, bold, True), # STATE_MISSING (unk_fg, roman, normal, True), # STATE_NONEXIST (None, italic, normal, None), # STATE_SPINNER ] self.icon_details = [ # file-icon, folder-icon, file-tint ("text-x-generic", "folder", None), # IGNORED ("text-x-generic", "folder", None), # NONE ("text-x-generic", "folder", None), # NORMAL ("text-x-generic", "folder", None), # NOCHANGE ("dialog-warning-symbolic", None, None), # ERROR (None, None, None), # EMPTY ("text-x-generic", "folder", new_fg), # NEW ("text-x-generic", "folder", mod_fg), # MODIFIED ("text-x-generic", "folder", mod_fg), # RENAMED ("text-x-generic", "folder", con_fg), # CONFLICT ("text-x-generic", "folder", del_fg), # REMOVED (None, "folder", unk_fg), # MISSING (None, "folder", unk_fg), # NONEXIST ("text-x-generic", "folder", None), # SPINNER ] assert len(self.icon_details) == len(self.text_attributes) == STATE_MAX def value_paths(self, it): return [self.value_path(it, i) for i in range(self.ntree)] def value_path(self, it, pane): return self.get_value(it, self.column_index(COL_PATH, pane)) def is_folder(self, it, pane, path): # A folder may no longer exist, and is only tracked by VC. # Therefore, check the icon instead, as the pane already knows. icon = self.get_value(it, self.column_index(COL_ICON, pane)) return icon == "folder" or (bool(path) and os.path.isdir(path)) def column_index(self, col, pane): return self.ntree * col + pane def add_entries(self, parent, names): it = self.append(parent) for pane, path in enumerate(names): self.unsafe_set(it, pane, {COL_PATH: path}) return it def add_empty(self, parent, text="empty folder"): it = self.append(parent) for pane in range(self.ntree): self.set_state(it, pane, STATE_EMPTY, text) return it def add_error(self, parent, msg, pane, defaults={}): it = self.append(parent) key_values = {COL_STATE: str(STATE_ERROR)} key_values.update(defaults) for i in range(self.ntree): self.unsafe_set(it, i, key_values) self.set_state(it, pane, STATE_ERROR, msg) def set_path_state(self, it, pane, state, isdir=0, display_text=None): if not display_text: fullname = self.get_value(it, self.column_index(COL_PATH, pane)) display_text = GLib.markup_escape_text(os.path.basename(fullname)) self.set_state(it, pane, state, display_text, isdir) def set_state(self, it, pane, state, label, isdir=0): icon = self.icon_details[state][1 if isdir else 0] tint = None if isdir else self.icon_details[state][2] fg, style, weight, strike = self.text_attributes[state] self.unsafe_set(it, pane, { COL_STATE: str(state), COL_TEXT: label, COL_ICON: icon, COL_TINT: tint, COL_FG: fg, COL_STYLE: style, COL_WEIGHT: weight, COL_STRIKE: strike }) def get_state(self, it, pane): state_idx = self.column_index(COL_STATE, pane) try: return int(self.get_value(it, state_idx)) except TypeError: return None def _find_next_prev_diff(self, start_path): def match_func(it): # TODO: It works, but matching on the first pane only is very poor return self.get_state(it, 0) not in ( STATE_NORMAL, STATE_NOCHANGE, STATE_EMPTY) return self.get_previous_next_paths(start_path, match_func) def state_rows(self, states): """Generator of rows in one of the given states Tree iterators are returned in depth-first tree order. """ root = self.get_iter_first() for it in self.inorder_search_down(root): state = self.get_state(it, 0) if state in states: yield it def unsafe_set(self, treeiter, pane, keys_values): """ This must be fastest than super.set, at the cost that may crash the application if you don't know what your're passing here. ie: pass treeiter or column as None crash meld treeiter: Gtk.TreeIter keys_values: dict<column, value> column: Int col index value: Str (UTF-8), Int, Float, Double, Boolean, None or GObject return None """ safe_keys_values = { self.column_index(col, pane): val if val is not None else self._none_of_cols.get(self.column_index(col, pane)) for col, val in keys_values.items() } if _GIGtk and treeiter: columns = [col for col in safe_keys_values.keys()] values = [val for val in safe_keys_values.values()] _GIGtk.TreeStore.set(self, treeiter, columns, values) else: self.set(treeiter, safe_keys_values) class TreeviewCommon: def on_treeview_popup_menu(self, treeview): cursor_path, cursor_col = treeview.get_cursor() if not cursor_path: self.popup_menu.popup_at_pointer(None) return True # We always want to pop up to the right of the first column, # ignoring the actual cursor column location. rect = treeview.get_background_area( cursor_path, treeview.get_column(0)) self.popup_menu.popup_at_rect( treeview.get_bin_window(), rect, Gdk.Gravity.SOUTH_EAST, Gdk.Gravity.NORTH_WEST, None, ) return True def on_treeview_button_press_event(self, treeview, event): # If we have multiple treeviews, unselect clear other tree selections num_panes = getattr(self, 'num_panes', 1) if num_panes > 1: for t in self.treeview[:self.num_panes]: if t != treeview: t.get_selection().unselect_all() if (event.triggers_context_menu() and event.type == Gdk.EventType.BUTTON_PRESS): treeview.grab_focus() path = treeview.get_path_at_pos(int(event.x), int(event.y)) if path is None: return False selection = treeview.get_selection() model, rows = selection.get_selected_rows() if path[0] not in rows: selection.unselect_all() selection.select_path(path[0]) treeview.set_cursor(path[0]) self.popup_menu.popup_at_pointer(event) return True return False def treeview_search_cb(model, column, key, it, data): # If the key contains a path separator, search the whole path, # otherwise just use the filename. If the key is all lower-case, do a # case-insensitive match. abs_search = '/' in key lower_key = key.islower() for path in model.value_paths(it): if not path: continue text = path if abs_search else os.path.basename(path) text = text.lower() if lower_key else text if key in text: return False return True
10,934
Python
.py
253
34.118577
79
0.603593
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,809
diffgrid.py
GNOME_meld/meld/diffgrid.py
# Copyright (C) 2014 Marco Brito <bcaza@null.net> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or (at # your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from gi.repository import Gdk, GObject, Gtk class DiffGrid(Gtk.Grid): __gtype_name__ = "DiffGrid" column_count = 10 handle_columns = (2, 6) def __init__(self): super().__init__() self._in_drag = False self._drag_pos = -1 self._drag_handle = None self._handle1 = HandleWindow() self._handle2 = HandleWindow() def do_realize(self): Gtk.Grid.do_realize(self) self._handle1.realize(self) self._handle2.realize(self) def do_unrealize(self): self._handle1.unrealize() self._handle2.unrealize() Gtk.Grid.do_unrealize(self) def do_map(self): Gtk.Grid.do_map(self) drag = self.get_child_at(2, 0) self._handle1.set_visible(drag and drag.get_visible()) drag = self.get_child_at(6, 0) self._handle2.set_visible(drag and drag.get_visible()) def do_unmap(self): self._handle1.set_visible(False) self._handle2.set_visible(False) Gtk.Grid.do_unmap(self) def _handle_set_prelight(self, window, flag): if hasattr(window, "handle"): window.handle.set_prelight(flag) def do_enter_notify_event(self, event): if hasattr(event.window, "handle"): event.window.handle.set_prelight(True) def do_leave_notify_event(self, event): if self._in_drag: return if hasattr(event.window, "handle"): event.window.handle.set_prelight(False) def do_button_press_event(self, event): if event.button & Gdk.BUTTON_PRIMARY: self._drag_pos = event.x self._in_drag = True return True return False def do_button_release_event(self, event): if event.button & Gdk.BUTTON_PRIMARY: self._in_drag = False return True return False def do_motion_notify_event(self, event): if event.state & Gdk.ModifierType.BUTTON1_MASK: if hasattr(event.window, "handle"): x, y = event.window.get_position() pos = round(x + event.x - self._drag_pos) event.window.handle.set_position(pos) self._drag_handle = event.window.handle self.queue_resize_no_redraw() return True return False def _calculate_positions( self, xmin, xmax, pane_sep_width_1, pane_sep_width_2, wpane1, wpane2, wpane3): wremain = max(0, xmax - xmin - pane_sep_width_1 - pane_sep_width_2) pos1 = self._handle1.get_position(wremain, xmin) pos2 = self._handle2.get_position(wremain, xmin + pane_sep_width_1) if not self._drag_handle: npanes = 0 if wpane1 > 0: npanes += 1 if wpane2 > 0: npanes += 1 if wpane3 > 0: npanes += 1 wpane = float(wremain) / max(1, npanes) if wpane1 > 0: wpane1 = wpane if wpane2 > 0: wpane2 = wpane if wpane3 > 0: wpane3 = wpane xminlink1 = xmin + wpane1 xmaxlink2 = xmax - wpane3 - pane_sep_width_2 wlinkpane = pane_sep_width_1 + wpane2 if wpane1 == 0: pos1 = xminlink1 if wpane3 == 0: pos2 = xmaxlink2 if wpane2 == 0: if wpane3 == 0: pos1 = pos2 - pane_sep_width_2 else: pos2 = pos1 + pane_sep_width_1 if self._drag_handle == self._handle2: xminlink2 = xminlink1 + wlinkpane pos2 = min(max(xminlink2, pos2), xmaxlink2) xmaxlink1 = pos2 - wlinkpane pos1 = min(max(xminlink1, pos1), xmaxlink1) else: xmaxlink1 = xmaxlink2 - wlinkpane pos1 = min(max(xminlink1, pos1), xmaxlink1) xminlink2 = pos1 + wlinkpane pos2 = min(max(xminlink2, pos2), xmaxlink2) self._handle1.set_position(pos1) self._handle2.set_position(pos2) return int(round(pos1)), int(round(pos2)) def do_size_allocate(self, allocation): # We should be chaining up here to: # Gtk.Grid.do_size_allocate(self, allocation) # However, when we do this, we hit issues with doing multiple # allocations in a single allocation cycle (see bgo#779883). self.set_allocation(allocation) wcols, hrows = self._get_min_sizes() yrows = [allocation.y, allocation.y + hrows[0], # Roughly equivalent to hard-coding row 1 to expand=True allocation.y + (allocation.height - hrows[2] - hrows[3]), allocation.y + (allocation.height - hrows[3]), allocation.y + allocation.height] (wpane1, wgutter1, wlink1, wgutter2, wpane2, wgutter3, wlink2, wgutter4, wpane3, wmap) = wcols xmin = allocation.x xmax = allocation.x + allocation.width - wmap pane_sep_width_1 = wgutter1 + wlink1 + wgutter2 pane_sep_width_2 = wgutter3 + wlink2 + wgutter4 pos1, pos2 = self._calculate_positions( xmin, xmax, pane_sep_width_1, pane_sep_width_2, wpane1, wpane2, wpane3 ) wpane1 = pos1 - allocation.x wpane2 = pos2 - (pos1 + pane_sep_width_1) wpane3 = xmax - (pos2 + pane_sep_width_2) wcols = ( allocation.x, wpane1, wgutter1, wlink1, wgutter2, wpane2, wgutter3, wlink2, wgutter4, wpane3, wmap) columns = [sum(wcols[:i + 1]) for i in range(len(wcols))] def child_allocate(child): if not child.get_visible(): return left, top, width, height = self.child_get( child, 'left-attach', 'top-attach', 'width', 'height') # This is a copy, and we have to do this because there's no Python # access to Gtk.Allocation. child_alloc = self.get_allocation() child_alloc.x = columns[left] child_alloc.y = yrows[top] child_alloc.width = columns[left + width] - columns[left] child_alloc.height = yrows[top + height] - yrows[top] if self.get_direction() == Gtk.TextDirection.RTL: child_alloc.x = ( allocation.x + allocation.width - (child_alloc.x - allocation.x) - child_alloc.width) child.size_allocate(child_alloc) for child in self.get_children(): child_allocate(child) if self.get_realized(): mapped = self.get_mapped() ydrag = yrows[0] hdrag = yrows[1] - yrows[0] self._handle1.set_visible(mapped and pane_sep_width_1 > 0) self._handle1.move_resize(pos1, ydrag, pane_sep_width_1, hdrag) self._handle2.set_visible(mapped and pane_sep_width_2 > 0) self._handle2.move_resize(pos2, ydrag, pane_sep_width_2, hdrag) def _get_min_sizes(self): hrows = [0] * 4 wcols = [0] * self.column_count for row in range(4): for col in range(self.column_count): child = self.get_child_at(col, row) if child and child.get_visible(): msize, nsize = child.get_preferred_size() # Ignore spanning columns in width calculations; we should # do this properly, but it's difficult. spanning = GObject.Value(int) self.child_get_property(child, 'width', spanning) spanning = spanning.get_int() # We ignore natural size when calculating required # width, but use it when doing required height. The # logic here is that height-for-width means that # minimum width requisitions mean more-than-minimum # heights. This is all extremely dodgy, but works # for now. if spanning == 1: wcols[col] = max(wcols[col], msize.width) hrows[row] = max(hrows[row], msize.height, nsize.height) return wcols, hrows def do_draw(self, context): Gtk.Grid.do_draw(self, context) self._handle1.draw(context) self._handle2.draw(context) class HandleWindow(): # We restrict the handle width because render_handle doesn't pay # attention to orientation. handle_width = 10 def __init__(self): self._widget = None self._window = None self._area_x = -1 self._area_y = -1 self._area_width = 1 self._area_height = 1 self._prelit = False self._pos = 0.0 self._transform = (0, 0) def get_position(self, width, xtrans): self._transform = (width, xtrans) return float(self._pos * width) + xtrans def set_position(self, pos): width, xtrans = self._transform self._pos = float(pos - xtrans) / width def realize(self, widget): attr = Gdk.WindowAttr() attr.window_type = Gdk.WindowType.CHILD attr.x = self._area_x attr.y = self._area_y attr.width = self._area_width attr.height = self._area_height attr.wclass = Gdk.WindowWindowClass.INPUT_OUTPUT attr.event_mask = (widget.get_events() | Gdk.EventMask.BUTTON_PRESS_MASK | Gdk.EventMask.BUTTON_RELEASE_MASK | Gdk.EventMask.ENTER_NOTIFY_MASK | Gdk.EventMask.LEAVE_NOTIFY_MASK | Gdk.EventMask.POINTER_MOTION_MASK) attr.cursor = Gdk.Cursor.new_from_name( widget.get_display(), "col-resize", ) attr_mask = (Gdk.WindowAttributesType.X | Gdk.WindowAttributesType.Y | Gdk.WindowAttributesType.CURSOR) parent = widget.get_parent_window() self._window = Gdk.Window(parent, attr, attr_mask) self._window.handle = self self._widget = widget self._widget.register_window(self._window) def unrealize(self): self._widget.unregister_window(self._window) def set_visible(self, visible): if visible: self._window.show() else: self._window.hide() def move_resize(self, x, y, width, height): self._window.move_resize(x, y, width, height) self._area_x = x self._area_y = y self._area_width = width self._area_height = height def set_prelight(self, flag): self._prelit = flag self._widget.queue_draw_area(self._area_x, self._area_y, self._area_width, self._area_height) def draw(self, cairocontext): alloc = self._widget.get_allocation() padding = 5 x = self._area_x - alloc.x + padding y = self._area_y - alloc.y + padding width = max(0, self._area_width - 2 * padding) height = max(0, self._area_height - 2 * padding) if width == 0 or height == 0: return stylecontext = self._widget.get_style_context() state = stylecontext.get_state() if self._widget.is_focus(): state |= Gtk.StateFlags.SELECTED if self._prelit: state |= Gtk.StateFlags.PRELIGHT if Gtk.cairo_should_draw_window(cairocontext, self._window): stylecontext.save() stylecontext.set_state(state) stylecontext.add_class(Gtk.STYLE_CLASS_PANE_SEPARATOR) stylecontext.add_class(Gtk.STYLE_CLASS_VERTICAL) color = stylecontext.get_background_color(state) if color.alpha > 0.0: xcenter = x + width / 2.0 - self.handle_width / 2.0 Gtk.render_handle( stylecontext, cairocontext, xcenter, y, self.handle_width, height) else: xcenter = x + width / 2.0 Gtk.render_line(stylecontext, cairocontext, xcenter, y, xcenter, y + height) stylecontext.restore()
12,994
Python
.py
300
31.926667
78
0.572005
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,810
patchdialog.py
GNOME_meld/meld/patchdialog.py
# Copyright (C) 2002-2006 Stephen Kennedy <stevek@gnome.org> # Copyright (C) 2009-2010, 2013 Kai Willadsen <kai.willadsen@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or (at # your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import difflib import os from gi.repository import Gdk, Gio, GLib, Gtk, GtkSource from meld.conf import _ from meld.iohelpers import prompt_save_filename from meld.misc import error_dialog from meld.settings import get_meld_settings from meld.sourceview import LanguageManager @Gtk.Template(resource_path='/org/gnome/meld/ui/patch-dialog.ui') class PatchDialog(Gtk.Dialog): __gtype_name__ = "PatchDialog" left_radiobutton = Gtk.Template.Child("left_radiobutton") reverse_checkbutton = Gtk.Template.Child("reverse_checkbutton") right_radiobutton = Gtk.Template.Child("right_radiobutton") side_selection_box = Gtk.Template.Child("side_selection_box") side_selection_label = Gtk.Template.Child("side_selection_label") textview: Gtk.TextView = Gtk.Template.Child("textview") def __init__(self, filediff): super().__init__() self.set_transient_for(filediff.get_toplevel()) self.filediff = filediff buf = GtkSource.Buffer() self.textview.set_buffer(buf) lang = LanguageManager.get_language_from_mime_type("text/x-diff") buf.set_language(lang) buf.set_highlight_syntax(True) self.index_map = {self.left_radiobutton: (0, 1), self.right_radiobutton: (1, 2)} self.left_patch = True self.reverse_patch = self.reverse_checkbutton.get_active() if self.filediff.num_panes < 3: self.side_selection_label.hide() self.side_selection_box.hide() meld_settings = get_meld_settings() self.textview.modify_font(meld_settings.font) self.textview.set_editable(False) meld_settings.connect('changed', self.on_setting_changed) def on_setting_changed(self, settings, key): if key == "font": self.textview.modify_font(settings.font) @Gtk.Template.Callback() def on_buffer_selection_changed(self, radiobutton): if not radiobutton.get_active(): return self.left_patch = radiobutton == self.left_radiobutton self.update_patch() @Gtk.Template.Callback() def on_reverse_checkbutton_toggled(self, checkbutton): self.reverse_patch = checkbutton.get_active() self.update_patch() def update_patch(self): indices = (0, 1) if not self.left_patch: indices = (1, 2) if self.reverse_patch: indices = (indices[1], indices[0]) texts = [] for b in self.filediff.textbuffer: start, end = b.get_bounds() text = b.get_text(start, end, False) lines = text.splitlines(True) # Ensure that the last line ends in a newline barelines = text.splitlines(False) if barelines and lines and barelines[-1] == lines[-1]: # Final line lacks a line-break; add in a best guess if len(lines) > 1: previous_linebreak = lines[-2][len(barelines[-2]):] else: previous_linebreak = "\n" lines[-1] += previous_linebreak texts.append(lines) names = [self.filediff.textbuffer[i].data.label for i in range(3)] prefix = os.path.commonprefix(names) names = [n[prefix.rfind("/") + 1:] for n in names] buf = self.textview.get_buffer() text0, text1 = texts[indices[0]], texts[indices[1]] name0, name1 = names[indices[0]], names[indices[1]] diff = difflib.unified_diff(text0, text1, name0, name1) diff_text = "".join(d for d in diff) buf.set_text(diff_text) def save_patch(self, targetfile: Gio.File): buf = self.textview.get_buffer() sourcefile = GtkSource.File.new() saver = GtkSource.FileSaver.new_with_target( buf, sourcefile, targetfile) saver.save_async( GLib.PRIORITY_HIGH, callback=self.file_saved_cb, ) def file_saved_cb(self, saver, result, *args): gfile = saver.get_location() try: saver.save_finish(result) except GLib.Error as err: filename = GLib.markup_escape_text(gfile.get_parse_name()) error_dialog( primary=_("Could not save file %s.") % filename, secondary=_("Couldn’t save file due to:\n%s") % ( GLib.markup_escape_text(str(err))), ) def run(self): self.update_patch() result = super().run() if result < 0: self.hide() return # Copy patch to clipboard if result == 1: buf = self.textview.get_buffer() start, end = buf.get_bounds() clip = Gtk.Clipboard.get_default(Gdk.Display.get_default()) clip.set_text(buf.get_text(start, end, False), -1) clip.store() # Save patch as a file else: gfile = prompt_save_filename(_("Save Patch")) if gfile: self.save_patch(gfile) self.hide()
5,845
Python
.py
134
34.716418
74
0.628476
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,811
recent.py
GNOME_meld/meld/recent.py
# Copyright (C) 2012-2013, 2017-2018 Kai Willadsen <kai.willadsen@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or (at # your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ Recent files integration for Meld's multi-element comparisons The GTK+ recent files mechanism is designed to take only single files with a limited set of metadata. In Meld, we almost always need to enter pairs or triples of files or directories, along with some information about the comparison type. The solution provided by this module is to create fake single-file registers for multi-file comparisons, and tell the recent files infrastructure that that's actually what we opened. """ import configparser import enum import logging import os import sys import tempfile from typing import List, Tuple from gi.repository import Gio, GLib, Gtk import meld.misc from meld.conf import _ from meld.iohelpers import is_file_on_tmpfs log = logging.getLogger(__name__) class RecentType(enum.Enum): File = "File" Folder = "Folder" VersionControl = "Version control" Merge = "Merge" class RecentFiles: mime_type = "application/x-meld-comparison" recent_path = os.path.join(GLib.get_user_data_dir(), "meld") recent_suffix = ".meldcmp" # Recent data app_name = "Meld" def __init__(self): self.recent_manager = Gtk.RecentManager.get_default() self.recent_filter = Gtk.RecentFilter() self.recent_filter.add_mime_type(self.mime_type) self._stored_comparisons = {} self.app_exec = os.path.abspath(sys.argv[0]) if not os.path.exists(self.recent_path): os.makedirs(self.recent_path) self._clean_recent_files() self._update_recent_files() self.recent_manager.connect("changed", self._update_recent_files) def add(self, tab, flags=None): """Add a tab to our recently-used comparison list The passed flags are currently ignored. In the future these are to be used for extra initialisation not captured by the tab itself. """ try: recent_type, gfiles = tab.get_comparison() except Exception: log.warning(f'Failed to get recent comparison data for {tab}') return # While Meld handles comparisons including None, recording these as # recently-used comparisons just isn't that sane. if not gfiles or None in gfiles: return if any(is_file_on_tmpfs(f) for f in gfiles): log.debug("Not adding comparison because it includes tmpfs path") return uris = [f.get_uri() for f in gfiles] if not all(uris): return names = [f.get_parse_name() for f in gfiles] # If a (type, uris) comparison is already registered, then re-add # the corresponding comparison file comparison_key = (recent_type, tuple(uris)) if comparison_key in self._stored_comparisons: gfile = Gio.File.new_for_uri( self._stored_comparisons[comparison_key]) else: recent_path = self._write_recent_file(recent_type, uris) gfile = Gio.File.new_for_path(recent_path) if len(uris) > 1: display_name = " : ".join(meld.misc.shorten_names(*names)) else: display_path = names[0] userhome = os.path.expanduser("~") if display_path.startswith(userhome): # FIXME: What should we show on Windows? display_path = "~" + display_path[len(userhome):] display_name = _("Version control:") + " " + display_path # FIXME: Should this be translatable? It's not actually used anywhere. description = "{} comparison\n{}".format( recent_type.value, ", ".join(uris)) recent_metadata = Gtk.RecentData() recent_metadata.mime_type = self.mime_type recent_metadata.app_name = self.app_name recent_metadata.app_exec = "%s --comparison-file %%u" % self.app_exec recent_metadata.display_name = display_name recent_metadata.description = description recent_metadata.is_private = True self.recent_manager.add_full(gfile.get_uri(), recent_metadata) def read(self, uri: str) -> Tuple[RecentType, List[Gio.File]]: """Read stored comparison from URI""" comp_gfile = Gio.File.new_for_uri(uri) comp_path = comp_gfile.get_path() if not comp_gfile.query_exists(None) or not comp_path: raise IOError("Recent comparison file does not exist") try: config = configparser.RawConfigParser() config.read(comp_path) assert (config.has_section("Comparison") and config.has_option("Comparison", "type") and config.has_option("Comparison", "uris")) except (configparser.Error, AssertionError): raise ValueError("Invalid recent comparison file") try: recent_type = RecentType(config.get("Comparison", "type")) except ValueError: raise ValueError("Invalid recent comparison file") uris = config.get("Comparison", "uris").split(";") gfiles = [Gio.File.new_for_uri(u) for u in uris] return recent_type, gfiles def _write_recent_file(self, recent_type: RecentType, uris): # TODO: Use GKeyFile instead, and return a Gio.File. This is why we're # using ';' to join comparison paths. with tempfile.NamedTemporaryFile( mode='w+t', prefix='recent-', suffix=self.recent_suffix, dir=self.recent_path, delete=False) as f: config = configparser.RawConfigParser() config.add_section("Comparison") config.set("Comparison", "type", recent_type.value) config.set("Comparison", "uris", ";".join(uris)) config.write(f) name = f.name return name def _clean_recent_files(self): # Remove from RecentManager any comparisons with no existing file meld_items = self._filter_items(self.recent_filter, self.recent_manager.get_items()) for item in meld_items: if not item.exists(): self.recent_manager.remove_item(item.get_uri()) meld_items = [item for item in meld_items if item.exists()] # Remove any comparison files that are not listed by RecentManager item_uris = [item.get_uri() for item in meld_items] item_paths = [ Gio.File.new_for_uri(uri).get_path() for uri in item_uris] stored = [p for p in os.listdir(self.recent_path) if p.endswith(self.recent_suffix)] for path in stored: file_path = os.path.abspath(os.path.join(self.recent_path, path)) if file_path not in item_paths: try: os.remove(file_path) except OSError: pass def _update_recent_files(self, *args): meld_items = self._filter_items(self.recent_filter, self.recent_manager.get_items()) item_uris = [item.get_uri() for item in meld_items if item.exists()] self._stored_comparisons = {} for item_uri in item_uris: try: recent_type, gfiles = self.read(item_uri) except (IOError, ValueError): continue # Store and look up comparisons by type and paths gfile_uris = tuple(gfile.get_uri() for gfile in gfiles) self._stored_comparisons[recent_type, gfile_uris] = item_uri def _filter_items(self, recent_filter, items): getters = {Gtk.RecentFilterFlags.URI: "uri", Gtk.RecentFilterFlags.DISPLAY_NAME: "display_name", Gtk.RecentFilterFlags.MIME_TYPE: "mime_type", Gtk.RecentFilterFlags.APPLICATION: "applications", Gtk.RecentFilterFlags.GROUP: "groups", Gtk.RecentFilterFlags.AGE: "age"} needed = recent_filter.get_needed() attrs = [v for k, v in getters.items() if needed & k] filtered_items = [] for i in items: filter_data = {} for attr in attrs: filter_data[attr] = getattr(i, "get_" + attr)() filter_info = Gtk.RecentFilterInfo() filter_info.contains = needed for f, v in filter_data.items(): # https://bugzilla.gnome.org/show_bug.cgi?id=695970 if isinstance(v, list): continue setattr(filter_info, f, v) if recent_filter.filter(filter_info): filtered_items.append(i) return filtered_items def __str__(self): items = self.recent_manager.get_items() descriptions = [] for i in self._filter_items(self.recent_filter, items): descriptions.append("%s\n%s\n" % (i.get_display_name(), i.get_uri_display())) return "\n".join(descriptions) recent_comparisons = RecentFiles()
9,755
Python
.py
207
37.169082
78
0.624461
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,812
settings.py
GNOME_meld/meld/settings.py
# Copyright (C) 2013 Kai Willadsen <kai.willadsen@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or (at # your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import sys from typing import Optional from gi.repository import Gio, GObject, GtkSource, Pango import meld.conf import meld.filters class MeldSettings(GObject.GObject): """Handler for settings that can't easily be bound to object properties""" __gsignals__ = { 'file-filters-changed': (GObject.SignalFlags.RUN_FIRST, None, ()), 'text-filters-changed': (GObject.SignalFlags.RUN_FIRST, None, ()), 'changed': (GObject.SignalFlags.RUN_FIRST, None, (str,)), } def __init__(self): super().__init__() self.on_setting_changed(settings, 'filename-filters') self.on_setting_changed(settings, 'text-filters') self.on_setting_changed(settings, 'use-system-font') self.on_setting_changed(settings, 'prefer-dark-theme') self.style_scheme = self._style_scheme_from_gsettings() settings.connect('changed', self.on_setting_changed) def on_setting_changed(self, settings, key): if key == 'filename-filters': self.file_filters = self._filters_from_gsetting( 'filename-filters', meld.filters.FilterEntry.SHELL) self.emit('file-filters-changed') elif key == 'text-filters': self.text_filters = self._filters_from_gsetting( 'text-filters', meld.filters.FilterEntry.REGEX) self.emit('text-filters-changed') elif key in ('use-system-font', 'custom-font'): self.font = self._current_font_from_gsetting() self.emit('changed', 'font') elif key in ('style-scheme', 'prefer-dark-theme'): self.style_scheme = self._style_scheme_from_gsettings() self.emit('changed', 'style-scheme') def _style_scheme_from_gsettings(self): from meld.style import set_base_style_scheme manager = GtkSource.StyleSchemeManager.get_default() scheme = manager.get_scheme(settings.get_string('style-scheme')) prefer_dark = settings.get_boolean("prefer-dark-theme") set_base_style_scheme(scheme, prefer_dark) return scheme def _filters_from_gsetting(self, key, filt_type): filter_params = settings.get_value(key) filters = [ meld.filters.FilterEntry.new_from_gsetting(params, filt_type) for params in filter_params ] return filters def _current_font_from_gsetting(self, *args): if settings.get_boolean('use-system-font'): if sys.platform == 'win32': font_string = 'Consolas 11' elif interface_settings: font_string = interface_settings.get_string( 'monospace-font-name') else: font_string = 'monospace' else: font_string = settings.get_string('custom-font') return Pango.FontDescription(font_string) def load_settings_schema(schema_id): if meld.conf.DATADIR_IS_UNINSTALLED: schema_source = Gio.SettingsSchemaSource.new_from_directory( str(meld.conf.DATADIR), Gio.SettingsSchemaSource.get_default(), False, ) schema = schema_source.lookup(schema_id, False) settings = Gio.Settings.new_full( schema=schema, backend=None, path=None) else: settings = Gio.Settings.new(schema_id) return settings def load_interface_settings() -> Optional[Gio.Settings]: # We conditionally load these since they're only used for default # fonts and can sometimes be missing (e.g., in some Windows setups) default_source = Gio.SettingsSchemaSource.get_default() schema = default_source.lookup("org.gnome.desktop.interface", False) if not schema: return None return Gio.Settings.new_full(schema=schema, backend=None, path=None) def create_settings(): global settings, interface_settings, _meldsettings settings = load_settings_schema(meld.conf.SETTINGS_SCHEMA_ID) interface_settings = load_interface_settings() _meldsettings = MeldSettings() def bind_settings(obj): global settings bind_flags = ( Gio.SettingsBindFlags.DEFAULT | Gio.SettingsBindFlags.NO_SENSITIVITY) for binding in getattr(obj, '__gsettings_bindings__', ()): settings_id, property_id = binding settings.bind(settings_id, obj, property_id, bind_flags) bind_flags = ( Gio.SettingsBindFlags.GET | Gio.SettingsBindFlags.NO_SENSITIVITY) for binding in getattr(obj, '__gsettings_bindings_view__', ()): settings_id, property_id = binding settings.bind(settings_id, obj, property_id, bind_flags) def get_settings() -> Gio.Settings: return settings def get_meld_settings() -> MeldSettings: return _meldsettings settings = None interface_settings = None _meldsettings = None
5,519
Python
.py
120
38.583333
78
0.676909
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,813
imagediff.py
GNOME_meld/meld/imagediff.py
# Copyright (C) 2002-2006 Stephen Kennedy <stevek@gnome.org> # Copyright (C) 2009-2019 Kai Willadsen <kai.willadsen@gmail.com> # Copyright (C) 2023 Martin van Zijl <martin.vanzijl@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or (at # your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import logging from collections.abc import Sequence from typing import Optional from gi.repository import Gdk, GdkPixbuf, Gio, GLib, GObject, Gtk, GtkSource # TODO: Don't from-import whole modules from meld import misc from meld.conf import _ from meld.const import FileComparisonMode from meld.externalhelpers import open_files_external from meld.melddoc import ComparisonState, MeldDoc from meld.misc import with_focused_pane from meld.settings import bind_settings from meld.ui.util import map_widgets_into_lists log = logging.getLogger(__name__) # Cache the supported image MIME types. _supported_mime_types: Optional[Sequence[str]] = None def get_supported_image_mime_types() -> Sequence[str]: global _supported_mime_types if _supported_mime_types is None: # Get list of supported formats. _supported_mime_types = [] supported_image_formats = GdkPixbuf.Pixbuf.get_formats() for image_format in supported_image_formats: _supported_mime_types += image_format.get_mime_types() return _supported_mime_types def file_is_image(gfile): """Check if file is an image.""" # Check for null value. if not gfile: return False # Check MIME type of the file. try: info = gfile.query_info( Gio.FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE, Gio.FileQueryInfoFlags.NONE, None, ) file_content_type = info.get_content_type() return file_content_type in get_supported_image_mime_types() except GLib.Error as err: if err.code == Gio.IOErrorEnum.NOT_FOUND: return False raise def files_are_images(gfiles): """Check if all files in the list are images.""" for gfile in gfiles: if not file_is_image(gfile): return False # All files are images. return True @Gtk.Template(resource_path='/org/gnome/meld/ui/imagediff.ui') class ImageDiff(Gtk.Box, MeldDoc): """Two or three way comparison of image files""" __gtype_name__ = "ImageDiff" close_signal = MeldDoc.close_signal create_diff_signal = MeldDoc.create_diff_signal file_changed_signal = MeldDoc.file_changed_signal label_changed = MeldDoc.label_changed tab_state_changed = MeldDoc.tab_state_changed scroll_window0 = Gtk.Template.Child() viewport0 = Gtk.Template.Child() image_event_box0 = Gtk.Template.Child() image_main0 = Gtk.Template.Child() scroll_window1 = Gtk.Template.Child() viewport1 = Gtk.Template.Child() image_event_box1 = Gtk.Template.Child() image_main1 = Gtk.Template.Child() scroll_window2 = Gtk.Template.Child() viewport2 = Gtk.Template.Child() image_event_box2 = Gtk.Template.Child() image_main2 = Gtk.Template.Child() lock_scrolling = GObject.Property( type=bool, nick='Lock scrolling of all panes', default=False, ) def __init__( self, num_panes, *, comparison_mode: FileComparisonMode = FileComparisonMode.Compare, ): super().__init__() self.files = [None, None, None] # FIXME: # This unimaginable hack exists because GObject (or GTK+?) # doesn't actually correctly chain init calls, even if they're # not to GObjects. As a workaround, we *should* just be able to # put our class first, but because of Gtk.Template we can't do # that if it's a GObject, because GObject doesn't support # multiple inheritance and we need to inherit from our Widget # parent to make Template work. MeldDoc.__init__(self) bind_settings(self) widget_lists = [ "image_main", "image_event_box", "scroll_window", "viewport", ] map_widgets_into_lists(self, widget_lists) self.warned_bad_comparison = False self._keymask = 0 self.meta = {} self.lines_removed = 0 self.focus_pane = None # TODO: Add synchronized scrolling for large images. # Set up per-view action group for top-level menu insertion self.view_action_group = Gio.SimpleActionGroup() # Manually handle GAction additions # TODO: Highlight the selected image. actions = ( ('copy-full-path', self.action_copy_full_path), ('open-external', self.action_open_external), ('open-folder', self.action_open_folder), ) for name, callback in actions: action = Gio.SimpleAction.new(name, None) action.connect('activate', callback) self.view_action_group.add_action(action) builder = Gtk.Builder.new_from_resource( '/org/gnome/meld/ui/imagediff-menus.ui') self.popup_menu_model = builder.get_object('imagediff-context-menu') self.popup_menu = Gtk.Menu.new_from_model(self.popup_menu_model) self.popup_menu.attach_to_widget(self) builder = Gtk.Builder.new_from_resource( '/org/gnome/meld/ui/imagediff-actions.ui') self.toolbar_actions = builder.get_object('view-toolbar') self.copy_action_button = builder.get_object('copy_action_button') self.set_num_panes(num_panes) def set_files(self, gfiles, encodings=None): """Load the given files If an element is None, the text of a pane is left as is. """ if len(gfiles) != self.num_panes: return encodings = encodings or ((None,) * len(gfiles)) files = [] for pane, (gfile, encoding) in enumerate(zip(gfiles, encodings)): if gfile: files.append((pane, gfile, encoding)) for pane, gfile, encoding in files: self.load_file_in_pane(pane, gfile, encoding) # Update tab label. self.files = gfiles self.recompute_label() def load_file_in_pane( self, pane: int, gfile: Gio.File, encoding: GtkSource.Encoding = None): """Load a file into the given pane Don't call this directly; use `set_file()` or `set_files()`, which handle sensitivity and signal connection. Even if you don't care about those things, you need it because they'll be unconditionally added after file load, which will cause duplicate handlers, etc. if you don't do this thing. """ self.image_main[pane].set_from_file(gfile.get_path()) def set_num_panes(self, n): if n == self.num_panes or n not in (1, 2, 3): return for widget in ( self.image_main[:n] + self.image_event_box[:n] + self.scroll_window[:n] + self.viewport[:n]): widget.show() for widget in ( self.image_main[n:] + self.image_event_box[n:] + self.scroll_window[n:] + self.viewport[n:]): widget.hide() self.num_panes = n def on_delete_event(self): self.state = ComparisonState.Closing self.close_signal.emit(0) return Gtk.ResponseType.OK def recompute_label(self): filenames = [f.get_path() for f in self.files if f] shortnames = misc.shorten_names(*filenames) label = self.meta.get("tablabel", "") if label: self.label_text = label tooltip_names = [label] else: self.label_text = " — ".join(shortnames) tooltip_names = filenames self.tooltip_text = "\n".join((_("File comparison:"), *tooltip_names)) self.label_changed.emit(self.label_text, self.tooltip_text) @with_focused_pane def action_open_folder(self, pane, *args): gfile = self.files[pane] if not gfile: return parent = gfile.get_parent() if parent: open_files_external(gfiles=[parent]) @with_focused_pane def action_open_external(self, pane, *args): gfile = self.files[pane] if not gfile: return gfiles = [gfile] open_files_external(gfiles=gfiles) @Gtk.Template.Callback() def on_imageview_popup_menu(self, imageview): self.popup_menu.popup_at_pointer() return True @Gtk.Template.Callback() def on_imageview_button_press_event(self, event_box, event): if event.button == 3: event_box.grab_focus() self.popup_menu.popup_at_pointer(event) return True return False def _get_focused_pane(self): for i in range(self.num_panes): if self.image_event_box[i].is_focus(): return i return -1 @with_focused_pane def action_copy_full_path(self, pane, *args): gfile = self.files[pane] if not gfile: return path = gfile.get_path() or gfile.get_uri() clip = Gtk.Clipboard.get_default(Gdk.Display.get_default()) clip.set_text(path, -1) clip.store() def _set_external_action_sensitivity(self): # FIXME: This sensitivity is very confused. Essentially, it's always # enabled because we don't unset focus_pane, but the action uses the # current pane focus (i.e., _get_focused_pane) instead of focus_pane. have_file = self.focus_pane is not None self.set_action_enabled("open-external", have_file) @Gtk.Template.Callback() def on_imageview_focus_in_event(self, view, event): self.focus_pane = view self._set_external_action_sensitivity() @Gtk.Template.Callback() def on_imageview_focus_out_event(self, view, event): self._set_external_action_sensitivity()
10,551
Python
.py
256
33.199219
78
0.643339
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,814
chunkmap.py
GNOME_meld/meld/chunkmap.py
# Copyright (C) 2019 Kai Willadsen <kai.willadsen@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or (at # your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import collections import logging from typing import Any, List, Mapping, Tuple import cairo from gi.repository import Gdk, GObject, Gtk from meld.settings import get_meld_settings from meld.style import get_common_theme from meld.tree import STATE_ERROR, STATE_MODIFIED, STATE_NEW from meld.ui.gtkutil import make_gdk_rgba log = logging.getLogger(__name__) class ChunkMap(Gtk.DrawingArea): __gtype_name__ = "ChunkMap" adjustment = GObject.Property( type=Gtk.Adjustment, nick='Adjustment used for scrolling the mapped view', flags=( GObject.ParamFlags.READWRITE | GObject.ParamFlags.CONSTRUCT_ONLY ), ) handle_overdraw_alpha = GObject.Property( type=float, nick='Alpha of the document handle overdraw', default=0.2, ) handle_outline_alpha = GObject.Property( type=float, nick='Alpha of the document handle outline', default=0.4, ) @GObject.Property( type=GObject.TYPE_PYOBJECT, nick='Chunks defining regions in the mapped view', ) def chunks(self): return self._chunks @chunks.setter def chunks_set(self, chunks): self._chunks = chunks self._cached_map = None self.queue_draw() overdraw_padding: int = 2 def __init__(self): super().__init__() self.chunks = [] self._have_grab = False self._cached_map = None self.click_controller = Gtk.GestureMultiPress(widget=self) self.click_controller.connect("pressed", self.button_press_event) self.click_controller.connect("released", self.button_release_event) self.motion_controller = Gtk.EventControllerMotion(widget=self) self.motion_controller.set_propagation_phase(Gtk.PropagationPhase.TARGET) self.motion_controller.connect("motion", self.motion_event) def do_realize(self): if not self.adjustment: log.critical( f'{self.__gtype_name__} initialized without an adjustment') return Gtk.DrawingArea.do_realize(self) self.set_events( Gdk.EventMask.POINTER_MOTION_MASK | Gdk.EventMask.BUTTON_PRESS_MASK | Gdk.EventMask.BUTTON_RELEASE_MASK ) self.adjustment.connect('changed', lambda w: self.queue_draw()) self.adjustment.connect('value-changed', lambda w: self.queue_draw()) meld_settings = get_meld_settings() meld_settings.connect('changed', self.on_setting_changed) self.on_setting_changed(meld_settings, 'style-scheme') return Gtk.DrawingArea.do_realize(self) def do_size_allocate(self, *args): self._cached_map = None return Gtk.DrawingArea.do_size_allocate(self, *args) def on_setting_changed(self, settings, key): if key == 'style-scheme': self.fill_colors, self.line_colors = get_common_theme() self._cached_map = None def get_height_scale(self) -> float: return 1.0 def get_map_base_colors( self) -> Tuple[Gdk.RGBA, Gdk.RGBA, Gdk.RGBA, Gdk.RGBA]: raise NotImplementedError() def _make_map_base_colors( self, widget) -> Tuple[Gdk.RGBA, Gdk.RGBA, Gdk.RGBA, Gdk.RGBA]: stylecontext = widget.get_style_context() base_set, base = ( stylecontext.lookup_color('theme_base_color')) if not base_set: base = make_gdk_rgba(1.0, 1.0, 1.0, 1.0) text_set, text = ( stylecontext.lookup_color('theme_text_color')) if not text_set: base = make_gdk_rgba(0.0, 0.0, 0.0, 1.0) border_set, border = ( stylecontext.lookup_color('borders')) if not border_set: base = make_gdk_rgba(0.95, 0.95, 0.95, 1.0) handle_overdraw = text.copy() handle_overdraw.alpha = self.handle_overdraw_alpha handle_outline = text.copy() handle_outline.alpha = self.handle_outline_alpha return base, border, handle_overdraw, handle_outline def chunk_coords_by_tag(self) -> Mapping[str, List[Tuple[float, float]]]: """Map chunks to buffer offsets for drawing, ordered by tag""" raise NotImplementedError() def do_draw(self, context: cairo.Context) -> bool: if not self.adjustment or self.adjustment.get_upper() <= 0: return False height = self.get_allocated_height() width = self.get_allocated_width() if width <= 0 or height <= 0: return False base_bg, base_outline, handle_overdraw, handle_outline = ( self.get_map_base_colors()) x0 = self.overdraw_padding + 0.5 x1 = width - 2 * x0 height_scale = height * self.get_height_scale() if self._cached_map is None: surface = cairo.Surface.create_similar( context.get_target(), cairo.CONTENT_COLOR_ALPHA, width, height) cache_ctx = cairo.Context(surface) cache_ctx.set_line_width(1) cache_ctx.rectangle(x0, -0.5, x1, height_scale + 0.5) Gdk.cairo_set_source_rgba(cache_ctx, base_bg) cache_ctx.fill() # We get drawing coordinates by tag to minimise our source # colour setting, and make this loop slightly cleaner. tagged_diffs = self.chunk_coords_by_tag() for tag, diffs in tagged_diffs.items(): Gdk.cairo_set_source_rgba(cache_ctx, self.fill_colors[tag]) for y0, y1 in diffs: y0 = round(y0 * height_scale) + 0.5 y1 = round(y1 * height_scale) - 0.5 cache_ctx.rectangle(x0, y0, x1, y1 - y0) cache_ctx.fill_preserve() Gdk.cairo_set_source_rgba(cache_ctx, self.line_colors[tag]) cache_ctx.stroke() cache_ctx.rectangle(x0, -0.5, x1, height_scale + 0.5) Gdk.cairo_set_source_rgba(cache_ctx, base_outline) cache_ctx.stroke() self._cached_map = surface context.set_source_surface(self._cached_map, 0, 0) context.paint() # Draw our scroll position indicator context.set_line_width(1) Gdk.cairo_set_source_rgba(context, handle_overdraw) adj_y = self.adjustment.get_value() / self.adjustment.get_upper() adj_h = self.adjustment.get_page_size() / self.adjustment.get_upper() context.rectangle( x0 - self.overdraw_padding, round(height_scale * adj_y) + 0.5, x1 + 2 * self.overdraw_padding, round(height_scale * adj_h) - 1, ) context.fill_preserve() Gdk.cairo_set_source_rgba(context, handle_outline) context.stroke() return True def _scroll_to_location(self, location: float, animate: bool): raise NotImplementedError() def _scroll_fraction(self, position: float, *, animate: bool = True): """Scroll the mapped textview to the given position This uses GtkTextView's scrolling so that the movement is animated. :param position: Position to scroll to, in event coordinates """ if not self.adjustment: return height = self.get_height_scale() * self.get_allocated_height() fraction = position / height adj = self.adjustment location = fraction * (adj.get_upper() - adj.get_lower()) self._scroll_to_location(location, animate) def button_press_event( self, controller: Gtk.GestureMultiPress, npress: int, x: float, y: float, ) -> None: self._scroll_fraction(y) self.grab_add() self._have_grab = True def button_release_event( self, controller: Gtk.GestureMultiPress, npress: int, x: float, y: float, ) -> bool: self.grab_remove() self._have_grab = False def motion_event( self, controller: Gtk.EventControllerMotion, x: float | None = None, y: float | None = None, ): if self._have_grab: self._scroll_fraction(y, animate=False) return True class TextViewChunkMap(ChunkMap): __gtype_name__ = 'TextViewChunkMap' textview = GObject.Property( type=Gtk.TextView, nick='Textview being mapped', flags=( GObject.ParamFlags.READWRITE | GObject.ParamFlags.CONSTRUCT_ONLY ), ) paired_adjustment_1 = GObject.Property( type=Gtk.Adjustment, nick='Paired adjustment used for scaling the map', flags=( GObject.ParamFlags.READWRITE | GObject.ParamFlags.CONSTRUCT_ONLY ), ) paired_adjustment_2 = GObject.Property( type=Gtk.Adjustment, nick='Paired adjustment used for scaling the map', flags=( GObject.ParamFlags.READWRITE | GObject.ParamFlags.CONSTRUCT_ONLY ), ) def do_realize(self): def force_redraw(*args: Any) -> None: self._cached_map = None self.queue_draw() self.textview.connect("notify::wrap-mode", force_redraw) return ChunkMap.do_realize(self) def get_height_scale(self): adjustments = [ self.props.adjustment, self.props.paired_adjustment_1, self.props.paired_adjustment_2, ] heights = [ adj.get_upper() for adj in adjustments if adj.get_upper() > 0 ] return self.props.adjustment.get_upper() / max(heights) def get_map_base_colors(self): return self._make_map_base_colors(self.textview) def chunk_coords_by_tag(self): buf = self.textview.get_buffer() tagged_diffs: Mapping[str, List[Tuple[float, float]]] tagged_diffs = collections.defaultdict(list) y, h = self.textview.get_line_yrange(buf.get_end_iter()) max_y = float(y + h) for chunk in self.chunks: start_iter = buf.get_iter_at_line(chunk.start_a) y0, _ = self.textview.get_line_yrange(start_iter) if chunk.start_a == chunk.end_a: y, h = y0, 0 else: end_iter = buf.get_iter_at_line(chunk.end_a - 1) y, h = self.textview.get_line_yrange(end_iter) tagged_diffs[chunk.tag].append((y0 / max_y, (y + h) / max_y)) return tagged_diffs def do_draw(self, context: cairo.Context) -> bool: if not self.textview: return False return ChunkMap.do_draw(self, context) def _scroll_to_location(self, location: float, animate: bool): if not self.textview: return _, it = self.textview.get_iter_at_location(0, location) if animate: self.textview.scroll_to_iter(it, 0.0, True, 1.0, 0.5) else: # TODO: Add handling for centreing adjustment like we do # for animated scroll above. self.adjustment.set_value(location) class TreeViewChunkMap(ChunkMap): __gtype_name__ = 'TreeViewChunkMap' treeview = GObject.Property( type=Gtk.TreeView, nick='Treeview being mapped', flags=( GObject.ParamFlags.READWRITE | GObject.ParamFlags.CONSTRUCT_ONLY ), ) treeview_idx = GObject.Property( type=int, nick='Index of the Treeview within the store', flags=( GObject.ParamFlags.READWRITE | GObject.ParamFlags.CONSTRUCT_ONLY ), ) chunk_type_map = { STATE_NEW: "insert", STATE_ERROR: "error", STATE_MODIFIED: "replace", } def __init__(self): super().__init__() self.model_signal_ids = [] def do_realize(self): self.treeview.connect('row-collapsed', self.clear_cached_map) self.treeview.connect('row-expanded', self.clear_cached_map) self.treeview.connect('notify::model', self.connect_model) self.connect_model() return ChunkMap.do_realize(self) def connect_model(self, *args): for model, signal_id in self.model_signal_ids: model.disconnect(signal_id) model = self.treeview.get_model() self.model_signal_ids = [ (model, model.connect('row-changed', self.clear_cached_map)), (model, model.connect('row-deleted', self.clear_cached_map)), (model, model.connect('row-inserted', self.clear_cached_map)), (model, model.connect('rows-reordered', self.clear_cached_map)), ] def clear_cached_map(self, *args): self._cached_map = None def get_map_base_colors(self): return self._make_map_base_colors(self.treeview) def chunk_coords_by_tag(self): def recurse_tree_states(rowiter): row_states.append( model.get_state(rowiter.iter, self.treeview_idx)) if self.treeview.row_expanded(rowiter.path): for row in rowiter.iterchildren(): recurse_tree_states(row) row_states = [] model = self.treeview.get_model() recurse_tree_states(next(iter(model))) # Terminating mark to force the last chunk to be added row_states.append(None) tagged_diffs: Mapping[str, List[Tuple[float, float]]] tagged_diffs = collections.defaultdict(list) numlines = len(row_states) - 1 chunkstart, laststate = 0, row_states[0] for index, state in enumerate(row_states): if state != laststate: action = self.chunk_type_map.get(laststate) if action is not None: chunk = (chunkstart / numlines, index / numlines) tagged_diffs[action].append(chunk) chunkstart, laststate = index, state return tagged_diffs def do_draw(self, context: cairo.Context) -> bool: if not self.treeview: return False return ChunkMap.do_draw(self, context) def _scroll_to_location(self, location: float, animate: bool): if not self.treeview or self.adjustment.get_upper() <= 0: return location -= self.adjustment.get_page_size() / 2 if animate: self.treeview.scroll_to_point(-1, location) else: self.adjustment.set_value(location)
15,200
Python
.py
369
31.775068
81
0.615285
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,815
style.py
GNOME_meld/meld/style.py
# Copyright (C) 2002-2006 Stephen Kennedy <stevek@gnome.org> # Copyright (C) 2009 Vincent Legoll <vincent.legoll@gmail.com> # Copyright (C) 2012-2019 Kai Willadsen <kai.willadsen@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or (at # your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import enum from typing import Mapping, Optional, Tuple from gi.repository import Gdk, Gtk, GtkSource from meld.conf import _ class MeldStyleScheme(enum.Enum): base = "meld-base" dark = "meld-dark" style_scheme: Optional[GtkSource.StyleScheme] = None base_style_scheme: Optional[GtkSource.StyleScheme] = None def set_base_style_scheme( new_style_scheme: GtkSource.StyleScheme, prefer_dark: bool, ) -> GtkSource.StyleScheme: global base_style_scheme global style_scheme gtk_settings = Gtk.Settings.get_default() if gtk_settings: gtk_settings.props.gtk_application_prefer_dark_theme = prefer_dark style_scheme = new_style_scheme # Get our text background colour by checking the 'text' style of # the user's selected style scheme, falling back to the GTK+ theme # background if there is no style scheme background set. style = style_scheme.get_style('text') if style_scheme else None if style: background = style.props.background rgba = Gdk.RGBA() rgba.parse(background) else: # This case will only be hit for GtkSourceView style schemes # that don't set a text background, like the "Classic" scheme. from meld.sourceview import MeldSourceView stylecontext = MeldSourceView().get_style_context() background_set, rgba = ( stylecontext.lookup_color('theme_bg_color')) if not background_set: rgba = Gdk.RGBA(1, 1, 1, 1) # This heuristic is absolutely dire. I made it up. There's # literally no basis to this. use_dark = (rgba.red + rgba.green + rgba.blue) < 1.0 base_scheme_name = ( MeldStyleScheme.dark if use_dark else MeldStyleScheme.base) manager = GtkSource.StyleSchemeManager.get_default() base_style_scheme = manager.get_scheme(base_scheme_name.value) base_schemes = (MeldStyleScheme.dark.value, MeldStyleScheme.base.value) if style_scheme and style_scheme.props.id in base_schemes: style_scheme = base_style_scheme return base_style_scheme def colour_lookup_with_fallback(name: str, attribute: str) -> Gdk.RGBA: style = style_scheme.get_style(name) if style_scheme else None style_attr = getattr(style.props, attribute) if style else None if not style or not style_attr: try: style = base_style_scheme.get_style(name) style_attr = getattr(style.props, attribute) except AttributeError: pass if not style_attr: import sys style_detail = f'{name}-{attribute}' print(_( "Couldn’t find color scheme details for {}; " "this is a bad install").format(style_detail), file=sys.stderr) sys.exit(1) colour = Gdk.RGBA() colour.parse(style_attr) return colour ColourMap = Mapping[str, Gdk.RGBA] def get_common_theme() -> Tuple[ColourMap, ColourMap]: lookup = colour_lookup_with_fallback fill_colours = { "insert": lookup("meld:insert", "background"), "delete": lookup("meld:insert", "background"), "conflict": lookup("meld:conflict", "background"), "replace": lookup("meld:replace", "background"), "error": lookup("meld:error", "background"), "focus-highlight": lookup("meld:current-line-highlight", "foreground"), "current-chunk-highlight": lookup( "meld:current-chunk-highlight", "background"), "overscroll": lookup("meld:overscroll", "background"), } line_colours = { "insert": lookup("meld:insert", "line-background"), "delete": lookup("meld:insert", "line-background"), "conflict": lookup("meld:conflict", "line-background"), "replace": lookup("meld:replace", "line-background"), "error": lookup("meld:error", "line-background"), } return fill_colours, line_colours
4,706
Python
.py
104
39.278846
79
0.691938
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,816
iohelpers.py
GNOME_meld/meld/iohelpers.py
import pathlib from typing import Optional, Sequence from gi.repository import Gio, GLib, Gtk from meld.conf import _ from meld.misc import get_modal_parent, modal_dialog def trash_or_confirm(gfile: Gio.File) -> bool: """Trash or delete the given Gio.File Files and folders will be moved to the system Trash location without confirmation. If they can't be trashed, then the user is prompted for an irreversible deletion. :rtype: bool :returns: whether the file was deleted """ try: gfile.trash(None) return True except GLib.Error as e: # Handle not-supported, as that's due to the trashing target # being a (probably network) mount-point, not an underlying # problem. We also have to handle the generic FAILED code # because that's what we get with NFS mounts. expected_error = ( e.code == Gio.IOErrorEnum.NOT_SUPPORTED or e.code == Gio.IOErrorEnum.FAILED ) if not expected_error: raise RuntimeError(str(e)) file_type = gfile.query_file_type( Gio.FileQueryInfoFlags.NONE, None) if file_type == Gio.FileType.DIRECTORY: raise RuntimeError(_("Deleting remote folders is not supported")) elif file_type != Gio.FileType.REGULAR: raise RuntimeError(_("Not a file or directory")) delete_permanently = modal_dialog( primary=_( "“{}” can’t be put in the trash. Do you want to " "delete it immediately?".format( GLib.markup_escape_text(gfile.get_parse_name())) ), secondary=_( "This remote location does not support sending items " "to the trash." ), buttons=[ (_("_Cancel"), Gtk.ResponseType.CANCEL, None), ( _("_Delete Permanently"), Gtk.ResponseType.OK, Gtk.STYLE_CLASS_DESTRUCTIVE_ACTION, ), ], ) if delete_permanently != Gtk.ResponseType.OK: return False try: gfile.delete(None) # TODO: Deleting remote folders involves reimplementing # shutil.rmtree for gio, and then calling # self.recursively_update(). except Exception as e: raise RuntimeError(str(e)) return True def prompt_save_filename( title: str, parent: Optional[Gtk.Widget] = None) -> Optional[Gio.File]: dialog = Gtk.FileChooserNative( title=title, transient_for=get_modal_parent(parent), action=Gtk.FileChooserAction.SAVE, ) response = dialog.run() gfile = dialog.get_file() dialog.destroy() if response != Gtk.ResponseType.ACCEPT or not gfile: return None try: file_info = gfile.query_info( 'standard::name,standard::display-name', Gio.FileQueryInfoFlags.NONE, None, ) except GLib.Error as err: if err.code == Gio.IOErrorEnum.NOT_FOUND: return gfile raise # The selected file exists, so we need to prompt for overwrite. parent_folder = gfile.get_parent() parent_name = parent_folder.get_parse_name() if parent_folder else '' file_name = file_info.get_display_name() replace = modal_dialog( primary=_("Replace file “%s”?") % file_name, secondary=_( "A file with this name already exists in “%s”.\n" "If you replace the existing file, its contents " "will be lost.") % parent_name, buttons=[ (_("_Cancel"), Gtk.ResponseType.CANCEL, None), (_("_Replace"), Gtk.ResponseType.OK, None), ], messagetype=Gtk.MessageType.WARNING, ) if replace != Gtk.ResponseType.OK: return None return gfile def find_shared_parent_path( paths: Sequence[Optional[Gio.File]], ) -> Optional[Gio.File]: if not paths or not paths[0] or any(path is None for path in paths): return None current_parent = paths[0].get_parent() if len(paths) == 1: return current_parent while current_parent: is_valid_parent = all( current_parent.get_relative_path(path) for path in paths ) if is_valid_parent: break current_parent = current_parent.get_parent() # Either we've broken out of the loop early, in which case we have # a valid common parent path, or we've fallen through, in which # case the path return is None. return current_parent def format_home_relative_path(gfile: Gio.File) -> str: home_file = Gio.File.new_for_path(GLib.get_home_dir()) home_relative = home_file.get_relative_path(gfile) if home_relative: return GLib.build_filenamev(['~', home_relative]) else: return gfile.get_parse_name() def format_parent_relative_path(parent: Gio.File, descendant: Gio.File) -> str: """Format shortened child paths using a common parent This is a helper for shortening sets of paths using their common parent as a guide for what is required to distinguish the paths from one another. The helper operates on every path individually, so that this work can be done in individual widgets using only the path being displayed (`descendent` here) and the common parent (`parent` here). """ # When thinking about the segmentation we do here, there are # four path components that we care about: # # * any path components above the non-common parent # * the earliest non-common parent # * any path components between the actual filename and the # earliest non-common parent # * the actual filename # # This is easiest to think about with an example of comparing # two files in a parallel repository structure (or similar). # Let's say that you have two copies of Meld at # /home/foo/checkouts/meld and /home/foo/checkouts/meld-new, # and you're comparing meld/filediff.py within those checkouts. # The components we want would then be (left to right): # # --------------------------------------------- # | /home/foo/checkouts | /home/foo/checkouts | # | meld | meld-new | # | meld | meld | # | filediff.py | filediff.py | # --------------------------------------------- # # Of all of these, the first (the first common parent) is the # *only* one that's actually guaranteed to be the same. The # second will *always* be different (or won't exist if e.g., # you're comparing files in the same folder or similar). The # third component can be basically anything. The fourth # components will often be the same but that's not guaranteed. base_path_str = None immediate_parent_strs = [] has_elided_path = False descendant_parent = descendant.get_parent() if descendant_parent is None: raise ValueError(f'Path {descendant.get_path()} has no parent') relative_path_str = parent.get_relative_path(descendant_parent) if relative_path_str: relative_path = pathlib.Path(relative_path_str) # We always try to leave the first and last path segments, to # try to handle e.g., <parent>/<project>/src/<module>/main.py. base_path_str = relative_path.parts[0] if len(relative_path.parts) > 1: immediate_parent_strs.append(relative_path.parts[-1]) # As an additional heuristic, we try to include the second-last # path segment as well, to handle paths like e.g., # <parent>/<some package structure>/<module>/src/main.py. # We only do this if the last component is short, to # handle src, dist, pkg, etc. without using too much space. if len(relative_path.parts) > 2 and len(immediate_parent_strs[0]) < 5: immediate_parent_strs.insert(0, relative_path.parts[-2]) # We have elided paths if we have more parts than our immediate # parent count plus one for the base component. included_path_count = len(immediate_parent_strs) + 1 has_elided_path = len(relative_path.parts) > included_path_count show_parent = not parent.has_parent() # It looks odd to have a single component, so if we don't have a # base path, we'll use the direct parent. In this case the parent # won't provide any disambiguation... it's just for appearances. if not show_parent and not base_path_str: base_path_str = parent.get_basename() label_segments = [ '…' if not show_parent else None, base_path_str, '…' if has_elided_path else None, *immediate_parent_strs, descendant.get_basename(), ] label_text = format_home_relative_path(parent) if show_parent else "" label_text += GLib.build_filenamev([s for s in label_segments if s]) return label_text def is_file_on_tmpfs(gfile: Gio.File) -> bool: """Check whether a given file is on a tmpfs filesystem This is a Unix-specific operation. On any exception, this will return False. """ try: path = gfile.get_path() if not path: return False mount, _timestamp = Gio.unix_mount_for(path) if not mount: return False return Gio.unix_mount_get_fs_type(mount) == "tmpfs" except Exception: return False
9,442
Python
.py
223
34.811659
79
0.637526
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,817
actiongutter.py
GNOME_meld/meld/actiongutter.py
# Copyright (C) 2019 Kai Willadsen <kai.willadsen@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or (at # your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import bisect from typing import Dict, Optional from gi.repository import Gdk, GdkPixbuf, GObject, Gtk from meld.conf import _ from meld.const import ActionMode, ChunkAction from meld.settings import get_meld_settings from meld.style import get_common_theme from meld.ui.gtkcompat import get_style from meld.ui.gtkutil import make_gdk_rgba class ActionIcons: #: Fixed size of the renderer. Ideally this would be font-dependent and #: would adjust to other textview attributes, but that's both quite #: difficult and not necessarily desirable. pixbuf_height = 16 icon_cache: Dict[str, GdkPixbuf.Pixbuf] = {} icon_name_prefix = 'meld-change' @classmethod def load(cls, icon_name: str): icon = cls.icon_cache.get(icon_name) if not icon: icon_theme = Gtk.IconTheme.get_default() icon = icon_theme.load_icon( f'{cls.icon_name_prefix}-{icon_name}', cls.pixbuf_height, 0) cls.icon_cache[icon_name] = icon return icon class ActionGutter(Gtk.DrawingArea): __gtype_name__ = 'ActionGutter' action_mode = GObject.Property( type=int, nick='Action mode for chunk change actions', default=ActionMode.Replace, ) @GObject.Property( type=object, nick='List of diff chunks for display', ) def chunks(self): return self._chunks @chunks.setter def chunks_set(self, chunks): self._chunks = chunks self.chunk_starts = [c.start_a for c in chunks] @GObject.Property( type=Gtk.TextDirection, nick='Which direction should directional changes appear to go', flags=( GObject.ParamFlags.READABLE | GObject.ParamFlags.WRITABLE | GObject.ParamFlags.CONSTRUCT_ONLY ), default=Gtk.TextDirection.LTR, ) def icon_direction(self): return self._icon_direction @icon_direction.setter def icon_direction_set(self, direction: Gtk.TextDirection): if direction not in (Gtk.TextDirection.LTR, Gtk.TextDirection.RTL): raise ValueError('Invalid icon direction {}'.format(direction)) replace_icons = { Gtk.TextDirection.LTR: 'apply-right', Gtk.TextDirection.RTL: 'apply-left', } self.action_map = { ActionMode.Replace: ActionIcons.load(replace_icons[direction]), ActionMode.Delete: ActionIcons.load('delete'), ActionMode.Insert: ActionIcons.load('copy'), } self._icon_direction = direction _source_view: Gtk.TextView _source_editable_connect_id: int = 0 @GObject.Property( type=Gtk.TextView, nick='Text view for which action are displayed', default=None, ) def source_view(self): return self._source_view @source_view.setter def source_view_setter(self, view: Gtk.TextView): if self._source_editable_connect_id: self._source_view.disconnect(self._source_editable_connect_id) self._source_editable_connect_id = view.connect( 'notify::editable', lambda *args: self.queue_draw()) self._source_view = view self.queue_draw() _target_view: Gtk.TextView _target_editable_connect_id: int = 0 @GObject.Property( type=Gtk.TextView, nick='Text view to which actions are directed', default=None, ) def target_view(self): return self._target_view @target_view.setter def target_view_setter(self, view: Gtk.TextView): if self._target_editable_connect_id: self._target_view.disconnect(self._target_editable_connect_id) self._target_editable_connect_id = view.connect( 'notify::editable', lambda *args: self.queue_draw()) self._target_view = view self.queue_draw() @GObject.Signal def chunk_action_activated( self, action: str, # String-ified ChunkAction from_view: Gtk.TextView, to_view: Gtk.TextView, chunk: object, ) -> None: ... def __init__(self): super().__init__() # Object-type defaults self.chunks = [] self.action_map = {} # State for "button" implementation self.buttons = [] self.pointer_chunk = None self.pressed_chunk = None self.motion_controller = Gtk.EventControllerMotion(widget=self) self.motion_controller.set_propagation_phase(Gtk.PropagationPhase.TARGET) self.motion_controller.connect("enter", self.motion_event) self.motion_controller.connect("leave", self.motion_event) self.motion_controller.connect("motion", self.motion_event) def on_setting_changed(self, settings, key): if key == 'style-scheme': self.fill_colors, self.line_colors = get_common_theme() alpha = self.fill_colors['current-chunk-highlight'].alpha self.chunk_highlights = { state: make_gdk_rgba(*[alpha + c * (1.0 - alpha) for c in colour]) for state, colour in self.fill_colors.items() } def do_realize(self): self.set_events( Gdk.EventMask.ENTER_NOTIFY_MASK | Gdk.EventMask.LEAVE_NOTIFY_MASK | Gdk.EventMask.POINTER_MOTION_MASK | Gdk.EventMask.BUTTON_PRESS_MASK | Gdk.EventMask.BUTTON_RELEASE_MASK | Gdk.EventMask.SCROLL_MASK ) self.connect('notify::action-mode', lambda *args: self.queue_draw()) meld_settings = get_meld_settings() meld_settings.connect('changed', self.on_setting_changed) self.on_setting_changed(meld_settings, 'style-scheme') return Gtk.DrawingArea.do_realize(self) def update_pointer_chunk(self, x, y): # This is the simplest button/intersection implementation in # the world, but it basically works for our purposes. for button in self.buttons: x1, y1, x2, y2, chunk = button # Check y first; it's more likely to be out of range if y1 <= y <= y2 and x1 <= x <= x2: new_pointer_chunk = chunk break else: new_pointer_chunk = None if new_pointer_chunk != self.pointer_chunk: self.pointer_chunk = new_pointer_chunk self.queue_draw() def motion_event( self, controller: Gtk.EventControllerMotion, x: float | None = None, y: float | None = None, ): if x is None or y is None: # Missing coordinates are leave events if self.pointer_chunk: self.pointer_chunk = None self.queue_draw() else: # This is either an enter or motion event; we treat them the same self.update_pointer_chunk(x, y) def do_button_press_event(self, event): if self.pointer_chunk: self.pressed_chunk = self.pointer_chunk return Gtk.DrawingArea.do_button_press_event(self, event) def do_button_release_event(self, event): if self.pointer_chunk and self.pointer_chunk == self.pressed_chunk: self.activate(self.pressed_chunk) self.pressed_chunk = None return Gtk.DrawingArea.do_button_press_event(self, event) def _action_on_chunk(self, action: ChunkAction, chunk): self.chunk_action_activated.emit( action.value, self.source_view, self.target_view, chunk) def activate(self, chunk): action = self._classify_change_actions(chunk) # FIXME: When fully transitioned to GAction, we should see # whether we can do this by getting the container's action # group and activating the actions directly instead. if action == ActionMode.Replace: self._action_on_chunk(ChunkAction.replace, chunk) elif action == ActionMode.Delete: self._action_on_chunk(ChunkAction.delete, chunk) elif action == ActionMode.Insert: copy_menu = self._make_copy_menu(chunk) copy_menu.popup_at_pointer(None) def _make_copy_menu(self, chunk): copy_menu = Gtk.Menu() copy_up = Gtk.MenuItem.new_with_mnemonic(_('Copy _up')) copy_down = Gtk.MenuItem.new_with_mnemonic(_('Copy _down')) copy_menu.append(copy_up) copy_menu.append(copy_down) copy_menu.show_all() def copy_chunk(widget, action): self._action_on_chunk(action, chunk) copy_up.connect('activate', copy_chunk, ChunkAction.copy_up) copy_down.connect('activate', copy_chunk, ChunkAction.copy_down) return copy_menu def get_chunk_range(self, start_y, end_y): start_line = self.source_view.get_line_num_for_y(start_y) end_line = self.source_view.get_line_num_for_y(end_y) start_idx = bisect.bisect(self.chunk_starts, start_line) end_idx = bisect.bisect(self.chunk_starts, end_line) if start_idx > 0 and start_line <= self.chunks[start_idx - 1].end_a: start_idx -= 1 return self.chunks[start_idx:end_idx] def do_draw(self, context): view = self.source_view if not view or not view.get_realized(): return self.buttons = [] width = self.get_allocated_width() height = self.get_allocated_height() style_context = self.get_style_context() Gtk.render_background(style_context, context, 0, 0, width, height) buf = view.get_buffer() context.save() context.set_line_width(1.0) # Get our linked view's visible offset, get our vertical offset # against our view (e.g., for info bars at the top of the view) # and translate our context to match. view_y_start = view.get_visible_rect().y view_y_offset = view.translate_coordinates(self, 0, 0)[1] gutter_y_translate = view_y_offset - view_y_start context.translate(0, gutter_y_translate) button_x = 1 button_width = width - 2 for chunk in self.get_chunk_range(view_y_start, view_y_start + height): change_type, start_line, end_line, *_unused = chunk rect_y = view.get_y_for_line_num(start_line) rect_height = max( 0, view.get_y_for_line_num(end_line) - rect_y - 1) # Draw our rectangle outside x bounds, so we don't get # vertical lines. Fill first, over-fill with a highlight # if in the focused chunk, and then stroke the border. context.rectangle(-0.5, rect_y + 0.5, width + 1, rect_height) if start_line != end_line: context.set_source_rgba(*self.fill_colors[change_type]) context.fill_preserve() if view.current_chunk_check(chunk): highlight = self.fill_colors['current-chunk-highlight'] context.set_source_rgba(*highlight) context.fill_preserve() context.set_source_rgba(*self.line_colors[change_type]) context.stroke() # Button rendering and tracking action = self._classify_change_actions(chunk) if action is None: continue it = buf.get_iter_at_line(start_line) button_y, button_height = view.get_line_yrange(it) button_y += 1 button_height -= 2 button_style_context = get_style(None, 'button.flat.image-button') if chunk == self.pointer_chunk: button_style_context.set_state(Gtk.StateFlags.PRELIGHT) Gtk.render_background( button_style_context, context, button_x, button_y, button_width, button_height) Gtk.render_frame( button_style_context, context, button_x, button_y, button_width, button_height) # TODO: Ideally we'd do this in a pre-render step of some # kind, but I'm having trouble figuring out what that would # look like. self.buttons.append( ( button_x, button_y + gutter_y_translate, button_x + button_width, button_y + gutter_y_translate + button_height, chunk, ) ) pixbuf = self.action_map.get(action) icon_x = button_x + (button_width - pixbuf.props.width) // 2 icon_y = button_y + (button_height - pixbuf.props.height) // 2 Gtk.render_icon( button_style_context, context, pixbuf, icon_x, icon_y) context.restore() def _classify_change_actions(self, change) -> Optional[ActionMode]: """Classify possible actions for the given change Returns the action that can be performed given the content and context of the change. """ source_editable = self.source_view.get_editable() target_editable = self.target_view.get_editable() if not source_editable and not target_editable: return None # Reclassify conflict changes, since we treat them the same as a # normal two-way change as far as actions are concerned change_type = change[0] if change_type == 'conflict': if change[1] == change[2]: change_type = 'insert' elif change[3] == change[4]: change_type = 'delete' else: change_type = 'replace' if change_type == 'insert': return None action = self.action_mode if action == ActionMode.Delete and not source_editable: action = None elif action == ActionMode.Insert and change_type == 'delete': action = ActionMode.Replace if not target_editable: action = ActionMode.Delete return action ActionGutter.set_css_name('action-gutter')
14,789
Python
.py
337
34.047478
82
0.621016
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,818
meldbuffer.py
GNOME_meld/meld/meldbuffer.py
# Copyright (C) 2002-2006 Stephen Kennedy <stevek@gnome.org> # Copyright (C) 2009-2013 Kai Willadsen <kai.willadsen@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or (at # your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import enum import logging from typing import Any, List, Optional from gi.repository import Gio, GLib, GObject, GtkSource from meld.conf import _ from meld.settings import bind_settings log = logging.getLogger(__name__) class MeldBuffer(GtkSource.Buffer): __gtype_name__ = "MeldBuffer" __gsettings_bindings__ = ( ('highlight-syntax', 'highlight-syntax'), ) def __init__(self): super().__init__() bind_settings(self) self.data = MeldBufferData() self.undo_sequence = None def do_begin_user_action(self, *args): if self.undo_sequence: self.undo_sequence.begin_group() def do_end_user_action(self, *args): if self.undo_sequence: self.undo_sequence.end_group() def get_iter_at_line_or_eof(self, line): """Return a Gtk.TextIter at the given line, or the end of the buffer. This method is like get_iter_at_line, but if asked for a position past the end of the buffer, this returns the end of the buffer; the get_iter_at_line behaviour is to return the start of the last line in the buffer. """ if line >= self.get_line_count(): return self.get_end_iter() return self.get_iter_at_line(line) def insert_at_line(self, line, text): """Insert text at the given line, or the end of the buffer. This method is like insert, but if asked to insert something past the last line in the buffer, this will insert at the end, and will add a linebreak before the inserted text. The last line in a Gtk.TextBuffer is guaranteed never to have a newline, so we need to handle this. """ if line >= self.get_line_count(): # TODO: We need to insert a linebreak here, but there is no # way to be certain what kind of linebreak to use. text = "\n" + text it = self.get_iter_at_line_or_eof(line) self.insert(it, text) return it class MeldBufferState(enum.Enum): EMPTY = "EMPTY" LOADING = "LOADING" LOAD_FINISHED = "LOAD_FINISHED" LOAD_ERROR = "LOAD_ERROR" class MeldBufferData(GObject.GObject): state: MeldBufferState @GObject.Signal('file-changed') def file_changed_signal(self) -> None: ... encoding = GObject.Property( type=GtkSource.Encoding, nick="The file encoding of the linked GtkSourceFile", default=GtkSource.Encoding.get_utf8(), ) def __init__(self): super().__init__() self._gfile = None self._label = None self._monitor = None self._sourcefile = None self.reset(gfile=None, state=MeldBufferState.EMPTY) def reset(self, gfile: Optional[Gio.File], state: MeldBufferState): same_file = gfile and self._gfile and gfile.equal(self._gfile) self.gfile = gfile if same_file: self.label = self._label else: self.label = gfile.get_parse_name() if gfile else None self.state = state self.savefile = None def __del__(self): self.disconnect_monitor() @property def label(self): # TRANSLATORS: This is the label of a new, currently-unnamed file. return self._label or _("<unnamed>") @label.setter def label(self, value): if not value: return if not isinstance(value, str): log.warning('Invalid label ignored "%r"', value) return self._label = value def connect_monitor(self): if not self._gfile: return monitor = self._gfile.monitor_file(Gio.FileMonitorFlags.NONE, None) handler_id = monitor.connect('changed', self._handle_file_change) self._monitor = monitor, handler_id def disconnect_monitor(self): if not self._monitor: return monitor, handler_id = self._monitor monitor.disconnect(handler_id) monitor.cancel() self._monitor = None def _query_mtime(self, gfile): try: time_query = ",".join((Gio.FILE_ATTRIBUTE_TIME_MODIFIED, Gio.FILE_ATTRIBUTE_TIME_MODIFIED_USEC)) info = gfile.query_info(time_query, 0, None) except GLib.GError: return None mtime = info.get_modification_time() return (mtime.tv_sec, mtime.tv_usec) def _handle_file_change(self, monitor, f, other_file, event_type): mtime = self._query_mtime(f) if self._disk_mtime and mtime and mtime > self._disk_mtime: self.file_changed_signal.emit() self._disk_mtime = mtime or self._disk_mtime @property def gfile(self): return self._gfile @gfile.setter def gfile(self, value): self.disconnect_monitor() self._gfile = value self._sourcefile = GtkSource.File() self._sourcefile.set_location(value) self._sourcefile.bind_property( 'encoding', self, 'encoding', GObject.BindingFlags.DEFAULT) self.update_mtime() self.connect_monitor() @property def sourcefile(self): return self._sourcefile @property def gfiletarget(self): return self.savefile or self.gfile @property def is_special(self): try: info = self._gfile.query_info( Gio.FILE_ATTRIBUTE_STANDARD_TYPE, 0, None) return info.get_file_type() == Gio.FileType.SPECIAL except (AttributeError, GLib.GError): return False @property def file_id(self) -> Optional[str]: try: info = self._gfile.query_info(Gio.FILE_ATTRIBUTE_ID_FILE, 0, None) return info.get_attribute_string(Gio.FILE_ATTRIBUTE_ID_FILE) except (AttributeError, GLib.GError): return None @property def writable(self): try: info = self.gfiletarget.query_info( Gio.FILE_ATTRIBUTE_ACCESS_CAN_WRITE, 0, None) except GLib.GError as err: if err.code == Gio.IOErrorEnum.NOT_FOUND: return True return False except AttributeError: return False return info.get_attribute_boolean(Gio.FILE_ATTRIBUTE_ACCESS_CAN_WRITE) def update_mtime(self): if self._gfile: self._disk_mtime = self._query_mtime(self._gfile) self._mtime = self._disk_mtime def current_on_disk(self): return self._mtime == self._disk_mtime class BufferLines: """Gtk.TextBuffer shim with line-based access and optional filtering This class allows a Gtk.TextBuffer to be treated as a list of lines of possibly-filtered text. If no filter is given, the raw output from the Gtk.TextBuffer is used. """ #: Cached copy of the (possibly filtered) text in a single line, #: where an entry of None indicates that there is no cached result #: available. lines: List[Optional[str]] def __init__(self, buf, textfilter=None, *, cache_debug: bool = False): self.buf = buf if textfilter is not None: self.textfilter = textfilter else: self.textfilter = lambda x, buf, start_iter, end_iter: x self.lines = [None] * self.buf.get_line_count() self.mark = buf.create_mark( "bufferlines-insert", buf.get_start_iter(), True, ) buf.connect("insert-text", self.on_insert_text), buf.connect("delete-range", self.on_delete_range), buf.connect_after("insert-text", self.after_insert_text), if cache_debug: buf.connect_after("insert-text", self._check_cache_invariant) buf.connect_after("delete-range", self._check_cache_invariant) def _check_cache_invariant(self, *args: Any) -> None: if len(self.lines) != len(self): log.error( "Cache line count does not match buffer line count: " f"{len(self.lines)} != {len(self)}", ) def clear_cache(self) -> None: self.lines = [None] * self.buf.get_line_count() def on_insert_text(self, buf, it, text, textlen): buf.move_mark(self.mark, it) def after_insert_text(self, buf, it, newtext, textlen): start_idx = buf.get_iter_at_mark(self.mark).get_line() end_idx = it.get_line() + 1 # Replace the insertion-point cache line with a list of empty # lines. In the single-line case this will be a single element # substitution; for multi-line inserts, we will replace the # single insertion point line with several empty cache lines. self.lines[start_idx:start_idx + 1] = [None] * (end_idx - start_idx) def on_delete_range(self, buf, it0, it1): start_idx = it0.get_line() end_idx = it1.get_line() + 1 self.lines[start_idx:end_idx] = [None] def __getitem__(self, key): if isinstance(key, slice): lo, hi, _ = key.indices(self.buf.get_line_count()) for idx in range(lo, hi): if self.lines[idx] is None: self.lines[idx] = self[idx] return self.lines[lo:hi] elif isinstance(key, int): if key >= len(self): raise IndexError if self.lines[key] is None: line_start = self.buf.get_iter_at_line_or_eof(key) line_end = line_start.copy() if not line_end.ends_line(): line_end.forward_to_line_end() txt = self.buf.get_text(line_start, line_end, False) txt = self.textfilter(txt, self.buf, line_start, line_end) self.lines[key] = txt return self.lines[key] def __len__(self): return self.buf.get_line_count() class BufferAction: """A helper to undo/redo text insertion/deletion into/from a text buffer""" def __init__(self, buf, offset, text): self.buffer = buf self.offset = offset self.text = text def delete(self): start = self.buffer.get_iter_at_offset(self.offset) end = self.buffer.get_iter_at_offset(self.offset + len(self.text)) self.buffer.delete(start, end) self.buffer.place_cursor(end) return [self] def insert(self): start = self.buffer.get_iter_at_offset(self.offset) self.buffer.place_cursor(start) self.buffer.insert(start, self.text) return [self] class BufferInsertionAction(BufferAction): undo = BufferAction.delete redo = BufferAction.insert class BufferDeletionAction(BufferAction): undo = BufferAction.insert redo = BufferAction.delete
11,517
Python
.py
278
32.830935
79
0.626768
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,819
accelerators.py
GNOME_meld/meld/accelerators.py
from typing import Dict, Sequence, Union from gi.repository import Gtk VIEW_ACCELERATORS: Dict[str, Union[str, Sequence[str]]] = { 'app.quit': '<Primary>Q', 'app.help': 'F1', 'app.preferences': '<Primary>comma', 'view.find': '<Primary>F', 'view.find-next': ('<Primary>G', 'F3'), 'view.find-previous': ('<Primary><Shift>G', '<Shift>F3'), 'view.find-replace': '<Primary>H', 'view.go-to-line': '<Primary>I', # Overridden in CSS 'view.next-change': ('<Alt>Down', '<Alt>KP_Down', '<Primary>D'), 'view.next-pane': '<Alt>Page_Down', 'view.open-external': '<Primary><Shift>O', # Overridden in CSS 'view.previous-change': ('<Alt>Up', '<Alt>KP_Up', '<Primary>E'), 'view.previous-pane': '<Alt>Page_Up', 'view.redo': '<Primary><Shift>Z', 'view.refresh': ('<control>R', 'F5'), 'view.save': '<Primary>S', 'view.save-all': '<Primary><Shift>L', 'view.save-as': '<Primary><Shift>S', 'view.undo': '<Primary>Z', 'win.close': '<Primary>W', 'win.gear-menu': 'F10', 'win.fullscreen': 'F11', 'win.new-tab': '<Primary>N', 'win.stop': 'Escape', # Shared bindings for per-view filter menu buttons 'view.vc-filter': 'F8', 'view.folder-filter': 'F8', 'view.text-filter': 'F8', # File comparison actions 'view.file-previous-conflict': '<Primary>J', 'view.file-next-conflict': '<Primary>K', 'view.file-push-left': '<Alt>Left', 'view.file-push-right': '<Alt>Right', 'view.file-pull-left': '<Alt><shift>Right', 'view.file-pull-right': '<Alt><shift>Left', 'view.file-copy-left-up': '<Alt>bracketleft', 'view.file-copy-right-up': '<Alt>bracketright', 'view.file-copy-left-down': '<Alt>semicolon', 'view.file-copy-right-down': '<Alt>quoteright', 'view.file-delete': ('<Alt>Delete', '<Alt>KP_Delete'), 'view.show-overview-map': 'F9', # Folder comparison actions 'view.folder-compare': 'Return', 'view.folder-copy-left': '<Alt>Left', 'view.folder-copy-right': '<Alt>Right', 'view.folder-delete': 'Delete', # Version control actions 'view.vc-commit': '<Primary>M', 'view.vc-console-visible': 'F9', # Swap the two panes 'view.swap-2-panes': '<Alt>backslash', } def register_accels(app: Gtk.Application): for name, accel in VIEW_ACCELERATORS.items(): accel = accel if isinstance(accel, tuple) else (accel,) app.set_accels_for_action(name, accel)
2,443
Python
.py
61
35.163934
68
0.620109
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,820
windowstate.py
GNOME_meld/meld/windowstate.py
# Copyright (C) 2016 Kai Willadsen <kai.willadsen@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or (at # your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from gi.repository import Gdk, Gio, GObject from meld.settings import load_settings_schema WINDOW_STATE_SCHEMA = 'org.gnome.meld.WindowState' class SavedWindowState(GObject.GObject): '''Utility class for saving and restoring GtkWindow state''' __gtype_name__ = 'SavedWindowState' width = GObject.Property( type=int, nick='Current window width', default=-1) height = GObject.Property( type=int, nick='Current window height', default=-1) is_maximized = GObject.Property( type=bool, nick='Is window maximized', default=False) is_fullscreen = GObject.Property( type=bool, nick='Is window fullscreen', default=False) def bind(self, window): window.connect('size-allocate', self.on_size_allocate) # FIXME: just `maximized` and `fullscreened` for GTK 4 window.connect("notify::is-maximized", self.on_window_state_event) window.connect("notify::is-fullscreened", self.on_window_state_event) # Don't re-read from gsettings after initialisation; we've seen # what looked like issues with buggy debounce here. bind_flags = ( Gio.SettingsBindFlags.DEFAULT | Gio.SettingsBindFlags.GET_NO_CHANGES ) self.settings = load_settings_schema(WINDOW_STATE_SCHEMA) self.settings.bind('width', self, 'width', bind_flags) self.settings.bind('height', self, 'height', bind_flags) self.settings.bind('is-maximized', self, 'is-maximized', bind_flags) window.set_default_size(self.props.width, self.props.height) if self.props.is_maximized: window.maximize() def on_size_allocate(self, window, allocation): if not (self.props.is_maximized or self.props.is_fullscreen): width, height = window.get_size() if width != self.props.width: self.props.width = width if height != self.props.height: self.props.height = height def on_window_state_event(self, window, param): is_maximized = window.is_maximized() if is_maximized != self.props.is_maximized: self.props.is_maximized = is_maximized # TODO: Migrate to use is_fullscreen in GTK 4 state = window.props.window.get_state() is_fullscreen = state & Gdk.WindowState.FULLSCREEN if is_fullscreen != self.props.is_fullscreen: self.props.is_fullscreen = is_fullscreen
3,156
Python
.py
62
43.806452
77
0.691234
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,821
const.py
GNOME_meld/meld/const.py
import enum from gi.repository import GtkSource from meld.conf import _ class ActionMode(enum.IntEnum): """Action mode for chunk change actions""" Replace = 0 Delete = 1 Insert = 2 class ChunkAction(enum.Enum): delete = 'delete' replace = 'replace' copy_down = 'copy_down' copy_up = 'copy_up' class FileComparisonMode(enum.Enum): AutoMerge = 'AutoMerge' Compare = 'Compare' class FileLoadError(enum.IntEnum): LINE_TOO_LONG = 1 NEWLINES = { GtkSource.NewlineType.LF: ('\n', _("UNIX (LF)")), GtkSource.NewlineType.CR_LF: ('\r\n', _("DOS/Windows (CR-LF)")), GtkSource.NewlineType.CR: ('\r', _("Mac OS (CR)")), } FILE_FILTER_ACTION_FORMAT = 'folder-custom-filter-{}' TEXT_FILTER_ACTION_FORMAT = 'text-custom-filter-{}' #: Sentinel value for mtimes on files that don't exist. MISSING_TIMESTAMP = -2147483648
875
Python
.py
27
28.740741
68
0.688702
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,822
build_helpers.py
GNOME_meld/meld/build_helpers.py
# This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or (at # your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # Copied and adapted from the DistUtilsExtra project # Created by Sebastian Heinlein and Martin Pitt # Copyright Canonical Ltd. # Modified by Kai Willadsen for the Meld project # Copyright (C) 2013-2014 Kai Willadsen <kai.willadsen@gmail.com> import distutils.cmd import distutils.command.build import distutils.command.build_py import distutils.command.install import distutils.command.install_data import distutils.dir_util import distutils.dist import glob import os.path import platform import sys from distutils.log import info try: import distro except ImportError: python_version = tuple(int(x) for x in platform.python_version_tuple()[:2]) if python_version >= (3, 8): print( 'Missing build requirement "distro" Python module; ' 'install paths may be incorrect', file=sys.stderr) windows_build = os.name == 'nt' def has_help(self): return "build_help" in self.distribution.cmdclass and not windows_build def has_icons(self): return "build_icons" in self.distribution.cmdclass def has_i18n(self): return "build_i18n" in self.distribution.cmdclass and not windows_build def has_data(self): return "build_data" in self.distribution.cmdclass distutils.command.build.build.sub_commands.extend([ ("build_i18n", has_i18n), ("build_icons", has_icons), ("build_help", has_help), ("build_data", has_data), ]) class MeldDistribution(distutils.dist.Distribution): global_options = distutils.dist.Distribution.global_options + [ ("no-update-icon-cache", None, "Don't run gtk-update-icon-cache"), ("no-compile-schemas", None, "Don't compile gsettings schemas"), ] def __init__(self, *args, **kwargs): self.no_update_icon_cache = False self.no_compile_schemas = False super().__init__(*args, **kwargs) class build_data(distutils.cmd.Command): gschemas = [ ('share/glib-2.0/schemas', ['data/org.gnome.Meld.gschema.xml']) ] frozen_gschemas = [ ('share/meld', ['data/gschemas.compiled']), ] win32_settings_ini = '[Settings]\ngtk-application-prefer-dark-theme=0\n' style_source = "data/styles/*.style-scheme.xml.in" style_target_dir = 'share/meld/styles' # FIXME: This is way too much hard coding, but I really hope # it also doesn't last that long. resource_source = "meld/resources/meld.gresource.xml" resource_target = "org.gnome.Meld.gresource" def initialize_options(self): pass def finalize_options(self): pass def get_data_files(self): data_files = [] build_path = os.path.join('build', 'data') if not os.path.exists(build_path): os.makedirs(build_path) info("compiling gresources") resource_dir = os.path.dirname(self.resource_source) target = os.path.join(build_path, self.resource_target) self.spawn([ "glib-compile-resources", "--target={}".format(target), "--sourcedir={}".format(resource_dir), "--sourcedir={}".format("data/icons/hicolor"), self.resource_source, ]) data_files.append(('share/meld', [target])) if windows_build: # Write out a default settings.ini for Windows to make # e.g., dark theme selection slightly easier. settings_dir = os.path.join('build', 'etc', 'gtk-3.0') if not os.path.exists(settings_dir): os.makedirs(settings_dir) settings_path = os.path.join(settings_dir, 'settings.ini') with open(settings_path, 'w') as f: print(self.win32_settings_ini, file=f) gschemas = self.frozen_gschemas + [ ('etc/gtk-3.0', [settings_path]) ] else: gschemas = self.gschemas data_files.extend(gschemas) if windows_build: # These should get moved/installed by i18n, but until that # runs on Windows we need this hack. styles = glob.glob(self.style_source) import shutil targets = [] for style in styles: assert style.endswith('.in') target = style[:-len('.in')] shutil.copyfile(style, target) targets.append(target) data_files.append((self.style_target_dir, targets)) return data_files def run(self): data_files = self.distribution.data_files data_files.extend(self.get_data_files()) class build_help(distutils.cmd.Command): help_dir = 'help' def initialize_options(self): pass def finalize_options(self): pass def get_data_files(self): data_files = [] name = self.distribution.metadata.name if "LINGUAS" in os.environ: self.selected_languages = os.environ["LINGUAS"].split() else: self.selected_languages = [ d for d in os.listdir(self.help_dir) if os.path.isdir(d) ] if 'C' not in self.selected_languages: self.selected_languages.append('C') self.C_PAGES = glob.glob(os.path.join(self.help_dir, 'C', '*.page')) self.C_EXTRA = glob.glob(os.path.join(self.help_dir, 'C', '*.xml')) for lang in self.selected_languages: source_path = os.path.join(self.help_dir, lang) if not os.path.exists(source_path): continue build_path = os.path.join('build', self.help_dir, lang) if not os.path.exists(build_path): os.makedirs(build_path) if lang != 'C': po_file = os.path.join(source_path, lang + '.po') mo_file = os.path.join(build_path, lang + '.mo') msgfmt = ['msgfmt', po_file, '-o', mo_file] self.spawn(msgfmt) for page in self.C_PAGES: itstool = [ 'itstool', '-m', mo_file, '-o', build_path, page] self.spawn(itstool) for extra in self.C_EXTRA: extra_path = os.path.join( build_path, os.path.basename(extra)) if os.path.exists(extra_path): os.unlink(extra_path) os.symlink(os.path.relpath(extra, source_path), extra_path) else: distutils.dir_util.copy_tree(source_path, build_path) xml_files = glob.glob('%s/*.xml' % build_path) mallard_files = glob.glob('%s/*.page' % build_path) path_help = os.path.join('share', 'help', lang, name) path_figures = os.path.join(path_help, 'figures') data_files.append((path_help, xml_files + mallard_files)) figures = glob.glob('%s/figures/*.png' % build_path) if figures: data_files.append((path_figures, figures)) return data_files def run(self): data_files = self.distribution.data_files data_files.extend(self.get_data_files()) self.check_help() def check_help(self): for lang in self.selected_languages: build_path = os.path.join('build', self.help_dir, lang) if not os.path.exists(build_path): continue pages = [os.path.basename(p) for p in self.C_PAGES] for page in pages: page_path = os.path.join(build_path, page) if not os.path.exists(page_path): info("skipping missing file %s", page_path) continue lint = ['xmllint', '--noout', '--noent', '--path', build_path, '--xinclude', page_path] self.spawn(lint) class build_icons(distutils.cmd.Command): icon_dir = os.path.join("data", "icons") target = "share/icons" frozen_target = "share/meld/icons" def initialize_options(self): pass def finalize_options(self): pass def run(self): target_dir = self.frozen_target if windows_build else self.target data_files = self.distribution.data_files for theme in glob.glob(os.path.join(self.icon_dir, "*")): for size in glob.glob(os.path.join(theme, "*")): for category in glob.glob(os.path.join(size, "*")): icons = (glob.glob(os.path.join(category, "*.png")) + glob.glob(os.path.join(category, "*.svg"))) icons = [ icon for icon in icons if not os.path.islink(icon)] if not icons: continue data_files.append(("%s/%s/%s/%s" % (target_dir, os.path.basename(theme), os.path.basename(size), os.path.basename(category)), icons)) class build_i18n(distutils.cmd.Command): bug_contact = None domain = "meld" po_dir = "po" merge_po = False # FIXME: It's ridiculous to specify these here, but I know of no other # way except magically extracting them from self.distribution.data_files desktop_files = [('share/applications', glob.glob("data/*.desktop.in"))] xml_files = [ ('share/meld/styles', glob.glob("data/styles/*.style-scheme.xml.in")), ('share/metainfo', glob.glob("data/*.appdata.xml.in")), ('share/mime/packages', glob.glob("data/mime/*.xml.in")) ] schemas_files = [] key_files = [] def initialize_options(self): pass def finalize_options(self): pass def _rebuild_po(self): # If there is a po/LINGUAS file, or the LINGUAS environment variable # is set, only compile the languages listed there. selected_languages = None linguas_file = os.path.join(self.po_dir, "LINGUAS") if "LINGUAS" in os.environ: selected_languages = os.environ["LINGUAS"].split() elif os.path.isfile(linguas_file): selected_languages = open(linguas_file).read().split() # If we're on Windows, assume we're building frozen and make a bunch # of insane assumptions. if windows_build: msgfmt = "C:\\Python27\\Tools\\i18n\\msgfmt" else: msgfmt = "msgfmt" # Update po(t) files and print a report # We have to change the working dir to the po dir for intltool cmd = [ "intltool-update", (self.merge_po and "-r" or "-p"), "-g", self.domain ] wd = os.getcwd() os.chdir(self.po_dir) self.spawn(cmd) os.chdir(wd) max_po_mtime = 0 for po_file in glob.glob("%s/*.po" % self.po_dir): lang = os.path.basename(po_file[:-3]) if selected_languages and lang not in selected_languages: continue mo_dir = os.path.join("build", "mo", lang, "LC_MESSAGES") mo_file = os.path.join(mo_dir, "%s.mo" % self.domain) if not os.path.exists(mo_dir): os.makedirs(mo_dir) cmd = [msgfmt, po_file, "-o", mo_file] po_mtime = os.path.getmtime(po_file) mo_mtime = ( os.path.exists(mo_file) and os.path.getmtime(mo_file) or 0) if po_mtime > max_po_mtime: max_po_mtime = po_mtime if po_mtime > mo_mtime: self.spawn(cmd) targetpath = os.path.join("share/locale", lang, "LC_MESSAGES") self.distribution.data_files.append((targetpath, (mo_file,))) self.max_po_mtime = max_po_mtime def run(self): if self.bug_contact is not None: os.environ["XGETTEXT_ARGS"] = "--msgid-bugs-address=%s " % \ self.bug_contact # These copies are pure hacks to work around not having the # Meson-based initial variable templating in distutils. import shutil shutil.copyfile( 'data/org.gnome.Meld.desktop.in.in', 'data/org.gnome.Meld.desktop.in', ) shutil.copyfile( 'data/org.gnome.Meld.appdata.xml.in.in', 'data/org.gnome.Meld.appdata.xml.in', ) self._rebuild_po() intltool_switches = [ (self.xml_files, "-x"), (self.desktop_files, "-d"), (self.schemas_files, "-s"), (self.key_files, "-k"), ] for file_set, switch in intltool_switches: for target, files in file_set: build_target = os.path.join("build", target) if not os.path.exists(build_target): os.makedirs(build_target) files_merged = [] for file in files: file_merged = os.path.basename(file) if file_merged.endswith(".in"): file_merged = file_merged[:-3] file_merged = os.path.join(build_target, file_merged) cmd = ["intltool-merge", switch, self.po_dir, file, file_merged] mtime_merged = (os.path.exists(file_merged) and os.path.getmtime(file_merged) or 0) mtime_file = os.path.getmtime(file) if (mtime_merged < self.max_po_mtime or mtime_merged < mtime_file): # Only build if output is older than input (.po,.in) self.spawn(cmd) files_merged.append(file_merged) self.distribution.data_files.append((target, files_merged)) class build_py(distutils.command.build_py.build_py): """Insert real package installation locations into conf module Adapted from gottengeography """ data_line = 'DATADIR = "%s"' locale_line = 'LOCALEDIR = "%s"' def build_module(self, module, module_file, package): if module_file == 'meld/conf.py': with open(module_file) as f: contents = f.read() try: options = self.distribution.get_option_dict('install') prefix = options['prefix'][1] except KeyError as e: print(e) prefix = sys.prefix datadir = os.path.join(prefix, 'share', 'meld') localedir = os.path.join(prefix, 'share', 'locale') start, end = 0, 0 lines = contents.splitlines() for i, line in enumerate(lines): if line.startswith('# START'): start = i elif line.startswith('# END'): end = i if start and end: lines[start:end + 1] = [ self.data_line % datadir, self.locale_line % localedir, ] module_file = module_file + "-installed" contents = "\n".join(lines) with open(module_file, 'w') as f: f.write(contents) distutils.command.build_py.build_py.build_module( self, module, module_file, package) class install(distutils.command.install.install): def finalize_options(self): special_cases = ('debian', 'ubuntu', 'linuxmint') if platform.system() == 'Linux': # linux_distribution has been removed in Python 3.8; we require # the third-party distro package for future handling. try: distribution = platform.linux_distribution()[0].lower() except AttributeError: try: distribution = distro.id() except NameError: distribution = 'unknown' if distribution in special_cases: # Maintain an explicit install-layout, but use deb by default specified_layout = getattr(self, 'install_layout', None) self.install_layout = specified_layout or 'deb' distutils.command.install.install.finalize_options(self) class install_data(distutils.command.install_data.install_data): def run(self): distutils.command.install_data.install_data.run(self) if not self.distribution.no_update_icon_cache: # TODO: Generalise to non-hicolor icon themes info("running gtk-update-icon-cache") icon_path = os.path.join(self.install_dir, "share/icons/hicolor") self.spawn(["gtk-update-icon-cache", "-q", "-t", icon_path]) if not self.distribution.no_compile_schemas: info("compiling gsettings schemas") gschema_path = build_data.gschemas[0][0] gschema_install = os.path.join(self.install_dir, gschema_path) self.spawn(["glib-compile-schemas", gschema_install])
17,731
Python
.py
397
33.11335
79
0.57491
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,823
conf.py.in
GNOME_meld/meld/conf.py.in
import os import sys from pathlib import Path __package__ = "meld" __version__ = "3.23.0" APPLICATION_NAME = 'Meld' APPLICATION_ID = 'org.gnome.Meld' SETTINGS_SCHEMA_ID = 'org.gnome.meld' RESOURCE_BASE = '/org/gnome/meld' # START; these paths are clobbered on install by meld.build_helpers DATADIR = Path(sys.prefix) / "share" / "meld" LOCALEDIR = Path(sys.prefix) / "share" / "locale" # END CONFIGURED = '@configured@' # Treat an unconfigured installation as development PROFILE = "Devel" if CONFIGURED == 'True': APPLICATION_ID = '@application_id@' DATADIR = '@pkgdatadir@' LOCALEDIR = '@localedir@' PROFILE = '@profile@' # Flag enabling some workarounds if data dir isn't installed in standard prefix DATADIR_IS_UNINSTALLED = False PYTHON_REQUIREMENT_TUPLE = (3, 6) # Installed from main script def no_translation(gettext_string: str) -> str: return gettext_string _ = no_translation ngettext = no_translation def frozen(): global DATADIR, LOCALEDIR, DATADIR_IS_UNINSTALLED melddir = os.path.dirname(sys.executable) DATADIR = os.path.join(melddir, "share", "meld") LOCALEDIR = os.path.join(melddir, "share", "mo") DATADIR_IS_UNINSTALLED = True PROFILE = "" def uninstalled(): global DATADIR, LOCALEDIR, DATADIR_IS_UNINSTALLED melddir = Path(__file__).resolve().parent.parent DATADIR = melddir / "data" LOCALEDIR = melddir / "build" / "mo" DATADIR_IS_UNINSTALLED = True resource_path = melddir / "meld" / "resources" os.environ['G_RESOURCE_OVERLAYS'] = f'{RESOURCE_BASE}={resource_path}'
1,582
Python
.py
44
32.863636
79
0.715415
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,824
sourceview.py
GNOME_meld/meld/sourceview.py
# Copyright (C) 2009 Vincent Legoll <vincent.legoll@gmail.com> # Copyright (C) 2010-2011, 2013-2019 Kai Willadsen <kai.willadsen@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or (at # your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import logging from enum import Enum from gi.repository import Gdk, Gio, GLib, GObject, Gtk, GtkSource, Pango from meld.meldbuffer import MeldBuffer from meld.settings import bind_settings, get_meld_settings, settings from meld.style import colour_lookup_with_fallback, get_common_theme log = logging.getLogger(__name__) def get_custom_encoding_candidates(): custom_candidates = [] try: for charset in settings.get_value('detect-encodings'): encoding = GtkSource.Encoding.get_from_charset(charset) if not encoding: log.warning('Invalid charset "%s" skipped', charset) continue custom_candidates.append(encoding) if custom_candidates: custom_candidates.extend( GtkSource.Encoding.get_default_candidates()) except AttributeError: # get_default_candidates() is only available in GtkSourceView 3.18 # and we'd rather use their defaults than our old detect list. pass return custom_candidates class LanguageManager: manager = GtkSource.LanguageManager() @classmethod def get_language_from_file(cls, gfile): try: info = gfile.query_info( Gio.FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE, 0, None) except (GLib.GError, AttributeError): return None content_type = info.get_content_type() return cls.manager.guess_language(gfile.get_basename(), content_type) @classmethod def get_language_from_mime_type(cls, mime_type): content_type = Gio.content_type_from_mime_type(mime_type) return cls.manager.guess_language(None, content_type) class TextviewLineAnimationType(Enum): fill = 'fill' stroke = 'stroke' class TextviewLineAnimation: __slots__ = ("start_mark", "end_mark", "start_rgba", "end_rgba", "start_time", "duration", "anim_type") def __init__(self, mark0, mark1, rgba0, rgba1, duration, anim_type): self.start_mark = mark0 self.end_mark = mark1 self.start_rgba = rgba0 self.end_rgba = rgba1 self.start_time = GLib.get_monotonic_time() self.duration = duration self.anim_type = anim_type class SourceViewHelperMixin: def get_y_for_line_num(self, line): buf = self.get_buffer() it = buf.get_iter_at_line(line) y, h = self.get_line_yrange(it) if line >= buf.get_line_count(): return y + h return y def get_line_num_for_y(self, y): return self.get_line_at_y(y)[0].get_line() class MeldSourceView(GtkSource.View, SourceViewHelperMixin): __gtype_name__ = "MeldSourceView" __gsettings_bindings_view__ = ( ('highlight-current-line', 'highlight-current-line-local'), ('indent-width', 'tab-width'), ('insert-spaces-instead-of-tabs', 'insert-spaces-instead-of-tabs'), ('enable-space-drawer', 'draw-spaces-bool'), ('wrap-mode', 'wrap-mode'), ('show-line-numbers', 'show-line-numbers'), ) # Named so as not to conflict with the GtkSourceView property highlight_current_line_local = GObject.Property(type=bool, default=False) def get_show_line_numbers(self): return self._show_line_numbers def set_show_line_numbers(self, show): if show == self._show_line_numbers: return if getattr(self, 'line_renderer', None): self.line_renderer.set_visible(show) self._show_line_numbers = bool(show) self.notify("show-line-numbers") show_line_numbers = GObject.Property( type=bool, default=False, getter=get_show_line_numbers, setter=set_show_line_numbers) wrap_mode_bool = GObject.Property( type=bool, default=False, nick="Wrap mode (Boolean version)", blurb=( "Mirror of the wrap-mode GtkTextView property, reduced to " "a single Boolean for UI ease-of-use." ), ) draw_spaces_bool = GObject.Property( type=bool, default=False, nick="Draw spaces (Boolean version)", blurb=( "Mirror of the draw-spaces GtkSourceView property, " "reduced to a single Boolean for UI ease-of-use." ), ) overscroll_num_lines = GObject.Property( type=int, default=5, minimum=0, maximum=100, nick="Overscroll line count", flags=( GObject.ParamFlags.READWRITE | GObject.ParamFlags.CONSTRUCT ), ) replaced_entries = ( # We replace the default GtkSourceView undo mechanism (Gdk.KEY_z, Gdk.ModifierType.CONTROL_MASK), (Gdk.KEY_z, Gdk.ModifierType.CONTROL_MASK | Gdk.ModifierType.SHIFT_MASK), # We replace the default line movement behaviour of Alt+Up/Down (Gdk.KEY_Up, Gdk.ModifierType.MOD1_MASK), (Gdk.KEY_KP_Up, Gdk.ModifierType.MOD1_MASK), (Gdk.KEY_KP_Up, Gdk.ModifierType.MOD1_MASK | Gdk.ModifierType.SHIFT_MASK), (Gdk.KEY_Down, Gdk.ModifierType.MOD1_MASK), (Gdk.KEY_KP_Down, Gdk.ModifierType.MOD1_MASK), (Gdk.KEY_KP_Down, Gdk.ModifierType.MOD1_MASK | Gdk.ModifierType.SHIFT_MASK), # ...and Alt+Left/Right (Gdk.KEY_Left, Gdk.ModifierType.MOD1_MASK), (Gdk.KEY_KP_Left, Gdk.ModifierType.MOD1_MASK), (Gdk.KEY_Right, Gdk.ModifierType.MOD1_MASK), (Gdk.KEY_KP_Right, Gdk.ModifierType.MOD1_MASK), # ...and Ctrl+Page Up/Down (Gdk.KEY_Page_Up, Gdk.ModifierType.CONTROL_MASK), (Gdk.KEY_KP_Page_Up, Gdk.ModifierType.CONTROL_MASK), (Gdk.KEY_Page_Down, Gdk.ModifierType.CONTROL_MASK), (Gdk.KEY_KP_Page_Down, Gdk.ModifierType.CONTROL_MASK), ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.drag_dest_add_uri_targets() # Most bindings are on SourceView, except the Page Up/Down ones # which are on TextView. binding_set_names = ('GtkSourceView', 'GtkTextView') for set_name in binding_set_names: binding_set = Gtk.binding_set_find(set_name) for key, modifiers in self.replaced_entries: Gtk.binding_entry_remove(binding_set, key, modifiers) self.anim_source_id = None self.animating_chunks = [] self.syncpoints = [] self._show_line_numbers = None buf = MeldBuffer() inline_tag = GtkSource.Tag.new("inline") inline_tag.props.draw_spaces = True buf.get_tag_table().add(inline_tag) buf.create_tag("dimmed") self.set_buffer(buf) self.connect('notify::overscroll-num-lines', self.notify_overscroll) @property def line_height(self) -> int: if not getattr(self, '_approx_line_height', None): context = self.get_pango_context() layout = Pango.Layout(context) layout.set_text('X', -1) _width, self._approx_line_height = layout.get_pixel_size() return self._approx_line_height def notify_overscroll(self, view, param): self.props.bottom_margin = self.overscroll_num_lines * self.line_height def do_paste_clipboard(self, *args): # This is an awful hack to replace another awful hack. The idea # here is to sanitise the clipboard contents so that it doesn't # contain GtkTextTags, by requesting and setting plain text. def text_received_cb(clipboard, text, *user_data): # On clipboard failure, text will be None if not text: return # Manual encoding is required here, or the length will be # incorrect, and the API requires a UTF-8 bytestring. utf8_text = text.encode('utf-8') clipboard.set_text(text, len(utf8_text)) self.get_buffer().paste_clipboard( clipboard, None, self.get_editable()) clipboard = self.get_clipboard(Gdk.SELECTION_CLIPBOARD) clipboard.request_text(text_received_cb) def add_fading_highlight( self, mark0, mark1, colour_name, duration, anim_type=TextviewLineAnimationType.fill, starting_alpha=1.0): if not self.get_realized(): return rgba0 = self.fill_colors[colour_name].copy() rgba1 = self.fill_colors[colour_name].copy() rgba0.alpha = starting_alpha rgba1.alpha = 0.0 anim = TextviewLineAnimation( mark0, mark1, rgba0, rgba1, duration, anim_type) self.animating_chunks.append(anim) def on_setting_changed(self, settings, key): if key == 'font': self.override_font(settings.font) self._approx_line_height = None elif key == 'style-scheme': self.highlight_color = colour_lookup_with_fallback( "meld:current-line-highlight", "background") self.syncpoint_color = colour_lookup_with_fallback( "meld:syncpoint-outline", "foreground") self.fill_colors, self.line_colors = get_common_theme() buf = self.get_buffer() buf.set_style_scheme(settings.style_scheme) tag = buf.get_tag_table().lookup("inline") tag.props.background_rgba = colour_lookup_with_fallback( "meld:inline", "background") tag = buf.get_tag_table().lookup("dimmed") tag.props.foreground_rgba = colour_lookup_with_fallback( "meld:dimmed", "foreground") def do_realize(self): bind_settings(self) def wrap_mode_from_bool(binding, from_value): if from_value: settings_mode = settings.get_enum('wrap-mode') if settings_mode == Gtk.WrapMode.NONE: mode = Gtk.WrapMode.WORD else: mode = settings_mode else: mode = Gtk.WrapMode.NONE return mode def wrap_mode_to_bool(binding, from_value): return bool(from_value) self.bind_property( 'wrap-mode-bool', self, 'wrap-mode', GObject.BindingFlags.BIDIRECTIONAL, wrap_mode_from_bool, wrap_mode_to_bool, ) self.wrap_mode_bool = wrap_mode_to_bool(None, self.props.wrap_mode) self.bind_property( 'draw-spaces-bool', self.props.space_drawer, 'enable-matrix', GObject.BindingFlags.DEFAULT | GObject.BindingFlags.SYNC_CREATE, ) meld_settings = get_meld_settings() self.on_setting_changed(meld_settings, 'font') self.on_setting_changed(meld_settings, 'style-scheme') self.get_buffer().set_style_scheme(meld_settings.style_scheme) meld_settings.connect('changed', self.on_setting_changed) return GtkSource.View.do_realize(self) def do_unrealize(self): if self.anim_source_id: GLib.source_remove(self.anim_source_id) return GtkSource.View.do_unrealize(self) def do_draw_layer(self, layer, context): if layer != Gtk.TextViewLayer.BELOW_TEXT: return GtkSource.View.do_draw_layer(self, layer, context) context.save() context.set_line_width(1.0) _, clip = Gdk.cairo_get_clip_rectangle(context) clip_end = clip.y + clip.height bounds = ( self.get_line_num_for_y(clip.y), self.get_line_num_for_y(clip_end), ) x = clip.x - 0.5 width = clip.width + 1 # Paint chunk backgrounds and outlines for change in self.chunk_iter(bounds): ypos0 = self.get_y_for_line_num(change[1]) ypos1 = self.get_y_for_line_num(change[2]) height = max(0, ypos1 - ypos0 - 1) context.rectangle(x, ypos0 + 0.5, width, height) if change[1] != change[2]: context.set_source_rgba(*self.fill_colors[change[0]]) context.fill_preserve() if self.current_chunk_check(change): highlight = self.fill_colors['current-chunk-highlight'] context.set_source_rgba(*highlight) context.fill_preserve() context.set_source_rgba(*self.line_colors[change[0]]) context.stroke() textbuffer = self.get_buffer() # Check whether we're drawing past the last line in the buffer # (i.e., the overscroll) and draw a custom background if so. end_y, end_height = self.get_line_yrange(textbuffer.get_end_iter()) end_y += end_height visible_bottom_margin = clip_end - end_y if visible_bottom_margin > 0: context.rectangle(x + 1, end_y, width - 1, visible_bottom_margin) context.set_source_rgba(*self.fill_colors['overscroll']) context.fill() # Paint current line highlight if self.props.highlight_current_line_local and self.is_focus(): it = textbuffer.get_iter_at_mark(textbuffer.get_insert()) ypos, line_height = self.get_line_yrange(it) context.rectangle(x, ypos, width, line_height) context.set_source_rgba(*self.highlight_color) context.fill() # Draw syncpoint indicator lines for syncpoint in self.syncpoints: if syncpoint is None: continue syncline = textbuffer.get_iter_at_mark(syncpoint).get_line() if bounds[0] <= syncline <= bounds[1]: ypos = self.get_y_for_line_num(syncline) context.rectangle(x, ypos - 0.5, width, 1) context.set_source_rgba(*self.syncpoint_color) context.stroke() # Overdraw all animated chunks, and update animation states new_anim_chunks = [] for c in self.animating_chunks: current_time = GLib.get_monotonic_time() percent = min( 1.0, (current_time - c.start_time) / float(c.duration)) rgba_pairs = zip(c.start_rgba, c.end_rgba) rgba = [s + (e - s) * percent for s, e in rgba_pairs] it = textbuffer.get_iter_at_mark(c.start_mark) ystart, _ = self.get_line_yrange(it) it = textbuffer.get_iter_at_mark(c.end_mark) yend, _ = self.get_line_yrange(it) if ystart == yend: ystart -= 1 context.set_source_rgba(*rgba) context.rectangle(x, ystart, width, yend - ystart) if c.anim_type == TextviewLineAnimationType.stroke: context.stroke() else: context.fill() if current_time <= c.start_time + c.duration: new_anim_chunks.append(c) else: textbuffer.delete_mark(c.start_mark) textbuffer.delete_mark(c.end_mark) self.animating_chunks = new_anim_chunks if self.animating_chunks and self.anim_source_id is None: def anim_cb(): self.queue_draw() return True # Using timeout_add interferes with recalculation of inline # highlighting; this mechanism could be improved. self.anim_source_id = GLib.idle_add(anim_cb) elif not self.animating_chunks and self.anim_source_id: GLib.source_remove(self.anim_source_id) self.anim_source_id = None context.restore() return GtkSource.View.do_draw_layer(self, layer, context) class CommitMessageSourceView(GtkSource.View): __gtype_name__ = "CommitMessageSourceView" __gsettings_bindings_view__ = ( ('indent-width', 'tab-width'), ('insert-spaces-instead-of-tabs', 'insert-spaces-instead-of-tabs'), ('enable-space-drawer', 'enable-space-drawer'), ) enable_space_drawer = GObject.Property(type=bool, default=False) def do_realize(self): bind_settings(self) self.bind_property( 'enable-space-drawer', self.props.space_drawer, 'enable-matrix', GObject.BindingFlags.DEFAULT | GObject.BindingFlags.SYNC_CREATE, ) return GtkSource.View.do_realize(self) class MeldSourceMap(GtkSource.Map, SourceViewHelperMixin): __gtype_name__ = "MeldSourceMap" compact_view = GObject.Property( type=bool, nick="Limit the view to a fixed width", default=False, ) COMPACT_MODE_WIDTH = 40 def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.connect('notify::compact-view', lambda *args: self.queue_resize()) def do_draw_layer(self, layer, context): if layer != Gtk.TextViewLayer.BELOW_TEXT: return GtkSource.Map.do_draw_layer(self, layer, context) # Handle bad view assignments and partial initialisation parent_view = self.props.view if not hasattr(parent_view, 'chunk_iter'): return GtkSource.Map.do_draw_layer(self, layer, context) context.save() context.set_line_width(1.0) _, clip = Gdk.cairo_get_clip_rectangle(context) x = clip.x - 0.5 width = clip.width + 1 bounds = ( self.get_line_num_for_y(clip.y), self.get_line_num_for_y(clip.y + clip.height), ) # Paint chunk backgrounds for change in parent_view.chunk_iter(bounds): if change[1] == change[2]: # We don't have room to paint inserts in this widget continue ypos0 = self.get_y_for_line_num(change[1]) ypos1 = self.get_y_for_line_num(change[2]) height = max(0, ypos1 - ypos0 - 1) context.rectangle(x, ypos0 + 0.5, width, height) context.set_source_rgba(*parent_view.fill_colors[change[0]]) context.fill() context.restore() return GtkSource.Map.do_draw_layer(self, layer, context) def do_get_preferred_width(self): if self.props.compact_view: return (self.COMPACT_MODE_WIDTH, self.COMPACT_MODE_WIDTH) else: return GtkSource.Map.do_get_preferred_width(self)
19,001
Python
.py
416
35.59375
79
0.619805
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,825
vcview.py
GNOME_meld/meld/vcview.py
# Copyright (C) 2002-2006 Stephen Kennedy <stevek@gnome.org> # Copyright (C) 2010-2019 Kai Willadsen <kai.willadsen@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or (at # your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import atexit import functools import logging import os import shutil import stat import sys import tempfile from typing import Tuple from gi.repository import Gdk, Gio, GLib, GObject, Gtk, Pango from meld import tree from meld.conf import _ from meld.externalhelpers import open_files_external from meld.iohelpers import trash_or_confirm from meld.melddoc import MeldDoc from meld.misc import error_dialog, read_pipe_iter from meld.recent import RecentType from meld.settings import bind_settings, settings from meld.ui.vcdialogs import CommitDialog, PushDialog from meld.vc import _null, get_vcs from meld.vc._vc import Entry log = logging.getLogger(__name__) def cleanup_temp(): temp_location = tempfile.gettempdir() # The strings below will probably end up as debug log, and are deliberately # not marked for translation. for f in _temp_files: try: assert (os.path.exists(f) and os.path.isabs(f) and os.path.dirname(f) == temp_location) # Windows throws permissions errors if we remove read-only files if os.name == "nt": os.chmod(f, stat.S_IWRITE) os.remove(f) except Exception: except_str = "{0[0]}: \"{0[1]}\"".format(sys.exc_info()) print("File \"{0}\" not removed due to".format(f), except_str, file=sys.stderr) for f in _temp_dirs: try: assert (os.path.exists(f) and os.path.isabs(f) and os.path.dirname(f) == temp_location) shutil.rmtree(f, ignore_errors=1) except Exception: except_str = "{0[0]}: \"{0[1]}\"".format(sys.exc_info()) print("Directory \"{0}\" not removed due to".format(f), except_str, file=sys.stderr) _temp_dirs, _temp_files = [], [] atexit.register(cleanup_temp) class ConsoleStream: def __init__(self, textview): self.textview = textview buf = textview.get_buffer() self.command_tag = buf.create_tag("command") self.command_tag.props.weight = Pango.Weight.BOLD self.output_tag = buf.create_tag("output") self.error_tag = buf.create_tag("error") # FIXME: Need to add this to the gtkrc? self.error_tag.props.foreground = "#cc0000" self.end_mark = buf.create_mark(None, buf.get_end_iter(), left_gravity=False) def command(self, message): self.write(message, self.command_tag) def output(self, message): self.write(message, self.output_tag) def error(self, message): self.write(message, self.error_tag) def write(self, message, tag): if not message: return buf = self.textview.get_buffer() buf.insert_with_tags(buf.get_end_iter(), message, tag) self.textview.scroll_mark_onscreen(self.end_mark) COL_LOCATION, COL_STATUS, COL_OPTIONS, COL_END = \ list(range(tree.COL_END, tree.COL_END + 4)) class VcTreeStore(tree.DiffTreeStore): def __init__(self): super().__init__(1, [str] * 5) def get_file_path(self, it): return self.get_value(it, self.column_index(tree.COL_PATH, 0)) @Gtk.Template(resource_path='/org/gnome/meld/ui/vcview.ui') class VcView(Gtk.Box, tree.TreeviewCommon, MeldDoc): __gtype_name__ = "VcView" __gsettings_bindings__ = ( ('vc-status-filters', 'status-filters'), ('vc-left-is-local', 'left-is-local'), ('vc-merge-file-order', 'merge-file-order'), ) close_signal = MeldDoc.close_signal create_diff_signal = MeldDoc.create_diff_signal file_changed_signal = MeldDoc.file_changed_signal label_changed = MeldDoc.label_changed move_diff = MeldDoc.move_diff tab_state_changed = MeldDoc.tab_state_changed status_filters = GObject.Property( type=GObject.TYPE_STRV, nick="File status filters", blurb="Files with these statuses will be shown by the comparison.", ) left_is_local = GObject.Property(type=bool, default=False) merge_file_order = GObject.Property(type=str, default="local-merge-remote") # Map for inter-tab command() calls command_map = { 'resolve': 'resolve', } state_actions = { 'flatten': ('vc-flatten', None), 'modified': ('vc-status-modified', Entry.is_modified), 'normal': ('vc-status-normal', Entry.is_normal), 'unknown': ('vc-status-unknown', Entry.is_nonvc), 'ignored': ('vc-status-ignored', Entry.is_ignored), } combobox_vcs = Gtk.Template.Child() console_vbox = Gtk.Template.Child() consoleview = Gtk.Template.Child() emblem_renderer = Gtk.Template.Child() extra_column = Gtk.Template.Child() extra_renderer = Gtk.Template.Child() filelabel = Gtk.Template.Child() liststore_vcs = Gtk.Template.Child() location_column = Gtk.Template.Child() location_renderer = Gtk.Template.Child() name_column = Gtk.Template.Child() name_renderer = Gtk.Template.Child() status_column = Gtk.Template.Child() status_renderer = Gtk.Template.Child() treeview = Gtk.Template.Child() vc_console_vpaned = Gtk.Template.Child() def __init__(self): super().__init__() # FIXME: # This unimaginable hack exists because GObject (or GTK+?) # doesn't actually correctly chain init calls, even if they're # not to GObjects. As a workaround, we *should* just be able to # put our class first, but because of Gtk.Template we can't do # that if it's a GObject, because GObject doesn't support # multiple inheritance and we need to inherit from our Widget # parent to make Template work. MeldDoc.__init__(self) bind_settings(self) # Set up per-view action group for top-level menu insertion self.view_action_group = Gio.SimpleActionGroup() property_actions = ( ('vc-console-visible', self.console_vbox, 'visible'), ) for action_name, obj, prop_name in property_actions: action = Gio.PropertyAction.new(action_name, obj, prop_name) self.view_action_group.add_action(action) # Manually handle GAction additions actions = ( ('compare', self.action_diff), ('find', self.action_find), ('next-change', self.action_next_change), ('open-external', self.action_open_external), ('previous-change', self.action_previous_change), ('refresh', self.action_refresh), ('vc-add', self.action_add), ('vc-commit', self.action_commit), ('vc-delete-locally', self.action_delete), ('vc-push', self.action_push), ('vc-remove', self.action_remove), ('vc-resolve', self.action_resolved), ('vc-revert', self.action_revert), ('vc-update', self.action_update), ) for name, callback in actions: action = Gio.SimpleAction.new(name, None) action.connect('activate', callback) self.view_action_group.add_action(action) new_boolean = GLib.Variant.new_boolean stateful_actions = ( ('vc-filter', None, GLib.Variant.new_boolean(False)), ('vc-flatten', self.action_filter_state_change, new_boolean('flatten' in self.props.status_filters)), ('vc-status-modified', self.action_filter_state_change, new_boolean('modified' in self.props.status_filters)), ('vc-status-normal', self.action_filter_state_change, new_boolean('normal' in self.props.status_filters)), ('vc-status-unknown', self.action_filter_state_change, new_boolean('unknown' in self.props.status_filters)), ('vc-status-ignored', self.action_filter_state_change, new_boolean('ignored' in self.props.status_filters)), ) for (name, callback, state) in stateful_actions: action = Gio.SimpleAction.new_stateful(name, None, state) if callback: action.connect('change-state', callback) self.view_action_group.add_action(action) builder = Gtk.Builder.new_from_resource( '/org/gnome/meld/ui/vcview-menus.ui') context_menu = builder.get_object('vcview-context-menu') self.popup_menu = Gtk.Menu.new_from_model(context_menu) self.popup_menu.attach_to_widget(self) self.model = VcTreeStore() self.treeview.set_model(self.model) self.treeview.get_selection().connect( "changed", self.on_treeview_selection_changed) self.treeview.set_search_equal_func(tree.treeview_search_cb, None) self.current_path, self.prev_path, self.next_path = None, None, None self.name_column.set_attributes( self.emblem_renderer, icon_name=tree.COL_ICON, icon_tint=tree.COL_TINT) self.name_column.set_attributes( self.name_renderer, text=tree.COL_TEXT, foreground_rgba=tree.COL_FG, style=tree.COL_STYLE, weight=tree.COL_WEIGHT, strikethrough=tree.COL_STRIKE) self.location_column.set_attributes( self.location_renderer, markup=COL_LOCATION) self.status_column.set_attributes( self.status_renderer, markup=COL_STATUS) self.extra_column.set_attributes( self.extra_renderer, markup=COL_OPTIONS) self.consolestream = ConsoleStream(self.consoleview) self.location = None self.vc = None settings.bind('vc-console-visible', self.console_vbox, 'visible', Gio.SettingsBindFlags.DEFAULT) settings.bind('vc-console-pane-position', self.vc_console_vpaned, 'position', Gio.SettingsBindFlags.DEFAULT) def on_container_switch_in_event(self, window): super().on_container_switch_in_event(window) # FIXME: open-external should be tied to having a treeview selection self.set_action_enabled("open-external", True) self.scheduler.add_task(self.on_treeview_cursor_changed) def on_container_switch_out_event(self, window): self.set_action_enabled("open-external", False) super().on_container_switch_out_event(window) def get_default_vc(self, vcs): target_name = self.vc.NAME if self.vc else None for i, (name, vc, enabled) in enumerate(vcs): if not enabled: continue if target_name and name == target_name: return i depths = [len(getattr(vc, 'root', [])) for name, vc, enabled in vcs] target_depth = max(depths, default=0) for i, (name, vc, enabled) in enumerate(vcs): if not enabled: continue if target_depth and len(vc.root) == target_depth: return i return 0 def populate_vcs_for_location(self, location): """Display VC plugin(s) that can handle the location""" vcs_model = self.combobox_vcs.get_model() vcs_model.clear() # VC systems can be executed at the directory level, so make sure # we're checking for VC support there instead of # on a specific file or on deleted/unexisting path inside vc location = os.path.abspath(location or ".") while not os.path.isdir(location): parent_location = os.path.dirname(location) if len(parent_location) >= len(location): # no existing parent: for example unexisting drive on Windows break location = parent_location else: # existing parent directory was found for avc, enabled in get_vcs(location): err_str = '' vc_details = {'name': avc.NAME, 'cmd': avc.CMD} if not enabled: # Translators: This error message is shown when no # repository of this type is found. err_str = _("%(name)s (not found)") elif not avc.is_installed(): # Translators: This error message is shown when a version # control binary isn't installed. err_str = _("%(name)s (%(cmd)s not installed)") elif not avc.valid_repo(location): # Translators: This error message is shown when a version # controlled repository is invalid. err_str = _("%(name)s (invalid repository)") if err_str: vcs_model.append([err_str % vc_details, avc, False]) continue vcs_model.append([avc.NAME, avc(location), True]) default_active = self.get_default_vc(vcs_model) if not any(enabled for _, _, enabled in vcs_model): # If we didn't get any valid vcs then fallback to null null_vcs = _null.Vc(location) vcs_model.insert(0, [null_vcs.NAME, null_vcs, True]) tooltip = _("No valid version control system found in this folder") else: tooltip = _("Choose which version control system to use") self.combobox_vcs.set_tooltip_text(tooltip) self.combobox_vcs.set_active(default_active) @Gtk.Template.Callback() def on_vc_change(self, combobox_vcs): active_iter = combobox_vcs.get_active_iter() if active_iter is None: return self.vc = combobox_vcs.get_model()[active_iter][1] self._set_location(self.vc.location) def set_location(self, location): self.populate_vcs_for_location(location) def _set_location(self, location): self.location = location self.current_path = None self.model.clear() self.filelabel.props.gfile = Gio.File.new_for_path(location) it = self.model.add_entries(None, [location]) self.treeview.get_selection().select_iter(it) self.model.set_path_state(it, 0, tree.STATE_NORMAL, isdir=1) self.recompute_label() self.scheduler.remove_all_tasks() # If the user is just diffing a file (i.e., not a directory), # there's no need to scan the rest of the repository. if not os.path.isdir(self.vc.location): return root = self.model.get_iter_first() root_path = self.model.get_path(root) try: self.model.set_value( root, COL_OPTIONS, self.vc.get_commits_to_push_summary()) except NotImplementedError: pass self.scheduler.add_task(self.vc.refresh_vc_state) self.scheduler.add_task(self._search_recursively_iter(root_path)) self.scheduler.add_task(self.on_treeview_selection_changed) self.scheduler.add_task(self.on_treeview_cursor_changed) def get_comparison(self): if self.location: uris = [Gio.File.new_for_path(self.location)] else: uris = [] return RecentType.VersionControl, uris def recompute_label(self): self.label_text = os.path.basename(self.location) self.tooltip_text = "\n".join(( # TRANSLATORS: This is the name of the version control # system being used, e.g., "Git" or "Subversion" _("{vc} comparison:").format(vc=self.vc.NAME), self.location, )) self.label_changed.emit(self.label_text, self.tooltip_text) def _search_recursively_iter(self, start_path, replace=False): # Initial yield so when we add this to our tasks, we don't # create iterators that may be invalidated. yield _("Scanning repository") if replace: # Replace the row at start_path with a new, empty row ready # to be filled. old_iter = self.model.get_iter(start_path) file_path = self.model.get_file_path(old_iter) new_iter = self.model.insert_after(None, old_iter) self.model.set_value(new_iter, tree.COL_PATH, file_path) self.model.set_path_state(new_iter, 0, tree.STATE_NORMAL, True) self.model.remove(old_iter) iterstart = self.model.get_iter(start_path) rootname = self.model.get_file_path(iterstart) display_prefix = len(rootname) + 1 symlinks_followed = set() todo = [(self.model.get_path(iterstart), rootname)] flattened = 'flatten' in self.props.status_filters active_actions = [ self.state_actions.get(k) for k in self.props.status_filters] filters = [a[1] for a in active_actions if a and a[1]] while todo: # This needs to happen sorted and depth-first in order for our row # references to remain valid while we traverse. todo.sort() treepath, path = todo.pop(0) it = self.model.get_iter(treepath) yield _("Scanning %s") % path[display_prefix:] entries = self.vc.get_entries(path) entries = [e for e in entries if any(f(e) for f in filters)] entries = sorted(entries, key=lambda e: e.name) entries = sorted(entries, key=lambda e: not e.isdir) for e in entries: if e.isdir and e.is_present(): try: st = os.lstat(e.path) # Covers certain unreadable symlink cases; see bgo#585895 except OSError as err: error_string = "%r: %s" % (e.path, err.strerror) self.model.add_error(it, error_string, 0) continue if stat.S_ISLNK(st.st_mode): key = (st.st_dev, st.st_ino) if key in symlinks_followed: continue symlinks_followed.add(key) if flattened: if e.state != tree.STATE_IGNORED: # If directory state is changed, render it in # in flattened mode. if e.state != tree.STATE_NORMAL: child = self.model.add_entries(it, [e.path]) self._update_item_state(child, e) todo.append((Gtk.TreePath.new_first(), e.path)) continue child = self.model.add_entries(it, [e.path]) if e.isdir and e.state != tree.STATE_IGNORED: todo.append((self.model.get_path(child), e.path)) self._update_item_state(child, e) if not flattened: if not entries: self.model.add_empty(it, _("(Empty)")) elif any(e.state != tree.STATE_NORMAL for e in entries): self.treeview.expand_to_path(treepath) self.treeview.expand_row(Gtk.TreePath.new_first(), False) self.treeview.set_cursor(Gtk.TreePath.new_first()) # TODO: This doesn't fire when the user selects a shortcut folder @Gtk.Template.Callback() def on_file_selected( self, button: Gtk.Button, pane: int, file: Gio.File) -> None: path = file.get_path() self.set_location(path) def on_delete_event(self): self.scheduler.remove_all_tasks() self.close_signal.emit(0) return Gtk.ResponseType.OK @Gtk.Template.Callback() def on_row_activated(self, treeview, path, tvc): it = self.model.get_iter(path) if self.model.iter_has_child(it): if self.treeview.row_expanded(path): self.treeview.collapse_row(path) else: self.treeview.expand_row(path, False) else: path = self.model.get_file_path(it) if not self.model.is_folder(it, 0, path): self.run_diff(path) def run_diff(self, path): if os.path.isdir(path): self.create_diff_signal.emit([Gio.File.new_for_path(path)], {}) return basename = os.path.basename(path) meta = { 'parent': self, 'prompt_resolve': False, } # May have removed directories in list. vc_entry = self.vc.get_entry(path) if vc_entry and vc_entry.state == tree.STATE_CONFLICT and \ hasattr(self.vc, 'get_path_for_conflict'): local_label = _("%s — local") % basename remote_label = _("%s — remote") % basename # We create new temp files for other, base and this, and # then set the output to the current file. if self.props.merge_file_order == "local-merge-remote": conflicts = (tree.CONFLICT_THIS, tree.CONFLICT_MERGED, tree.CONFLICT_OTHER) meta['labels'] = (local_label, None, remote_label) meta['tablabel'] = _("%s (local, merge, remote)") % basename else: conflicts = (tree.CONFLICT_OTHER, tree.CONFLICT_MERGED, tree.CONFLICT_THIS) meta['labels'] = (remote_label, None, local_label) meta['tablabel'] = _("%s (remote, merge, local)") % basename diffs = [self.vc.get_path_for_conflict(path, conflict=c) for c in conflicts] temps = [p for p, is_temp in diffs if is_temp] diffs = [p for p, is_temp in diffs] kwargs = { 'auto_merge': False, 'merge_output': Gio.File.new_for_path(path), } meta['prompt_resolve'] = True else: remote_label = _("%s — repository") % basename comp_path = self.vc.get_path_for_repo_file(path) temps = [comp_path] if self.props.left_is_local: diffs = [path, comp_path] meta['labels'] = (None, remote_label) meta['tablabel'] = _("%s (working, repository)") % basename else: diffs = [comp_path, path] meta['labels'] = (remote_label, None) meta['tablabel'] = _("%s (repository, working)") % basename kwargs = {} kwargs['meta'] = meta for temp_file in temps: os.chmod(temp_file, 0o444) _temp_files.append(temp_file) self.create_diff_signal.emit( [Gio.File.new_for_path(d) for d in diffs], kwargs, ) def get_filter_visibility(self) -> Tuple[bool, bool, bool]: return False, False, True def action_filter_state_change(self, action, value): action.set_state(value) active_filters = [ k for k, (action_name, fn) in self.state_actions.items() if self.get_action_state(action_name) ] if set(active_filters) == set(self.props.status_filters): return self.props.status_filters = active_filters self.refresh() def on_treeview_selection_changed(self, selection=None): if selection is None: selection = self.treeview.get_selection() model, rows = selection.get_selected_rows() paths = [self.model.get_file_path(model.get_iter(r)) for r in rows] states = [self.model.get_state(model.get_iter(r), 0) for r in rows] path_states = dict(zip(paths, states)) valid_actions = self.vc.get_valid_actions(path_states) action_sensitivity = { 'compare': 'compare' in valid_actions, 'vc-add': 'add' in valid_actions, 'vc-commit': 'commit' in valid_actions, 'vc-delete-locally': bool(paths) and self.vc.root not in paths, 'vc-push': 'push' in valid_actions, 'vc-remove': 'remove' in valid_actions, 'vc-resolve': 'resolve' in valid_actions, 'vc-revert': 'revert' in valid_actions, 'vc-update': 'update' in valid_actions, } for action, sensitivity in action_sensitivity.items(): self.set_action_enabled(action, sensitivity) def _get_selected_files(self): model, rows = self.treeview.get_selection().get_selected_rows() sel = [self.model.get_file_path(self.model.get_iter(r)) for r in rows] # Remove empty entries and trailing slashes return [x[-1] != "/" and x or x[:-1] for x in sel if x is not None] def _command_iter(self, command, files, refresh, working_dir): """An iterable that runs a VC command on a set of files This method is intended to be used as a scheduled task, with standard out and error output displayed in this view's consolestream. """ def shelljoin(command): def quote(s): return '"%s"' % s if len(s.split()) > 1 else s return " ".join(quote(tok) for tok in command) files = [os.path.relpath(f, working_dir) for f in files] msg = shelljoin(command + files) + " (in %s)\n" % working_dir self.consolestream.command(msg) readiter = read_pipe_iter( command + files, workdir=working_dir, errorstream=self.consolestream) try: result = next(readiter) while not result: yield 1 result = next(readiter) except IOError as err: error_dialog( "Error running command", "While running '%s'\nError: %s" % (msg, err)) result = (1, "") returncode, output = result self.consolestream.output(output + "\n") if returncode: self.console_vbox.show() if refresh: refresh = functools.partial(self.refresh_partial, working_dir) GLib.idle_add(refresh) def has_command(self, command): vc_command = self.command_map.get(command) return vc_command and hasattr(self.vc, vc_command) def command(self, command, files, sync=False): """ Run a command against this view's version control subsystem This is the intended way for things outside of the VCView to call in to version control methods, e.g., to mark a conflict as resolved from a file comparison. :param command: The version control command to run, taken from keys in `VCView.command_map`. :param files: File parameters to the command as paths :param sync: If True, the command will be executed immediately (as opposed to being run by the idle scheduler). """ if not self.has_command(command): log.error("Couldn't understand command %s", command) return if not isinstance(files, list): log.error("Invalid files argument to '%s': %r", command, files) return runner = self.runner if not sync else self.sync_runner command = getattr(self.vc, self.command_map[command]) command(runner, files) def runner(self, command, files, refresh, working_dir): """Schedule a version control command to run as an idle task""" self.scheduler.add_task( self._command_iter(command, files, refresh, working_dir)) def sync_runner(self, command, files, refresh, working_dir): """Run a version control command immediately""" for it in self._command_iter(command, files, refresh, working_dir): pass def action_update(self, *args): self.vc.update(self.runner) def action_push(self, *args): response = PushDialog(self).run() if response == Gtk.ResponseType.OK: self.vc.push(self.runner) def action_commit(self, *args): response, commit_msg = CommitDialog(self).run() if response == Gtk.ResponseType.OK: self.vc.commit( self.runner, self._get_selected_files(), commit_msg) def action_add(self, *args): self.vc.add(self.runner, self._get_selected_files()) def action_remove(self, *args): selected = self._get_selected_files() if any(os.path.isdir(p) for p in selected): # TODO: Improve and reuse this dialog for the non-VC delete action dialog = Gtk.MessageDialog( parent=self.get_toplevel(), flags=(Gtk.DialogFlags.MODAL | Gtk.DialogFlags.DESTROY_WITH_PARENT), type=Gtk.MessageType.WARNING, message_format=_("Remove folder and all its files?")) dialog.format_secondary_text( _("This will remove all selected files and folders, and all " "files within any selected folders, from version control.")) dialog.add_button(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL) dialog.add_button(_("_Remove"), Gtk.ResponseType.OK) response = dialog.run() dialog.destroy() if response != Gtk.ResponseType.OK: return self.vc.remove(self.runner, selected) def action_resolved(self, *args): self.vc.resolve(self.runner, self._get_selected_files()) def action_revert(self, *args): self.vc.revert(self.runner, self._get_selected_files()) def action_delete(self, *args): files = self._get_selected_files() for name in files: gfile = Gio.File.new_for_path(name) try: trash_or_confirm(gfile) except Exception as e: error_dialog( _("Error deleting {}").format( GLib.markup_escape_text(gfile.get_parse_name()), ), str(e), ) workdir = os.path.dirname(os.path.commonprefix(files)) self.refresh_partial(workdir) def action_diff(self, *args): # TODO: Review the compare/diff action. It doesn't really add much # over activate, since the folder compare doesn't work and hasn't # for... a long time. files = self._get_selected_files() for f in files: self.run_diff(f) def action_open_external(self, *args): gfiles = [Gio.File.new_for_path(f) for f in self._get_selected_files() if f] open_files_external(gfiles) def refresh(self): root = self.model.get_iter_first() if root is None: return self.set_location(self.model.get_file_path(root)) def refresh_partial(self, where): if not self.get_action_state('vc-flatten'): it = self.find_iter_by_name(where) if not it: return path = self.model.get_path(it) self.treeview.grab_focus() self.vc.refresh_vc_state(where) self.scheduler.add_task( self._search_recursively_iter(path, replace=True)) self.scheduler.add_task(self.on_treeview_selection_changed) self.scheduler.add_task(self.on_treeview_cursor_changed) else: # XXX fixme self.refresh() def _update_item_state(self, it, entry): self.model.set_path_state(it, 0, entry.state, entry.isdir) location = Gio.File.new_for_path(self.vc.location) parent = Gio.File.new_for_path(entry.path).get_parent() display_location = location.get_relative_path(parent) self.model.set_value(it, COL_LOCATION, display_location) self.model.set_value(it, COL_STATUS, entry.get_status()) self.model.set_value(it, COL_OPTIONS, entry.options) def on_file_changed(self, filename): it = self.find_iter_by_name(filename) if it: path = self.model.get_file_path(it) self.vc.refresh_vc_state(path) entry = self.vc.get_entry(path) self._update_item_state(it, entry) def find_iter_by_name(self, name): it = self.model.get_iter_first() path = self.model.get_file_path(it) while it: if name == path: return it elif name.startswith(path): child = self.model.iter_children(it) while child: path = self.model.get_file_path(child) if name == path: return child elif name.startswith(path): break else: child = self.model.iter_next(child) it = child else: break return None @Gtk.Template.Callback() def on_consoleview_populate_popup(self, textview, menu): buf = textview.get_buffer() clear_action = Gtk.MenuItem.new_with_label(_("Clear")) clear_action.connect( "activate", lambda *args: buf.delete(*buf.get_bounds())) menu.insert(clear_action, 0) menu.insert(Gtk.SeparatorMenuItem(), 1) menu.show_all() @Gtk.Template.Callback() def on_treeview_popup_menu(self, treeview): return tree.TreeviewCommon.on_treeview_popup_menu(self, treeview) @Gtk.Template.Callback() def on_treeview_button_press_event(self, treeview, event): return tree.TreeviewCommon.on_treeview_button_press_event( self, treeview, event) @Gtk.Template.Callback() def on_treeview_cursor_changed(self, *args): cursor_path, cursor_col = self.treeview.get_cursor() if not cursor_path: self.set_action_enabled("previous-change", False) self.set_action_enabled("next-change", False) self.current_path = cursor_path return # If invoked directly rather than through a callback, we always check if not args: skip = False else: try: old_cursor = self.model.get_iter(self.current_path) except (ValueError, TypeError): # An invalid path gives ValueError; None gives a TypeError skip = False else: # We can skip recalculation if the new cursor is between # the previous/next bounds, and we weren't on a changed row state = self.model.get_state(old_cursor, 0) if state not in (tree.STATE_NORMAL, tree.STATE_EMPTY): skip = False else: if self.prev_path is None and self.next_path is None: skip = True elif self.prev_path is None: skip = cursor_path < self.next_path elif self.next_path is None: skip = self.prev_path < cursor_path else: skip = self.prev_path < cursor_path < self.next_path if not skip: prev, next_ = self.model._find_next_prev_diff(cursor_path) self.prev_path, self.next_path = prev, next_ self.set_action_enabled("previous-change", prev is not None) self.set_action_enabled("next-change", next_ is not None) self.current_path = cursor_path def next_diff(self, direction): if direction == Gdk.ScrollDirection.UP: path = self.prev_path else: path = self.next_path if path: self.treeview.expand_to_path(path) self.treeview.set_cursor(path) else: self.error_bell() def action_previous_change(self, *args): self.next_diff(Gdk.ScrollDirection.UP) def action_next_change(self, *args): self.next_diff(Gdk.ScrollDirection.DOWN) def action_refresh(self, *args): self.set_location(self.location) def action_find(self, *args): self.treeview.emit("start-interactive-search") def auto_compare(self): modified_states = (tree.STATE_MODIFIED, tree.STATE_CONFLICT) for it in self.model.state_rows(modified_states): row_paths = self.model.value_paths(it) paths = [p for p in row_paths if os.path.exists(p)] self.run_diff(paths[0]) VcView.set_css_name('meld-vc-view')
37,204
Python
.py
800
35.24
84
0.594891
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,826
task.py
GNOME_meld/meld/task.py
# Copyright (C) 2002-2006 Stephen Kennedy <stevek@gnome.org> # Copyright (C) 2012-2013 Kai Willadsen <kai.willadsen@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or (at # your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """Classes to implement scheduling for cooperative threads.""" import traceback class SchedulerBase: """Base class with common functionality for schedulers Derived classes must implement get_current_task. """ def __init__(self): self.tasks = [] self.callbacks = [] def __repr__(self): return "%s" % self.tasks def connect(self, signal, action): assert signal == "runnable" if action not in self.callbacks: self.callbacks.append(action) def add_task(self, task, atfront=False): """Add a task to the scheduler's task list The task may be a function, generator or scheduler, and is deemed to have finished when it returns a false value or raises StopIteration. """ self.remove_task(task) if atfront: self.tasks.insert(0, task) else: self.tasks.append(task) for callback in self.callbacks: callback(self) def remove_task(self, task): """Remove a single task from the scheduler""" try: self.tasks.remove(task) except ValueError: pass def remove_all_tasks(self): """Remove all tasks from the scheduler""" self.tasks = [] def add_scheduler(self, sched): """Adds a subscheduler as a child task of this scheduler""" sched.connect("runnable", lambda t: self.add_task(t)) def remove_scheduler(self, sched): """Remove a sub-scheduler from this scheduler""" self.remove_task(sched) try: self.callbacks.remove(sched) except ValueError: pass def get_current_task(self): """Overridden function returning the next task to run""" raise NotImplementedError def __call__(self): """Run an iteration of the current task""" if len(self.tasks): r = self.iteration() if r: return r return self.tasks_pending() def complete_tasks(self): """Run all of the scheduler's current tasks to completion""" while self.tasks_pending(): self.iteration() def tasks_pending(self): return len(self.tasks) != 0 def iteration(self): """Perform one iteration of the current task""" try: task = self.get_current_task() except StopIteration: return 0 try: if hasattr(task, "__iter__"): ret = next(task) else: ret = task() except StopIteration: pass except Exception: traceback.print_exc() else: if ret: return ret self.tasks.remove(task) return 0 class LifoScheduler(SchedulerBase): """Scheduler calling most recently added tasks first""" def get_current_task(self): try: return self.tasks[-1] except IndexError: raise StopIteration class FifoScheduler(SchedulerBase): """Scheduler calling tasks in the order they were added""" def get_current_task(self): try: return self.tasks[0] except IndexError: raise StopIteration if __name__ == "__main__": import random import time m = LifoScheduler() def timetask(t): while time.time() - t < 1: print("***") time.sleep(0.1) print("!!!") def sayhello(x): for i in range(random.randint(2, 8)): print("hello", x) time.sleep(0.1) yield 1 print("end", x) s = FifoScheduler() m.add_task(s) s.add_task(sayhello(10)) s.add_task(sayhello(20)) s.add_task(sayhello(30)) while s.tasks_pending(): s.iteration() time.sleep(2) print("***")
4,646
Python
.py
136
26.102941
71
0.61054
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,827
dirdiff.py
GNOME_meld/meld/dirdiff.py
# Copyright (C) 2002-2006 Stephen Kennedy <stevek@gnome.org> # Copyright (C) 2009-2019 Kai Willadsen <kai.willadsen@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or (at # your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import collections import copy import errno import functools import logging import os import shutil import stat import sys import typing import unicodedata from collections import namedtuple from decimal import Decimal from mmap import ACCESS_COPY, mmap from typing import DefaultDict, Dict, List, NamedTuple, Optional, Tuple from gi.repository import Gdk, Gio, GLib, GObject, Gtk # TODO: Don't from-import whole modules from meld import misc, tree from meld.conf import _ from meld.const import FILE_FILTER_ACTION_FORMAT, MISSING_TIMESTAMP from meld.externalhelpers import open_files_external from meld.iohelpers import find_shared_parent_path, trash_or_confirm from meld.melddoc import MeldDoc from meld.misc import all_same, apply_text_filters, with_focused_pane from meld.recent import RecentType from meld.settings import bind_settings, get_meld_settings, settings from meld.treehelpers import refocus_deleted_path, tree_path_as_tuple from meld.ui.cellrenderers import ( CellRendererByteSize, CellRendererDate, CellRendererFileMode, CellRendererISODate, ) from meld.ui.emblemcellrenderer import EmblemCellRenderer from meld.ui.util import map_widgets_into_lists if typing.TYPE_CHECKING: from meld.ui.pathlabel import PathLabel log = logging.getLogger(__name__) class StatItem(namedtuple('StatItem', 'mode size time')): __slots__ = () @classmethod def _make(cls, stat_result): return StatItem(stat.S_IFMT(stat_result.st_mode), stat_result.st_size, stat_result.st_mtime) def shallow_equal(self, other: "StatItem", time_resolution_ns: int) -> bool: if self.size != other.size: return False # Check for the ignore-timestamp configuration first if time_resolution_ns == -1: return True # Shortcut to avoid expensive Decimal calculations. 2 seconds is our # current accuracy threshold (for VFAT), so should be safe for now. if abs(self.time - other.time) > 2: return False dectime1 = Decimal(self.time).scaleb(Decimal(9)).quantize(1) dectime2 = Decimal(other.time).scaleb(Decimal(9)).quantize(1) mtime1 = dectime1 // time_resolution_ns mtime2 = dectime2 // time_resolution_ns return mtime1 == mtime2 CacheResult = namedtuple('CacheResult', 'stats result') _cache = {} Same, SameFiltered, DodgySame, DodgyDifferent, Different, FileError = ( list(range(6))) # TODO: Get the block size from os.stat CHUNK_SIZE = 4096 def remove_blank_lines(text): """ Remove blank lines from text. And normalize line ending """ return b'\n'.join(filter(bool, text.splitlines())) def _files_contents(files, stats): mmaps = [] is_bin = False contents = [b'' for file_obj in files] for index, file_and_stat in enumerate(zip(files, stats)): file_obj, stat_ = file_and_stat # use mmap for files with size > CHUNK_SIZE data = b'' if stat_.size > CHUNK_SIZE: data = mmap(file_obj.fileno(), 0, access=ACCESS_COPY) mmaps.append(data) else: data = file_obj.read() contents[index] = data # Rough test to see whether files are binary. chunk_size = min([stat_.size, CHUNK_SIZE]) if b"\0" in data[:chunk_size]: is_bin = True return contents, mmaps, is_bin def _contents_same(contents, file_size): other_files_index = list(range(1, len(contents))) chunk_range = zip( range(0, file_size, CHUNK_SIZE), range(CHUNK_SIZE, file_size + CHUNK_SIZE, CHUNK_SIZE), ) for start, end in chunk_range: chunk = contents[0][start:end] for index in other_files_index: if not chunk == contents[index][start:end]: return Different def _normalize(contents, ignore_blank_lines, regexes=()): contents = (bytes(c) for c in contents) # For probable text files, discard newline differences to match if ignore_blank_lines: contents = (remove_blank_lines(c) for c in contents) else: contents = (b"\n".join(c.splitlines()) for c in contents) if regexes: contents = (apply_text_filters(c, regexes) for c in contents) if ignore_blank_lines: # We re-remove blank lines here in case applying text # filters has caused more lines to be blank. contents = (remove_blank_lines(c) for c in contents) return contents def _files_same(files, regexes, comparison_args): """Determine whether a list of files are the same. Possible results are: Same: The files are the same SameFiltered: The files are identical only after filtering with 'regexes' DodgySame: The files are superficially the same (i.e., type, size, mtime) DodgyDifferent: The files are superficially different FileError: There was a problem reading one or more of the files """ if all_same(files): return Same files = tuple(files) stats = tuple([StatItem._make(os.stat(f)) for f in files]) shallow_comparison = comparison_args['shallow-comparison'] time_resolution_ns = comparison_args['time-resolution'] ignore_blank_lines = comparison_args['ignore_blank_lines'] apply_text_filters = comparison_args['apply-text-filters'] need_contents = ignore_blank_lines or apply_text_filters regexes = tuple(regexes) if apply_text_filters else () # If all entries are directories, they are considered to be the same if all([stat.S_ISDIR(s.mode) for s in stats]): return Same # If any entries are not regular files, consider them different if not all([stat.S_ISREG(s.mode) for s in stats]): return Different # Compare files superficially if the options tells us to if shallow_comparison: all_same_timestamp = all( s.shallow_equal(stats[0], time_resolution_ns) for s in stats[1:] ) return DodgySame if all_same_timestamp else Different same_size = all_same([s.size for s in stats]) # If there are no text filters, unequal sizes imply a difference if not need_contents and not same_size: return Different # Check the cache before doing the expensive comparison cache_key = (files, need_contents, regexes, ignore_blank_lines) cache = _cache.get(cache_key) if cache and cache.stats == stats: return cache.result # Open files and compare bit-by-bit result = None try: mmaps = [] handles = [open(file_path, "rb") for file_path in files] try: contents, mmaps, is_bin = _files_contents(handles, stats) # compare files chunk-by-chunk if same_size: result = _contents_same(contents, stats[0].size) else: result = Different # normalize and compare files again if result == Different and need_contents and not is_bin: contents = _normalize(contents, ignore_blank_lines, regexes) result = SameFiltered if all_same(contents) else Different # Files are too large; we can't apply filters except (MemoryError, OverflowError): result = DodgySame if all_same(stats) else DodgyDifferent finally: for m in mmaps: m.close() for h in handles: h.close() except IOError: # Don't cache generic errors as results return FileError if result is None: result = Same _cache[cache_key] = CacheResult(stats, result) return result EMBLEM_NEW = "emblem-new" EMBLEM_SELECTED = "emblem-default-symbolic" EMBLEM_SYMLINK = "emblem-symbolic-link" COL_EMBLEM, COL_SIZE, COL_TIME, COL_PERMS, COL_END = ( range(tree.COL_END, tree.COL_END + 5)) class DirDiffTreeStore(tree.DiffTreeStore): def __init__(self, ntree): # FIXME: size should be a GObject.TYPE_UINT64, but we use -1 as a flag super().__init__(ntree, [str, GObject.TYPE_INT64, float, int]) def add_error(self, parent, msg, pane): defaults = { COL_TIME: MISSING_TIMESTAMP, COL_SIZE: -1, COL_PERMS: -1, } super().add_error(parent, msg, pane, defaults) class ComparisonOptions: def __init__( self, *, ignore_case: bool = False, normalize_encoding: bool = False, ): self.ignore_case = ignore_case self.normalize_encoding = normalize_encoding class CanonicalListing: """Multi-pane lists with canonicalised matching and error detection""" items: DefaultDict[str, List[Optional[str]]] stripped_items: Dict[str, str] errors: List[Tuple[int, str, str]] whitespace: List[Tuple[int, str]] def __init__(self, n: int, options: ComparisonOptions): self.items = collections.defaultdict(lambda: [None] * n) self.stripped_items = {} self.errors = [] self.whitespace = [] self.options = options def add(self, pane: int, item: str): # normalize the name depending on settings ci = item if self.options.ignore_case: ci = ci.lower() if self.options.normalize_encoding: # NFC or NFD will work here, changing all composed or decomposed # characters to the same set for matching only. ci = unicodedata.normalize('NFC', ci) # add the item to the comparison tree existing_item = self.items[ci][pane] if existing_item is None: self.items[ci][pane] = item else: self.errors.append((pane, item, existing_item)) stripped_item = ci.strip() if stripped_item in self.stripped_items: # If we have an existing stripped item and its pre-stripping # value differs, then we have a case of misleading whitespace if self.stripped_items[stripped_item] != ci: self.whitespace.append((pane, item)) else: self.stripped_items[stripped_item] = ci def get(self): def filled(seq): fill_value = next(s for s in seq if s) return tuple(s or fill_value for s in seq) return sorted(filled(v) for v in self.items.values()) class ComparisonMarker(NamedTuple): """A stable row + pane marker This marker is used for selecting a specific file or folder when the user wants to compare paths that don't have matching names, and so aren't aligned in our tree view. """ pane: int row: Gtk.TreeRowReference def get_iter(self) -> Gtk.TreeIter: return self.row.get_model().get_iter(self.row.get_path()) def matches_iter(self, pane: int, it: Gtk.TreeIter) -> bool: return ( pane == self.pane and self.row.get_model().get_path(it) == self.row.get_path() ) @classmethod def from_selection( cls, treeview: Gtk.TreeView, pane: int, ) -> "ComparisonMarker": if pane is None or pane == -1: raise ValueError("Invalid pane for marker") model = treeview.get_model() _, selected_paths = treeview.get_selection().get_selected_rows() # We'll assume that in any multi-select, the first row was the # intended mark. selected_row = Gtk.TreeRowReference.new(model, selected_paths[0]) return cls( pane=pane, row=selected_row, ) @Gtk.Template(resource_path='/org/gnome/meld/ui/dirdiff.ui') class DirDiff(Gtk.Box, tree.TreeviewCommon, MeldDoc): __gtype_name__ = "DirDiff" close_signal = MeldDoc.close_signal create_diff_signal = MeldDoc.create_diff_signal file_changed_signal = MeldDoc.file_changed_signal label_changed = MeldDoc.label_changed move_diff = MeldDoc.move_diff tab_state_changed = MeldDoc.tab_state_changed __gsettings_bindings__ = ( ('folder-ignore-symlinks', 'ignore-symlinks'), ('folder-shallow-comparison', 'shallow-comparison'), ('folder-time-resolution', 'time-resolution'), ('folder-status-filters', 'status-filters'), ('folder-filter-text', 'apply-text-filters'), ('ignore-blank-lines', 'ignore-blank-lines'), ) apply_text_filters = GObject.Property( type=bool, nick="Apply text filters", blurb=( "Whether text filters and other text sanitisation preferences " "should be applied when comparing file contents"), default=False, ) folders: List[Optional[Gio.File]] = GObject.Property( type=object, nick="Folders being compared", blurb="List of folders being compared, as GFiles", ) ignore_blank_lines = GObject.Property( type=bool, nick="Ignore blank lines", blurb="Whether to ignore blank lines when comparing file contents", default=False, ) ignore_symlinks = GObject.Property( type=bool, nick="Ignore symbolic links", blurb="Whether to follow symbolic links when comparing folders", default=False, ) shallow_comparison = GObject.Property( type=bool, nick="Use shallow comparison", blurb="Whether to compare files based solely on size and mtime", default=False, ) status_filters = GObject.Property( type=GObject.TYPE_STRV, nick="File status filters", blurb="Files with these statuses will be shown by the comparison.", ) time_resolution = GObject.Property( type=int, nick="Time resolution", blurb="When comparing based on mtime, the minimum difference in " "nanoseconds between two files before they're considered to " "have different mtimes.", default=100, ) show_overview_map = GObject.Property(type=bool, default=True) chunkmap0 = Gtk.Template.Child() chunkmap1 = Gtk.Template.Child() chunkmap2 = Gtk.Template.Child() folder_label: 'List[PathLabel]' folder_label0 = Gtk.Template.Child() folder_label1 = Gtk.Template.Child() folder_label2 = Gtk.Template.Child() folder_open_button0 = Gtk.Template.Child() folder_open_button1 = Gtk.Template.Child() folder_open_button2 = Gtk.Template.Child() treeview0 = Gtk.Template.Child() treeview1 = Gtk.Template.Child() treeview2 = Gtk.Template.Child() scrolledwindow0 = Gtk.Template.Child() scrolledwindow1 = Gtk.Template.Child() scrolledwindow2 = Gtk.Template.Child() linkmap0 = Gtk.Template.Child() linkmap1 = Gtk.Template.Child() msgarea_mgr0 = Gtk.Template.Child() msgarea_mgr1 = Gtk.Template.Child() msgarea_mgr2 = Gtk.Template.Child() overview_map_revealer = Gtk.Template.Child() pane_actionbar0 = Gtk.Template.Child() pane_actionbar1 = Gtk.Template.Child() pane_actionbar2 = Gtk.Template.Child() vbox0 = Gtk.Template.Child() vbox1 = Gtk.Template.Child() vbox2 = Gtk.Template.Child() dummy_toolbar_linkmap0 = Gtk.Template.Child() dummy_toolbar_linkmap1 = Gtk.Template.Child() toolbar_sourcemap_revealer = Gtk.Template.Child() state_actions = { tree.STATE_NORMAL: ("normal", "folder-status-same"), tree.STATE_NOCHANGE: ("normal", "folder-status-same"), tree.STATE_NEW: ("new", "folder-status-new"), tree.STATE_MODIFIED: ("modified", "folder-status-modified"), } def __init__(self, num_panes): super().__init__() # FIXME: # This unimaginable hack exists because GObject (or GTK+?) # doesn't actually correctly chain init calls, even if they're # not to GObjects. As a workaround, we *should* just be able to # put our class first, but because of Gtk.Template we can't do # that if it's a GObject, because GObject doesn't support # multiple inheritance and we need to inherit from our Widget # parent to make Template work. MeldDoc.__init__(self) bind_settings(self) self.view_action_group = Gio.SimpleActionGroup() property_actions = ( ('show-overview-map', self, 'show-overview-map'), ) for action_name, obj, prop_name in property_actions: action = Gio.PropertyAction.new(action_name, obj, prop_name) self.view_action_group.add_action(action) # Manually handle GAction additions actions = ( ('find', self.action_find), ('folder-collapse', self.action_folder_collapse), ('folder-compare', self.action_diff), ('folder-mark', self.action_mark), ('folder-compare-marked', self.action_diff_marked), ('folder-copy-left', self.action_copy_left), ('folder-copy-right', self.action_copy_right), ('swap-2-panes', self.action_swap), ('folder-delete', self.action_delete), ('folder-expand', self.action_folder_expand), ('next-change', self.action_next_change), ('next-pane', self.action_next_pane), ('open-external', self.action_open_external), ('previous-change', self.action_previous_change), ('previous-pane', self.action_prev_pane), ('refresh', self.action_refresh), ('copy-file-paths', self.action_copy_file_paths), ) for name, callback in actions: action = Gio.SimpleAction.new(name, None) action.connect('activate', callback) self.view_action_group.add_action(action) actions = ( ("folder-filter", None, GLib.Variant.new_boolean(False)), ("folder-status-same", self.action_filter_state_change, GLib.Variant.new_boolean(False)), ("folder-status-new", self.action_filter_state_change, GLib.Variant.new_boolean(False)), ("folder-status-modified", self.action_filter_state_change, GLib.Variant.new_boolean(False)), ("folder-ignore-case", self.action_ignore_case_change, GLib.Variant.new_boolean(False)), ("folder-normalize-encoding", self.action_ignore_case_change, GLib.Variant.new_boolean(False)), ) for (name, callback, state) in actions: action = Gio.SimpleAction.new_stateful(name, None, state) if callback: action.connect("change-state", callback) self.view_action_group.add_action(action) builder = Gtk.Builder.new_from_resource( '/org/gnome/meld/ui/dirdiff-menus.ui') context_menu = builder.get_object('dirdiff-context-menu') self.popup_menu = Gtk.Menu.new_from_model(context_menu) self.popup_menu.attach_to_widget(self) builder = Gtk.Builder.new_from_resource( '/org/gnome/meld/ui/dirdiff-actions.ui') self.toolbar_actions = builder.get_object('view-toolbar') self.folders = [None, None, None] self.name_filters = [] self.text_filters = [] self.create_name_filters() self.create_text_filters() meld_settings = get_meld_settings() self.settings_handlers = [ meld_settings.connect( "file-filters-changed", self.on_file_filters_changed), meld_settings.connect( "text-filters-changed", self.on_text_filters_changed) ] # Handle overview map visibility binding. Because of how we use # grid packing, we need two revealers here instead of the more # obvious one. revealers = ( self.toolbar_sourcemap_revealer, self.overview_map_revealer, ) for revealer in revealers: self.bind_property( 'show-overview-map', revealer, 'reveal-child', ( GObject.BindingFlags.DEFAULT | GObject.BindingFlags.SYNC_CREATE ), ) map_widgets_into_lists( self, [ "treeview", "folder_label", "scrolledwindow", "chunkmap", "linkmap", "msgarea_mgr", "vbox", "dummy_toolbar_linkmap", "pane_actionbar", "folder_open_button", ], ) self.ensure_style() self.custom_labels = [] self.set_num_panes(num_panes) self.do_to_others_lock = False for treeview in self.treeview: treeview.set_search_equal_func(tree.treeview_search_cb, None) self.force_cursor_recalculate = False self.current_path, self.prev_path, self.next_path = None, None, None self.focus_pane = None self.row_expansions = set() # One column-dict for each treeview, for changing visibility and order self.columns_dict = [{}, {}, {}] for i in range(3): col_index = self.model.column_index # Create icon and filename CellRenderer column = Gtk.TreeViewColumn(_("Name")) column.set_resizable(True) rentext = Gtk.CellRendererText() renicon = EmblemCellRenderer() column.pack_start(renicon, False) column.pack_start(rentext, True) column.set_attributes(rentext, markup=col_index(tree.COL_TEXT, i), foreground_rgba=col_index(tree.COL_FG, i), style=col_index(tree.COL_STYLE, i), weight=col_index(tree.COL_WEIGHT, i), strikethrough=col_index(tree.COL_STRIKE, i)) column.set_attributes( renicon, icon_name=col_index(tree.COL_ICON, i), emblem_name=col_index(COL_EMBLEM, i), icon_tint=col_index(tree.COL_TINT, i) ) self.treeview[i].append_column(column) self.columns_dict[i]["name"] = column # Create file size CellRenderer column = Gtk.TreeViewColumn(_("Size")) column.set_resizable(True) rentext = CellRendererByteSize() column.pack_start(rentext, True) column.set_attributes(rentext, bytesize=col_index(COL_SIZE, i)) self.treeview[i].append_column(column) self.columns_dict[i]["size"] = column # Create date-time CellRenderer column = Gtk.TreeViewColumn(_("Modification time")) column.set_resizable(True) rentext = CellRendererDate() column.pack_start(rentext, True) column.set_attributes(rentext, timestamp=col_index(COL_TIME, i)) self.treeview[i].append_column(column) self.columns_dict[i]["modification time"] = column # Create ISO-format date-time CellRenderer column = Gtk.TreeViewColumn(_("Modification time (ISO)")) column.set_resizable(True) rentext = CellRendererISODate() column.pack_start(rentext, True) column.set_attributes(rentext, timestamp=col_index(COL_TIME, i)) self.treeview[i].append_column(column) self.columns_dict[i]["iso-time"] = column # Create permissions CellRenderer column = Gtk.TreeViewColumn(_("Permissions")) column.set_resizable(True) rentext = CellRendererFileMode() column.pack_start(rentext, False) column.set_attributes(rentext, file_mode=col_index(COL_PERMS, i)) self.treeview[i].append_column(column) self.columns_dict[i]["permissions"] = column for i in range(3): selection = self.treeview[i].get_selection() selection.set_mode(Gtk.SelectionMode.MULTIPLE) selection.connect('changed', self.on_treeview_selection_changed, i) self.scrolledwindow[i].get_vadjustment().connect( "value-changed", self._sync_vscroll) self.scrolledwindow[i].get_hadjustment().connect( "value-changed", self._sync_hscroll) self.linediffs = [[], []] self.update_treeview_columns(settings, 'folder-columns') settings.connect('changed::folder-columns', self.update_treeview_columns) self.update_comparator() self.connect("notify::shallow-comparison", self.update_comparator) self.connect("notify::time-resolution", self.update_comparator) self.connect("notify::ignore-blank-lines", self.update_comparator) self.connect("notify::apply-text-filters", self.update_comparator) # The list copying and state_filters reset here is because the action # toggled callback modifies the state while we're constructing it. self.state_filters = [] state_filters = [] for s in self.state_actions: if self.state_actions[s][0] in self.props.status_filters: state_filters.append(s) action_name = self.state_actions[s][1] self.set_action_state( action_name, GLib.Variant.new_boolean(True)) self.state_filters = state_filters self._scan_in_progress = 0 self.marked = None def queue_draw(self): for treeview in self.treeview: treeview.queue_draw() def update_comparator(self, *args): comparison_args = { 'shallow-comparison': self.props.shallow_comparison, 'time-resolution': self.props.time_resolution, 'apply-text-filters': self.props.apply_text_filters, 'ignore_blank_lines': self.props.ignore_blank_lines, } self.file_compare = functools.partial( _files_same, comparison_args=comparison_args) self.refresh() def update_treeview_columns( self, settings: Gio.Settings, key: str, ) -> None: """Update the visibility and order of columns""" columns = settings.get_value(key) have_extra_columns = any(visible for name, visible in columns) # Check for columns missing from the settings, special-casing # the always-present name column configured_columns = [name for name, visible in columns] + ["name"] missing_columns = [ c for c in self.columns_dict[0].keys() if c not in configured_columns ] for i, treeview in enumerate(self.treeview): last_column = treeview.get_column(0) for column_name, visible in columns: try: current_column = self.columns_dict[i][column_name] except KeyError: log.warning(f"Invalid column {column_name} in settings") continue current_column.set_visible(visible) treeview.move_column_after(current_column, last_column) last_column = current_column for column_name in missing_columns: self.columns_dict[i][column_name].set_visible(False) treeview.set_headers_visible(have_extra_columns) def get_filter_visibility(self) -> Tuple[bool, bool, bool]: # TODO: Make text filters available in folder comparison return False, True, False def on_file_filters_changed(self, app): relevant_change = self.create_name_filters() if relevant_change: self.refresh() def create_name_filters(self): meld_settings = get_meld_settings() # Ordering of name filters is irrelevant old_active = set([f.filter_string for f in self.name_filters if f.active]) new_active = set([f.filter_string for f in meld_settings.file_filters if f.active]) active_filters_changed = old_active != new_active # TODO: Rework name_filters to use a map-like structure so that we # don't need _action_name_filter_map. self._action_name_filter_map = {} self.name_filters = [copy.copy(f) for f in meld_settings.file_filters] for i, filt in enumerate(self.name_filters): action = Gio.SimpleAction.new_stateful( name=FILE_FILTER_ACTION_FORMAT.format(i), parameter_type=None, state=GLib.Variant.new_boolean(filt.active), ) action.connect('change-state', self._update_name_filter) action.set_enabled(filt.filter is not None) self.view_action_group.add_action(action) self._action_name_filter_map[action] = filt return active_filters_changed def on_text_filters_changed(self, app): relevant_change = self.create_text_filters() if relevant_change: self.refresh() def create_text_filters(self): meld_settings = get_meld_settings() # In contrast to file filters, ordering of text filters can matter old_active = [f.filter_string for f in self.text_filters if f.active] new_active = [f.filter_string for f in meld_settings.text_filters if f.active] active_filters_changed = old_active != new_active self.text_filters = [copy.copy(f) for f in meld_settings.text_filters] return active_filters_changed def _do_to_others(self, master, objects, methodname, args): if self.do_to_others_lock: return self.do_to_others_lock = True try: others = [o for o in objects[:self.num_panes] if o != master] for o in others: method = getattr(o, methodname) method(*args) finally: self.do_to_others_lock = False def _sync_vscroll(self, adjustment): adjs = [sw.get_vadjustment() for sw in self.scrolledwindow] self._do_to_others( adjustment, adjs, "set_value", (int(adjustment.get_value()),)) def _sync_hscroll(self, adjustment): adjs = [sw.get_hadjustment() for sw in self.scrolledwindow] self._do_to_others( adjustment, adjs, "set_value", (int(adjustment.get_value()),)) def _get_focused_pane(self): for i, treeview in enumerate(self.treeview): if treeview.is_focus(): return i return None def file_deleted(self, path, pane): # is file still extant in other pane? it = self.model.get_iter(path) files = self.model.value_paths(it) is_present = [os.path.exists(f) for f in files] if 1 in is_present: self._update_item_state(it) else: # nope its gone self.model.remove(it) def file_created(self, path, pane): it = self.model.get_iter(path) root = Gtk.TreePath.new_first() while it and self.model.get_path(it) != root: self._update_item_state(it) it = self.model.iter_parent(it) @Gtk.Template.Callback() def on_file_selected( self, button: Gtk.Button, pane: int, file: Gio.File) -> None: self.folders[pane] = file self.set_locations() def set_locations(self) -> None: locations = [f.get_path() for f in self.folders if f] if not locations: return self.set_num_panes(len(locations)) parent_path = find_shared_parent_path(self.folders) for pane, folder in enumerate(self.folders): self.folder_label[pane].gfile = folder self.folder_label[pane].parent_gfile = parent_path self.folder_open_button[pane].props.file = folder # This is difficult to trigger, and to test. Most of the time here we # will actually have had UTF-8 from GTK, which has been unicode-ed by # the time we get this far. This is a fallback, and may be wrong! locations = list(locations) for i, location in enumerate(locations): if location and not isinstance(location, str): locations[i] = location.decode(sys.getfilesystemencoding()) locations = [os.path.abspath(loc) if loc else '' for loc in locations] self.current_path = None self.marked = None self.model.clear() for m in self.msgarea_mgr: m.clear() child = self.model.add_entries(None, locations) self.on_treeview_focus_in_event(self.treeview0, None) self._update_item_state(child) self.recompute_label() self.scheduler.remove_all_tasks() self._scan_in_progress = 0 self.recursively_update(Gtk.TreePath.new_first()) def get_comparison(self): root = self.model.get_iter_first() if root: uris = [Gio.File.new_for_path(d) for d in self.model.value_paths(root)] else: uris = [] return RecentType.Folder, uris def mark_in_progress_row(self, it: Gtk.TreeIter) -> None: """Mark a tree row as having a scan in progress After the scan is finished, `_update_item_state()` must be called on the row to restore its actual state. """ for pane in range(self.model.ntree): path = self.model.get_value( it, self.model.column_index(tree.COL_PATH, pane)) filename = GLib.markup_escape_text(os.path.basename(path)) label = _(f"{filename} (scanning…)") self.model.set_state(it, pane, tree.STATE_SPINNER, label, True) self.model.unsafe_set(it, pane, { COL_EMBLEM: None, COL_TIME: MISSING_TIMESTAMP, COL_SIZE: -1, COL_PERMS: -1 }) def recursively_update(self, path): """Recursively update from tree path 'path'. """ it = self.model.get_iter(path) child = self.model.iter_children(it) while child: self.model.remove(child) child = self.model.iter_children(it) if self._scan_in_progress == 0: # Starting a scan, so set up progress indicator self.mark_in_progress_row(it) else: self._update_item_state(it) self._scan_in_progress += 1 self.scheduler.add_task(self._search_recursively_iter(path)) def _search_recursively_iter(self, rootpath): for t in self.treeview: sel = t.get_selection() sel.unselect_all() yield _('[{label}] Scanning {folder}').format( label=self.label_text, folder='') prefixlen = 1 + len( self.model.value_path(self.model.get_iter(rootpath), 0)) symlinks_followed = set() # TODO: This is horrible. if isinstance(rootpath, tuple): rootpath = Gtk.TreePath(rootpath) todo = [rootpath] expanded = set() shadowed_entries = [] invalid_filenames = [] whitespace_filenames = [] # TODO: Map these action states to GObject props instead? comparison_options = ComparisonOptions( ignore_case=self.get_action_state('folder-ignore-case'), normalize_encoding=self.get_action_state( 'folder-normalize-encoding'), ) while len(todo): todo.sort() # depth first path = todo.pop(0) it = self.model.get_iter(path) roots = self.model.value_paths(it) # Buggy ordering when deleting rows means that we sometimes try to # recursively update files; this fix seems the least invasive. if not any(os.path.isdir(root) for root in roots): continue yield _('[{label}] Scanning {folder}').format( label=self.label_text, folder=roots[0][prefixlen:]) differences = False encoding_errors = [] dirs = CanonicalListing(self.num_panes, comparison_options) files = CanonicalListing(self.num_panes, comparison_options) for pane, root in enumerate(roots): if not os.path.isdir(root): continue try: entries = os.listdir(root) except OSError as err: self.model.add_error(it, err.strerror, pane) differences = True continue for f in self.name_filters: if not f.active or f.filter is None: continue entries = [e for e in entries if f.filter.match(e) is None] for e in entries: try: e.encode('utf8') except UnicodeEncodeError: invalid = e.encode('utf8', 'surrogatepass') printable = invalid.decode('utf8', 'backslashreplace') encoding_errors.append((pane, printable)) continue try: s = os.lstat(os.path.join(root, e)) # Covers certain unreadable symlink cases; see bgo#585895 except OSError as err: error_string = e + err.strerror self.model.add_error(it, error_string, pane) continue if stat.S_ISLNK(s.st_mode): if self.props.ignore_symlinks: continue key = (s.st_dev, s.st_ino) if key in symlinks_followed: continue symlinks_followed.add(key) try: s = os.stat(os.path.join(root, e)) if stat.S_ISREG(s.st_mode): files.add(pane, e) elif stat.S_ISDIR(s.st_mode): dirs.add(pane, e) except OSError as err: if err.errno == errno.ENOENT: error_string = e + ": Dangling symlink" else: error_string = e + err.strerror self.model.add_error(it, error_string, pane) differences = True elif stat.S_ISREG(s.st_mode): files.add(pane, e) elif stat.S_ISDIR(s.st_mode): dirs.add(pane, e) else: # FIXME: Unhandled stat type pass for pane, f in encoding_errors: invalid_filenames.append((pane, roots[pane], f)) for pane, f1, f2 in dirs.errors + files.errors: shadowed_entries.append((pane, roots[pane], f1, f2)) for pane, f in dirs.whitespace + files.whitespace: whitespace_filenames.append((pane, roots[pane], f)) alldirs = self._filter_on_state(roots, dirs.get()) allfiles = self._filter_on_state(roots, files.get()) if alldirs or allfiles: for names in alldirs: entries = [ os.path.join(r, n) for r, n in zip(roots, names)] child = self.model.add_entries(it, entries) differences |= self._update_item_state(child) todo.append(self.model.get_path(child)) for names in allfiles: entries = [ os.path.join(r, n) for r, n in zip(roots, names)] child = self.model.add_entries(it, entries) differences |= self._update_item_state(child) else: # Our subtree is empty, or has been filtered to be empty if (tree.STATE_NORMAL in self.state_filters or not all(os.path.isdir(f) for f in roots)): self.model.add_empty(it) if self.model.iter_parent(it) is None: expanded.add(tree_path_as_tuple(rootpath)) else: # At this point, we have an empty folder tree node; we can # prune this and any ancestors that then end up empty. while not self.model.iter_has_child(it): parent = self.model.iter_parent(it) # In our tree, there is always a top-level parent with # no siblings. If we're here, we have an empty tree. if parent is None: self.model.add_empty(it) break # Remove the current row, and then revalidate all # sibling paths on the stack by removing and # readding them. had_siblings = self.model.remove(it) if had_siblings: parent_path = self.model.get_path(parent) for path in todo: if parent_path.is_ancestor(path): path.prev() it = parent if differences: expanded.add(tree_path_as_tuple(path)) duplicate_dirs = list(set(p for p in roots if roots.count(p) > 1)) if any((invalid_filenames, shadowed_entries, whitespace_filenames)): self._show_tree_wide_errors( invalid_filenames, shadowed_entries, whitespace_filenames ) elif duplicate_dirs: # Since we can only load 3 dirs we can have at most 1 duplicate self._show_duplicate_directory(duplicate_dirs[0]) elif rootpath == Gtk.TreePath.new_first() and not expanded: self._show_identical_status() self.treeview[0].expand_to_path(Gtk.TreePath(("0",))) for path in sorted(expanded): self.treeview[0].expand_to_path(Gtk.TreePath(path)) yield _('[{label}] Done').format(label=self.label_text) self._scan_in_progress -= 1 if self._scan_in_progress == 0: # Finishing a scan, so remove progress indicator self._update_item_state(self.model.get_iter(rootpath)) self.force_cursor_recalculate = True self.treeview[0].set_cursor(Gtk.TreePath.new_first()) def _show_duplicate_directory(self, duplicate_directory): for index in range(self.num_panes): primary = _( 'Folder {} is being compared to itself').format( duplicate_directory) self.msgarea_mgr[index].add_dismissable_msg( 'dialog-warning-symbolic', primary, '', self.msgarea_mgr) def _show_identical_status(self): primary = _("Folders have no differences") identical_note = _( "Contents of scanned files in folders are identical.") shallow_note = _( "Scanned files in folders appear identical, but contents have not " "been scanned.") file_filter_qualifier = _( "File filters are in use, so not all files have been scanned.") text_filter_qualifier = _( "Text filters are in use and may be masking content differences.") is_shallow = self.props.shallow_comparison have_file_filters = any(f.active for f in self.name_filters) have_text_filters = any(f.active for f in self.text_filters) secondary = [shallow_note if is_shallow else identical_note] if have_file_filters: secondary.append(file_filter_qualifier) if not is_shallow and have_text_filters: secondary.append(text_filter_qualifier) secondary = " ".join(secondary) for pane in range(self.num_panes): msgarea = self.msgarea_mgr[pane].new_from_text_and_icon( primary, secondary) button = msgarea.add_button(_("Hide"), Gtk.ResponseType.CLOSE) if pane == 0: button.props.label = _("Hi_de") def clear_all(*args): for p in range(self.num_panes): self.msgarea_mgr[p].clear() msgarea.connect("response", clear_all) msgarea.show_all() def _show_tree_wide_errors( self, invalid_filenames, shadowed_entries, whitespace_filenames ) -> None: header = _("Multiple errors occurred while scanning this folder") invalid_header = _("Files with invalid encodings found") # TRANSLATORS: This is followed by a list of files invalid_secondary = _("Some files were in an incorrect encoding. " "The names are something like:") shadowed_header = _("Files hidden by case insensitive comparison") # TRANSLATORS: This is followed by a list of files shadowed_secondary = _("You are running a case insensitive comparison " "on a case sensitive filesystem. The following " "files in this folder are hidden:") whitespace_header = _("Files had mismatched leading or trailing whitespace") # TRANSLATORS: This is followed by a list of files whitespace_secondary = _( "This comparison found some files that differed only in leading or " "trailing whitespace. Their names appear as:" ) invalid_entries = [[] for i in range(self.num_panes)] for pane, root, f in invalid_filenames: invalid_entries[pane].append(os.path.join(root, f)) formatted_entries = [[] for i in range(self.num_panes)] for pane, root, f1, f2 in shadowed_entries: paths = [os.path.join(root, f) for f in (f1, f2)] entry_str = _("“{first_file}” hidden by “{second_file}”").format( first_file=paths[0], second_file=paths[1], ) formatted_entries[pane].append(entry_str) whitespace_entries = [[] for i in range(self.num_panes)] for _pane, root, f in whitespace_filenames: for pane in range(self.num_panes): whitespace_entries[pane].append(os.path.join(root, f)) if invalid_filenames or shadowed_entries or whitespace_filenames: for pane in range(self.num_panes): invalid = "\n".join(invalid_entries[pane]) shadowed = "\n".join(formatted_entries[pane]) whitespace = "\n".join(whitespace_entries[pane]) error_type_count = [ bool(err) for err in (invalid, shadowed, whitespace) ].count(True) if error_type_count == 0: continue elif error_type_count == 1: if invalid: header = invalid_header elif shadowed: header = shadowed_header elif whitespace: header = whitespace_header messages = [] if invalid: messages.extend([invalid_secondary, invalid, ""]) if shadowed: messages.extend([shadowed_secondary, shadowed, ""]) if whitespace: messages.extend([whitespace_secondary, whitespace, ""]) secondary = ("\n".join(messages)).strip() self.msgarea_mgr[pane].add_dismissable_msg( "dialog-error-symbolic", header, secondary ) def copy_selected(self, direction): assert direction in (-1, 1) src_pane = self._get_focused_pane() if src_pane is None: return dst_pane = src_pane + direction assert dst_pane >= 0 and dst_pane < self.num_panes paths = self._get_selected_paths(src_pane) paths.reverse() model = self.model for path in paths: # filter(lambda x: x.name is not None, sel): it = model.get_iter(path) name = model.value_path(it, src_pane) if name is None: continue src = model.value_path(it, src_pane) dst = model.value_path(it, dst_pane) try: if os.path.isfile(src): dstdir = os.path.dirname(dst) if not os.path.exists(dstdir): os.makedirs(dstdir) misc.copy2(src, dstdir) self.file_created(path, dst_pane) elif os.path.isdir(src): if os.path.exists(dst): parent_name = os.path.dirname(dst) folder_name = os.path.basename(dst) dialog_buttons = [ (_("_Cancel"), Gtk.ResponseType.CANCEL, None), ( _("_Replace"), Gtk.ResponseType.OK, Gtk.STYLE_CLASS_DESTRUCTIVE_ACTION, ), ] replace = misc.modal_dialog( primary=_("Replace folder “%s”?") % folder_name, secondary=_( "Another folder with the same name already " "exists in “%s”.\n" "If you replace the existing folder, all " "files in it will be lost.") % parent_name, buttons=dialog_buttons, messagetype=Gtk.MessageType.WARNING, ) if replace != Gtk.ResponseType.OK: continue misc.copytree(src, dst) self.recursively_update(path) except (OSError, IOError, shutil.Error) as err: misc.error_dialog( _("Error copying file"), _("Couldn’t copy {source}\nto {dest}.\n\n{error}").format( source=GLib.markup_escape_text(src), dest=GLib.markup_escape_text(dst), error=GLib.markup_escape_text(str(err)), ) ) @with_focused_pane def delete_selected(self, pane): """Trash or delete all selected files/folders recursively""" paths = self._get_selected_paths(pane) # Reversing paths means that we remove tree rows bottom-up, so # tree paths don't change during the iteration. paths.reverse() for path in paths: it = self.model.get_iter(path) name = self.model.value_path(it, pane) gfile = Gio.File.new_for_path(name) try: deleted = trash_or_confirm(gfile) except Exception as e: misc.error_dialog( _("Error deleting {}").format( GLib.markup_escape_text(gfile.get_parse_name()), ), str(e), ) else: if deleted: self.file_deleted(path, pane) def on_treemodel_row_deleted(self, model, path): if self.current_path == path: self.current_path = refocus_deleted_path(model, path) if self.current_path and self.focus_pane: self.focus_pane.set_cursor(self.current_path) self.row_expansions = set() def on_treeview_selection_changed(self, selection, pane): if not self.treeview[pane].is_focus(): return self.update_action_sensitivity() def update_action_sensitivity(self): pane = self._get_focused_pane() if pane is not None: selection = self.treeview[pane].get_selection() have_selection = bool(selection.count_selected_rows()) else: have_selection = False if have_selection: is_valid = True for path in selection.get_selected_rows()[1]: state = self.model.get_state(self.model.get_iter(path), pane) if state in (tree.STATE_ERROR, tree.STATE_NONEXIST): is_valid = False break busy = self._scan_in_progress > 0 is_valid = is_valid and not busy is_single_foldable_row = False if (selection.count_selected_rows() == 1): path = selection.get_selected_rows()[1][0] it = self.model.get_iter(path) is_single_foldable_row = self.model.iter_has_child(it) self.set_action_enabled('folder-collapse', is_single_foldable_row) self.set_action_enabled('folder-expand', is_single_foldable_row) self.set_action_enabled('folder-compare', True) self.set_action_enabled('folder-mark', True) self.set_action_enabled( 'folder-compare-marked', self.marked is not None and self.marked.pane != pane) self.set_action_enabled('swap-2-panes', self.num_panes == 2) self.set_action_enabled('folder-delete', is_valid) self.set_action_enabled('folder-copy-left', is_valid and pane > 0) self.set_action_enabled( 'folder-copy-right', is_valid and pane + 1 < self.num_panes) self.set_action_enabled('open-external', is_valid) else: actions = ( 'folder-collapse', 'folder-compare', 'folder-mark', 'folder-compare-marked', 'folder-copy-left', 'folder-copy-right', 'folder-delete', 'folder-expand', 'open-external', ) for action in actions: self.set_action_enabled(action, False) @Gtk.Template.Callback() def on_treeview_cursor_changed(self, view): pane = self.treeview.index(view) if len(self.model) == 0: return cursor_path, cursor_col = self.treeview[pane].get_cursor() if not cursor_path: self.set_action_enabled("previous-change", False) self.set_action_enabled("next-change", False) self.current_path = cursor_path return if self.force_cursor_recalculate: # We force cursor recalculation on initial load, and when # we handle model change events. skip = False self.force_cursor_recalculate = False else: try: old_cursor = self.model.get_iter(self.current_path) except (ValueError, TypeError): # An invalid path gives ValueError; None gives a TypeError skip = False else: # We can skip recalculation if the new cursor is between # the previous/next bounds, and we weren't on a changed row state = self.model.get_state(old_cursor, 0) if state not in ( tree.STATE_NORMAL, tree.STATE_NOCHANGE, tree.STATE_EMPTY): skip = False else: if self.prev_path is None and self.next_path is None: skip = True elif self.prev_path is None: skip = cursor_path < self.next_path elif self.next_path is None: skip = self.prev_path < cursor_path else: skip = self.prev_path < cursor_path < self.next_path if not skip: prev, next_ = self.model._find_next_prev_diff(cursor_path) self.prev_path, self.next_path = prev, next_ self.set_action_enabled("previous-change", prev is not None) self.set_action_enabled("next-change", next_ is not None) self.current_path = cursor_path @Gtk.Template.Callback() def on_treeview_popup_menu(self, treeview): return tree.TreeviewCommon.on_treeview_popup_menu(self, treeview) @Gtk.Template.Callback() def on_treeview_button_press_event(self, treeview, event): return tree.TreeviewCommon.on_treeview_button_press_event( self, treeview, event) @with_focused_pane def action_prev_pane(self, pane, *args): new_pane = (pane - 1) % self.num_panes self.change_focused_tree(self.treeview[pane], self.treeview[new_pane]) @with_focused_pane def action_next_pane(self, pane, *args): new_pane = (pane + 1) % self.num_panes self.change_focused_tree(self.treeview[pane], self.treeview[new_pane]) @Gtk.Template.Callback() def on_treeview_key_press_event(self, view, event): if event.keyval not in (Gdk.KEY_Left, Gdk.KEY_Right): return False pane = self.treeview.index(view) target_pane = pane + 1 if event.keyval == Gdk.KEY_Right else pane - 1 if 0 <= target_pane < self.num_panes: self.change_focused_tree(view, self.treeview[target_pane]) return True def change_focused_tree( self, old_view: Gtk.TreeView, new_view: Gtk.TreeView): paths = old_view.get_selection().get_selected_rows()[1] old_view.get_selection().unselect_all() new_view.grab_focus() new_view.get_selection().unselect_all() if paths: new_view.set_cursor(paths[0]) for p in paths: new_view.get_selection().select_path(p) new_view.emit("cursor-changed") @Gtk.Template.Callback() def on_treeview_row_activated(self, view, path, column): pane = self.treeview.index(view) it = self.model.get_iter(path) rows = self.model.value_paths(it) # Click a file: compare; click a directory: expand; click a missing # entry: check the next neighbouring entry pane_ordering = ((0, 1, 2), (1, 2, 0), (2, 1, 0)) for p in pane_ordering[pane]: if p < self.num_panes and rows[p] and os.path.exists(rows[p]): pane = p break if not rows[pane]: return if os.path.isfile(rows[pane]): self.run_diff_from_iter(it) elif os.path.isdir(rows[pane]): if view.row_expanded(path): view.collapse_row(path) else: view.expand_row(path, False) @Gtk.Template.Callback() def on_treeview_row_expanded(self, view, it, path): self.row_expansions.add(str(path)) for row in self.model[path].iterchildren(): if str(row.path) in self.row_expansions: view.expand_row(row.path, False) self._do_to_others(view, self.treeview, "expand_row", (path, False)) @Gtk.Template.Callback() def on_treeview_row_collapsed(self, view, me, path): self.row_expansions.discard(str(path)) self._do_to_others(view, self.treeview, "collapse_row", (path,)) @Gtk.Template.Callback() def on_treeview_focus_in_event(self, tree, event): self.focus_pane = tree self.update_action_sensitivity() tree.emit("cursor-changed") def run_diff_from_iter(self, it): rows = self.model.value_paths(it) gfiles = [ Gio.File.new_for_path(r) if os.path.isfile(r) else None for r in rows ] self.create_diff_signal.emit(gfiles, {}) def action_diff(self, *args): pane = self._get_focused_pane() if pane is None: return selected = self._get_selected_paths(pane) for row in selected: self.run_diff_from_iter(self.model.get_iter(row)) def action_mark(self, *args): pane = self._get_focused_pane() if pane is None: return selected = self._get_selected_paths(pane) if selected is None: return old_mark_it = self.marked.get_iter() if self.marked else None self.marked = ComparisonMarker.from_selection( self.treeview[pane], pane) self._update_item_state(self.marked.get_iter()) if old_mark_it: self._update_item_state(old_mark_it) def action_diff_marked(self, *args): pane = self._get_focused_pane() if pane is None: return selected = self.model.get_iter(self._get_selected_paths(pane)[0]) if selected is None: return mark_it = self.marked.get_iter() marked_path = self.model.value_paths(mark_it)[self.marked.pane] selected_path = self.model.value_paths(selected)[pane] # Maintain the pane ordering in the new comparison, regardless # of which pane is the marked one. if pane < self.marked.pane: row_paths = [selected_path, marked_path] else: row_paths = [marked_path, selected_path] gfiles = [Gio.File.new_for_path(p) for p in row_paths if os.path.exists(p)] self.create_diff_signal.emit(gfiles, {}) def action_folder_collapse(self, *args): pane = self._get_focused_pane() if pane is None: return root_path = self._get_selected_paths(pane)[0] filter_model = Gtk.TreeModelFilter( child_model=self.model, virtual_root=root_path) paths_to_collapse = [] filter_model.foreach(self.append_paths_to_collapse, paths_to_collapse) paths_to_collapse.insert(0, root_path) for path in reversed(paths_to_collapse): self.treeview[pane].collapse_row(path) def append_paths_to_collapse( self, filter_model, filter_path, filter_iter, paths_to_collapse): path = filter_model.convert_path_to_child_path(filter_path) paths_to_collapse.append(path) def action_folder_expand(self, *args): pane = self._get_focused_pane() if pane is None: return paths = self._get_selected_paths(pane) for path in paths: self.treeview[pane].expand_row(path, True) def action_copy_left(self, *args): self.copy_selected(-1) def action_copy_right(self, *args): self.copy_selected(1) def action_swap(self, *args): self.folders.reverse() self.refresh() def action_delete(self, *args): self.delete_selected() def action_open_external(self, *args): pane = self._get_focused_pane() if pane is None: return files = [ self.model.value_path(self.model.get_iter(p), pane) for p in self._get_selected_paths(pane) ] gfiles = [Gio.File.new_for_path(f) for f in files if f] open_files_external(gfiles) def action_copy_file_paths(self, *args): pane = self._get_focused_pane() if pane is None: return files = [ self.model.value_path(self.model.get_iter(p), pane) for p in self._get_selected_paths(pane) ] files = [f for f in files if f] if files: clip = Gtk.Clipboard.get_default(Gdk.Display.get_default()) clip.set_text('\n'.join(str(f) for f in files), -1) clip.store() def action_ignore_case_change(self, action, value): action.set_state(value) self.refresh() def action_filter_state_change(self, action, value): action.set_state(value) active_filters = [ a for a in self.state_actions if self.get_action_state(self.state_actions[a][1]) ] if set(active_filters) == set(self.state_filters): return state_strs = [self.state_actions[s][0] for s in active_filters] self.state_filters = active_filters # TODO: Updating the property won't have any effect on its own self.props.status_filters = state_strs self.refresh() def _update_name_filter(self, action, state): self._action_name_filter_map[action].active = state.get_boolean() action.set_state(state) self.refresh() # # Selection # def _get_selected_paths(self, pane): assert pane is not None return self.treeview[pane].get_selection().get_selected_rows()[1] # # Filtering # def _filter_on_state(self, roots, fileslist): """Get state of 'files' for filtering purposes. Returns STATE_NORMAL, STATE_NOCHANGE, STATE_NEW or STATE_MODIFIED roots - array of root directories fileslist - array of filename tuples of length len(roots) """ ret = [] regexes = [f.byte_filter for f in self.text_filters if f.active] for files in fileslist: curfiles = [os.path.join(r, f) for r, f in zip(roots, files)] is_present = [os.path.exists(f) for f in curfiles] if all(is_present): comparison_result = self.file_compare(curfiles, regexes) if comparison_result in (Same, DodgySame): states = {tree.STATE_NORMAL} elif comparison_result == SameFiltered: states = {tree.STATE_NOCHANGE} else: states = {tree.STATE_MODIFIED} elif is_present.count(True) > 1: # In a three-way comparison, we can have files in e.g., pane # 1 and 2 be different to each other, and there be no file in # pane 3. This row should be considered both modified (1 -> 2) # and new (2 -> 3). curfiles = [ f for f, exists in zip(curfiles, is_present) if exists ] comparison_result = self.file_compare(curfiles, regexes) if comparison_result in (Same, DodgySame, SameFiltered): states = {tree.STATE_NEW} else: states = {tree.STATE_NEW, tree.STATE_MODIFIED} else: states = {tree.STATE_NEW} # Always retain NORMAL folders for comparison; we remove these # later if they have no children. all_folders = all(os.path.isdir(f) for f in curfiles) states_match_filters = bool(states & set(self.state_filters)) if states_match_filters or all_folders: ret.append(files) return ret def _update_item_state(self, it): """Update the state of a tree row All changes and updates to tree rows should happen here; structural changes happen elsewhere, but they only delete rows or add new rows with path information. This function is the only place where row details are changed. """ files = self.model.value_paths(it) regexes = [f.byte_filter for f in self.text_filters if f.active] def none_stat(f): try: return os.stat(f) except OSError: return None stats = [none_stat(f) for f in files[:self.num_panes]] sizes = [s.st_size if s else 0 for s in stats] perms = [s.st_mode if s else 0 for s in stats] times = [s.st_mtime if s else 0 for s in stats] def none_lstat(f): try: return os.lstat(f) except OSError: return None lstats = [none_lstat(f) for f in files[:self.num_panes]] symlinks = { i for i, s in enumerate(lstats) if s and stat.S_ISLNK(s.st_mode) } def format_name_override(f): source = GLib.markup_escape_text(os.path.basename(f)) target = GLib.markup_escape_text(os.readlink(f)) return "{} ⟶ {}".format(source, target) name_overrides = [ format_name_override(f) if i in symlinks else None for i, f in enumerate(files) ] existing_times = [s.st_mtime for s in stats if s] newest_time = max(existing_times) if existing_times else 0 if existing_times.count(newest_time) == len(existing_times): # If all actually-present files have the same mtime, don't # pretend that any are "newer", and do the same if e.g., # there's only one file. newest = set() else: newest = {i for i, t in enumerate(times) if t == newest_time} if all(stats): all_same = self.file_compare(files, regexes) all_present_same = all_same else: lof = [f for f, time in zip(files, times) if time] all_same = Different all_present_same = self.file_compare(lof, regexes) # TODO: Differentiate the DodgySame case if all_same == Same or all_same == DodgySame: state = tree.STATE_NORMAL elif all_same == SameFiltered: state = tree.STATE_NOCHANGE # TODO: Differentiate the SameFiltered and DodgySame cases elif all_present_same in (Same, SameFiltered, DodgySame): state = tree.STATE_NEW elif all_same == FileError or all_present_same == FileError: state = tree.STATE_ERROR # Different and DodgyDifferent else: state = tree.STATE_MODIFIED different = state not in {tree.STATE_NORMAL, tree.STATE_NOCHANGE} isdir = [os.path.isdir(files[j]) for j in range(self.model.ntree)] for j in range(self.model.ntree): if stats[j]: self.model.set_path_state( it, j, state, isdir[j], display_text=name_overrides[j]) if self.marked and self.marked.matches_iter(j, it): emblem = EMBLEM_SELECTED else: emblem = EMBLEM_NEW if j in newest else None self.model.unsafe_set(it, j, { COL_EMBLEM: emblem, COL_TIME: times[j], COL_PERMS: perms[j] }) if j in symlinks: self.model.unsafe_set(it, j, { tree.COL_ICON: "symbolic-link-symbolic", }) # Size is handled independently, because unsafe_set # can't correctly box GObject.TYPE_INT64. self.model.set( it, self.model.column_index(COL_SIZE, j), sizes[j]) else: self.model.set_path_state( it, j, tree.STATE_NONEXIST, any(isdir)) # Set sentinel values for time, size and perms # TODO: change sentinels to float('nan'), pending: # https://gitlab.gnome.org/GNOME/glib/issues/183 self.model.unsafe_set(it, j, { COL_TIME: MISSING_TIMESTAMP, COL_SIZE: -1, COL_PERMS: -1 }) return different def set_num_panes(self, num_panes): if num_panes == self.num_panes or num_panes not in (1, 2, 3): return self.model = DirDiffTreeStore(num_panes) self.model.connect("row-deleted", self.on_treemodel_row_deleted) for treeview in self.treeview: treeview.set_model(self.model) for widget in ( self.vbox[:num_panes] + self.pane_actionbar[:num_panes] + self.chunkmap[:num_panes] + self.linkmap[:num_panes - 1] + self.dummy_toolbar_linkmap[:num_panes - 1]): widget.show() for widget in ( self.vbox[num_panes:] + self.pane_actionbar[num_panes:] + self.chunkmap[num_panes:] + self.linkmap[num_panes - 1:] + self.dummy_toolbar_linkmap[num_panes - 1:]): widget.hide() self.num_panes = num_panes def refresh(self): self.set_locations() def recompute_label(self): root = self.model.get_iter_first() filenames = self.model.value_paths(root) filenames = [f or _('No folder') for f in filenames] if self.custom_labels: shortnames = [ custom or filename for custom, filename in zip(self.custom_labels, filenames) ] tooltip_names = shortnames else: shortnames = misc.shorten_names(*filenames) tooltip_names = filenames self.label_text = " : ".join(shortnames) self.tooltip_text = "\n".join(( _("Folder comparison:"), *tooltip_names, )) self.label_changed.emit(self.label_text, self.tooltip_text) def set_labels(self, labels): labels = labels[:self.num_panes] extra = self.num_panes - len(labels) if extra: labels.extend([""] * extra) self.custom_labels = labels self.recompute_label() def on_file_changed(self, changed_filename): """When a file has changed, try to find it in our tree and update its status if necessary """ model = self.model changed_paths = [] # search each panes tree for changed_filename for pane in range(self.num_panes): it = model.get_iter_first() current = model.value_path(it, pane).split(os.sep) changed = changed_filename.split(os.sep) # early exit. does filename begin with root? try: if changed[:len(current)] != current: continue except IndexError: continue changed = changed[len(current):] # search the tree one path part at a time for part in changed: child = model.iter_children(it) while child: child_path = model.value_path(child, pane) # Found the changed path if child_path and part == os.path.basename(child_path): it = child break child = self.model.iter_next(child) if not it: break # save if found and unique if it: path = model.get_path(it) if path not in changed_paths: changed_paths.append(path) # do the update for path in changed_paths: self._update_item_state(model.get_iter(path)) self.force_cursor_recalculate = True @Gtk.Template.Callback() def on_linkmap_scroll_event(self, linkmap, event): self.next_diff(event.direction) def next_diff(self, direction): if self.focus_pane: pane = self.treeview.index(self.focus_pane) else: pane = 0 if direction == Gdk.ScrollDirection.UP: path = self.prev_path else: path = self.next_path if path: self.treeview[pane].expand_to_path(path) self.treeview[pane].set_cursor(path) else: self.error_bell() def action_previous_change(self, *args): self.next_diff(Gdk.ScrollDirection.UP) def action_next_change(self, *args): self.next_diff(Gdk.ScrollDirection.DOWN) def action_refresh(self, *args): self.refresh() def on_delete_event(self): meld_settings = get_meld_settings() for h in self.settings_handlers: meld_settings.disconnect(h) self.close_signal.emit(0) return Gtk.ResponseType.OK def action_find(self, *args): self.focus_pane.emit("start-interactive-search") def auto_compare(self): modified_states = (tree.STATE_MODIFIED, tree.STATE_CONFLICT) for it in self.model.state_rows(modified_states): self.run_diff_from_iter(it) DirDiff.set_css_name('meld-folder-diff')
77,169
Python
.py
1,703
33.394598
84
0.58287
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,828
preferences.py
GNOME_meld/meld/preferences.py
# Copyright (C) 2002-2009 Stephen Kennedy <stevek@gnome.org> # Copyright (C) 2010-2013 Kai Willadsen <kai.willadsen@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or (at # your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from gi.repository import Gio, GLib, GObject, Gtk, GtkSource from meld.conf import _ from meld.filters import FilterEntry from meld.settings import settings from meld.ui.listwidget import EditableListWidget @Gtk.Template(resource_path='/org/gnome/meld/ui/filter-list.ui') class FilterList(Gtk.Box, EditableListWidget): __gtype_name__ = "FilterList" treeview = Gtk.Template.Child() remove = Gtk.Template.Child() move_up = Gtk.Template.Child() move_down = Gtk.Template.Child() pattern_column = Gtk.Template.Child() validity_renderer = Gtk.Template.Child() default_entry = [_("label"), False, _("pattern"), True] filter_type = GObject.Property( type=int, flags=( GObject.ParamFlags.READABLE | GObject.ParamFlags.WRITABLE | GObject.ParamFlags.CONSTRUCT_ONLY ), ) settings_key = GObject.Property( type=str, flags=( GObject.ParamFlags.READABLE | GObject.ParamFlags.WRITABLE | GObject.ParamFlags.CONSTRUCT_ONLY ), ) def __init__(self, **kwargs): super().__init__(**kwargs) self.model = self.treeview.get_model() self.pattern_column.set_cell_data_func( self.validity_renderer, self.valid_icon_celldata) for filter_params in settings.get_value(self.settings_key): filt = FilterEntry.new_from_gsetting( filter_params, self.filter_type) if filt is None: continue valid = filt.filter is not None self.model.append( [filt.label, filt.active, filt.filter_string, valid]) for signal in ('row-changed', 'row-deleted', 'row-inserted', 'rows-reordered'): self.model.connect(signal, self._update_filter_string) self.setup_sensitivity_handling() def valid_icon_celldata(self, col, cell, model, it, user_data=None): is_valid = model.get_value(it, 3) icon_name = "dialog-warning-symbolic" if not is_valid else None cell.set_property("icon-name", icon_name) @Gtk.Template.Callback() def on_add_clicked(self, button): self.add_entry() @Gtk.Template.Callback() def on_remove_clicked(self, button): self.remove_selected_entry() @Gtk.Template.Callback() def on_move_up_clicked(self, button): self.move_up_selected_entry() @Gtk.Template.Callback() def on_move_down_clicked(self, button): self.move_down_selected_entry() @Gtk.Template.Callback() def on_name_edited(self, ren, path, text): self.model[path][0] = text @Gtk.Template.Callback() def on_cellrenderertoggle_toggled(self, ren, path): self.model[path][1] = not ren.get_active() @Gtk.Template.Callback() def on_pattern_edited(self, ren, path, text): valid = FilterEntry.check_filter(text, self.filter_type) self.model[path][2] = text self.model[path][3] = valid def _update_filter_string(self, *args): value = [(row[0], row[1], row[2]) for row in self.model] settings.set_value(self.settings_key, GLib.Variant('a(sbs)', value)) @Gtk.Template(resource_path='/org/gnome/meld/ui/column-list.ui') class ColumnList(Gtk.Box, EditableListWidget): __gtype_name__ = "ColumnList" treeview = Gtk.Template.Child() remove = Gtk.Template.Child() move_up = Gtk.Template.Child() move_down = Gtk.Template.Child() default_entry = [_("label"), False, _("pattern"), True] available_columns = { "size": _("Size"), "modification time": _("Modification time"), "iso-time": _("Modification time (ISO)"), "permissions": _("Permissions"), } settings_key = GObject.Property( type=str, flags=( GObject.ParamFlags.READABLE | GObject.ParamFlags.WRITABLE | GObject.ParamFlags.CONSTRUCT_ONLY ), ) def __init__(self, **kwargs): super().__init__(**kwargs) self.model = self.treeview.get_model() # Unwrap the variant prefs_columns = [ (k, v) for k, v in settings.get_value(self.settings_key) ] column_vis = {} column_order = {} for sort_key, (column_name, visibility) in enumerate(prefs_columns): column_vis[column_name] = bool(int(visibility)) column_order[column_name] = sort_key columns = [ (column_vis.get(name, False), name, label) for name, label in self.available_columns.items() ] columns = sorted( columns, key=lambda c: column_order.get(c[1], len(self.available_columns)), ) for visibility, name, label in columns: self.model.append([visibility, name, label]) for signal in ('row-changed', 'row-deleted', 'row-inserted', 'rows-reordered'): self.model.connect(signal, self._update_columns) self.setup_sensitivity_handling() @Gtk.Template.Callback() def on_move_up_clicked(self, button): self.move_up_selected_entry() @Gtk.Template.Callback() def on_move_down_clicked(self, button): self.move_down_selected_entry() @Gtk.Template.Callback() def on_cellrenderertoggle_toggled(self, ren, path): self.model[path][0] = not ren.get_active() def _update_columns(self, *args): value = [(c[1].lower(), c[0]) for c in self.model] settings.set_value(self.settings_key, GLib.Variant('a(sb)', value)) class GSettingsComboBox(Gtk.ComboBox): def __init__(self): super().__init__() self.connect('notify::gsettings-value', self._setting_changed) self.connect('notify::active', self._active_changed) def bind_to(self, key): settings.bind( key, self, 'gsettings-value', Gio.SettingsBindFlags.DEFAULT) def _setting_changed(self, obj, val): column = self.get_property('gsettings-column') value = self.get_property('gsettings-value') for row in self.get_model(): if value == row[column]: idx = row.path[0] break else: idx = 0 if self.get_property('active') != idx: self.set_property('active', idx) def _active_changed(self, obj, val): active_iter = self.get_active_iter() if active_iter is None: return column = self.get_property('gsettings-column') value = self.get_model()[active_iter][column] self.set_property('gsettings-value', value) class GSettingsIntComboBox(GSettingsComboBox): __gtype_name__ = "GSettingsIntComboBox" gsettings_column = GObject.Property(type=int, default=0) gsettings_value = GObject.Property(type=int) class GSettingsBoolComboBox(GSettingsComboBox): __gtype_name__ = "GSettingsBoolComboBox" gsettings_column = GObject.Property(type=int, default=0) gsettings_value = GObject.Property(type=bool, default=False) class GSettingsStringComboBox(GSettingsComboBox): __gtype_name__ = "GSettingsStringComboBox" gsettings_column = GObject.Property(type=int, default=0) gsettings_value = GObject.Property(type=str, default="") @Gtk.Template(resource_path='/org/gnome/meld/ui/preferences.ui') class PreferencesDialog(Gtk.Dialog): __gtype_name__ = "PreferencesDialog" checkbutton_break_commit_lines = Gtk.Template.Child() checkbutton_default_font = Gtk.Template.Child() checkbutton_folder_filter_text = Gtk.Template.Child() checkbutton_highlight_current_line = Gtk.Template.Child() checkbutton_ignore_blank_lines = Gtk.Template.Child() checkbutton_ignore_symlinks = Gtk.Template.Child() checkbutton_prefer_dark_theme = Gtk.Template.Child() checkbutton_shallow_compare = Gtk.Template.Child() checkbutton_show_commit_margin = Gtk.Template.Child() checkbutton_show_line_numbers = Gtk.Template.Child() checkbutton_show_overview_map = Gtk.Template.Child() checkbutton_show_whitespace = Gtk.Template.Child() checkbutton_spaces_instead_of_tabs = Gtk.Template.Child() checkbutton_use_syntax_highlighting = Gtk.Template.Child() checkbutton_wrap_text = Gtk.Template.Child() checkbutton_wrap_word = Gtk.Template.Child() column_list_vbox = Gtk.Template.Child() combo_file_order = Gtk.Template.Child() combo_merge_order = Gtk.Template.Child() combo_overview_map = Gtk.Template.Child() combo_timestamp = Gtk.Template.Child() combobox_style_scheme = Gtk.Template.Child() custom_edit_command_entry = Gtk.Template.Child() file_filters_vbox = Gtk.Template.Child() fontpicker = Gtk.Template.Child() spinbutton_commit_margin = Gtk.Template.Child() spinbutton_tabsize = Gtk.Template.Child() syntaxschemestore = Gtk.Template.Child() system_editor_checkbutton = Gtk.Template.Child() text_filters_vbox = Gtk.Template.Child() def __init__(self, **kwargs): super().__init__(**kwargs) bindings = [ ('use-system-font', self.checkbutton_default_font, 'active'), ('custom-font', self.fontpicker, 'font'), ('indent-width', self.spinbutton_tabsize, 'value'), ('insert-spaces-instead-of-tabs', self.checkbutton_spaces_instead_of_tabs, 'active'), # noqa: E501 ('highlight-current-line', self.checkbutton_highlight_current_line, 'active'), # noqa: E501 ('show-line-numbers', self.checkbutton_show_line_numbers, 'active'), # noqa: E501 ('prefer-dark-theme', self.checkbutton_prefer_dark_theme, 'active'), # noqa: E501 ('highlight-syntax', self.checkbutton_use_syntax_highlighting, 'active'), # noqa: E501 ('enable-space-drawer', self.checkbutton_show_whitespace, 'active'), # noqa: E501 ('use-system-editor', self.system_editor_checkbutton, 'active'), ('custom-editor-command', self.custom_edit_command_entry, 'text'), ('folder-shallow-comparison', self.checkbutton_shallow_compare, 'active'), # noqa: E501 ('folder-filter-text', self.checkbutton_folder_filter_text, 'active'), # noqa: E501 ('folder-ignore-symlinks', self.checkbutton_ignore_symlinks, 'active'), # noqa: E501 ('vc-show-commit-margin', self.checkbutton_show_commit_margin, 'active'), # noqa: E501 ('show-overview-map', self.checkbutton_show_overview_map, 'active'), # noqa: E501 ('vc-commit-margin', self.spinbutton_commit_margin, 'value'), ('vc-break-commit-message', self.checkbutton_break_commit_lines, 'active'), # noqa: E501 ('ignore-blank-lines', self.checkbutton_ignore_blank_lines, 'active'), # noqa: E501 # Sensitivity bindings must come after value bindings, or the key # writability in gsettings overrides manual sensitivity setting. ('vc-show-commit-margin', self.spinbutton_commit_margin, 'sensitive'), # noqa: E501 ('vc-show-commit-margin', self.checkbutton_break_commit_lines, 'sensitive'), # noqa: E501 ] for key, obj, attribute in bindings: settings.bind(key, obj, attribute, Gio.SettingsBindFlags.DEFAULT) invert_bindings = [ ('use-system-editor', self.custom_edit_command_entry, 'sensitive'), ('use-system-font', self.fontpicker, 'sensitive'), ('folder-shallow-comparison', self.checkbutton_folder_filter_text, 'sensitive'), # noqa: E501 ] for key, obj, attribute in invert_bindings: settings.bind( key, obj, attribute, Gio.SettingsBindFlags.DEFAULT | Gio.SettingsBindFlags.INVERT_BOOLEAN) self.checkbutton_wrap_text.bind_property( 'active', self.checkbutton_wrap_word, 'sensitive', GObject.BindingFlags.DEFAULT) wrap_mode = settings.get_enum('wrap-mode') self.checkbutton_wrap_text.set_active(wrap_mode != Gtk.WrapMode.NONE) self.checkbutton_wrap_word.set_active(wrap_mode == Gtk.WrapMode.WORD) filefilter = FilterList( filter_type=FilterEntry.SHELL, settings_key="filename-filters", ) self.file_filters_vbox.pack_start(filefilter, True, True, 0) textfilter = FilterList( filter_type=FilterEntry.REGEX, settings_key="text-filters", ) self.text_filters_vbox.pack_start(textfilter, True, True, 0) columnlist = ColumnList(settings_key="folder-columns") self.column_list_vbox.pack_start(columnlist, True, True, 0) self.combo_timestamp.bind_to('folder-time-resolution') self.combo_file_order.bind_to('vc-left-is-local') self.combo_overview_map.bind_to('overview-map-style') self.combo_merge_order.bind_to('vc-merge-file-order') # Fill color schemes manager = GtkSource.StyleSchemeManager.get_default() for scheme_id in manager.get_scheme_ids(): scheme = manager.get_scheme(scheme_id) self.syntaxschemestore.append([scheme_id, scheme.get_name()]) self.combobox_style_scheme.bind_to('style-scheme') self.show() @Gtk.Template.Callback() def on_checkbutton_wrap_text_toggled(self, button): if not self.checkbutton_wrap_text.get_active(): wrap_mode = Gtk.WrapMode.NONE elif self.checkbutton_wrap_word.get_active(): wrap_mode = Gtk.WrapMode.WORD else: wrap_mode = Gtk.WrapMode.CHAR settings.set_enum('wrap-mode', wrap_mode) @Gtk.Template.Callback() def on_response(self, dialog, response_id): self.destroy()
14,554
Python
.py
303
39.656766
111
0.652886
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,829
melddoc.py
GNOME_meld/meld/melddoc.py
# Copyright (C) 2002-2006 Stephen Kennedy <stevek@gnome.org> # Copyright (C) 2011-2021 Kai Willadsen <kai.willadsen@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or (at # your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import enum import logging from typing import Sequence from gi.repository import Gio, GObject, Gtk from meld.conf import _ from meld.recent import RecentType from meld.task import FifoScheduler log = logging.getLogger(__name__) class ComparisonState(enum.IntEnum): # TODO: Consider use-cases for states in gedit-enum-types.c Normal = 0 Closing = 1 SavingError = 2 class LabeledObjectMixin(GObject.GObject): label_text = _("untitled") tooltip_text = None @GObject.Signal def label_changed(self, label_text: str, tooltip_text: str) -> None: ... class MeldDoc(LabeledObjectMixin, GObject.GObject): """Base class for documents in the meld application. """ @GObject.Signal(name='close') def close_signal(self, exit_code: int) -> None: ... @GObject.Signal(name='create-diff') def create_diff_signal( self, gfiles: object, options: object) -> None: ... @GObject.Signal('file-changed') def file_changed_signal(self, path: str) -> None: ... @GObject.Signal def tab_state_changed(self, old_state: int, new_state: int) -> None: ... @GObject.Signal( name='move-diff', flags=GObject.SignalFlags.RUN_FIRST | GObject.SignalFlags.ACTION, ) def move_diff(self, direction: int) -> None: self.next_diff(direction) def __init__(self) -> None: super().__init__() self.scheduler = FifoScheduler() self.num_panes = 0 self.view_action_group = Gio.SimpleActionGroup() self._state = ComparisonState.Normal @property def state(self) -> ComparisonState: return self._state @state.setter def state(self, value: ComparisonState) -> None: if value == self._state: return self.tab_state_changed.emit(self._state, value) self._state = value def get_comparison(self) -> RecentType: """Get the comparison type and URI(s) being compared""" pass def action_stop(self, *args) -> None: if self.scheduler.tasks_pending(): self.scheduler.remove_task(self.scheduler.get_current_task()) def on_file_changed(self, filename: str): pass def set_labels(self, lst: Sequence[str]) -> None: pass def get_action_state(self, action_name: str): action = self.view_action_group.lookup_action(action_name) if not action: log.error(f'No action {action_name!r} found') return return action.get_state().unpack() def set_action_state(self, action_name: str, state) -> None: # TODO: Try to do GLib.Variant things here instead of in callers action = self.view_action_group.lookup_action(action_name) if not action: log.error(f'No action {action_name!r} found') return action.set_state(state) def set_action_enabled(self, action_name: str, enabled: bool) -> None: action = self.view_action_group.lookup_action(action_name) if not action: log.error(f'No action {action_name!r} found') return action.set_enabled(enabled) def on_container_switch_in_event(self, window): """Called when the container app switches to this tab""" window.insert_action_group( 'view', getattr(self, 'view_action_group', None)) if hasattr(self, "get_filter_visibility"): text, folder, vc = self.get_filter_visibility() else: text, folder, vc = False, False, False if hasattr(self, "get_conflict_visibility"): show_conflict_actions = self.get_conflict_visibility() else: show_conflict_actions = False window.text_filter_button.set_visible(text) window.folder_filter_button.set_visible(folder) window.vc_filter_button.set_visible(vc) window.next_conflict_button.set_visible(show_conflict_actions) window.previous_conflict_button.set_visible(show_conflict_actions) if hasattr(self, "focus_pane") and self.focus_pane: self.scheduler.add_task(self.focus_pane.grab_focus) def on_container_switch_out_event(self, window): """Called when the container app switches away from this tab""" window.insert_action_group('view', None) # FIXME: Here and in subclasses, on_delete_event are not real GTK+ # event handlers, and should be renamed. def on_delete_event(self) -> Gtk.ResponseType: """Called when the docs container is about to close. A doc normally returns Gtk.ResponseType.OK, but may instead return Gtk.ResponseType.CANCEL to request that the container not delete it. """ return Gtk.ResponseType.OK
5,548
Python
.py
130
35.692308
76
0.67026
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,830
misc.py
GNOME_meld/meld/misc.py
# Copyright (C) 2002-2006 Stephen Kennedy <stevek@gnome.org> # Copyright (C) 2009 Vincent Legoll <vincent.legoll@gmail.com> # Copyright (C) 2012-2013 Kai Willadsen <kai.willadsen@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or (at # your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """Module of commonly used helper classes and functions """ import collections import errno import functools import os import shutil import subprocess from pathlib import PurePath from typing import ( TYPE_CHECKING, AnyStr, Callable, Generator, List, Optional, Pattern, Sequence, Tuple, Union, ) from gi.repository import GLib, Gtk from meld.conf import _ if TYPE_CHECKING: from meld.vcview import ConsoleStream if os.name != "nt": from select import select else: import time def select(rlist, wlist, xlist, timeout): time.sleep(timeout) return rlist, wlist, xlist def with_focused_pane(function): @functools.wraps(function) def wrap_function(*args, **kwargs): pane = args[0]._get_focused_pane() if pane == -1: return return function(args[0], pane, *args[1:], **kwargs) return wrap_function def get_modal_parent(widget: Optional[Gtk.Widget] = None) -> Gtk.Window: parent: Gtk.Window if not widget: parent = Gtk.Application.get_default().get_active_window() elif not isinstance(widget, Gtk.Window): parent = widget.get_toplevel() else: parent = widget return parent def error_dialog(primary: str, secondary: str) -> Gtk.ResponseType: """A common error dialog handler for Meld This should only ever be used as a last resort, and for errors that a user is unlikely to encounter. If you're tempted to use this, think twice. Primary must be plain text. Secondary must be valid markup. """ return modal_dialog( primary, secondary, Gtk.ButtonsType.CLOSE, parent=None, messagetype=Gtk.MessageType.ERROR) def modal_dialog( primary: str, secondary: str, buttons: Union[Gtk.ButtonsType, Sequence[Tuple[str, int, Optional[str]]]], *, parent: Optional[Gtk.Window] = None, messagetype: Gtk.MessageType = Gtk.MessageType.WARNING, ) -> Gtk.ResponseType: """A common message dialog handler for Meld This should only ever be used for interactions that must be resolved before the application flow can continue. Primary must be plain text. Secondary must be valid markup. """ custom_buttons: Sequence[Tuple[str, int, Optional[str]]] = [] if not isinstance(buttons, Gtk.ButtonsType): custom_buttons, buttons = buttons, Gtk.ButtonsType.NONE dialog = Gtk.MessageDialog( transient_for=get_modal_parent(parent), modal=True, destroy_with_parent=True, message_type=messagetype, buttons=buttons, text=primary, ) dialog.format_secondary_markup(secondary) for label, response_id, style_class in custom_buttons: button = dialog.add_button(label, response_id) if style_class: button.get_style_context().add_class(style_class) response = dialog.run() dialog.destroy() return response def user_critical( primary: str, message: str) -> Callable[[Callable], Callable]: """Decorator for when the user must be told about failures The use case here is for e.g., saving a file, where even if we don't handle errors, the user *still* needs to know that something failed. This should be extremely sparingly used, but anything where the user might not otherwise see a problem and data loss is a potential side effect should be considered a candidate. """ def wrap(function): @functools.wraps(function) def wrap_function(locked, *args, **kwargs): try: return function(locked, *args, **kwargs) except Exception: error_dialog( primary=primary, secondary=_( "{}\n\n" "Meld encountered a critical error while running:\n" "<tt>{}</tt>").format( message, GLib.markup_escape_text(str(function)) ), ) raise return wrap_function return wrap def all_same(iterable: Sequence) -> bool: """Return True if all elements of the list are equal""" sample, has_no_sample = None, True for item in iterable or (): if has_no_sample: sample, has_no_sample = item, False elif sample != item: return False return True def shorten_names(*names: str) -> List[str]: """Remove common parts of a list of paths For example, `('/tmp/foo1', '/tmp/foo2')` would be summarised as `('foo1', 'foo2')`. Paths that share a basename are distinguished by prepending an indicator, e.g., `('/a/b/c', '/a/d/c')` would be summarised to `['[b] c', '[d] c']`. """ paths = [PurePath(n) for n in names] # Identify the longest common path among the list of path common = set(paths[0].parents) common = common.intersection(*(p.parents for p in paths)) if not common: return list(names) common_parent = sorted(common, key=lambda p: -len(p.parts))[0] paths = [p.relative_to(common_parent) for p in paths] basenames = [p.name for p in paths] if all_same(basenames): def firstpart(path: PurePath) -> str: if len(path.parts) > 1 and path.parts[0]: return "[%s] " % path.parts[0] else: return "" return [firstpart(p) + p.name for p in paths] return [name or _("[None]") for name in basenames] @functools.lru_cache def guess_if_remote_x11(): """Try to guess whether we're being X11 forwarded""" display = os.environ.get("DISPLAY") ssh_connection = os.environ.get("SSH_CONNECTION") return bool(display and ssh_connection) def get_hide_window_startupinfo(): if os.name != "nt": return None startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW return startupinfo SubprocessGenerator = Generator[Union[Tuple[int, str], None], None, None] def read_pipe_iter( command: List[str], workdir: str, errorstream: 'ConsoleStream', yield_interval: float = 0.1, ) -> SubprocessGenerator: """Read the output of a shell command iteratively. Each time 'callback_interval' seconds pass without reading any data, this function yields None. When all the data is read, the entire string is yielded. """ class Sentinel: proc: Optional[subprocess.Popen] def __init__(self) -> None: self.proc = None def __del__(self) -> None: if self.proc: errorstream.error("killing '%s'\n" % command[0]) self.proc.terminate() errorstream.error("killed (status was '%i')\n" % self.proc.wait()) def __call__(self) -> SubprocessGenerator: self.proc = subprocess.Popen( command, cwd=workdir, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, startupinfo=get_hide_window_startupinfo(), ) self.proc.stdin.close() childout, childerr = self.proc.stdout, self.proc.stderr bits: List[str] = [] while len(bits) == 0 or bits[-1] != "": state = select([childout, childerr], [], [childout, childerr], yield_interval) if len(state[0]) == 0: if len(state[2]) == 0: yield None else: raise Exception("Error reading pipe") if childout in state[0]: try: # get buffer size bits.append(childout.read(4096)) except IOError: # FIXME: ick need to fix break if childerr in state[0]: try: # how many chars? errorstream.error(childerr.read(1)) except IOError: # FIXME: ick need to fix break status = self.proc.wait() errorstream.error(childerr.read()) self.proc = None if status: errorstream.error("Exit code: %i\n" % status) yield status, "".join(bits) return Sentinel()() def copy2(src: str, dst: str) -> None: """Like shutil.copy2 but ignores chmod errors, and copies symlinks as links See [Bug 568000] Copying to NTFS fails """ if os.path.isdir(dst): dst = os.path.join(dst, os.path.basename(src)) if os.path.islink(src) and os.path.isfile(src): if os.path.lexists(dst): os.unlink(dst) os.symlink(os.readlink(src), dst) elif os.path.isfile(src): shutil.copyfile(src, dst) else: raise OSError("Not a file") try: shutil.copystat(src, dst) except OSError as e: if e.errno not in (errno.EPERM, errno.ENOTSUP): raise def copytree(src: str, dst: str) -> None: """Similar to shutil.copytree, but always copies symlinks and doesn't error out if the destination path already exists. """ # If the source tree is a symlink, duplicate the link and we're done. if os.path.islink(src): os.symlink(os.readlink(src), dst) return try: os.mkdir(dst) except OSError as e: if e.errno != errno.EEXIST: raise names = os.listdir(src) for name in names: srcname = os.path.join(src, name) dstname = os.path.join(dst, name) if os.path.islink(srcname): os.symlink(os.readlink(srcname), dstname) elif os.path.isdir(srcname): copytree(srcname, dstname) else: copy2(srcname, dstname) try: shutil.copystat(src, dst) except OSError as e: if e.errno != errno.EPERM: raise def merge_intervals( interval_list: List[Tuple[int, int]]) -> List[Tuple[int, int]]: """Merge a list of intervals Returns a list of itervals as 2-tuples with all overlapping intervals merged. interval_list must be a list of 2-tuples of integers representing the start and end of an interval. """ if len(interval_list) < 2: return interval_list interval_deque = collections.deque(sorted(interval_list)) merged_intervals = [interval_deque.popleft()] current_start, current_end = merged_intervals[-1] while interval_deque: new_start, new_end = interval_deque.popleft() if current_end >= new_end: continue if current_end < new_start: # Intervals do not overlap; create a new one merged_intervals.append((new_start, new_end)) elif current_end < new_end: # Intervals overlap; extend the current one merged_intervals[-1] = (current_start, new_end) current_start, current_end = merged_intervals[-1] return merged_intervals def apply_text_filters( txt: AnyStr, regexes: Sequence[Pattern], apply_fn: Optional[Callable[[int, int], None]] = None ) -> AnyStr: """Apply text filters Text filters "regexes", resolved as regular expressions are applied to "txt". "txt" may be either strings or bytes, but the supplied regexes must match the type. "apply_fn" is a callable run for each filtered interval """ empty_string = b"" if isinstance(txt, bytes) else "" newline = b"\n" if isinstance(txt, bytes) else "\n" filter_ranges = [] for r in regexes: if not r: continue for match in r.finditer(txt): # If there are no groups in the match, use the whole match if not r.groups: span = match.span() if span[0] != span[1]: filter_ranges.append(span) continue # If there are groups in the regex, include all groups that # participated in the match for i in range(r.groups): span = match.span(i + 1) if span != (-1, -1) and span[0] != span[1]: filter_ranges.append(span) filter_ranges = merge_intervals(filter_ranges) if apply_fn: for (start, end) in reversed(filter_ranges): apply_fn(start, end) offset = 0 result_txts = [] for (start, end) in filter_ranges: assert txt[start:end].count(newline) == 0 result_txts.append(txt[offset:start]) offset = end result_txts.append(txt[offset:]) return empty_string.join(result_txts) def calc_syncpoint(adj: Gtk.Adjustment) -> float: """Calculate a cross-pane adjustment synchronisation point Our normal syncpoint is the middle of the screen. If the current position is within the first half screen of a document, we scale the sync point linearly back to 0.0 (top of the screen); if it's the the last half screen, we again scale linearly to 1.0. The overall effect of this is to make sure that the top and bottom parts of documents with different lengths and chunk offsets correctly scroll into view. """ current = adj.get_value() half_a_screen = adj.get_page_size() / 2 syncpoint = 0.0 # How far through the first half-screen our adjustment is top_val = adj.get_lower() first_scale = (current - top_val) / half_a_screen syncpoint += 0.5 * min(1, first_scale) # How far through the last half-screen our adjustment is bottom_val = adj.get_upper() - 1.5 * adj.get_page_size() last_scale = (current - bottom_val) / half_a_screen syncpoint += 0.5 * max(0, last_scale) return syncpoint
14,743
Python
.py
377
30.790451
79
0.62289
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,831
filediff.py
GNOME_meld/meld/filediff.py
# Copyright (C) 2002-2006 Stephen Kennedy <stevek@gnome.org> # Copyright (C) 2009-2019 Kai Willadsen <kai.willadsen@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or (at # your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import copy import functools import logging import math from enum import Enum from typing import Optional, Tuple, Type from gi.repository import Gdk, Gio, GLib, GObject, Gtk, GtkSource # TODO: Don't from-import whole modules from meld import misc from meld.conf import _ from meld.const import ( NEWLINES, TEXT_FILTER_ACTION_FORMAT, ActionMode, ChunkAction, FileComparisonMode, FileLoadError, ) from meld.externalhelpers import open_files_external from meld.gutterrendererchunk import GutterRendererChunkLines from meld.iohelpers import find_shared_parent_path, prompt_save_filename from meld.matchers.diffutil import Differ, merged_chunk_order from meld.matchers.helpers import CachedSequenceMatcher from meld.matchers.merge import AutoMergeDiffer, Merger from meld.meldbuffer import ( BufferDeletionAction, BufferInsertionAction, BufferLines, MeldBufferState, ) from meld.melddoc import ComparisonState, MeldDoc from meld.menuhelpers import replace_menu_section from meld.misc import user_critical, with_focused_pane from meld.patchdialog import PatchDialog from meld.recent import RecentType from meld.settings import bind_settings, get_meld_settings from meld.sourceview import ( LanguageManager, TextviewLineAnimationType, get_custom_encoding_candidates, ) from meld.ui.findbar import FindBar from meld.ui.util import ( make_multiobject_property_action, map_widgets_into_lists, ) from meld.undo import UndoSequence log = logging.getLogger(__name__) def with_scroll_lock(lock_attr): """Decorator for locking a callback based on an instance attribute This is used when scrolling panes. Since a scroll event in one pane causes us to set the scroll position in other panes, we need to stop these other panes re-scrolling the initial one. Unlike a threading-style lock, this decorator discards any calls that occur while the lock is held, rather than queuing them. :param lock_attr: The instance attribute used to lock access """ def wrap(function): @functools.wraps(function) def wrap_function(locked, *args, **kwargs): force_locked = locked.props.lock_scrolling if getattr(locked, lock_attr, False) or force_locked: return try: setattr(locked, lock_attr, True) return function(locked, *args, **kwargs) finally: setattr(locked, lock_attr, False) return wrap_function return wrap MASK_SHIFT, MASK_CTRL = 1, 2 PANE_LEFT, PANE_RIGHT = -1, +1 LOAD_PROGRESS_MARK = "meld-load-progress" #: Line length at which we'll cancel loads because of potential hangs LINE_LENGTH_LIMIT = 8 * 1024 class CursorDetails: __slots__ = ( "pane", "pos", "line", "chunk", "prev", "next", "prev_conflict", "next_conflict", ) def __init__(self): for var in self.__slots__: setattr(self, var, None) @Gtk.Template(resource_path='/org/gnome/meld/ui/filediff.ui') class FileDiff(Gtk.Box, MeldDoc): """Two or three way comparison of text files""" __gtype_name__ = "FileDiff" close_signal = MeldDoc.close_signal create_diff_signal = MeldDoc.create_diff_signal file_changed_signal = MeldDoc.file_changed_signal label_changed = MeldDoc.label_changed move_diff = MeldDoc.move_diff tab_state_changed = MeldDoc.tab_state_changed __gsettings_bindings_view__ = ( ('ignore-blank-lines', 'ignore-blank-lines'), ('show-overview-map', 'show-overview-map'), ('overview-map-style', 'overview-map-style'), ) ignore_blank_lines = GObject.Property( type=bool, nick="Ignore blank lines", blurb="Whether to ignore blank lines when comparing file contents", default=False, ) show_overview_map = GObject.Property(type=bool, default=True) overview_map_style = GObject.Property(type=str, default='chunkmap') actiongutter0 = Gtk.Template.Child() actiongutter1 = Gtk.Template.Child() actiongutter2 = Gtk.Template.Child() actiongutter3 = Gtk.Template.Child() chunkmap0 = Gtk.Template.Child() chunkmap1 = Gtk.Template.Child() chunkmap2 = Gtk.Template.Child() chunkmap_hbox = Gtk.Template.Child() dummy_toolbar_actiongutter0 = Gtk.Template.Child() dummy_toolbar_actiongutter1 = Gtk.Template.Child() dummy_toolbar_actiongutter2 = Gtk.Template.Child() dummy_toolbar_actiongutter3 = Gtk.Template.Child() dummy_toolbar_linkmap0 = Gtk.Template.Child() dummy_toolbar_linkmap1 = Gtk.Template.Child() file_open_button0 = Gtk.Template.Child() file_open_button1 = Gtk.Template.Child() file_open_button2 = Gtk.Template.Child() file_save_button0 = Gtk.Template.Child() file_save_button1 = Gtk.Template.Child() file_save_button2 = Gtk.Template.Child() file_toolbar0 = Gtk.Template.Child() file_toolbar1 = Gtk.Template.Child() file_toolbar2 = Gtk.Template.Child() filelabel0 = Gtk.Template.Child() filelabel1 = Gtk.Template.Child() filelabel2 = Gtk.Template.Child() grid = Gtk.Template.Child() msgarea_mgr0 = Gtk.Template.Child() msgarea_mgr1 = Gtk.Template.Child() msgarea_mgr2 = Gtk.Template.Child() readonlytoggle0 = Gtk.Template.Child() readonlytoggle1 = Gtk.Template.Child() readonlytoggle2 = Gtk.Template.Child() scrolledwindow0 = Gtk.Template.Child() scrolledwindow1 = Gtk.Template.Child() scrolledwindow2 = Gtk.Template.Child() sourcemap_revealer = Gtk.Template.Child() sourcemap0 = Gtk.Template.Child() sourcemap1 = Gtk.Template.Child() sourcemap2 = Gtk.Template.Child() sourcemap_hbox = Gtk.Template.Child() statusbar0 = Gtk.Template.Child() statusbar1 = Gtk.Template.Child() statusbar2 = Gtk.Template.Child() statusbar_sourcemap_revealer = Gtk.Template.Child() linkmap0 = Gtk.Template.Child() linkmap1 = Gtk.Template.Child() textview0 = Gtk.Template.Child() textview1 = Gtk.Template.Child() textview2 = Gtk.Template.Child() toolbar_sourcemap_revealer = Gtk.Template.Child() vbox0 = Gtk.Template.Child() vbox1 = Gtk.Template.Child() vbox2 = Gtk.Template.Child() differ: Type[Differ] comparison_mode: FileComparisonMode keylookup = { Gdk.KEY_Shift_L: MASK_SHIFT, Gdk.KEY_Shift_R: MASK_SHIFT, Gdk.KEY_Control_L: MASK_CTRL, Gdk.KEY_Control_R: MASK_CTRL, } # Identifiers for MsgArea messages (MSG_SAME, MSG_SLOW_HIGHLIGHT, MSG_SYNCPOINTS) = list(range(3)) # Transient messages that should be removed if any file in the # comparison gets reloaded. TRANSIENT_MESSAGES = {MSG_SAME, MSG_SLOW_HIGHLIGHT} __gsignals__ = { 'next-conflict-changed': ( GObject.SignalFlags.RUN_FIRST, None, (bool, bool)), } action_mode = GObject.Property( type=int, nick='Action mode for chunk change actions', default=ActionMode.Replace, ) lock_scrolling = GObject.Property( type=bool, nick='Lock scrolling of all panes', default=False, ) def __init__( self, num_panes, *, comparison_mode: FileComparisonMode = FileComparisonMode.Compare, ): super().__init__() # FIXME: # This unimaginable hack exists because GObject (or GTK+?) # doesn't actually correctly chain init calls, even if they're # not to GObjects. As a workaround, we *should* just be able to # put our class first, but because of Gtk.Template we can't do # that if it's a GObject, because GObject doesn't support # multiple inheritance and we need to inherit from our Widget # parent to make Template work. MeldDoc.__init__(self) bind_settings(self) widget_lists = [ "sourcemap", "file_save_button", "file_toolbar", "linkmap", "msgarea_mgr", "readonlytoggle", "scrolledwindow", "textview", "vbox", "dummy_toolbar_linkmap", "filelabel", "file_open_button", "statusbar", "actiongutter", "dummy_toolbar_actiongutter", "chunkmap", ] map_widgets_into_lists(self, widget_lists) self.comparison_mode = comparison_mode if comparison_mode == FileComparisonMode.AutoMerge: self.differ = AutoMergeDiffer else: self.differ = Differ self.warned_bad_comparison = False self._keymask = 0 self.meta = {} self.lines_removed = 0 self.focus_pane = None self.textbuffer = [v.get_buffer() for v in self.textview] self.buffer_texts = [BufferLines(b) for b in self.textbuffer] self.undosequence = UndoSequence(self.textbuffer) self.text_filters = [] meld_settings = get_meld_settings() self.settings_handlers = [ meld_settings.connect( "text-filters-changed", self.on_text_filters_changed) ] self.buffer_filtered = [ BufferLines(b, self._filter_text) for b in self.textbuffer ] for (i, w) in enumerate(self.scrolledwindow): w.get_vadjustment().connect("value-changed", self._sync_vscroll, i) w.get_hadjustment().connect("value-changed", self._sync_hscroll) self._connect_buffer_handlers() self._sync_vscroll_lock = False self._sync_hscroll_lock = False self.linediffer = self.differ() self.force_highlight = False def get_mark_line(pane, mark): return self.textbuffer[pane].get_iter_at_mark(mark).get_line() self.syncpoints = Syncpoints(num_panes, get_mark_line) self.in_nested_textview_gutter_expose = False self._cached_match = CachedSequenceMatcher(self.scheduler) # Set up property actions for statusbar toggles sourceview_prop_actions = [ 'draw-spaces-bool', 'highlight-current-line-local', 'show-line-numbers', 'wrap-mode-bool', ] prop_action_group = Gio.SimpleActionGroup() for prop in sourceview_prop_actions: action = make_multiobject_property_action(self.textview, prop) prop_action_group.add_action(action) self.insert_action_group('view-local', prop_action_group) # Set up per-view action group for top-level menu insertion self.view_action_group = Gio.SimpleActionGroup() property_actions = ( ('show-overview-map', self, 'show-overview-map'), ('lock-scrolling', self, 'lock_scrolling'), ) for action_name, obj, prop_name in property_actions: action = Gio.PropertyAction.new(action_name, obj, prop_name) self.view_action_group.add_action(action) # Manually handle GAction additions actions = ( ('add-sync-point', self.add_sync_point), ('remove-sync-point', self.remove_sync_point), ('clear-sync-point', self.clear_sync_points), ('copy', self.action_copy), ('copy-full-path', self.action_copy_full_path), ('cut', self.action_cut), ('file-previous-conflict', self.action_previous_conflict), ('file-next-conflict', self.action_next_conflict), ('file-push-left', self.action_push_change_left), ('file-push-right', self.action_push_change_right), ('file-pull-left', self.action_pull_change_left), ('file-pull-right', self.action_pull_change_right), ('file-copy-left-up', self.action_copy_change_left_up), ('file-copy-right-up', self.action_copy_change_right_up), ('file-copy-left-down', self.action_copy_change_left_down), ('file-copy-right-down', self.action_copy_change_right_down), ('file-delete', self.action_delete_change), ('find', self.action_find), ('find-next', self.action_find_next), ('find-previous', self.action_find_previous), ('find-replace', self.action_find_replace), ('format-as-patch', self.action_format_as_patch), ('go-to-line', self.action_go_to_line), ('merge-all-left', self.action_pull_all_changes_left), ('merge-all-right', self.action_pull_all_changes_right), ('merge-all', self.action_merge_all_changes), ('next-change', self.action_next_change), ('next-pane', self.action_next_pane), ('open-external', self.action_open_external), ('open-folder', self.action_open_folder), ('paste', self.action_paste), ('previous-change', self.action_previous_change), ('previous-pane', self.action_prev_pane), ('redo', self.action_redo), ('refresh', self.action_refresh), ('revert', self.action_revert), ('save', self.action_save), ('save-all', self.action_save_all), ('save-as', self.action_save_as), ('undo', self.action_undo), ('swap-2-panes', self.action_swap), ) for name, callback in actions: action = Gio.SimpleAction.new(name, None) action.connect('activate', callback) self.view_action_group.add_action(action) state_actions = ( ("text-filter", None, GLib.Variant.new_boolean(False)), ) for (name, callback, state) in state_actions: action = Gio.SimpleAction.new_stateful(name, None, state) if callback: action.connect("change-state", callback) self.view_action_group.add_action(action) builder = Gtk.Builder.new_from_resource( '/org/gnome/meld/ui/filediff-menus.ui') self.popup_menu_model = builder.get_object('filediff-context-menu') self.popup_menu = Gtk.Menu.new_from_model(self.popup_menu_model) self.popup_menu.attach_to_widget(self) builder = Gtk.Builder.new_from_resource( '/org/gnome/meld/ui/filediff-actions.ui') self.toolbar_actions = builder.get_object('view-toolbar') self.copy_action_button = builder.get_object('copy_action_button') self.create_text_filters() # Handle overview map visibility binding. Because of how we use # grid packing, we need three revealers here instead of the # more obvious one. revealers = ( self.toolbar_sourcemap_revealer, self.sourcemap_revealer, self.statusbar_sourcemap_revealer, ) for revealer in revealers: self.bind_property( 'show-overview-map', revealer, 'reveal-child', ( GObject.BindingFlags.DEFAULT | GObject.BindingFlags.SYNC_CREATE ), ) # Handle overview map style mapping manually self.connect( 'notify::overview-map-style', self.on_overview_map_style_changed) self.on_overview_map_style_changed() for buf in self.textbuffer: buf.create_mark(LOAD_PROGRESS_MARK, buf.get_start_iter(), True) buf.undo_sequence = self.undosequence buf.connect( 'notify::has-selection', self.update_text_actions_sensitivity) buf.data.file_changed_signal.connect(self.notify_file_changed) self.update_text_actions_sensitivity() self.findbar = FindBar(self.grid) self.grid.attach(self.findbar, 0, 2, 10, 1) self.set_num_panes(num_panes) self.cursor = CursorDetails() for t in self.textview: t.connect("focus-in-event", self.on_current_diff_changed) t.connect("focus-out-event", self.on_current_diff_changed) t.connect( "drag_data_received", self.on_textview_drag_data_received) for label in self.filelabel: label.connect( "drag_data_received", self.on_textview_drag_data_received ) # Bind all overwrite properties together, so that toggling # overwrite mode is per-FileDiff. for t in self.textview[1:]: t.bind_property( 'overwrite', self.textview[0], 'overwrite', GObject.BindingFlags.BIDIRECTIONAL) for gutter in self.actiongutter: self.bind_property('action_mode', gutter, 'action_mode') gutter.connect( 'chunk_action_activated', self.on_chunk_action_activated) self.linediffer.connect("diffs-changed", self.on_diffs_changed) self.undosequence.connect("checkpointed", self.on_undo_checkpointed) self.undosequence.connect("can-undo", self.on_can_undo) self.undosequence.connect("can-redo", self.on_can_redo) self.connect("next-conflict-changed", self.on_next_conflict_changed) # TODO: If UndoSequence expose can_undo and can_redo as # GProperties instead, this would be much, much nicer. self.set_action_enabled('redo', self.undosequence.can_redo()) self.set_action_enabled('undo', self.undosequence.can_undo()) for statusbar, buf in zip(self.statusbar, self.textbuffer): buf.bind_property( 'cursor-position', statusbar, 'cursor_position', GObject.BindingFlags.DEFAULT, self.bind_adapt_cursor_position, ) buf.bind_property( 'language', statusbar, 'source-language', GObject.BindingFlags.BIDIRECTIONAL) buf.data.bind_property( 'encoding', statusbar, 'source-encoding', GObject.BindingFlags.DEFAULT) def reload_with_encoding(widget, encoding, pane): buffer = self.textbuffer[pane] if not self.check_unsaved_changes([buffer]): return self.set_file(pane, buffer.data.gfile, encoding) def go_to_line(widget, line, pane): if self.cursor.pane == pane and self.cursor.line == line: return self.move_cursor(pane, line, focus=False) pane = self.statusbar.index(statusbar) statusbar.connect('encoding-changed', reload_with_encoding, pane) statusbar.connect('go-to-line', go_to_line, pane) # Prototype implementation for pane, t in enumerate(self.textview): # FIXME: set_num_panes will break this good direction = t.get_direction() # TODO: This renderer handling should all be part of # MeldSourceView, but our current diff-chunk-handling makes # this difficult. window = Gtk.TextWindowType.LEFT if direction == Gtk.TextDirection.RTL: window = Gtk.TextWindowType.RIGHT renderer = GutterRendererChunkLines( pane, pane - 1, self.linediffer) gutter = t.get_gutter(window) gutter.insert(renderer, -30) t.line_renderer = renderer self.connect("notify::ignore-blank-lines", self.refresh_comparison) def do_realize(self): Gtk.Box().do_realize(self) builder = Gtk.Builder.new_from_resource( '/org/gnome/meld/ui/filediff-menus.ui') filter_menu = builder.get_object('file-copy-actions-menu') self.copy_action_button.set_popover( Gtk.Popover.new_from_model(self.copy_action_button, filter_menu)) def get_keymask(self): return self._keymask def set_keymask(self, value): if value & MASK_SHIFT: mode = ActionMode.Delete elif value & MASK_CTRL: mode = ActionMode.Insert else: mode = ActionMode.Replace self._keymask = value self.action_mode = mode keymask = property(get_keymask, set_keymask) @Gtk.Template.Callback() def on_key_event(self, object, event): keymap = Gdk.Keymap.get_default() ok, keyval, group, lvl, consumed = keymap.translate_keyboard_state( event.hardware_keycode, 0, event.group) mod_key = self.keylookup.get(keyval, 0) if event.type == Gdk.EventType.KEY_PRESS: self.keymask |= mod_key if event.keyval == Gdk.KEY_Escape: self.findbar.hide() elif event.type == Gdk.EventType.KEY_RELEASE: self.keymask &= ~mod_key def on_overview_map_style_changed(self, *args): style = self.props.overview_map_style self.chunkmap_hbox.set_visible(style == 'chunkmap') self.sourcemap_hbox.set_visible( style in ('compact-sourcemap', 'full-sourcemap')) for sourcemap in self.sourcemap: sourcemap.props.compact_view = style == 'compact-sourcemap' def get_filter_visibility(self) -> Tuple[bool, bool, bool]: return True, False, False def get_conflict_visibility(self) -> bool: return self.num_panes == 3 def on_text_filters_changed(self, app): relevant_change = self.create_text_filters() if relevant_change: self.refresh_comparison() def _update_text_filter(self, action, state): self._action_text_filter_map[action].active = state.get_boolean() action.set_state(state) self.refresh_comparison() def create_text_filters(self): meld_settings = get_meld_settings() # In contrast to file filters, ordering of text filters can matter old_active = [f.filter_string for f in self.text_filters if f.active] new_active = [ f.filter_string for f in meld_settings.text_filters if f.active ] active_filters_changed = old_active != new_active # TODO: Rework text_filters to use a map-like structure so that we # don't need _action_text_filter_map. self._action_text_filter_map = {} self.text_filters = [copy.copy(f) for f in meld_settings.text_filters] for i, filt in enumerate(self.text_filters): action = Gio.SimpleAction.new_stateful( name=TEXT_FILTER_ACTION_FORMAT.format(i), parameter_type=None, state=GLib.Variant.new_boolean(filt.active), ) action.connect('change-state', self._update_text_filter) action.set_enabled(filt.filter is not None) self.view_action_group.add_action(action) self._action_text_filter_map[action] = filt return active_filters_changed def _disconnect_buffer_handlers(self): for textview in self.textview: textview.set_sensitive(False) for buf in self.textbuffer: for h in buf.handlers: buf.disconnect(h) buf.handlers = [] def _connect_buffer_handlers(self): for textview in self.textview: textview.set_sensitive(True) for buf in self.textbuffer: id0 = buf.connect("insert-text", self.on_text_insert_text) id1 = buf.connect("delete-range", self.on_text_delete_range) id2 = buf.connect_after("insert-text", self.after_text_insert_text) id3 = buf.connect_after( "delete-range", self.after_text_delete_range) id4 = buf.connect( "notify::cursor-position", self.on_cursor_position_changed) buf.handlers = id0, id1, id2, id3, id4 if self.comparison_mode == FileComparisonMode.AutoMerge: self.textview[0].set_editable(0) self.textview[2].set_editable(0) def bind_adapt_cursor_position(self, binding, from_value): buf = binding.get_source() textview = self.textview[self.textbuffer.index(buf)] cursor_it = buf.get_iter_at_offset(from_value) offset = textview.get_visual_column(cursor_it) line = cursor_it.get_line() return (line, offset) def on_cursor_position_changed(self, buf, pspec, force=False): # Avoid storing cursor changes for non-focused panes. These # happen when we e.g., copy a chunk between panes. if not self.focus_pane or self.focus_pane.get_buffer() != buf: return pane = self.textbuffer.index(buf) pos = buf.props.cursor_position if pane == self.cursor.pane and pos == self.cursor.pos and not force: return self.cursor.pane, self.cursor.pos = pane, pos cursor_it = buf.get_iter_at_offset(pos) line = cursor_it.get_line() if line != self.cursor.line or force: chunk, prev, next_ = self.linediffer.locate_chunk(pane, line) if chunk != self.cursor.chunk or force: self.cursor.chunk = chunk self.on_current_diff_changed() if prev != self.cursor.prev or next_ != self.cursor.next or force: self.set_action_enabled("previous-change", prev is not None) self.set_action_enabled("next-change", next_ is not None) prev_conflict, next_conflict = None, None for conflict in self.linediffer.conflicts: if prev is not None and conflict <= prev: prev_conflict = conflict if next_ is not None and conflict >= next_: next_conflict = conflict break if prev_conflict != self.cursor.prev_conflict or \ next_conflict != self.cursor.next_conflict or force: self.emit("next-conflict-changed", prev_conflict is not None, next_conflict is not None) self.cursor.prev, self.cursor.next = prev, next_ self.cursor.prev_conflict = prev_conflict self.cursor.next_conflict = next_conflict self.cursor.line = line def on_current_diff_changed(self, *args): try: pane = self.textview.index(self.focus_pane) except ValueError: pane = -1 if pane != -1: # While this *should* be redundant, it's possible for focus pane # and cursor pane to be different in several situations. pane = self.cursor.pane chunk_id = self.cursor.chunk if pane == -1 or chunk_id is None: push_left, push_right, pull_left, pull_right, delete, \ copy_left, copy_right = (False,) * 7 else: push_left, push_right, pull_left, pull_right, delete, \ copy_left, copy_right = (True,) * 7 three_way = self.num_panes == 3 # Push and Delete are active if the current pane has something to # act on, and the target pane exists and is editable. Pull is # sensitive if the source pane has something to get, and the # current pane is editable. Copy actions are sensitive if the # conditions for push are met, *and* there is some content in the # target pane. editable = self.textview[pane].get_editable() # editable_left is relative to current pane and it is False for the # leftmost frame. The same logic applies to editable_right. editable_left = pane > 0 and self.textview[pane - 1].get_editable() editable_right = ( pane < self.num_panes - 1 and self.textview[pane + 1].get_editable() ) if pane == 0 or pane == 2: chunk = self.linediffer.get_chunk(chunk_id, pane) is_insert = chunk[1] == chunk[2] is_delete = chunk[3] == chunk[4] push_left = editable_left push_right = editable_right pull_left = pane == 2 and editable and not is_delete pull_right = pane == 0 and editable and not is_delete delete = editable and not is_insert copy_left = editable_left and not (is_insert or is_delete) copy_right = editable_right and not (is_insert or is_delete) elif pane == 1: chunk0 = self.linediffer.get_chunk(chunk_id, 1, 0) chunk2 = None if three_way: chunk2 = self.linediffer.get_chunk(chunk_id, 1, 2) left_mid_exists = bool(chunk0 and chunk0[1] != chunk0[2]) left_exists = bool(chunk0 and chunk0[3] != chunk0[4]) right_mid_exists = bool(chunk2 and chunk2[1] != chunk2[2]) right_exists = bool(chunk2 and chunk2[3] != chunk2[4]) push_left = editable_left and bool(not three_way or chunk0) push_right = editable_right and bool(not three_way or chunk2) pull_left = editable and left_exists pull_right = editable and right_exists delete = editable and (left_mid_exists or right_mid_exists) copy_left = editable_left and left_mid_exists and left_exists copy_right = ( editable_right and right_mid_exists and right_exists) # If there is chunk and there are only two panes (#25) if self.num_panes == 2: pane0_editable = self.textview[0].get_editable() pane1_editable = self.textview[1].get_editable() push_left = pane0_editable push_right = pane1_editable self.set_action_enabled('file-push-left', push_left) self.set_action_enabled('file-push-right', push_right) self.set_action_enabled('file-pull-left', pull_left) self.set_action_enabled('file-pull-right', pull_right) self.set_action_enabled('file-delete', delete) self.set_action_enabled('file-copy-left-up', copy_left) self.set_action_enabled('file-copy-left-down', copy_left) self.set_action_enabled('file-copy-right-up', copy_right) self.set_action_enabled('file-copy-right-down', copy_right) self.set_action_enabled('previous-pane', pane > 0) self.set_action_enabled('next-pane', pane < self.num_panes - 1) self.set_action_enabled('swap-2-panes', self.num_panes == 2) self.update_text_actions_sensitivity() # FIXME: don't queue_draw() on everything... just on what changed self.queue_draw() def on_next_conflict_changed(self, doc, have_prev, have_next): self.set_action_enabled('file-previous-conflict', have_prev) self.set_action_enabled('file-next-conflict', have_next) def scroll_to_chunk_index(self, chunk_index, tolerance): """Scrolls chunks with the given index on screen in all panes""" starts = self.linediffer.get_chunk_starts(chunk_index) for pane, start in enumerate(starts): if start is None: continue buf = self.textbuffer[pane] it = buf.get_iter_at_line(start) self.textview[pane].scroll_to_iter(it, tolerance, True, 0.5, 0.5) def go_to_chunk(self, target, pane=None, centered=False): if target is None: self.error_bell() return if pane is None: pane = self._get_focused_pane() if pane == -1: pane = 1 if self.num_panes > 1 else 0 chunk = self.linediffer.get_chunk(target, pane) if not chunk: self.error_bell() return # Warp the cursor to the first line of the chunk buf = self.textbuffer[pane] if self.cursor.line != chunk[1]: buf.place_cursor(buf.get_iter_at_line(chunk[1])) # Scroll all panes to the given chunk, and then ensure that the newly # placed cursor is definitely on-screen. tolerance = 0.0 if centered else 0.2 self.scroll_to_chunk_index(target, tolerance) self.textview[pane].scroll_to_mark( buf.get_insert(), tolerance, True, 0.5, 0.5) # If we've moved to a valid chunk (or stayed in the first/last chunk) # then briefly highlight the chunk for better visual orientation. chunk_start = buf.get_iter_at_line_or_eof(chunk[1]) chunk_end = buf.get_iter_at_line_or_eof(chunk[2]) mark0 = buf.create_mark(None, chunk_start, True) mark1 = buf.create_mark(None, chunk_end, True) self.textview[pane].add_fading_highlight( mark0, mark1, 'focus-highlight', 400000, starting_alpha=0.3, anim_type=TextviewLineAnimationType.stroke) @Gtk.Template.Callback() def on_linkmap_scroll_event(self, linkmap, event): self.next_diff(event.direction, use_viewport=True) def _is_chunk_in_area( self, chunk_id: Optional[int], pane: int, area: Gdk.Rectangle): if chunk_id is None: return False chunk = self.linediffer.get_chunk(chunk_id, pane) target_iter = self.textbuffer[pane].get_iter_at_line(chunk.start_a) target_y, _height = self.textview[pane].get_line_yrange(target_iter) return area.y <= target_y <= area.y + area.height def next_diff(self, direction, centered=False, use_viewport=False): # use_viewport: seek next and previous diffes based on where # the user is currently scrolling at. scroll_down = direction == Gdk.ScrollDirection.DOWN target = self.cursor.next if scroll_down else self.cursor.prev if use_viewport: pane = self.cursor.pane text_area = self.textview[pane].get_visible_rect() # Only do viewport-relative calculations if the chunk we'd # otherwise scroll to is *not* on screen. This avoids 3-way # comparison cases where scrolling won't go past a chunk # because the scroll doesn't go past 50% of the screen. if not self._is_chunk_in_area(target, pane, text_area): halfscreen = text_area.y + text_area.height / 2 halfline = self.textview[pane].get_line_at_y( halfscreen).target_iter.get_line() _, prev, next_ = self.linediffer.locate_chunk(1, halfline) target = next_ if scroll_down else prev self.go_to_chunk(target, centered=centered) def action_previous_change(self, *args): self.next_diff(Gdk.ScrollDirection.UP) def action_next_change(self, *args): self.next_diff(Gdk.ScrollDirection.DOWN) def action_previous_conflict(self, *args): self.go_to_chunk(self.cursor.prev_conflict, self.cursor.pane) def action_next_conflict(self, *args): self.go_to_chunk(self.cursor.next_conflict, self.cursor.pane) def action_previous_diff(self, *args): self.go_to_chunk(self.cursor.prev) def action_next_diff(self, *args): self.go_to_chunk(self.cursor.next) def get_action_chunk(self, src, dst): valid_panes = list(range(0, self.num_panes)) if src not in valid_panes or dst not in valid_panes: raise ValueError("Action was taken on invalid panes") if self.cursor.chunk is None: raise ValueError("Action was taken without chunk") chunk = self.linediffer.get_chunk(self.cursor.chunk, src, dst) if chunk is None: raise ValueError("Action was taken on a missing chunk") return chunk def get_action_panes(self, direction, reverse=False): src = self._get_focused_pane() dst = src + direction return (dst, src) if reverse else (src, dst) def on_chunk_action_activated( self, gutter, action, from_view, to_view, chunk): try: chunk_action = ChunkAction(action) except ValueError: log.error('Invalid chunk action %s', action) return # TODO: There's no reason the replace_chunk(), etc. calls should take # an index instead of just taking the views themselves. from_pane = self.textview.index(from_view) to_pane = self.textview.index(to_view) if chunk_action == ChunkAction.replace: self.replace_chunk(from_pane, to_pane, chunk) elif chunk_action == ChunkAction.delete: self.delete_chunk(from_pane, chunk) elif chunk_action == ChunkAction.copy_up: self.copy_chunk(from_pane, to_pane, chunk, copy_up=True) elif chunk_action == ChunkAction.copy_down: self.copy_chunk(from_pane, to_pane, chunk, copy_up=False) def action_push_change_left(self, *args): if self.num_panes == 2: src, dst = 1, 0 else: src, dst = self.get_action_panes(PANE_LEFT) self.replace_chunk(src, dst, self.get_action_chunk(src, dst)) def action_push_change_right(self, *args): if self.num_panes == 2: src, dst = 0, 1 else: src, dst = self.get_action_panes(PANE_RIGHT) self.replace_chunk(src, dst, self.get_action_chunk(src, dst)) def action_pull_change_left(self, *args): src, dst = self.get_action_panes(PANE_LEFT, reverse=True) self.replace_chunk(src, dst, self.get_action_chunk(src, dst)) def action_pull_change_right(self, *args): src, dst = self.get_action_panes(PANE_RIGHT, reverse=True) self.replace_chunk(src, dst, self.get_action_chunk(src, dst)) def action_copy_change_left_up(self, *args): src, dst = self.get_action_panes(PANE_LEFT) self.copy_chunk( src, dst, self.get_action_chunk(src, dst), copy_up=True) def action_copy_change_right_up(self, *args): src, dst = self.get_action_panes(PANE_RIGHT) self.copy_chunk( src, dst, self.get_action_chunk(src, dst), copy_up=True) def action_copy_change_left_down(self, *args): src, dst = self.get_action_panes(PANE_LEFT) self.copy_chunk( src, dst, self.get_action_chunk(src, dst), copy_up=False) def action_copy_change_right_down(self, *args): src, dst = self.get_action_panes(PANE_RIGHT) self.copy_chunk( src, dst, self.get_action_chunk(src, dst), copy_up=False) def pull_all_non_conflicting_changes(self, src, dst): merger = Merger() merger.differ = self.linediffer merger.texts = self.buffer_texts for mergedfile in merger.merge_2_files(src, dst): pass self._sync_vscroll_lock = True self.textbuffer[dst].begin_user_action() self.textbuffer[dst].set_text(mergedfile) self.textbuffer[dst].end_user_action() def resync(): self._sync_vscroll_lock = False self._sync_vscroll(self.scrolledwindow[src].get_vadjustment(), src) self.scheduler.add_task(resync) def action_pull_all_changes_left(self, *args): src, dst = self.get_action_panes(PANE_LEFT, reverse=True) self.pull_all_non_conflicting_changes(src, dst) def action_pull_all_changes_right(self, *args): src, dst = self.get_action_panes(PANE_RIGHT, reverse=True) self.pull_all_non_conflicting_changes(src, dst) def action_merge_all_changes(self, *args): dst = 1 merger = Merger() merger.differ = self.linediffer merger.texts = self.buffer_texts for mergedfile in merger.merge_3_files(False): pass self._sync_vscroll_lock = True self.textbuffer[dst].begin_user_action() self.textbuffer[dst].set_text(mergedfile) self.textbuffer[dst].end_user_action() def resync(): self._sync_vscroll_lock = False self._sync_vscroll(self.scrolledwindow[0].get_vadjustment(), 0) self.scheduler.add_task(resync) @with_focused_pane def action_delete_change(self, pane, *args): if self.cursor.chunk is None: return chunk = self.linediffer.get_chunk(self.cursor.chunk, pane) if chunk is None: return self.delete_chunk(pane, chunk) def _synth_chunk(self, pane0, pane1, line): """Returns the Same chunk that would exist at the given location if we didn't remove Same chunks""" # This method is a hack around our existing diffutil data structures; # getting rid of the Same chunk removal is difficult, as several places # have baked in the assumption of only being given changed blocks. buf0, buf1 = self.textbuffer[pane0], self.textbuffer[pane1] start0, end0 = 0, buf0.get_line_count() - 1 start1, end1 = 0, buf1.get_line_count() - 1 # This hack is required when pane0's prev/next chunk doesn't exist # (i.e., is Same) between pane0 and pane1. prev_chunk0, prev_chunk1, next_chunk0, next_chunk1 = (None,) * 4 _, prev, next_ = self.linediffer.locate_chunk(pane0, line) if prev is not None: while prev >= 0: prev_chunk0 = self.linediffer.get_chunk(prev, pane0, pane1) prev_chunk1 = self.linediffer.get_chunk(prev, pane1, pane0) if None not in (prev_chunk0, prev_chunk1): start0 = prev_chunk0[2] start1 = prev_chunk1[2] break prev -= 1 if next_ is not None: while next_ < self.linediffer.diff_count(): next_chunk0 = self.linediffer.get_chunk(next_, pane0, pane1) next_chunk1 = self.linediffer.get_chunk(next_, pane1, pane0) if None not in (next_chunk0, next_chunk1): end0 = next_chunk0[1] end1 = next_chunk1[1] break next_ += 1 # TODO: Move myers.DiffChunk to a more general place, update # this to use it, and update callers to use nice attributes. return "Same", start0, end0, start1, end1 def _corresponding_chunk_line(self, chunk, line, pane, new_pane): """Approximates the corresponding line between panes""" new_buf = self.textbuffer[new_pane] # Special-case cross-pane jumps if (pane == 0 and new_pane == 2) or (pane == 2 and new_pane == 0): proxy = self._corresponding_chunk_line(chunk, line, pane, 1) return self._corresponding_chunk_line(chunk, proxy, 1, new_pane) # Either we are currently in a identifiable chunk, or we are in a Same # chunk; if we establish the start/end of that chunk in both panes, we # can figure out what our new offset should be. cur_chunk = None if chunk is not None: cur_chunk = self.linediffer.get_chunk(chunk, pane, new_pane) if cur_chunk is None: cur_chunk = self._synth_chunk(pane, new_pane, line) cur_start, cur_end, new_start, new_end = cur_chunk[1:5] # If the new buffer's current cursor is already in the correct chunk, # assume that we have in-progress editing, and don't move it. cursor_it = new_buf.get_iter_at_mark(new_buf.get_insert()) cursor_line = cursor_it.get_line() cursor_chunk, _, _ = self.linediffer.locate_chunk( new_pane, cursor_line) if cursor_chunk is not None: already_in_chunk = cursor_chunk == chunk else: cursor_chunk = self._synth_chunk(pane, new_pane, cursor_line) already_in_chunk = ( cursor_chunk[3] == new_start and cursor_chunk[4] == new_end) if already_in_chunk: new_line = cursor_line else: # Guess where to put the cursor: in the same chunk, at about the # same place within the chunk, calculated proportionally by line. # Insert chunks and one-line chunks are placed at the top. if cur_end == cur_start: chunk_offset = 0.0 else: chunk_offset = (line - cur_start) / float(cur_end - cur_start) new_line = new_start + int(chunk_offset * (new_end - new_start)) return new_line def move_cursor(self, pane, line, focus=True): buf, view = self.textbuffer[pane], self.textview[pane] if focus: view.grab_focus() buf.place_cursor(buf.get_iter_at_line(line)) view.scroll_to_mark(buf.get_insert(), 0.1, True, 0.5, 0.5) def move_cursor_pane(self, pane, new_pane): chunk, line = self.cursor.chunk, self.cursor.line new_line = self._corresponding_chunk_line(chunk, line, pane, new_pane) self.move_cursor(new_pane, new_line) def action_prev_pane(self, *args): pane = self._get_focused_pane() new_pane = (pane - 1) % self.num_panes self.move_cursor_pane(pane, new_pane) def action_next_pane(self, *args): pane = self._get_focused_pane() new_pane = (pane + 1) % self.num_panes self.move_cursor_pane(pane, new_pane) def _set_external_action_sensitivity(self): # FIXME: This sensitivity is very confused. Essentially, it's always # enabled because we don't unset focus_pane, but the action uses the # current pane focus (i.e., _get_focused_pane) instead of focus_pane. have_file = self.focus_pane is not None self.set_action_enabled("open-external", have_file) def on_textview_drag_data_received( self, widget, context, x, y, selection_data, info, time): uris = selection_data.get_uris() if uris: gfiles = [Gio.File.new_for_uri(uri) for uri in uris] if len(gfiles) == self.num_panes: if self.check_unsaved_changes(): self.set_files(gfiles) elif len(gfiles) == 1: if widget in self.textview: pane = self.textview.index(widget) elif widget in self.filelabel: pane = self.filelabel.index(widget) else: log.error("Unrecognised drag destination") return True buffer = self.textbuffer[pane] if self.check_unsaved_changes([buffer]): self.set_file(pane, gfiles[0]) return True @Gtk.Template.Callback() def on_textview_focus_in_event(self, view, event): self.focus_pane = view self.findbar.set_text_view(self.focus_pane) self.on_cursor_position_changed(view.get_buffer(), None, True) self._set_save_action_sensitivity() self._set_merge_action_sensitivity() self._set_external_action_sensitivity() @Gtk.Template.Callback() def on_textview_focus_out_event(self, view, event): self.keymask = 0 self._set_merge_action_sensitivity() self._set_external_action_sensitivity() def _after_text_modified(self, buf, startline, sizechange): if self.num_panes > 1: pane = self.textbuffer.index(buf) if not self.linediffer.syncpoints: self.linediffer.change_sequence(pane, startline, sizechange, self.buffer_filtered) # TODO: We should have a diff-changed signal for the # current buffer instead of passing everything through # cursor change logic. focused_pane = self._get_focused_pane() if focused_pane != -1: self.on_cursor_position_changed(self.textbuffer[focused_pane], None, True) def _filter_text(self, txt, buf, txt_start_iter, txt_end_iter): dimmed_tag = buf.get_tag_table().lookup("dimmed") buf.remove_tag(dimmed_tag, txt_start_iter, txt_end_iter) def highlighter(start, end): start_iter = txt_start_iter.copy() start_iter.forward_chars(start) end_iter = txt_start_iter.copy() end_iter.forward_chars(end) buf.apply_tag(dimmed_tag, start_iter, end_iter) try: regexes = [f.filter for f in self.text_filters if f.active] txt = misc.apply_text_filters(txt, regexes, apply_fn=highlighter) except AssertionError: if not self.warned_bad_comparison: misc.error_dialog( primary=_("Comparison results will be inaccurate"), secondary=_( "A filter changed the number of lines in the " "file, which is unsupported. The comparison will " "not be accurate."), ) self.warned_bad_comparison = True return txt def after_text_insert_text(self, buf, it, newtext, textlen): start_mark = buf.get_mark("insertion-start") starting_at = buf.get_iter_at_mark(start_mark).get_line() buf.delete_mark(start_mark) lines_added = it.get_line() - starting_at self._after_text_modified(buf, starting_at, lines_added) def after_text_delete_range(self, buf, it0, it1): starting_at = it0.get_line() self._after_text_modified(buf, starting_at, -self.lines_removed) self.lines_removed = 0 def check_save_modified(self, buffers=None): response = Gtk.ResponseType.OK buffers = buffers or self.textbuffer[:self.num_panes] if any(b.get_modified() for b in buffers): builder = Gtk.Builder.new_from_resource( '/org/gnome/meld/ui/save-confirm-dialog.ui') dialog = builder.get_object('save-confirm-dialog') dialog.set_transient_for(self.get_toplevel()) message_area = dialog.get_message_area() buttons = [] for buf in buffers: button = Gtk.CheckButton.new_with_label(buf.data.label) needs_save = buf.get_modified() button.set_sensitive(needs_save) button.set_active(needs_save) message_area.pack_start( button, expand=False, fill=True, padding=0) buttons.append(button) message_area.show_all() response = dialog.run() try_save = [b.get_active() for b in buttons] dialog.destroy() if response == Gtk.ResponseType.OK: for i, buf in enumerate(buffers): if try_save[i]: self.save_file(self.textbuffer.index(buf)) # We return an APPLY instead of OK here to indicate that other # closing logic shouldn't run. Instead, the file-saved callback # from save_file() handles closing files and setting state. return Gtk.ResponseType.APPLY elif response == Gtk.ResponseType.DELETE_EVENT: response = Gtk.ResponseType.CANCEL elif response == Gtk.ResponseType.CLOSE: response = Gtk.ResponseType.OK if response == Gtk.ResponseType.OK and self.meta: self.prompt_resolve_conflict() elif response == Gtk.ResponseType.CANCEL: self.state = ComparisonState.Normal return response def prompt_resolve_conflict(self): parent = self.meta.get('parent', None) saved = self.meta.get('middle_saved', False) prompt_resolve = self.meta.get('prompt_resolve', False) if prompt_resolve and saved and parent.has_command('resolve'): primary = _("Mark conflict as resolved?") secondary = _( "If the conflict was resolved successfully, you may mark " "it as resolved now.") buttons = ( (_("Cancel"), Gtk.ResponseType.CANCEL, None), (_("Mark _Resolved"), Gtk.ResponseType.OK, None), ) resolve_response = misc.modal_dialog( primary, secondary, buttons, parent=self, messagetype=Gtk.MessageType.QUESTION) if resolve_response == Gtk.ResponseType.OK: bufdata = self.textbuffer[1].data conflict_gfile = bufdata.savefile or bufdata.gfile # It's possible that here we're in a quit callback, # so we can't schedule the resolve action to an # idle loop; it might never happen. parent.command( 'resolve', [conflict_gfile.get_path()], sync=True) def on_delete_event(self): self.state = ComparisonState.Closing response = self.check_save_modified() if response == Gtk.ResponseType.OK: meld_settings = get_meld_settings() for h in self.settings_handlers: meld_settings.disconnect(h) # This is a workaround for cleaning up file monitors. for buf in self.textbuffer: buf.data.disconnect_monitor() try: self._cached_match.stop() except Exception: # Ignore any cross-process exceptions that happen when # shutting down our matcher process. log.exception('Failed to shut down matcher process') # TODO: Base the return code on something meaningful for VC tools self.close_signal.emit(0) elif response == Gtk.ResponseType.CANCEL: self.state = ComparisonState.Normal elif response == Gtk.ResponseType.APPLY: # We have triggered an async save, and need to let it finish ... return response def _scroll_to_actions(self, actions): """Scroll all views affected by *actions* to the current cursor""" affected_buffers = set(a.buffer for a in actions) for buf in affected_buffers: buf_index = self.textbuffer.index(buf) view = self.textview[buf_index] view.scroll_mark_onscreen(buf.get_insert()) def action_undo(self, *args): if self.undosequence.can_undo(): actions = self.undosequence.undo() self._scroll_to_actions(actions) def action_redo(self, *args): if self.undosequence.can_redo(): actions = self.undosequence.redo() self._scroll_to_actions(actions) def on_text_insert_text(self, buf, it, text, textlen): self.undosequence.add_action( BufferInsertionAction(buf, it.get_offset(), text)) buf.create_mark("insertion-start", it, True) def on_text_delete_range(self, buf, it0, it1): text = buf.get_text(it0, it1, False) self.lines_removed = it1.get_line() - it0.get_line() self.undosequence.add_action( BufferDeletionAction(buf, it0.get_offset(), text)) def on_undo_checkpointed(self, undosequence, buf, checkpointed): buf.set_modified(not checkpointed) self.recompute_label() def on_can_undo(self, undosequence, can_undo): self.set_action_enabled('undo', can_undo) def on_can_redo(self, undosequence, can_redo): self.set_action_enabled('redo', can_redo) @with_focused_pane def action_copy_full_path(self, pane, *args): gfile = self.textbuffer[pane].data.gfile if not gfile: return path = gfile.get_path() or gfile.get_uri() clip = Gtk.Clipboard.get_default(Gdk.Display.get_default()) clip.set_text(path, -1) clip.store() @with_focused_pane def action_open_folder(self, pane, *args): gfile = self.textbuffer[pane].data.gfile if not gfile: return parent = gfile.get_parent() if parent: open_files_external(gfiles=[parent]) @with_focused_pane def action_open_external(self, pane, *args): if not self.textbuffer[pane].data.gfile: return pos = self.textbuffer[pane].props.cursor_position cursor_it = self.textbuffer[pane].get_iter_at_offset(pos) line = cursor_it.get_line() + 1 gfiles = [self.textbuffer[pane].data.gfile] open_files_external(gfiles=gfiles, line=line) def update_text_actions_sensitivity(self, *args): widget = self.focus_pane if not widget: cut, copy, paste = False, False, False else: cut = copy = widget.get_buffer().get_has_selection() paste = widget.get_editable() for action, enabled in zip( ('cut', 'copy', 'paste'), (cut, copy, paste)): self.set_action_enabled(action, enabled) @with_focused_pane def get_selected_text(self, pane): """Returns selected text of active pane""" buf = self.textbuffer[pane] sel = buf.get_selection_bounds() if sel: return buf.get_text(sel[0], sel[1], False) def action_find(self, *args): selected_text = self.get_selected_text() self.findbar.start_find( textview=self.focus_pane, replace=False, text=selected_text) def action_find_replace(self, *args): selected_text = self.get_selected_text() self.findbar.start_find( textview=self.focus_pane, replace=True, text=selected_text) def action_find_next(self, *args): self.findbar.start_find_next(self.focus_pane) def action_find_previous(self, *args): self.findbar.start_find_previous(self.focus_pane) @with_focused_pane def action_go_to_line(self, pane, *args): self.statusbar[pane].emit('start-go-to-line') @Gtk.Template.Callback() def on_scrolledwindow_size_allocate(self, scrolledwindow, allocation): index = self.scrolledwindow.index(scrolledwindow) if index == 0 or index == 1: self.linkmap[0].queue_draw() if index == 1 or index == 2: self.linkmap[1].queue_draw() @Gtk.Template.Callback() def on_textview_popup_menu(self, textview): buffer = textview.get_buffer() cursor_it = buffer.get_iter_at_mark(buffer.get_insert()) location = textview.get_iter_location(cursor_it) rect = Gdk.Rectangle() rect.x, rect.y = textview.buffer_to_window_coords( Gtk.TextWindowType.WIDGET, location.x, location.y) pane = self.textview.index(textview) self.set_syncpoint_menuitem(pane) self.popup_menu.popup_at_rect( Gtk.Widget.get_window(textview), rect, Gdk.Gravity.SOUTH_EAST, Gdk.Gravity.NORTH_WEST, None, ) return True @Gtk.Template.Callback() def on_textview_button_press_event(self, textview, event): if event.button == 3: textview.grab_focus() pane = self.textview.index(textview) self.set_syncpoint_menuitem(pane) self.popup_menu.popup_at_pointer(event) return True return False def set_syncpoint_menuitem(self, pane): menu_actions = { SyncpointAction.ADD: [ _("Add Synchronization Point"), "view.add-sync-point" ], SyncpointAction.DELETE: [ _("Remove Synchronization Point"), "view.remove-sync-point" ], SyncpointAction.MOVE: [ _("Move Synchronization Point"), "view.add-sync-point" ], SyncpointAction.MATCH: [ _("Match Synchronization Point"), "view.add-sync-point" ], SyncpointAction.DISABLED: [ _("Add Synchronization Point"), "view.add-sync-point" ], } def get_mark(): return self.textbuffer[pane].get_insert() action = self.syncpoints.action(pane, get_mark) self.set_action_enabled( "add-sync-point", action != SyncpointAction.DISABLED ) label, action_id = menu_actions[action] syncpoint_menu = Gio.Menu() syncpoint_menu.append(label=label, detailed_action=action_id) syncpoint_menu.append( label=_("Clear Synchronization Points"), detailed_action='view.clear-sync-point', ) section = Gio.MenuItem.new_section(None, syncpoint_menu) section.set_attribute([("id", "s", "syncpoint-section")]) replace_menu_section(self.popup_menu_model, section) self.popup_menu = Gtk.Menu.new_from_model(self.popup_menu_model) self.popup_menu.attach_to_widget(self) def set_labels(self, labels): labels = labels[:self.num_panes] for label, buf, flabel in zip(labels, self.textbuffer, self.filelabel): if label: buf.data.label = label flabel.props.custom_label = label def set_merge_output_file(self, gfile): if self.num_panes < 2: return buf = self.textbuffer[1] buf.data.savefile = gfile buf.data.label = gfile.get_path() self.update_buffer_writable(buf) self.filelabel[1].props.gfile = gfile self.recompute_label() def _set_save_action_sensitivity(self): pane = self._get_focused_pane() modified_panes = [b.get_modified() for b in self.textbuffer] self.set_action_enabled('save', pane != -1 and modified_panes[pane]) self.set_action_enabled('save-all', any(modified_panes)) def recompute_label(self): self._set_save_action_sensitivity() buffers = self.textbuffer[:self.num_panes] filenames = [b.data.label for b in buffers] shortnames = misc.shorten_names(*filenames) for i, buf in enumerate(buffers): if buf.get_modified(): shortnames[i] += "*" self.file_save_button[i].set_sensitive(buf.get_modified()) self.file_save_button[i].get_child().props.icon_name = ( 'document-save-symbolic' if buf.data.writable else 'document-save-as-symbolic') parent_path = find_shared_parent_path( [b.data.gfiletarget for b in buffers] ) for pathlabel in self.filelabel: pathlabel.props.parent_gfile = parent_path label = self.meta.get("tablabel", "") if label: self.label_text = label tooltip_names = [label] else: self.label_text = " — ".join(shortnames) tooltip_names = filenames self.tooltip_text = "\n".join((_("File comparison:"), *tooltip_names)) self.label_changed.emit(self.label_text, self.tooltip_text) def pre_comparison_init(self): self._disconnect_buffer_handlers() self.linediffer.clear() for bufferlines in self.buffer_filtered: bufferlines.clear_cache() for buf in self.textbuffer: tag = buf.get_tag_table().lookup("inline") buf.remove_tag(tag, buf.get_start_iter(), buf.get_end_iter()) for mgr in self.msgarea_mgr: if mgr.get_msg_id() in self.TRANSIENT_MESSAGES: mgr.clear() def set_files(self, gfiles, encodings=None): """Load the given files If an element is None, the text of a pane is left as is. """ if len(gfiles) != self.num_panes: return self.pre_comparison_init() self.undosequence.clear() encodings = encodings or ((None,) * len(gfiles)) files = [] for pane, (gfile, encoding) in enumerate(zip(gfiles, encodings)): if gfile: files.append((pane, gfile, encoding)) else: self.textbuffer[pane].data.state = MeldBufferState.LOAD_FINISHED if not files: self.scheduler.add_task(self._compare_files_internal()) for pane, gfile, encoding in files: self.load_file_in_pane(pane, gfile, encoding) def set_file( self, pane: int, gfile: Gio.File, encoding: GtkSource.Encoding = None): self.pre_comparison_init() self.undosequence.clear() self.load_file_in_pane(pane, gfile, encoding) def load_file_in_pane( self, pane: int, gfile: Gio.File, encoding: GtkSource.Encoding = None): """Load a file into the given pane Don't call this directly; use `set_file()` or `set_files()`, which handle sensitivity and signal connection. Even if you don't care about those things, you need it because they'll be unconditionally added after file load, which will cause duplicate handlers, etc. if you don't do this thing. """ self.msgarea_mgr[pane].clear() buf = self.textbuffer[pane] buf.data.reset(gfile, MeldBufferState.LOADING) self.file_open_button[pane].props.file = gfile # FIXME: this was self.textbuffer[pane].data.label, which could be # either a custom label or the fallback self.filelabel[pane].props.gfile = gfile if buf.data.is_special: loader = GtkSource.FileLoader.new_from_stream( buf, buf.data.sourcefile, buf.data.gfile.read()) else: loader = GtkSource.FileLoader.new(buf, buf.data.sourcefile) custom_candidates = get_custom_encoding_candidates() if encoding: custom_candidates = [encoding] if custom_candidates: loader.set_candidate_encodings(custom_candidates) buf.move_mark_by_name(LOAD_PROGRESS_MARK, buf.get_start_iter()) cancellable = Gio.Cancellable() errors = {} loader.load_async( GLib.PRIORITY_HIGH, cancellable=cancellable, progress_callback=self.file_load_progress, progress_callback_data=(loader, cancellable, errors), callback=self.file_loaded, user_data=(pane, errors), ) def get_comparison(self): uris = [b.data.gfile for b in self.textbuffer[:self.num_panes]] if self.comparison_mode == FileComparisonMode.AutoMerge: comparison_type = RecentType.Merge else: comparison_type = RecentType.File return comparison_type, uris def file_load_progress( self, current_bytes: int, total_bytes: int, loader: GtkSource.FileLoader, cancellable: Gio.Cancellable, errors: dict[int, str], ) -> None: failed_it = None buffer = loader.get_buffer() progress_mark = buffer.get_mark(LOAD_PROGRESS_MARK) # If forward_line() returns False it points to the current end of the # buffer after the movement; if this happens, we assume that we don't # yet have a full line, and so don't can't check it for length. it = buffer.get_iter_at_mark(progress_mark) last_it = it.copy() while it.forward_line(): # last_it is now on a fully-loaded line, so we can check it if last_it.get_chars_in_line() > LINE_LENGTH_LIMIT: failed_it = last_it break last_it.assign(it) # We also have to check the last line in the file, which would # otherwise be skipped by the above logic. if (current_bytes == total_bytes) and (it.get_chars_in_line() > LINE_LENGTH_LIMIT): failed_it = it if failed_it: # Ideally we'd have custom GError handling here instead, but # set_error_if_cancelled() doesn't appear to work in pygobject # bindings. errors[self.textbuffer.index(buffer)] = ( FileLoadError.LINE_TOO_LONG, _( "Line {line_number} exceeded maximum line length " "({line_length} > {LINE_LENGTH_LIMIT})" ).format( line_number=failed_it.get_line() + 1, line_length=failed_it.get_chars_in_line(), LINE_LENGTH_LIMIT=LINE_LENGTH_LIMIT, ) ) cancellable.cancel() # Moving the mark invalidates the text iterators, so this must happen # *last* here, or the above line length accesses will be incorrect. buffer.move_mark(progress_mark, last_it) def file_loaded( self, loader: GtkSource.FileLoader, result: Gio.AsyncResult, user_data: Tuple[int, dict[int, str]], ): gfile = loader.get_location() buf = loader.get_buffer() pane, errors = user_data try: loader.load_finish(result) buf.data.state = MeldBufferState.LOAD_FINISHED except GLib.Error as err: if err.matches( GLib.convert_error_quark(), GLib.ConvertError.ILLEGAL_SEQUENCE): # While there are probably others, this is the main # case where GtkSourceView's loader doesn't finish its # in-progress user-action on error. See bgo#795387 for # the GtkSourceView bug report. # # The handling here is fragile, but it's better than # getting into a non-obvious corrupt state. buf.end_not_undoable_action() buf.end_user_action() if err.domain == GLib.quark_to_string( GtkSource.FileLoaderError.quark()): # TODO: Add custom reload-with-encoding handling for # GtkSource.FileLoaderError.CONVERSION_FALLBACK and # GtkSource.FileLoaderError.ENCODING_AUTO_DETECTION_FAILED pass filename = GLib.markup_escape_text( gfile.get_parse_name()) primary = _("There was a problem opening the file “%s”." % filename) # If we have custom errors defined, use those instead if errors.get(pane): error, error_text = errors[pane] else: error_text = err.message self.msgarea_mgr[pane].add_dismissable_msg( "dialog-error-symbolic", primary, error_text ) buf.data.state = MeldBufferState.LOAD_ERROR start, end = buf.get_bounds() buffer_text = buf.get_text(start, end, False) # Don't risk overwriting a more-important "we didn't load the file # correctly" message with this semi-helpful "is it binary?" prompt if ( not loader.get_encoding() and "\\00" in buffer_text and not self.msgarea_mgr[pane].has_message() ): filename = GLib.markup_escape_text(gfile.get_parse_name()) primary = _("File %s appears to be a binary file.") % filename secondary = _( "Do you want to open the file using the default application?") self.msgarea_mgr[pane].add_action_msg( 'dialog-warning-symbolic', primary, secondary, _("Open"), functools.partial(open_files_external, gfiles=[gfile])) # We checkpoint first, which will set modified state via the # checkpointed callback. We then check whether we're saving the # file to a different location than it was loaded from, in # which case we assume that this needs to be saved to persist # what the user is seeing. Finally, we update the writability, # which does label calculation. self.undosequence.checkpoint(buf) if buf.data.savefile: buf.set_modified(True) self.update_buffer_writable(buf) buf.data.update_mtime() buffer_states = [b.data.state for b in self.textbuffer[:self.num_panes]] if all(state == MeldBufferState.LOAD_FINISHED for state in buffer_states): self.scheduler.add_task(self._compare_files_internal()) def _merge_files(self): if self.comparison_mode == FileComparisonMode.AutoMerge: yield _("[%s] Merging files") % self.label_text merger = Merger() step = merger.initialize(self.buffer_filtered, self.buffer_texts) while next(step) is None: yield 1 for merged_text in merger.merge_3_files(): yield 1 self.linediffer.unresolved = merger.unresolved self.textbuffer[1].set_text(merged_text) self.recompute_label() else: yield 1 def _diff_files(self, refresh=False): yield _("[%s] Computing differences") % self.label_text texts = self.buffer_filtered[:self.num_panes] self.linediffer.ignore_blanks = self.props.ignore_blank_lines step = self.linediffer.set_sequences_iter(texts) while next(step) is None: yield 1 if not refresh: for buf in self.textbuffer: buf.place_cursor(buf.get_start_iter()) chunk, prev, next_ = self.linediffer.locate_chunk(1, 0) target_chunk = chunk if chunk is not None else next_ if target_chunk is not None: self.scheduler.add_task( lambda: self.go_to_chunk(target_chunk, centered=True), True) self.queue_draw() self._connect_buffer_handlers() self._set_merge_action_sensitivity() # Changing textview sensitivity removes focus and so triggers # our focus-out sensitivity handling. We manually trigger the # focus-in here to restablish the previous state. if self.cursor.pane is not None: self.on_textview_focus_in_event( self.textview[self.cursor.pane], None ) langs = [LanguageManager.get_language_from_file(buf.data.gfile) for buf in self.textbuffer[:self.num_panes]] # If we have only one identified language then we assume that all of # the files are actually of that type. real_langs = [lang for lang in langs if lang] if real_langs and real_langs.count(real_langs[0]) == len(real_langs): langs = (real_langs[0],) * len(langs) for i in range(self.num_panes): self.textbuffer[i].set_language(langs[i]) def _compare_files_internal(self): for i in self._merge_files(): yield i for i in self._diff_files(): yield i focus_pane = 0 if self.num_panes < 2 else 1 self.textview[focus_pane].grab_focus() def set_meta(self, meta): self.meta = meta labels = meta.get('labels', ()) if labels: for i, label in enumerate(labels): self.filelabel[i].props.custom_label = label def notify_file_changed(self, data): try: pane = [b.data for b in self.textbuffer].index(data) except ValueError: # Notification for unknown buffer return display_name = data.gfile.get_parse_name() primary = _("File %s has changed on disk") % display_name secondary = _("Do you want to reload the file?") self.msgarea_mgr[pane].add_action_msg( 'dialog-warning-symbolic', primary, secondary, _("_Reload"), self.action_revert) def refresh_comparison(self, *args): """Refresh the view by clearing and redoing all comparisons""" self.pre_comparison_init() self.queue_draw() self.scheduler.add_task(self._diff_files(refresh=True)) def _set_merge_action_sensitivity(self): if self.focus_pane: editable = self.focus_pane.get_editable() pane_idx = self.textview.index(self.focus_pane) mergeable = self.linediffer.has_mergeable_changes(pane_idx) else: editable = False mergeable = (False, False) self.set_action_enabled('merge-all-left', mergeable[0] and editable) self.set_action_enabled('merge-all-right', mergeable[1] and editable) if self.num_panes == 3 and self.textview[1].get_editable(): mergeable = self.linediffer.has_mergeable_changes(1) else: mergeable = (False, False) self.set_action_enabled('merge-all', mergeable[0] or mergeable[1]) def on_diffs_changed(self, linediffer, chunk_changes): for pane in range(self.num_panes): pane_changes = list(self.linediffer.single_changes(pane)) self.chunkmap[pane].chunks = pane_changes # TODO: Break out highlight recalculation to its own method, # and just update chunk lists in children here. for gutter in self.actiongutter: from_pane = self.textview.index(gutter.source_view) to_pane = self.textview.index(gutter.target_view) gutter.chunks = list(linediffer.paired_all_single_changes( from_pane, to_pane)) removed_chunks, added_chunks, modified_chunks = chunk_changes # We need to clear removed and modified chunks, and need to # re-highlight added and modified chunks. need_clearing = sorted( list(removed_chunks), key=merged_chunk_order) need_highlighting = sorted( list(added_chunks) + [modified_chunks], key=merged_chunk_order) alltags = [b.get_tag_table().lookup("inline") for b in self.textbuffer] for chunks in need_clearing: for i, chunk in enumerate(chunks): if not chunk or chunk.tag != "replace": continue to_idx = 2 if i == 1 else 0 bufs = self.textbuffer[1], self.textbuffer[to_idx] tags = alltags[1], alltags[to_idx] bufs[0].remove_tag(tags[0], *chunk.to_iters(buffer_a=bufs[0])) bufs[1].remove_tag(tags[1], *chunk.to_iters(buffer_b=bufs[1])) for chunks in need_highlighting: clear = chunks == modified_chunks for merge_cache_index, chunk in enumerate(chunks): if not chunk or chunk[0] != "replace": continue to_pane = 2 if merge_cache_index == 1 else 0 bufs = self.textbuffer[1], self.textbuffer[to_pane] tags = alltags[1], alltags[to_pane] buf_from_iters = chunk.to_iters(buffer_a=bufs[0]) buf_to_iters = chunk.to_iters(buffer_b=bufs[1]) # We don't use self.buffer_texts here, as removing line # breaks messes with inline highlighting in CRLF cases text1 = bufs[0].get_text(*buf_from_iters, False) textn = bufs[1].get_text(*buf_to_iters, False) # Bail on long sequences, rather than try a slow comparison inline_limit = 20000 if len(text1) + len(textn) > inline_limit and \ not self.force_highlight: bufs[0].apply_tag(tags[0], *buf_from_iters) bufs[1].apply_tag(tags[1], *buf_to_iters) self._prompt_long_highlighting() continue def apply_highlight( bufs, tags, start_marks, end_marks, texts, to_pane, chunk, matches): starts = [bufs[0].get_iter_at_mark(start_marks[0]), bufs[1].get_iter_at_mark(start_marks[1])] ends = [bufs[0].get_iter_at_mark(end_marks[0]), bufs[1].get_iter_at_mark(end_marks[1])] bufs[0].delete_mark(start_marks[0]) bufs[0].delete_mark(end_marks[0]) bufs[1].delete_mark(start_marks[1]) bufs[1].delete_mark(end_marks[1]) if not self.linediffer.has_chunk(to_pane, chunk): return text1 = bufs[0].get_text(starts[0], ends[0], False) textn = bufs[1].get_text(starts[1], ends[1], False) if texts != (text1, textn): return if clear: bufs[0].remove_tag(tags[0], starts[0], ends[0]) bufs[1].remove_tag(tags[1], starts[1], ends[1]) offsets = [ends[0].get_offset() - starts[0].get_offset(), ends[1].get_offset() - starts[1].get_offset()] def process_matches(match): if match.tag != "equal": return True # Always keep matches occurring at the start or end is_start = match.start_a == 0 and match.start_b == 0 is_end = ( match.end_a == offsets[0] and match.end_b == offsets[1]) if is_start or is_end: return False # Remove equal matches of size less than 3 too_short = ((match.end_a - match.start_a < 3) or (match.end_b - match.start_b < 3)) return too_short matches = [m for m in matches if process_matches(m)] for i in range(2): start, end = starts[i].copy(), starts[i].copy() offset = start.get_offset() for o in matches: start.set_offset(offset + o[1 + 2 * i]) end.set_offset(offset + o[2 + 2 * i]) # Check whether the identified difference is just a # combining diacritic. If so, we want to highlight # the visual character it's a part of if not start.is_cursor_position(): start.backward_cursor_position() if not end.is_cursor_position(): end.forward_cursor_position() bufs[i].apply_tag(tags[i], start, end) start_marks = [ bufs[0].create_mark(None, buf_from_iters[0], True), bufs[1].create_mark(None, buf_to_iters[0], True), ] end_marks = [ bufs[0].create_mark(None, buf_from_iters[1], True), bufs[1].create_mark(None, buf_to_iters[1], True), ] match_cb = functools.partial( apply_highlight, bufs, tags, start_marks, end_marks, (text1, textn), to_pane, chunk) self._cached_match.match(text1, textn, match_cb) self._cached_match.clean(self.linediffer.diff_count()) self._set_merge_action_sensitivity() # Check for self-comparison using Gio's file IDs, so that we catch # symlinks, admin:// URIs and similar situations. duplicate_file = None seen_file_ids = [] for tb in self.textbuffer: if not tb.data.gfile: continue if tb.data.file_id in seen_file_ids: duplicate_file = tb.data.label break seen_file_ids.append(tb.data.file_id) if duplicate_file: for index in range(self.num_panes): primary = _("File {} is being compared to itself").format(duplicate_file) self.msgarea_mgr[index].add_dismissable_msg( 'dialog-warning-symbolic', primary, '', self.msgarea_mgr) elif self.linediffer.sequences_identical(): error_message = True in [m.has_message() for m in self.msgarea_mgr] if self.num_panes == 1 or error_message: return for index, mgr in enumerate(self.msgarea_mgr): primary = _("Files are identical") secondary_text = None # TODO: Currently this only checks to see whether text filters # are active, and may be altering the comparison. It would be # better if we only showed this message if the filters *did* # change the text in question. active_filters = any([f.active for f in self.text_filters]) bufs = self.textbuffer[:self.num_panes] newlines = [b.data.sourcefile.get_newline_type() for b in bufs] different_newlines = not misc.all_same(newlines) if active_filters: secondary_text = _("Text filters are being used, and may " "be masking differences between files. " "Would you like to compare the " "unfiltered files?") elif different_newlines: primary = _("Files differ in line endings only") secondary_text = _( "Files are identical except for differing line " "endings:\n%s") labels = [b.data.label for b in bufs] newline_types = [ n if isinstance(n, tuple) else (n,) for n in newlines] newline_strings = [] for label, nl_types in zip(labels, newline_types): nl_string = ", ".join(NEWLINES[n][1] for n in nl_types) newline_strings.append("\t%s: %s" % (label, nl_string)) secondary_text %= "\n".join(newline_strings) msgarea = mgr.new_from_text_and_icon(primary, secondary_text) mgr.set_msg_id(FileDiff.MSG_SAME) button = msgarea.add_button(_("Hide"), Gtk.ResponseType.CLOSE) if index == 0: button.props.label = _("Hi_de") if active_filters: msgarea.add_button(_("Show without filters"), Gtk.ResponseType.OK) msgarea.connect("response", self.on_msgarea_identical_response) msgarea.show_all() else: for m in self.msgarea_mgr: if m.get_msg_id() == FileDiff.MSG_SAME: m.clear() def _prompt_long_highlighting(self): def on_msgarea_highlighting_response(msgarea, respid): for mgr in self.msgarea_mgr: mgr.clear() if respid == Gtk.ResponseType.OK: self.force_highlight = True self.refresh_comparison() for index, mgr in enumerate(self.msgarea_mgr): msgarea = mgr.new_from_text_and_icon( _("Change highlighting incomplete"), _("Some changes were not highlighted because they were too " "large. You can force Meld to take longer to highlight " "larger changes, though this may be slow."), ) mgr.set_msg_id(FileDiff.MSG_SLOW_HIGHLIGHT) button = msgarea.add_button(_("Hi_de"), Gtk.ResponseType.CLOSE) if index == 0: button.props.label = _("Hi_de") button = msgarea.add_button( _("Keep highlighting"), Gtk.ResponseType.OK) if index == 0: button.props.label = _("_Keep highlighting") msgarea.connect("response", on_msgarea_highlighting_response) msgarea.show_all() def on_msgarea_identical_response(self, msgarea, respid): for mgr in self.msgarea_mgr: mgr.clear() if respid == Gtk.ResponseType.OK: self.text_filters = [] self.refresh_comparison() @user_critical( _("Saving failed"), _("Please consider copying any critical changes to " "another program or file to avoid data loss."), ) def save_file(self, pane, saveas=False, force_overwrite=False): buf = self.textbuffer[pane] bufdata = buf.data if saveas or not (bufdata.gfile or bufdata.savefile) \ or not bufdata.writable: if pane == 0: prompt = _("Save Left Pane As") elif pane == 1 and self.num_panes == 3: prompt = _("Save Middle Pane As") else: prompt = _("Save Right Pane As") gfile = prompt_save_filename(prompt, self) if not gfile: return False bufdata.label = gfile.get_path() bufdata.gfile = gfile bufdata.savefile = None self.filelabel[pane].props.gfile = gfile if not force_overwrite and not bufdata.current_on_disk(): primary = ( _("File %s has changed on disk since it was opened") % bufdata.gfile.get_parse_name()) secondary = _("If you save it, any external changes will be lost.") msgarea = self.msgarea_mgr[pane].new_from_text_and_icon( primary, secondary, "dialog-warning-symbolic" ) msgarea.add_button(_("Save Anyway"), Gtk.ResponseType.ACCEPT) msgarea.add_button(_("Don’t Save"), Gtk.ResponseType.CLOSE) def on_file_changed_response(msgarea, response_id, *args): self.msgarea_mgr[pane].clear() if response_id == Gtk.ResponseType.ACCEPT: self.save_file(pane, saveas, force_overwrite=True) msgarea.connect("response", on_file_changed_response) msgarea.show_all() return False saver = GtkSource.FileSaver.new_with_target( self.textbuffer[pane], bufdata.sourcefile, bufdata.gfiletarget) # TODO: Think about removing this flag and above handling, and instead # handling the GtkSource.FileSaverError.EXTERNALLY_MODIFIED error if force_overwrite: saver.set_flags(GtkSource.FileSaverFlags.IGNORE_MODIFICATION_TIME) bufdata.disconnect_monitor() saver.save_async( GLib.PRIORITY_HIGH, callback=self.file_saved_cb, user_data=(pane,) ) return True def file_saved_cb(self, saver, result, user_data): gfile = saver.get_location() pane = user_data[0] buf = saver.get_buffer() buf.data.connect_monitor() try: saver.save_finish(result) except GLib.Error as err: # TODO: Handle recoverable error cases, like external modifications # or invalid buffer characters. filename = GLib.markup_escape_text( gfile.get_parse_name()) if err.matches(Gio.io_error_quark(), Gio.IOErrorEnum.INVALID_DATA): encoding = saver.get_file().get_encoding() secondary = _( "File “{}” contains characters that can’t be encoded " "using its current encoding “{}”." ).format(filename, encoding.to_string()) else: secondary = _("Couldn’t save file due to:\n%s") % ( GLib.markup_escape_text(str(err))) misc.error_dialog( primary=_("Could not save file %s.") % filename, secondary=secondary, ) self.state = ComparisonState.SavingError return self.file_changed_signal.emit(gfile.get_path()) self.undosequence.checkpoint(buf) buf.data.update_mtime() if pane == 1 and self.num_panes == 3: self.meta['middle_saved'] = True if self.state == ComparisonState.Closing: if not any(b.get_modified() for b in self.textbuffer): self.on_delete_event() else: self.state = ComparisonState.Normal def action_format_as_patch(self, *extra): dialog = PatchDialog(self) dialog.run() def update_buffer_writable(self, buf): writable = buf.data.writable self.recompute_label() index = self.textbuffer.index(buf) self.readonlytoggle[index].props.visible = not writable self.set_buffer_editable(buf, writable) def set_buffer_editable(self, buf, editable): index = self.textbuffer.index(buf) self.readonlytoggle[index].set_active(not editable) self.readonlytoggle[index].get_child().props.icon_name = ( 'changes-allow-symbolic' if editable else 'changes-prevent-symbolic') self.textview[index].set_editable(editable) self.on_cursor_position_changed(buf, None, True) @with_focused_pane def action_save(self, pane, *args): self.save_file(pane) @with_focused_pane def action_save_as(self, pane, *args): self.save_file(pane, saveas=True) def action_save_all(self, *args): for i in range(self.num_panes): if self.textbuffer[i].get_modified(): self.save_file(i) @Gtk.Template.Callback() def on_file_save_button_clicked(self, button): idx = self.file_save_button.index(button) self.save_file(idx) @Gtk.Template.Callback() def on_file_selected( self, button: Gtk.Button, pane: int, file: Gio.File) -> None: if not self.check_unsaved_changes(): return self.set_file(pane, file) def _get_focused_pane(self): for i in range(self.num_panes): if self.textview[i].is_focus(): return i return -1 def check_unsaved_changes(self, buffers=None): """Confirm discard of any unsaved changes Unlike `check_save_modified`, this does *not* prompt the user to save, but rather just confirms whether they want to discard changes. This simplifies call sites a *lot* because they don't then need to deal with the async state/callback issues associated with saving a file. """ buffers = buffers or self.textbuffer unsaved = [b.data.label for b in buffers if b.get_modified()] if not unsaved: return True builder = Gtk.Builder.new_from_resource( '/org/gnome/meld/ui/revert-dialog.ui') dialog = builder.get_object('revert_dialog') dialog.set_transient_for(self.get_toplevel()) filelist = Gtk.Label("\n".join(["\t• " + f for f in unsaved])) filelist.props.xalign = 0.0 filelist.show() message_area = dialog.get_message_area() message_area.pack_start(filelist, expand=False, fill=True, padding=0) response = dialog.run() dialog.destroy() return response == Gtk.ResponseType.OK def action_revert(self, *extra): if not self.check_unsaved_changes(): return buffers = self.textbuffer[:self.num_panes] gfiles = [b.data.gfile for b in buffers] encodings = [b.data.encoding for b in buffers] self.set_files(gfiles, encodings=encodings) def action_refresh(self, *extra): self.refresh_comparison() def queue_draw(self, junk=None): for t in self.textview: t.queue_draw() for i in range(self.num_panes - 1): self.linkmap[i].queue_draw() for gutter in self.actiongutter: gutter.queue_draw() @Gtk.Template.Callback() def on_readonly_button_toggled(self, button): index = self.readonlytoggle.index(button) buf = self.textbuffer[index] self.set_buffer_editable(buf, not button.get_active()) @with_scroll_lock('_sync_hscroll_lock') def _sync_hscroll(self, adjustment): val = adjustment.get_value() for sw in self.scrolledwindow[:self.num_panes]: adj = sw.get_hadjustment() if adj is not adjustment: adj.set_value(val) @with_scroll_lock('_sync_vscroll_lock') def _sync_vscroll(self, adjustment, master): syncpoint = misc.calc_syncpoint(adjustment) # Sync point in buffer coords; this will usually be the middle # of the screen, except at the top and bottom of the document. sync_y = ( adjustment.get_value() + adjustment.get_page_size() * syncpoint) # Find the target line. This is a float because, especially for # wrapped lines, the sync point may be half way through a line. # Not doing this calculation makes scrolling jerky. sync_iter, _ = self.textview[master].get_line_at_y(int(sync_y)) line_y, height = self.textview[master].get_line_yrange(sync_iter) height = height or 1 target_line = sync_iter.get_line() + ((sync_y - line_y) / height) # In the case of two pane scrolling, it's clear how to bind # scrollbars: if the user moves the left pane, we move the # right pane, and vice versa. # # For three pane scrolling, we want panes to be tied, but need # an influence mapping. In Meld, all influence flows through # the middle pane, e.g., the user moves the left pane, that # moves the middle pane, and the middle pane moves the right # pane. If the user moves the middle pane, then the left and # right panes are moved directly. scrollbar_influence = ((1, 2), (0, 2), (1, 0)) for i in scrollbar_influence[master][:self.num_panes - 1]: adj = self.scrolledwindow[i].get_vadjustment() # Find the chunk, or more commonly the space between # chunks, that contains the target line. # # This is a naive linear search that remains because it's # never shown up in profiles. We can't reuse our line cache # here; it doesn't have the necessary information in three- # way diffs. mbegin, mend = 0, self.textbuffer[master].get_line_count() obegin, oend = 0, self.textbuffer[i].get_line_count() for chunk in self.linediffer.pair_changes(master, i): if chunk.start_a >= target_line: mend = chunk.start_a oend = chunk.start_b break elif chunk.end_a >= target_line: mbegin, mend = chunk.start_a, chunk.end_a obegin, oend = chunk.start_b, chunk.end_b break else: mbegin = chunk.end_a obegin = chunk.end_b fraction = (target_line - mbegin) / ((mend - mbegin) or 1) other_line = obegin + fraction * (oend - obegin) # At this point, we've identified the line within the # corresponding chunk that we want to sync to. it = self.textbuffer[i].get_iter_at_line(int(other_line)) val, height = self.textview[i].get_line_yrange(it) # Special case line-height adjustment for EOF line_factor = 1.0 if it.is_end() else other_line - int(other_line) val += line_factor * height if syncpoint > 0.5: # If we're in the last half page, gradually factor in # the overscroll margin. overscroll_scale = (syncpoint - 0.5) / 0.5 overscroll_height = self.textview[i].get_bottom_margin() val += overscroll_height * overscroll_scale val -= adj.get_page_size() * syncpoint val = min(max(val, adj.get_lower()), adj.get_upper() - adj.get_page_size()) val = math.floor(val) adj.set_value(val) # If we just changed the central bar, make it the master if i == 1: master, target_line = 1, other_line # FIXME: We should really hook into the adjustments directly on # the widgets instead of doing this. for lm in self.linkmap: lm.queue_draw() for gutter in self.actiongutter: gutter.queue_draw() def set_num_panes(self, n): if n == self.num_panes or n not in (1, 2, 3): return self.num_panes = n for widget in ( self.vbox[:n] + self.file_toolbar[:n] + self.sourcemap[:n] + self.linkmap[:n - 1] + self.dummy_toolbar_linkmap[:n - 1] + self.statusbar[:n] + self.chunkmap[:n] + self.actiongutter[:(n - 1) * 2] + self.dummy_toolbar_actiongutter[:(n - 1) * 2]): widget.show() for widget in ( self.vbox[n:] + self.file_toolbar[n:] + self.sourcemap[n:] + self.linkmap[n - 1:] + self.dummy_toolbar_linkmap[n - 1:] + self.statusbar[n:] + self.chunkmap[n:] + self.actiongutter[(n - 1) * 2:] + self.dummy_toolbar_actiongutter[(n - 1) * 2:]): widget.hide() self.set_action_enabled('format-as-patch', n > 1) def chunk_iter(i): def chunks(bounds): for chunk in self.linediffer.single_changes(i, bounds): yield chunk return chunks def current_chunk_check(i): def chunks(change): chunk = self.linediffer.locate_chunk(i, change[1])[0] return chunk == self.cursor.chunk return chunks for (w, i) in zip(self.textview, range(self.num_panes)): w.chunk_iter = chunk_iter(i) w.current_chunk_check = current_chunk_check(i) for (w, i) in zip(self.linkmap, (0, self.num_panes - 2)): w.associate(self, self.textview[i], self.textview[i + 1]) for i in range(self.num_panes): self.file_save_button[i].set_sensitive( self.textbuffer[i].get_modified()) self.queue_draw() self.recompute_label() @with_focused_pane def action_cut(self, pane, *args): buffer = self.textbuffer[pane] view = self.textview[pane] clipboard = view.get_clipboard(Gdk.SELECTION_CLIPBOARD) buffer.cut_clipboard(clipboard, view.get_editable()) view.scroll_to_mark(buffer.get_insert(), 0.1, False, 0, 0) @with_focused_pane def action_copy(self, pane, *args): buffer = self.textbuffer[pane] view = self.textview[pane] clipboard = view.get_clipboard(Gdk.SELECTION_CLIPBOARD) buffer.copy_clipboard(clipboard) @with_focused_pane def action_paste(self, pane, *args): buffer = self.textbuffer[pane] view = self.textview[pane] clipboard = view.get_clipboard(Gdk.SELECTION_CLIPBOARD) buffer.paste_clipboard(clipboard, None, view.get_editable()) view.scroll_to_mark(buffer.get_insert(), 0.1, False, 0, 0) def copy_chunk(self, src, dst, chunk, copy_up): b0, b1 = self.textbuffer[src], self.textbuffer[dst] start = b0.get_iter_at_line_or_eof(chunk.start_a) end = b0.get_iter_at_line_or_eof(chunk.end_a) t0 = b0.get_text(start, end, False) if copy_up: if chunk.end_a >= b0.get_line_count() and \ chunk.start_b < b1.get_line_count(): # TODO: We need to insert a linebreak here, but there is no # way to be certain what kind of linebreak to use. t0 = t0 + "\n" dst_start = b1.get_iter_at_line_or_eof(chunk.start_b) mark0 = b1.create_mark(None, dst_start, True) new_end = b1.insert_at_line(chunk.start_b, t0) else: dst_start = b1.get_iter_at_line_or_eof(chunk.end_b) mark0 = b1.create_mark(None, dst_start, True) new_end = b1.insert_at_line(chunk.end_b, t0) mark1 = b1.create_mark(None, new_end, True) # FIXME: If the inserted chunk ends up being an insert chunk, then # this animation is not visible; this happens often in three-way diffs self.textview[dst].add_fading_highlight(mark0, mark1, 'insert', 500000) def replace_chunk(self, src, dst, chunk): b0, b1 = self.textbuffer[src], self.textbuffer[dst] src_start = b0.get_iter_at_line_or_eof(chunk.start_a) src_end = b0.get_iter_at_line_or_eof(chunk.end_a) dst_start = b1.get_iter_at_line_or_eof(chunk.start_b) dst_end = b1.get_iter_at_line_or_eof(chunk.end_b) t0 = b0.get_text(src_start, src_end, False) mark0 = b1.create_mark(None, dst_start, True) b1.begin_user_action() b1.delete(dst_start, dst_end) new_end = b1.insert_at_line(chunk.start_b, t0) b1.place_cursor(b1.get_iter_at_line(chunk.start_b)) b1.end_user_action() mark1 = b1.create_mark(None, new_end, True) if chunk.start_a == chunk.end_a: # TODO: Need a more specific colour here; conflict is wrong colour = 'conflict' else: # FIXME: If the inserted chunk ends up being an insert chunk, then # this animation is not visible; this happens often in three-way # diffs colour = 'insert' self.textview[dst].add_fading_highlight(mark0, mark1, colour, 500000) def delete_chunk(self, src, chunk): b0 = self.textbuffer[src] it = b0.get_iter_at_line_or_eof(chunk.start_a) if chunk.end_a >= b0.get_line_count(): # If this is the end of the buffer, we need to remove the # previous newline, because the current line has none. it.backward_cursor_position() b0.delete(it, b0.get_iter_at_line_or_eof(chunk.end_a)) mark0 = b0.create_mark(None, it, True) mark1 = b0.create_mark(None, it, True) # TODO: Need a more specific colour here; conflict is wrong self.textview[src].add_fading_highlight( mark0, mark1, 'conflict', 500000) @with_focused_pane def add_sync_point(self, pane, *args): cursor_it = self.textbuffer[pane].get_iter_at_mark( self.textbuffer[pane].get_insert()) self.syncpoints.add( pane, self.textbuffer[pane].create_mark(None, cursor_it) ) self.refresh_sync_points() @with_focused_pane def remove_sync_point(self, pane, *args): self.syncpoints.remove(pane, self.textbuffer[pane].get_insert()) self.refresh_sync_points() def refresh_sync_points(self): for i, t in enumerate(self.textview[:self.num_panes]): t.syncpoints = self.syncpoints.points(i) def make_line_retriever(pane, marks): buf = self.textbuffer[pane] mark = marks[pane] def get_line_for_mark(): return buf.get_iter_at_mark(mark).get_line() return get_line_for_mark valid_points = self.syncpoints.valid_points() if valid_points and self.num_panes == 2: self.linediffer.syncpoints = [ ((make_line_retriever(1, p), make_line_retriever(0, p)), ) for p in valid_points ] elif valid_points and self.num_panes == 3: self.linediffer.syncpoints = [ ((make_line_retriever(1, p), make_line_retriever(0, p)), (make_line_retriever(1, p), make_line_retriever(2, p))) for p in valid_points ] elif not valid_points: self.linediffer.syncpoints = [] if valid_points: for mgr in self.msgarea_mgr: msgarea = mgr.new_from_text_and_icon( _("Live comparison updating disabled"), _("Live updating of comparisons is disabled when " "synchronization points are active. You can still " "manually refresh the comparison, and live updates will " "resume when synchronization points are cleared."), ) mgr.set_msg_id(FileDiff.MSG_SYNCPOINTS) msgarea.show_all() self.refresh_comparison() def clear_sync_points(self, *args): self.syncpoints.clear() self.linediffer.syncpoints = [] for t in self.textview: t.syncpoints = [] for mgr in self.msgarea_mgr: if mgr.get_msg_id() == FileDiff.MSG_SYNCPOINTS: mgr.clear() self.refresh_comparison() def action_swap(self, *args): buffers = self.textbuffer[:self.num_panes] gfiles = [buf.data.gfile for buf in buffers] have_unnamed_files = any(gfile is None for gfile in gfiles) have_modified_files = any(buf.get_modified() for buf in buffers) if have_unnamed_files or have_modified_files: misc.error_dialog( primary=_("Can't swap unsaved files"), secondary=_( "Files must be saved to disk before swapping panes." ) ) return if self.meta.get("tablabel", None): misc.error_dialog( primary=_("Can't swap version control comparisons"), secondary=_( "Swapping panes is not supported in version control mode." ) ) return self.set_labels([self.filelabel[1].props.label, self.filelabel[0].props.label]) self.set_files([gfiles[1], gfiles[0]]) FileDiff.set_css_name('meld-file-diff') class SyncpointAction(Enum): # A dangling syncpoint can be moved to the line MOVE = "move" # A dangling syncpoint sits can be remove from this line DELETE = "delete" # A syncpoint can be added to this line to match existing ones # in other panes MATCH = "match" # A new, dangling syncpoint can be added to this line ADD = "add" # No syncpoint-related action can be taken on this line DISABLED = "disabled" class Syncpoints: def __init__(self, num_panes: int, comparator): self._num_panes = num_panes self._points = [[] for _i in range(0, num_panes)] self._comparator = comparator def add(self, pane_idx: int, point): pane_state = self._pane_state(pane_idx) if pane_state == self.PaneState.DANGLING: self._points[pane_idx].pop() self._points[pane_idx].append(point) lengths = set(len(p) for p in self._points) if len(lengths) == 1: for (i, p) in enumerate(self._points): p.sort(key=lambda point: self._comparator(i, point)) def remove(self, pane_idx: int, cursor_point): cursor_key = self._comparator(pane_idx, cursor_point) index = -1 for (i, point) in enumerate(self._points[pane_idx]): if self._comparator(pane_idx, point) == cursor_key: index = i break assert index is not None pane_state = self._pane_state(pane_idx) assert pane_state != self.PaneState.SHORT if pane_state == self.PaneState.MATCHED: for pane in self._points: pane.pop(index) elif pane_state == self.PaneState.DANGLING: self._points[pane_idx].pop() def clear(self): self._points = [[] for _i in range(0, self._num_panes)] def points(self, pane_idx: int): return self._points[pane_idx].copy() def valid_points(self): num_matched = min(len(p) for p in self._points) if not num_matched: return [] matched = [p[:num_matched] for p in self._points] return [ tuple(matched_point[i] for matched_point in matched) for i in range(0, num_matched) ] def _pane_state(self, pane_idx: int): lengths = set(len(points) for points in self._points) if len(lengths) == 1: return self.PaneState.MATCHED if len(self._points[pane_idx]) == min(lengths): return self.PaneState.SHORT else: return self.PaneState.DANGLING def action(self, pane_idx: int, get_mark): state = self._pane_state(pane_idx) if state == self.PaneState.SHORT: return SyncpointAction.MATCH target = self._comparator(pane_idx, get_mark()) points = self._points[pane_idx] if state == self.PaneState.MATCHED: is_syncpoint = any( self._comparator(pane_idx, point) == target for point in points ) if is_syncpoint: return SyncpointAction.DELETE else: return SyncpointAction.ADD # state == DANGLING if target == self._comparator(pane_idx, points[-1]): return SyncpointAction.DELETE is_syncpoint = any( self._comparator(pane_idx, point) == target for point in points ) if is_syncpoint: return SyncpointAction.DISABLED else: return SyncpointAction.MOVE class PaneState(Enum): # The state of a pane with all its syncpoints matched MATCHED = "matched" # The state of a pane waiting to be matched to existing syncpoints # in other panes SHORT = "short" # The state of a pane with a dangling syncpoint, not yet matched # across all panes DANGLING = "DANGLING"
114,491
Python
.py
2,402
36.068693
91
0.59663
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,832
menuhelpers.py
GNOME_meld/meld/menuhelpers.py
from gi.repository import Gio def replace_menu_section(menu: Gio.Menu, section: Gio.MenuItem): """Replaces an existing section in GMenu `menu` with `section` The sections are compared by their `id` attributes, with the matching section in `menu` being replaced by the passed `section`. If there is no section in `menu` that matches `section`'s `id` attribute, a ValueError is raised. """ section_id = section.get_attribute_value("id").get_string() for idx in range(menu.get_n_items()): item_id = menu.get_item_attribute_value(idx, "id").get_string() if item_id == section_id: break else: # FIXME: Better exception raise ValueError("Section %s not found" % section_id) menu.remove(idx) menu.insert_item(idx, section)
809
Python
.py
18
38.777778
71
0.678117
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,833
gutterrendererchunk.py
GNOME_meld/meld/gutterrendererchunk.py
# Copyright (C) 2013-2014 Kai Willadsen <kai.willadsen@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or (at # your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import math from typing import Any from gi.repository import Gdk, GtkSource, Pango from meld.settings import get_meld_settings from meld.style import get_common_theme from meld.ui.gtkutil import make_gdk_rgba def get_background_rgba(renderer): '''Get and cache the expected background for the renderer widget Current versions of GTK+ don't paint the background of text view gutters with the actual expected widget background, which causes them to look wrong when put next to any other widgets. This hack just gets the background from the renderer's view, and then caches it for performance, and on the basis that all renderers will be assigned to similarly-styled views. This is fragile, but the alternative is really significantly slower. ''' global _background_rgba if _background_rgba is None: if renderer.props.view: stylecontext = renderer.props.view.get_style_context() background_set, _background_rgba = ( stylecontext.lookup_color('theme_bg_color')) return _background_rgba _background_rgba = None class MeldGutterRenderer: def set_renderer_defaults(self): self.set_alignment_mode(GtkSource.GutterRendererAlignmentMode.FIRST) self.props.xpad = 3 self.props.ypad = 0 self.props.xalign = 0.5 self.props.yalign = 0.5 def on_setting_changed(self, settings, key): if key == 'style-scheme': self.fill_colors, self.line_colors = get_common_theme() alpha = self.fill_colors['current-chunk-highlight'].alpha self.chunk_highlights = { state: make_gdk_rgba(*[alpha + c * (1.0 - alpha) for c in colour]) for state, colour in self.fill_colors.items() } def draw_chunks( self, context, background_area, cell_area, start, end, state): chunk = self._chunk if not chunk: return line = start.get_line() is_first_line = line == chunk[1] is_last_line = line == chunk[2] - 1 if not (is_first_line or is_last_line): # Only paint for the first and last lines of a chunk return x = background_area.x - 1 y = background_area.y width = background_area.width + 2 height = 1 if chunk[1] == chunk[2] else background_area.height context.set_line_width(1.0) Gdk.cairo_set_source_rgba(context, self.line_colors[chunk[0]]) if is_first_line: context.move_to(x, y + 0.5) context.rel_line_to(width, 0) if is_last_line: context.move_to(x, y - 0.5 + height) context.rel_line_to(width, 0) context.stroke() def query_chunks(self, start, end, state): line = start.get_line() chunk_index = self.linediffer.locate_chunk(self.from_pane, line)[0] in_chunk = chunk_index is not None chunk = None if in_chunk: chunk = self.linediffer.get_chunk( chunk_index, self.from_pane, self.to_pane) if chunk is not None: if chunk[1] == chunk[2]: background_rgba = get_background_rgba(self) elif self.props.view.current_chunk_check(chunk): background_rgba = self.chunk_highlights[chunk[0]] else: background_rgba = self.fill_colors[chunk[0]] else: # TODO: Remove when fixed in upstream GTK+ background_rgba = get_background_rgba(self) self._chunk = chunk self.set_background(background_rgba) return in_chunk # GutterRendererChunkLines is an adaptation of GtkSourceGutterRendererLines # Copyright (C) 2010 - Jesse van den Kieboom # # Python reimplementation is Copyright (C) 2015 Kai Willadsen class GutterRendererChunkLines( GtkSource.GutterRendererText, MeldGutterRenderer): __gtype_name__ = "GutterRendererChunkLines" def __init__(self, from_pane, to_pane, linediffer): super().__init__() self.set_renderer_defaults() self.from_pane = from_pane self.to_pane = to_pane # FIXME: Don't pass in the linediffer; pass a generator like elsewhere self.linediffer = linediffer self.num_line_digits = 0 self.changed_handler_id = None meld_settings = get_meld_settings() meld_settings.connect('changed', self.on_setting_changed) self.font_string = meld_settings.font.to_string() self.on_setting_changed(meld_settings, 'style-scheme') self.connect("notify::view", self.on_view_changed) def on_view_changed(self, *args: Any) -> None: if not self.get_view(): return self.get_view().connect("style-updated", self.on_view_style_updated) def on_view_style_updated(self, view: GtkSource.View) -> None: stylecontext = view.get_style_context() # We should be using stylecontext.get_property, but it doesn't work # for reasons that according to the GTK code are "Yuck". font = stylecontext.get_font(stylecontext.get_state()) font_string = font.to_string() need_recalculate = font_string != self.font_string buf = self.get_view().get_buffer() self.font_string = font_string self.recalculate_size(buf, force=need_recalculate) def do_change_buffer(self, old_buffer): if old_buffer: old_buffer.disconnect(self.changed_handler_id) view = self.get_view() if view: buf = view.get_buffer() if buf: self.changed_handler_id = buf.connect( "changed", self.recalculate_size) self.recalculate_size(buf) def _measure_markup(self, markup): layout = self.get_view().create_pango_layout() layout.set_markup(markup) w, h = layout.get_size() return w / Pango.SCALE, h / Pango.SCALE def recalculate_size( self, buf: GtkSource.Buffer, force: bool = False, ) -> None: # Always calculate display size for at least two-digit line counts num_lines = max(buf.get_line_count(), 99) num_digits = int(math.ceil(math.log(num_lines, 10))) if num_digits == self.num_line_digits and not force: return self.num_line_digits = num_digits markup = "<b>%d</b>" % num_lines width, height = self._measure_markup(markup) self.set_size(width) def do_draw(self, context, background_area, cell_area, start, end, state): GtkSource.GutterRendererText.do_draw( self, context, background_area, cell_area, start, end, state) self.draw_chunks( context, background_area, cell_area, start, end, state) def do_query_data(self, start, end, state): self.query_chunks(start, end, state) line = start.get_line() + 1 current_line = state & GtkSource.GutterRendererState.CURSOR markup = "<b>%d</b>" % line if current_line else str(line) self.set_markup(markup, -1)
7,826
Python
.py
173
36.786127
82
0.64753
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,834
externalhelpers.py
GNOME_meld/meld/externalhelpers.py
# Copyright (C) 2002-2006 Stephen Kennedy <stevek@gnome.org> # Copyright (C) 2011-2014, 2018-2019, 2024 Kai Willadsen <kai.willadsen@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or (at # your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import logging import os import shlex import string import subprocess import sys from typing import List, Mapping, Sequence from gi.repository import Gdk, Gio, GLib, Gtk from meld.conf import _ from meld.misc import modal_dialog from meld.settings import get_settings log = logging.getLogger(__name__) OPEN_EXTERNAL_QUERY_ATTRS = ",".join( ( Gio.FILE_ATTRIBUTE_STANDARD_TYPE, Gio.FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE, ) ) def make_custom_editor_command(path: str, line: int = 0) -> Sequence[str]: custom_command = get_settings().get_string("custom-editor-command") fmt = string.Formatter() replacements = [tok[1] for tok in fmt.parse(custom_command)] if not any(replacements): return [custom_command, path] elif not all(r in (None, "file", "line") for r in replacements): log.error("Unsupported fields found") return [custom_command, path] else: cmd = custom_command.format(file=shlex.quote(path), line=line) return shlex.split(cmd) def launch_with_default_handler(gfile: Gio.File) -> None: # Ideally this function wouldn't exist, but the gtk_show_uri cross-platform # handling is less reliable than doing the below. if sys.platform in ("darwin", "win32"): path = gfile.get_path() if not path: log.warning(f"Couldn't open file {gfile.get_uri()}; no valid path") if sys.platform == "win32": os.startfile(gfile.get_path()) else: # sys.platform == "darwin" subprocess.Popen(["open", path]) else: Gtk.show_uri( Gdk.Screen.get_default(), gfile.get_uri(), Gtk.get_current_event_time(), ) def open_cb( gfile: Gio.File, result: Gio.AsyncResult, user_data: Mapping[str, int], ) -> None: info = gfile.query_info_finish(result) file_type = info.get_file_type() if file_type == Gio.FileType.DIRECTORY: launch_with_default_handler(gfile) elif file_type == Gio.FileType.REGULAR: # If we can't access a content type, we assume it's text because # context types aren't reliably detected cross-platform. content_type = info.get_content_type() if not content_type or Gio.content_type_is_a(content_type, "text/plain"): if get_settings().get_boolean("use-system-editor"): if sys.platform == "win32": handler = gfile.query_default_handler(None) result = handler.launch([gfile], None) else: Gio.AppInfo.launch_default_for_uri(gfile.get_uri(), None) else: line = user_data.get("line", 0) path = gfile.get_path() editor = make_custom_editor_command(path, line) if editor: try: subprocess.Popen(editor) except OSError as e: modal_dialog( _("Failed to launch custom editor"), str(e), Gtk.ButtonsType.CLOSE, ) else: launch_with_default_handler(gfile) else: launch_with_default_handler(gfile) else: # Being guarded about value_nick here, since it's probably not # exactly guaranteed API. file_type = getattr(file_type, "value_nick", "unknown") modal_dialog( _("Unsupported file type"), _("External opening of files of type {file_type} is not supported").format( file_type=file_type ), Gtk.ButtonsType.CLOSE, ) def open_files_external( gfiles: List[Gio.File], *, line: int = 0, ) -> None: for f in gfiles: f.query_info_async( OPEN_EXTERNAL_QUERY_ATTRS, Gio.FileQueryInfoFlags.NONE, GLib.PRIORITY_LOW, None, open_cb, {"line": line}, )
4,835
Python
.py
124
30.33871
87
0.61504
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,835
myers.py
GNOME_meld/meld/matchers/myers.py
# Copyright (C) 2009-2013 Piotr Piastucki <the_leech@users.berlios.de> # Copyright (C) 2012-2013 Kai Willadsen <kai.willadsen@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or (at # your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import difflib import typing if typing.TYPE_CHECKING: from gi.repository import Gtk def find_common_prefix(a, b): if not a or not b: return 0 if a[0] == b[0]: pointermax = min(len(a), len(b)) pointermid = pointermax pointermin = 0 while pointermin < pointermid: if a[pointermin:pointermid] == b[pointermin:pointermid]: pointermin = pointermid else: pointermax = pointermid pointermid = int((pointermax - pointermin) // 2 + pointermin) return pointermid return 0 def find_common_suffix(a, b): if not a or not b: return 0 if a[-1] == b[-1]: pointermax = min(len(a), len(b)) pointermid = pointermax pointermin = 0 while pointermin < pointermid: a_tail = a[-pointermid:len(a) - pointermin] b_tail = b[-pointermid:len(b) - pointermin] if a_tail == b_tail: pointermin = pointermid else: pointermax = pointermid pointermid = int((pointermax - pointermin) // 2 + pointermin) return pointermid return 0 class DiffChunk(typing.NamedTuple): tag: str start_a: int end_a: int start_b: int end_b: int def to_iters( self, *, buffer_a=None, buffer_b=None ) -> tuple["Gtk.TextIter", "Gtk.TextIter"]: if buffer_a and buffer_b: raise ValueError("Only pass one buffer argument at a time") elif not (buffer_a or buffer_b): raise ValueError("Buffer argument missing") if buffer_a: buffer, start, end = buffer_a, self.start_a, self.end_a else: buffer, start, end = buffer_b, self.start_b, self.end_b return ( buffer.get_iter_at_line_or_eof(start), buffer.get_iter_at_line_or_eof(end), ) class MyersSequenceMatcher(difflib.SequenceMatcher): def __init__(self, isjunk=None, a="", b=""): if isjunk is not None: raise NotImplementedError('isjunk is not supported yet') # The sequences we're comparing must be considered immutable; # calling e.g., GtkTextBuffer methods to retrieve these line-by-line # isn't really a thing we can or should do. self.a = a[:] self.b = b[:] self.matching_blocks = self.opcodes = None self.aindex = [] self.bindex = [] self.common_prefix = self.common_suffix = 0 self.lines_discarded = False def get_matching_blocks(self): if self.matching_blocks is None: for i in self.initialise(): pass return self.matching_blocks def get_opcodes(self): opcodes = super().get_opcodes() return [DiffChunk._make(chunk) for chunk in opcodes] def get_difference_opcodes(self): return [chunk for chunk in self.get_opcodes() if chunk.tag != "equal"] def preprocess_remove_prefix_suffix(self, a, b): # remove common prefix and common suffix self.common_prefix = self.common_suffix = 0 self.common_prefix = find_common_prefix(a, b) if self.common_prefix > 0: a = a[self.common_prefix:] b = b[self.common_prefix:] if len(a) > 0 and len(b) > 0: self.common_suffix = find_common_suffix(a, b) if self.common_suffix > 0: a = a[:len(a) - self.common_suffix] b = b[:len(b) - self.common_suffix] return (a, b) def preprocess_discard_nonmatching_lines(self, a, b): # discard lines that do not match any line from the other file if len(a) == 0 or len(b) == 0: self.aindex = [] self.bindex = [] return (a, b) def index_matching(a, b): aset = frozenset(a) matches, index = [], [] for i, line in enumerate(b): if line in aset: matches.append(line) index.append(i) return matches, index indexed_b, self.bindex = index_matching(a, b) indexed_a, self.aindex = index_matching(b, a) # We only use the optimised result if it's worthwhile. The constant # represents a heuristic of how many lines constitute 'worthwhile'. self.lines_discarded = (len(b) - len(indexed_b) > 10 or len(a) - len(indexed_a) > 10) if self.lines_discarded: a = indexed_a b = indexed_b return (a, b) def preprocess(self): """ Pre-processing optimizations: 1) remove common prefix and common suffix 2) remove lines that do not match """ a, b = self.preprocess_remove_prefix_suffix(self.a, self.b) return self.preprocess_discard_nonmatching_lines(a, b) def postprocess(self): """ Perform some post-processing cleanup to reduce 'chaff' and make the result more human-readable. Since Myers diff is a greedy algorithm backward scanning of matching chunks might reveal some smaller chunks that can be combined together. """ mb = [self.matching_blocks[-1]] i = len(self.matching_blocks) - 2 while i >= 0: cur_a, cur_b, cur_len = self.matching_blocks[i] i -= 1 while i >= 0: prev_a, prev_b, prev_len = self.matching_blocks[i] if prev_b + prev_len == cur_b or prev_a + prev_len == cur_a: prev_slice_a = self.a[cur_a - prev_len:cur_a] prev_slice_b = self.b[cur_b - prev_len:cur_b] if prev_slice_a == prev_slice_b: cur_b -= prev_len cur_a -= prev_len cur_len += prev_len i -= 1 continue break mb.append((cur_a, cur_b, cur_len)) mb.reverse() self.matching_blocks = mb def build_matching_blocks(self, lastsnake): """Build list of matching blocks based on snakes The resulting blocks take into consideration multiple preprocessing optimizations: * add separate blocks for common prefix and suffix * shift positions and split blocks based on the list of discarded non-matching lines """ self.matching_blocks = matching_blocks = [] common_prefix = self.common_prefix common_suffix = self.common_suffix aindex = self.aindex bindex = self.bindex while lastsnake is not None: lastsnake, x, y, snake = lastsnake if self.lines_discarded: # split snakes if needed because of discarded lines x += snake - 1 y += snake - 1 xprev = aindex[x] + common_prefix yprev = bindex[y] + common_prefix if snake > 1: newsnake = 1 for i in range(1, snake): x -= 1 y -= 1 xnext = aindex[x] + common_prefix ynext = bindex[y] + common_prefix if (xprev - xnext != 1) or (yprev - ynext != 1): matching_blocks.insert(0, (xprev, yprev, newsnake)) newsnake = 0 xprev = xnext yprev = ynext newsnake += 1 matching_blocks.insert(0, (xprev, yprev, newsnake)) else: matching_blocks.insert(0, (xprev, yprev, snake)) else: matching_blocks.insert(0, (x + common_prefix, y + common_prefix, snake)) if common_prefix: matching_blocks.insert(0, (0, 0, common_prefix)) if common_suffix: matching_blocks.append((len(self.a) - common_suffix, len(self.b) - common_suffix, common_suffix)) matching_blocks.append((len(self.a), len(self.b), 0)) # clean-up to free memory self.aindex = self.bindex = None def initialise(self): """ Optimized implementation of the O(NP) algorithm described by Sun Wu, Udi Manber, Gene Myers, Webb Miller ("An O(NP) Sequence Comparison Algorithm", 1989) http://research.janelia.org/myers/Papers/np_diff.pdf """ a, b = self.preprocess() m = len(a) n = len(b) middle = m + 1 lastsnake = None delta = n - m + middle dmin = min(middle, delta) dmax = max(middle, delta) if n > 0 and m > 0: size = n + m + 2 fp = [(-1, None)] * size p = -1 while True: p += 1 if not p % 100: yield None # move along vertical edge yv = -1 node = None for km in range(dmin - p, delta, 1): t = fp[km + 1] if yv < t[0]: yv, node = t else: yv += 1 x = yv - km + middle if x < m and yv < n and a[x] == b[yv]: snake = x x += 1 yv += 1 while x < m and yv < n and a[x] == b[yv]: x += 1 yv += 1 snake = x - snake node = (node, x - snake, yv - snake, snake) fp[km] = (yv, node) # move along horizontal edge yh = -1 node = None for km in range(dmax + p, delta, -1): t = fp[km - 1] if yh <= t[0]: yh, node = t yh += 1 x = yh - km + middle if x < m and yh < n and a[x] == b[yh]: snake = x x += 1 yh += 1 while x < m and yh < n and a[x] == b[yh]: x += 1 yh += 1 snake = x - snake node = (node, x - snake, yh - snake, snake) fp[km] = (yh, node) # point on the diagonal that leads to the sink if yv < yh: y, node = fp[delta + 1] else: y, node = fp[delta - 1] y += 1 x = y - delta + middle if x < m and y < n and a[x] == b[y]: snake = x x += 1 y += 1 while x < m and y < n and a[x] == b[y]: x += 1 y += 1 snake = x - snake node = (node, x - snake, y - snake, snake) fp[delta] = (y, node) if y >= n: lastsnake = node break self.build_matching_blocks(lastsnake) self.postprocess() yield 1 class InlineMyersSequenceMatcher(MyersSequenceMatcher): def preprocess_discard_nonmatching_lines(self, a, b): if len(a) <= 2 and len(b) <= 2: self.aindex = [] self.bindex = [] return (a, b) def index_matching_kmers(a, b): aset = set([a[i:i + 3] for i in range(len(a) - 2)]) matches, index = [], [] next_poss_match = 0 # Start from where we can get a valid triple for i in range(2, len(b)): if b[i - 2:i + 1] not in aset: continue # Make sure we don't re-record matches from overlapping kmers for j in range(max(next_poss_match, i - 2), i + 1): matches.append(b[j]) index.append(j) next_poss_match = i + 1 return matches, index indexed_b, self.bindex = index_matching_kmers(a, b) indexed_a, self.aindex = index_matching_kmers(b, a) # We only use the optimised result if it's worthwhile. The constant # represents a heuristic of how many lines constitute 'worthwhile'. self.lines_discarded = (len(b) - len(indexed_b) > 10 or len(a) - len(indexed_a) > 10) if self.lines_discarded: a = indexed_a b = indexed_b return (a, b) class SyncPointMyersSequenceMatcher(MyersSequenceMatcher): def __init__(self, isjunk=None, a="", b="", syncpoints=None): super().__init__(isjunk, a, b) self.isjunk = isjunk self.syncpoints = syncpoints def initialise(self): if self.syncpoints is None or len(self.syncpoints) == 0: for i in super().initialise(): yield i else: chunks = [] ai = 0 bi = 0 for aj, bj in self.syncpoints: chunks.append((ai, bi, self.a[ai:aj], self.b[bi:bj])) ai = aj bi = bj if ai < len(self.a) or bi < len(self.b): chunks.append((ai, bi, self.a[ai:], self.b[bi:])) self.split_matching_blocks = [] self.matching_blocks = [] for ai, bi, a, b in chunks: matching_blocks = [] matcher = MyersSequenceMatcher(self.isjunk, a, b) for i in matcher.initialise(): yield None blocks = matcher.get_matching_blocks() mb_len = len(matching_blocks) - 1 if mb_len >= 0 and len(blocks) > 1: aj = matching_blocks[mb_len][0] bj = matching_blocks[mb_len][1] bl = matching_blocks[mb_len][2] if (aj + bl == ai and bj + bl == bi and blocks[0][0] == 0 and blocks[0][1] == 0): block = blocks.pop(0) matching_blocks[mb_len] = (aj, bj, bl + block[2]) for x, y, length in blocks[:-1]: matching_blocks.append((ai + x, bi + y, length)) self.matching_blocks.extend(matching_blocks) # Split matching blocks each need to be terminated to get our # split chunks correctly created self.split_matching_blocks.append( matching_blocks + [(ai + len(a), bi + len(b), 0)]) self.matching_blocks.append((len(self.a), len(self.b), 0)) yield 1 def get_opcodes(self): # This is just difflib.SequenceMatcher.get_opcodes in which we instead # iterate over our internal set of split matching blocks. if self.opcodes is not None: return self.opcodes i = j = 0 self.opcodes = opcodes = [] self.get_matching_blocks() for matching_blocks in self.split_matching_blocks: for ai, bj, size in matching_blocks: tag = '' if i < ai and j < bj: tag = 'replace' elif i < ai: tag = 'delete' elif j < bj: tag = 'insert' if tag: opcodes.append((tag, i, ai, j, bj)) i, j = ai + size, bj + size # the list of matching blocks is terminated by a # sentinel with size 0 if size: opcodes.append(('equal', ai, i, bj, j)) return [DiffChunk._make(chunk) for chunk in opcodes]
16,835
Python
.py
402
28.154229
79
0.498353
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,836
merge.py
GNOME_meld/meld/matchers/merge.py
# Copyright (C) 2009-2010 Piotr Piastucki <the_leech@users.berlios.de> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or (at # your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from meld.matchers import diffutil from meld.matchers.myers import MyersSequenceMatcher LO, HI = 1, 2 class AutoMergeDiffer(diffutil.Differ): _matcher = MyersSequenceMatcher # _matcher = PatienceSequenceMatcher def __init__(self): super().__init__() self.auto_merge = False self.unresolved = [] def _auto_merge(self, using, texts): for out0, out1 in super()._auto_merge(using, texts): if self.auto_merge and out0[0] == 'conflict': # we will try to resolve more complex conflicts automatically # here... if possible l0, h0, l1, h1, l2, h2 = ( out0[3], out0[4], out0[1], out0[2], out1[3], out1[4]) len0 = h0 - l0 len1 = h1 - l1 len2 = h2 - l2 if (len0 > 0 and len2 > 0) and ( len0 == len1 or len2 == len1 or len1 == 0): matcher = self._matcher( None, texts[0][l0:h0], texts[2][l2:h2]) for chunk in matcher.get_opcodes(): s1 = l1 e1 = l1 if len0 == len1: s1 += chunk[1] e1 += chunk[2] elif len2 == len1: s1 += chunk[3] e1 += chunk[4] out0_bounds = (s1, e1, l0 + chunk[1], l0 + chunk[2]) out1_bounds = (s1, e1, l2 + chunk[3], l2 + chunk[4]) if chunk[0] == 'equal': out0 = ('replace',) + out0_bounds out1 = ('replace',) + out1_bounds yield out0, out1 else: out0 = ('conflict',) + out0_bounds out1 = ('conflict',) + out1_bounds yield out0, out1 return # elif len0 > 0 and len2 > 0: # # this logic will resolve more conflicts automatically, # # but unresolved conflicts may sometimes look confusing # # as the line numbers in ancestor file will be # # interpolated and may not reflect the actual changes # matcher = self._matcher( # None, texts[0][l0:h0], texts[2][l2:h2]) # if len0 > len2: # maxindex = 1 # maxlen = len0 # else: # maxindex = 3 # maxlen = len2 # for chunk in matcher.get_opcodes(): # new_start = l1 + len1 * chunk[maxindex] / maxlen # new_end = l1 + len1 * chunk[maxindex + 1] / maxlen # out0_bounds = ( # new_start, new_end, l0 + chunk[1], l0 + chunk[2]) # out1_bounds = ( # new_start, new_end, l2 + chunk[3], l2 + chunk[4]) # if chunk[0] == 'equal': # out0 = ('replace',) + out0_bounds # out1 = ('replace',) + out1_bounds # yield out0, out1 # else: # out0 = ('conflict',) + out0_bounds # out1 = ('conflict',) + out1_bounds # yield out0, out1 # return else: # some tricks to resolve even more conflicts automatically # unfortunately the resulting chunks cannot be used to # highlight changes but hey, they are good enough to merge # the resulting file :) chunktype = using[0][0][0] for chunkarr in using: for chunk in chunkarr: if chunk[0] != chunktype: chunktype = None break if not chunktype: break if chunktype == 'delete': # delete + delete -> split into delete/conflict seq0 = seq1 = None while 1: if seq0 is None: try: seq0 = using[0].pop(0) i0 = seq0[1] end0 = seq0[4] except IndexError: break if seq1 is None: try: seq1 = using[1].pop(0) i1 = seq1[1] end1 = seq1[4] except IndexError: break highstart = max(i0, i1) if i0 != i1: out0 = ( 'conflict', i0 - highstart + i1, highstart, seq0[3] - highstart + i1, seq0[3] ) out1 = ( 'conflict', i1 - highstart + i0, highstart, seq1[3] - highstart + i0, seq1[3] ) yield out0, out1 lowend = min(seq0[2], seq1[2]) if highstart != lowend: out0 = ( 'delete', highstart, lowend, seq0[3], seq0[4] ) out1 = ( 'delete', highstart, lowend, seq1[3], seq1[4] ) yield out0, out1 i0 = i1 = lowend if lowend == seq0[2]: seq0 = None if lowend == seq1[2]: seq1 = None if seq0: out0 = ( 'conflict', i0, seq0[2], seq0[3], seq0[4] ) out1 = ( 'conflict', i0, seq0[2], end1, end1 + seq0[2] - i0 ) yield out0, out1 elif seq1: out0 = ( 'conflict', i1, seq1[2], end0, end0 + seq1[2] - i1 ) out1 = ( 'conflict', i1, seq1[2], seq1[3], seq1[4] ) yield out0, out1 return yield out0, out1 def change_sequence(self, sequence, startidx, sizechange, texts): if sequence == 1: lo = 0 for c in self.unresolved: if startidx <= c: break lo += 1 if lo < len(self.unresolved): hi = lo if sizechange < 0: for c in self.unresolved[lo:]: if startidx - sizechange <= c: break hi += 1 elif sizechange == 0 and startidx == self.unresolved[lo]: hi += 1 if hi < len(self.unresolved): self.unresolved[hi:] = [ c + sizechange for c in self.unresolved[hi:] ] self.unresolved[lo:hi] = [] return super().change_sequence(sequence, startidx, sizechange, texts) def get_unresolved_count(self): return len(self.unresolved) class Merger(diffutil.Differ): def __init__(self, ): self.differ = AutoMergeDiffer() self.differ.auto_merge = True self.differ.unresolved = [] self.texts = [] def initialize(self, sequences, texts): step = self.differ.set_sequences_iter(sequences) while next(step) is None: yield None self.texts = texts yield 1 def _apply_change(self, text, change, mergedtext): if change[0] == 'insert': for i in range(change[LO + 2], change[HI + 2]): mergedtext.append(text[i]) return 0 elif change[0] == 'replace': for i in range(change[LO + 2], change[HI + 2]): mergedtext.append(text[i]) return change[HI] - change[LO] else: return change[HI] - change[LO] def merge_3_files(self, mark_conflicts=True): self.unresolved = [] lastline = 0 mergedline = 0 mergedtext = [] for change in self.differ.all_changes(): yield None low_mark = lastline if change[0] is not None: low_mark = change[0][LO] if change[1] is not None: if change[1][LO] > low_mark: low_mark = change[1][LO] for i in range(lastline, low_mark, 1): mergedtext.append(self.texts[1][i]) mergedline += low_mark - lastline lastline = low_mark if (change[0] is not None and change[1] is not None and change[0][0] == 'conflict'): high_mark = max(change[0][HI], change[1][HI]) if mark_conflicts: if low_mark < high_mark: for i in range(low_mark, high_mark): mergedtext.append("(??)" + self.texts[1][i]) self.unresolved.append(mergedline) mergedline += 1 else: mergedtext.append("(??)") self.unresolved.append(mergedline) mergedline += 1 lastline = high_mark elif change[0] is not None: lastline += self._apply_change( self.texts[0], change[0], mergedtext) mergedline += change[0][HI + 2] - change[0][LO + 2] else: lastline += self._apply_change( self.texts[2], change[1], mergedtext) mergedline += change[1][HI + 2] - change[1][LO + 2] baselen = len(self.texts[1]) for i in range(lastline, baselen, 1): mergedtext.append(self.texts[1][i]) # FIXME: We need to obtain the original line endings from the lines # that were merged and use those here instead of assuming '\n'. yield "\n".join(mergedtext) def merge_2_files(self, fromindex, toindex): self.unresolved = [] lastline = 0 mergedtext = [] for change in self.differ.pair_changes(toindex, fromindex): yield None if change[0] == 'conflict': low_mark = change[HI] else: low_mark = change[LO] for i in range(lastline, low_mark): mergedtext.append(self.texts[toindex][i]) lastline = low_mark if change[0] != 'conflict': lastline += self._apply_change( self.texts[fromindex], change, mergedtext) baselen = len(self.texts[toindex]) for i in range(lastline, baselen): mergedtext.append(self.texts[toindex][i]) # FIXME: We need to obtain the original line endings from the lines # that were merged and use those here instead of assuming '\n'. yield "\n".join(mergedtext)
13,035
Python
.py
281
27.163701
79
0.417576
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,837
diffutil.py
GNOME_meld/meld/matchers/diffutil.py
# Copyright (C) 2002-2006 Stephen Kennedy <stevek@gnome.org> # Copyright (C) 2009, 2012-2013 Kai Willadsen <kai.willadsen@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or (at # your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from gi.repository import GObject from meld.matchers.myers import ( DiffChunk, MyersSequenceMatcher, SyncPointMyersSequenceMatcher, ) LO, HI = 1, 2 opcode_reverse = { "replace": "replace", "insert": "delete", "delete": "insert", "conflict": "conflict", "equal": "equal" } def merged_chunk_order(merged_chunk): if not merged_chunk: return 0 chunk = merged_chunk[0] or merged_chunk[1] return chunk.start_a def reverse_chunk(chunk): tag = opcode_reverse[chunk[0]] return DiffChunk._make((tag, chunk[3], chunk[4], chunk[1], chunk[2])) def consume_blank_lines(chunk, texts, pane1, pane2): if chunk is None: return None def _find_blank_lines(txt, lo, hi): while lo < hi and not txt[lo]: lo += 1 while lo < hi and not txt[hi - 1]: hi -= 1 return lo, hi tag = chunk.tag c1, c2 = _find_blank_lines(texts[pane1], chunk[1], chunk[2]) c3, c4 = _find_blank_lines(texts[pane2], chunk[3], chunk[4]) if c1 == c2 and c3 == c4: return None if c1 == c2 and tag == "replace": tag = "insert" elif c3 == c4 and tag == "replace": tag = "delete" return DiffChunk._make((tag, c1, c2, c3, c4)) class Differ(GObject.GObject): """Utility class to hold diff2 or diff3 chunks""" __gsignals__ = { 'diffs-changed': (GObject.SignalFlags.RUN_FIRST, None, (object,)), } _matcher = MyersSequenceMatcher _sync_matcher = SyncPointMyersSequenceMatcher def __init__(self): # Internally, diffs are stored from text1 -> text0 and text1 -> text2. super().__init__() self.num_sequences = 0 self.seqlength = [0, 0, 0] self.diffs = [[], []] self.syncpoints = [] self.conflicts = [] self._old_merge_cache = set() self._changed_chunks = tuple() self._merge_cache = [] self._line_cache = [[], [], []] self.ignore_blanks = False self._initialised = False self._has_mergeable_changes = (False, False, False, False) def _update_merge_cache(self, texts): if self.num_sequences == 3: self._merge_cache = [c for c in self._merge_diffs(self.diffs[0], self.diffs[1], texts)] else: self._merge_cache = [(c, None) for c in self.diffs[0]] if self.ignore_blanks: # We don't handle altering the chunk-type of conflicts in three-way # comparisons where e.g., pane 1 and 3 differ in blank lines for i, c in enumerate(self._merge_cache): self._merge_cache[i] = (consume_blank_lines(c[0], texts, 1, 0), consume_blank_lines(c[1], texts, 1, 2)) self._merge_cache = [x for x in self._merge_cache if any(x)] # Calculate chunks that were added (in the new but not the old merge # cache), removed (in the old but not the new merge cache) and changed # (where the edit actually occurred, *and* the chunk is still around). # This information is used by the inline highlighting mechanism to # avoid re-highlighting existing chunks. removed_chunks = self._old_merge_cache - set(self._merge_cache) added_chunks = set(self._merge_cache) - self._old_merge_cache modified_chunks = self._changed_chunks if modified_chunks in removed_chunks: modified_chunks = tuple() chunk_changes = (removed_chunks, added_chunks, modified_chunks) mergeable0, mergeable1 = False, False for (c0, c1) in self._merge_cache: mergeable0 = mergeable0 or (c0 is not None and c0[0] != 'conflict') mergeable1 = mergeable1 or (c1 is not None and c1[0] != 'conflict') if mergeable0 and mergeable1: break self._has_mergeable_changes = (False, mergeable0, mergeable1, False) # Conflicts can only occur when there are three panes, and will always # involve the middle pane. self.conflicts = [] for i, (c1, c2) in enumerate(self._merge_cache): if (c1 is not None and c1[0] == 'conflict') or \ (c2 is not None and c2[0] == 'conflict'): self.conflicts.append(i) self._update_line_cache() self.emit("diffs-changed", chunk_changes) def _update_line_cache(self): """Cache a mapping from line index to per-pane chunk indices This cache exists so that the UI can quickly query for current, next and previous chunks when the current cursor line changes, enabling better action sensitivity feedback. """ for i, length in enumerate(self.seqlength): # seqlength + 1 for after-last-line requests, which we do self._line_cache[i] = [(None, None, None)] * (length + 1) last_chunk = len(self._merge_cache) def find_next(diff, seq, current): next_chunk = None if seq == 1 and current + 1 < last_chunk: next_chunk = current + 1 else: for j in range(current + 1, last_chunk): if self._merge_cache[j][diff] is not None: next_chunk = j break return next_chunk prev = [None, None, None] next = [find_next(0, 0, -1), find_next(0, 1, -1), find_next(1, 2, -1)] old_end = [0, 0, 0] for i, c in enumerate(self._merge_cache): seq_params = ((0, 0, 3, 4), (0, 1, 1, 2), (1, 2, 3, 4)) for (diff, seq, lo, hi) in seq_params: if c[diff] is None: if seq == 1: diff = 1 else: continue start, end, last = c[diff][lo], c[diff][hi], old_end[seq] if (start > last): chunk_ids = [(None, prev[seq], next[seq])] * (start - last) self._line_cache[seq][last:start] = chunk_ids # For insert chunks, claim the subsequent line. if start == end: end += 1 next[seq] = find_next(diff, seq, i) chunk_ids = [(i, prev[seq], next[seq])] * (end - start) self._line_cache[seq][start:end] = chunk_ids prev[seq], old_end[seq] = i, end for seq in range(3): last, end = old_end[seq], len(self._line_cache[seq]) if (last < end): chunk_ids = [(None, prev[seq], next[seq])] * (end - last) self._line_cache[seq][last:end] = chunk_ids def change_sequence(self, sequence, startidx, sizechange, texts): assert sequence in (0, 1, 2) if sequence == 0 or sequence == 1: self._change_sequence(0, sequence, startidx, sizechange, texts) if sequence == 2 or (sequence == 1 and self.num_sequences == 3): self._change_sequence(1, sequence, startidx, sizechange, texts) self.seqlength[sequence] += sizechange def offset(c, start, o1, o2): """Offset a chunk by o1/o2 if it's after the inserted lines""" if c is None: return None start_a = c.start_a + (o1 if c.start_a > start else 0) end_a = c.end_a + (o1 if c.end_a > start else 0) start_b = c.start_b + (o2 if c.start_b > start else 0) end_b = c.end_b + (o2 if c.end_b > start else 0) return DiffChunk._make((c.tag, start_a, end_a, start_b, end_b)) # Calculate the expected differences in the chunk set if no cascading # changes occur, making sure to not include the changed chunk itself self._old_merge_cache = set() self._changed_chunks = tuple() chunk_changed = False for (c1, c2) in self._merge_cache: if sequence == 0: if c1 and c1.start_b <= startidx < c1.end_b: chunk_changed = True c1 = offset(c1, startidx, 0, sizechange) elif sequence == 2: if c2 and c2.start_b <= startidx < c2.end_b: chunk_changed = True c2 = offset(c2, startidx, 0, sizechange) else: # Middle sequence changes alter both chunks if c1 and c1.start_a <= startidx < c1.end_a: chunk_changed = True c1 = offset(c1, startidx, sizechange, 0) if self.num_sequences == 3: c2 = offset(c2, startidx, sizechange, 0) if chunk_changed: assert not self._changed_chunks self._changed_chunks = (c1, c2) chunk_changed = False self._old_merge_cache.add((c1, c2)) self._update_merge_cache(texts) def _locate_chunk(self, whichdiffs, sequence, line): """Find the index of the chunk which contains line.""" high_index = 2 + 2 * int(sequence != 1) for i, c in enumerate(self.diffs[whichdiffs]): if line < c[high_index]: return i return len(self.diffs[whichdiffs]) def has_chunk(self, to_pane, chunk): """Return whether the pane/chunk exists in the current Differ""" sequence = 1 if to_pane == 2 else 0 chunk_index, _, _ = self.locate_chunk(1, chunk.start_a) if chunk_index is None: return False return self._merge_cache[chunk_index][sequence] == chunk def get_chunk(self, index, from_pane, to_pane=None): """Return the index-th change in from_pane If to_pane is provided, then only changes between from_pane and to_pane are considered, otherwise all changes starting at from_pane are used. """ sequence = int(from_pane == 2 or to_pane == 2) chunk = self._merge_cache[index][sequence] if from_pane in (0, 2): if chunk is None: return None return reverse_chunk(chunk) else: if to_pane is None and chunk is None: chunk = self._merge_cache[index][1] return chunk def get_chunk_starts(self, index): """Return the starting lines of all chunks at an index""" chunks = self._merge_cache[index] chunk_starts = [ chunks[0].start_b if chunks[0] else None, chunks[0].start_a if chunks[0] else None, chunks[1].start_b if chunks[1] else None, ] return chunk_starts def locate_chunk(self, pane, line): """Find the index of the chunk which contains line Returns a tuple containing the current, previous and next chunk indices in that order. If the line has no associated chunk, None will be returned as the first element. If there are no previous/next chunks then None will be returned as the second/third elements. """ try: return self._line_cache[pane][line] except IndexError: return (None, None, None) def diff_count(self): return len(self._merge_cache) def has_mergeable_changes(self, which): return self._has_mergeable_changes[which:which + 2] def _change_sequence(self, which, sequence, startidx, sizechange, texts): diffs = self.diffs[which] lines_added = [0, 0, 0] lines_added[sequence] = sizechange loidx = self._locate_chunk(which, sequence, startidx) if sizechange < 0: hiidx = self._locate_chunk(which, sequence, startidx - sizechange) else: hiidx = loidx if loidx > 0: loidx -= 1 lorange = diffs[loidx][3], diffs[loidx][1] else: lorange = (0, 0) x = which * 2 if hiidx < len(diffs): hiidx += 1 hirange = diffs[hiidx - 1][4], diffs[hiidx - 1][2] else: hirange = self.seqlength[x], self.seqlength[1] rangex = lorange[0], hirange[0] + lines_added[x] range1 = lorange[1], hirange[1] + lines_added[1] assert rangex[0] <= rangex[1] and range1[0] <= range1[1] linesx = texts[x][rangex[0]:rangex[1]] lines1 = texts[1][range1[0]:range1[1]] def offset(c, o1, o2): return DiffChunk._make((c[0], c[1] + o1, c[2] + o1, c[3] + o2, c[4] + o2)) newdiffs = self._matcher(None, lines1, linesx).get_difference_opcodes() newdiffs = [offset(c, range1[0], rangex[0]) for c in newdiffs] if hiidx < len(self.diffs[which]): offset_diffs = [offset(c, lines_added[1], lines_added[x]) for c in self.diffs[which][hiidx:]] self.diffs[which][hiidx:] = offset_diffs self.diffs[which][loidx:hiidx] = newdiffs def _range_from_lines(self, textindex, lines): lo_line, hi_line = lines top_chunk = self.locate_chunk(textindex, lo_line) start = top_chunk[0] if start is None: start = top_chunk[2] bottom_chunk = self.locate_chunk(textindex, hi_line) end = bottom_chunk[0] if end is None: end = bottom_chunk[1] return start, end def all_changes(self): return iter(self._merge_cache) def pair_changes(self, fromindex, toindex, lines=(None, None, None, None)): """Give all changes between file1 and either file0 or file2. """ if None not in lines: start1, end1 = self._range_from_lines(fromindex, lines[0:2]) start2, end2 = self._range_from_lines(toindex, lines[2:4]) if (start1 is None or end1 is None) and \ (start2 is None or end2 is None): return start = min([x for x in (start1, start2) if x is not None]) end = max([x for x in (end1, end2) if x is not None]) merge_cache = self._merge_cache[start:end + 1] else: merge_cache = self._merge_cache if fromindex == 1: seq = toindex // 2 for c in merge_cache: if c[seq]: yield c[seq] else: seq = fromindex // 2 for c in merge_cache: if c[seq]: yield reverse_chunk(c[seq]) # FIXME: This is gratuitous copy-n-paste at this point def paired_all_single_changes(self, fromindex, toindex): if fromindex == 1: seq = toindex // 2 for c in self._merge_cache: if c[seq]: yield c[seq] else: seq = fromindex // 2 for c in self._merge_cache: if c[seq]: yield reverse_chunk(c[seq]) def single_changes(self, textindex, lines=(None, None)): """Give changes for single file only. do not return 'equal' hunks. """ if None not in lines: start, end = self._range_from_lines(textindex, lines) if start is None or end is None: return merge_cache = self._merge_cache[start:end + 1] else: merge_cache = self._merge_cache if textindex in (0, 2): seq = textindex // 2 for cs in merge_cache: if cs[seq]: yield reverse_chunk(cs[seq]) else: for cs in merge_cache: yield cs[0] or cs[1] def sequences_identical(self): # check so that we don't call an uninitialised comparison 'identical' return self.diffs == [[], []] and self._initialised def _merge_blocks(self, using): lowc = min(using[0][0][LO], using[1][0][LO]) highc = max(using[0][-1][HI], using[1][-1][HI]) low = [] high = [] for i in (0, 1): d = using[i][0] low.append(lowc - d[LO] + d[2 + LO]) d = using[i][-1] high.append(highc - d[HI] + d[2 + HI]) return low[0], high[0], lowc, highc, low[1], high[1] def _auto_merge(self, using, texts): """Automatically merge two sequences of change blocks""" l0, h0, l1, h1, l2, h2 = self._merge_blocks(using) if h0 - l0 == h2 - l2 and texts[0][l0:h0] == texts[2][l2:h2]: if l1 != h1 and l0 == h0: tag = "delete" elif l1 != h1: tag = "replace" else: tag = "insert" else: tag = "conflict" out0 = DiffChunk._make((tag, l1, h1, l0, h0)) out1 = DiffChunk._make((tag, l1, h1, l2, h2)) yield out0, out1 def _merge_diffs(self, seq0, seq1, texts): seq0, seq1 = seq0[:], seq1[:] seq = seq0, seq1 while len(seq0) or len(seq1): if not seq0: high_seq = 1 elif not seq1: high_seq = 0 else: high_seq = int(seq0[0].start_a > seq1[0].start_a) if seq0[0].start_a == seq1[0].start_a: if seq0[0].tag == "insert": high_seq = 0 elif seq1[0].tag == "insert": high_seq = 1 high_diff = seq[high_seq].pop(0) high_mark = high_diff.end_a other_seq = 0 if high_seq == 1 else 1 using = [[], []] using[high_seq].append(high_diff) while seq[other_seq]: other_diff = seq[other_seq][0] if high_mark < other_diff.start_a: break if high_mark == other_diff.start_a and \ not (high_diff.tag == other_diff.tag == "insert"): break using[other_seq].append(other_diff) seq[other_seq].pop(0) if high_mark < other_diff.end_a: high_seq, other_seq = other_seq, high_seq high_mark = other_diff.end_a if len(using[0]) == 0: assert len(using[1]) == 1 yield None, using[1][0] elif len(using[1]) == 0: assert len(using[0]) == 1 yield using[0][0], None else: for c in self._auto_merge(using, texts): yield c def set_sequences_iter(self, sequences): assert 0 <= len(sequences) <= 3 self.diffs = [[], []] self.num_sequences = len(sequences) self.seqlength = [len(s) for s in sequences] for i in range(self.num_sequences - 1): if self.syncpoints: syncpoints = [(s[i][0](), s[i][1]()) for s in self.syncpoints] matcher = self._sync_matcher(None, sequences[1], sequences[i * 2], syncpoints=syncpoints) else: matcher = self._matcher(None, sequences[1], sequences[i * 2]) work = matcher.initialise() while next(work) is None: yield None self.diffs[i] = matcher.get_difference_opcodes() self._initialised = True self._update_merge_cache(sequences) yield 1 def clear(self): self.diffs = [[], []] self.seqlength = [0] * self.num_sequences self._initialised = False self._old_merge_cache = set() self._update_merge_cache([""] * self.num_sequences)
20,493
Python
.py
462
32.649351
79
0.54356
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,838
helpers.py
GNOME_meld/meld/matchers/helpers.py
import logging import multiprocessing import queue import time from gi.repository import GLib from meld.matchers import myers log = logging.getLogger(__name__) class MatcherWorker(multiprocessing.Process): END_TASK = -1 matcher_class = myers.InlineMyersSequenceMatcher def __init__(self, tasks, results): super().__init__() self.tasks = tasks self.results = results self.daemon = True def run(self): while True: task_id, (text1, textn) = self.tasks.get() if task_id == self.END_TASK: break try: matcher = self.matcher_class(None, text1, textn) self.results.put((task_id, matcher.get_opcodes())) except Exception as e: log.error("Exception while running diff: %s", e) time.sleep(0) class CachedSequenceMatcher: """Simple class for caching diff results, with LRU-based eviction Results from the SequenceMatcher are cached and timestamped, and subsequently evicted based on least-recent generation/usage. The LRU-based eviction is overly simplistic, but is okay for our usage pattern. """ TASK_GRACE_PERIOD = 1 def __init__(self, scheduler): """Create a new caching sequence matcher :param scheduler: a `meld.task.SchedulerBase` used to schedule sequence comparison result checks """ self.scheduler = scheduler self.cache = {} self.tasks = multiprocessing.Queue() self.tasks.cancel_join_thread() # Limiting the result queue here has the effect of giving us # much better interactivity. Without this limit, the # result-checker tends to get starved and all highlights get # delayed until we're almost completely finished. self.results = multiprocessing.Queue(5) self.results.cancel_join_thread() self.thread = MatcherWorker(self.tasks, self.results) self.task_id = 1 self.queued_matches = {} GLib.idle_add(self.thread.start) def stop(self) -> None: self.tasks.put((MatcherWorker.END_TASK, ('', ''))) if self.thread.is_alive(): self.thread.join(self.TASK_GRACE_PERIOD) if self.thread.exitcode is None: self.thread.terminate() self.cache = {} self.queued_matches = {} def match(self, text1, textn, cb): texts = (text1, textn) try: self.cache[texts][1] = time.time() opcodes = self.cache[texts][0] GLib.idle_add(lambda: cb(opcodes)) except KeyError: GLib.idle_add(lambda: self.enqueue_task(texts, cb)) def enqueue_task(self, texts, cb): if not bool(self.queued_matches): self.scheduler.add_task(self.check_results) self.queued_matches[self.task_id] = (texts, cb) self.tasks.put((self.task_id, texts)) self.task_id += 1 def check_results(self): try: task_id, opcodes = self.results.get(block=True, timeout=0.01) texts, cb = self.queued_matches.pop(task_id) self.cache[texts] = [opcodes, time.time()] GLib.idle_add(lambda: cb(opcodes)) except queue.Empty: pass return bool(self.queued_matches) def clean(self, size_hint): """Clean the cache if necessary @param size_hint: the recommended minimum number of cache entries """ if len(self.cache) <= size_hint * 3: return items = list(self.cache.items()) items.sort(key=lambda it: it[1][1]) for item in items[:-size_hint * 2]: del self.cache[item[0]]
3,740
Python
.py
93
31.129032
78
0.618272
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,839
filebutton.py
GNOME_meld/meld/ui/filebutton.py
from typing import Optional from gi.repository import Gio, GObject, Gtk class MeldFileButton(Gtk.Button): __gtype_name__ = "MeldFileButton" file: Optional[Gio.File] = GObject.Property( type=Gio.File, nick="Most recently selected file", ) pane: int = GObject.Property( type=int, nick="Index of pane associated with this file selector", flags=( GObject.ParamFlags.READWRITE | GObject.ParamFlags.CONSTRUCT_ONLY ), ) action: Gtk.FileChooserAction = GObject.Property( type=Gtk.FileChooserAction, nick="File selector action", flags=( GObject.ParamFlags.READWRITE | GObject.ParamFlags.CONSTRUCT_ONLY ), default=Gtk.FileChooserAction.OPEN, ) local_only: bool = GObject.Property( type=bool, nick="Whether selected files should be limited to local file:// URIs", flags=( GObject.ParamFlags.READWRITE | GObject.ParamFlags.CONSTRUCT_ONLY ), default=True, ) dialog_label: str = GObject.Property( type=str, nick="Label for the file selector dialog", flags=( GObject.ParamFlags.READWRITE | GObject.ParamFlags.CONSTRUCT_ONLY ), ) @GObject.Signal('file-selected') def file_selected_signal(self, pane: int, file: Gio.File) -> None: ... icon_action_map = { Gtk.FileChooserAction.OPEN: "document-open-symbolic", Gtk.FileChooserAction.SELECT_FOLDER: "folder-open-symbolic", } def do_realize(self) -> None: Gtk.Button.do_realize(self) image = Gtk.Image.new_from_icon_name( self.icon_action_map[self.action], Gtk.IconSize.BUTTON) self.set_image(image) def do_clicked(self) -> None: dialog = Gtk.FileChooserNative( title=self.dialog_label, transient_for=self.get_toplevel(), action=self.action, local_only=self.local_only ) if self.file and self.file.get_path(): dialog.set_file(self.file) response = dialog.run() gfile = dialog.get_file() dialog.destroy() if response != Gtk.ResponseType.ACCEPT or not gfile: return self.file = gfile self.file_selected_signal.emit(self.pane, self.file)
2,410
Python
.py
70
25.628571
78
0.615418
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,840
emblemcellrenderer.py
GNOME_meld/meld/ui/emblemcellrenderer.py
# Copyright (C) 2002-2006 Stephen Kennedy <stevek@gnome.org> # Copyright (C) 2010, 2012-2013 Kai Willadsen <kai.willadsen@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or (at # your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import logging from typing import Dict, Tuple import cairo from gi.repository import Gdk, GdkPixbuf, GLib, GObject, Gtk log = logging.getLogger(__name__) class EmblemCellRenderer(Gtk.CellRenderer): __gtype_name__ = "EmblemCellRenderer" icon_cache: Dict[Tuple[str, int], GdkPixbuf.Pixbuf] = {} icon_name = GObject.Property( type=str, nick='Named icon', blurb='Name for base icon', default='text-x-generic', ) emblem_name = GObject.Property( type=str, nick='Named emblem icon', blurb='Name for emblem icon to overlay', ) icon_tint = GObject.Property( type=Gdk.RGBA, nick='Icon tint', blurb='GDK-parseable color to be used to tint icon', ) def __init__(self): super().__init__() self._state = None # FIXME: hardcoded sizes self._icon_size = 16 self._emblem_size = 8 def _get_pixbuf(self, name, size): if not name: return None if (name, size) not in self.icon_cache: icon_theme = Gtk.IconTheme.get_default() try: pixbuf = icon_theme.load_icon(name, size, 0).copy() except GLib.GError as err: if err.domain != GLib.quark_to_string( Gtk.IconThemeError.quark() ): raise log.error(f"Icon {name!r} not found; an icon theme is missing") pixbuf = None self.icon_cache[(name, size)] = pixbuf return self.icon_cache[(name, size)] def do_render(self, context, widget, background_area, cell_area, flags): context.translate(cell_area.x, cell_area.y) context.rectangle(0, 0, cell_area.width, cell_area.height) context.clip() # TODO: Incorporate padding context.push_group() pixbuf = self._get_pixbuf(self.icon_name, self._icon_size) if pixbuf: context.set_operator(cairo.OPERATOR_SOURCE) # Assumes square icons; may break if we don't get the requested # size height_offset = int((cell_area.height - pixbuf.get_height()) / 2) Gdk.cairo_set_source_pixbuf(context, pixbuf, 0, height_offset) context.rectangle(0, height_offset, pixbuf.get_width(), pixbuf.get_height()) context.fill() if self.icon_tint: c = self.icon_tint r, g, b = c.red, c.green, c.blue # Figure out the difference between our tint colour and an # empirically determined (i.e., guessed) satisfying luma and # adjust the base colours accordingly luma = (r + r + b + g + g + g) / 6. extra_luma = (1.2 - luma) / 3. r, g, b = [min(x + extra_luma, 1.) for x in (r, g, b)] context.set_source_rgba(r, g, b, 0.4) context.set_operator(cairo.OPERATOR_ATOP) context.paint() if self.emblem_name: pixbuf = self._get_pixbuf(self.emblem_name, self._emblem_size) x_offset = self._icon_size - self._emblem_size context.set_operator(cairo.OPERATOR_OVER) Gdk.cairo_set_source_pixbuf(context, pixbuf, x_offset, 0) context.rectangle(x_offset, 0, cell_area.width, self._emblem_size) context.fill() context.pop_group_to_source() context.set_operator(cairo.OPERATOR_OVER) context.paint() def do_get_size(self, widget, cell_area): # TODO: Account for cell_area if we have alignment set x_offset, y_offset = 0, 0 width, height = self._icon_size, self._icon_size # TODO: Account for padding return (x_offset, y_offset, width, height)
4,680
Python
.py
106
34.122642
79
0.600044
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,841
util.py
GNOME_meld/meld/ui/util.py
# Copyright (C) 2013 Kai Willadsen <kai.willadsen@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or (at # your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import logging from typing import List from gi.repository import Gio, GObject, Gtk log = logging.getLogger(__name__) def map_widgets_into_lists(widget, widgetnames): """Put sequentially numbered widgets into lists. Given an object with widgets self.button0, self.button1, ..., after a call to object.map_widgets_into_lists(["button"]) object.button == [self.button0, self.button1, ...] """ for item in widgetnames: i, lst = 0, [] while 1: key = "%s%i" % (item, i) try: val = getattr(widget, key) except AttributeError: if i == 0: log.critical( f"Tried to map missing attribute {key}") break lst.append(val) i += 1 setattr(widget, item, lst) # The functions `extract_accel_from_menu_item` and `extract_accels_from_menu` # are converted straight from GTK+'s GtkApplication handling. I don't # understand why these aren't public API, but here we are. def extract_accel_from_menu_item( model: Gio.MenuModel, item: int, app: Gtk.Application): accel, action, target = None, None, None more, it = True, model.iterate_item_attributes(item) while more: more, key, value = it.get_next() if key == 'action': action = value.get_string() elif key == 'accel': accel = value.get_string() # TODO: Handle targets if accel and action: detailed_action_name = Gio.Action.print_detailed_name(action, target) app.set_accels_for_action(detailed_action_name, [accel]) def extract_accels_from_menu(model: Gio.MenuModel, app: Gtk.Application): for i in range(model.get_n_items()): extract_accel_from_menu_item(model, i, app) more, it = True, model.iterate_item_links(i) while more: more, name, submodel = it.get_next() if submodel: extract_accels_from_menu(submodel, app) def make_multiobject_property_action( obj_list: List[GObject.Object], prop_name: str) -> Gio.PropertyAction: """Construct a property action linked to multiple objects This is useful for creating actions linked to a GObject property, where changing the property via the action should affect multiple GObjects. As an example, changing the text wrapping mode of a file comparison pane should change the wrapping mode for *all* panes. """ source, *targets = obj_list action = Gio.PropertyAction.new(prop_name, source, prop_name) for target in targets: source.bind_property(prop_name, target, prop_name) return action
3,400
Python
.py
77
37.38961
78
0.672116
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,842
pathlabel.py
GNOME_meld/meld/ui/pathlabel.py
# Copyright (C) 2019-2021 Kai Willadsen <kai.willadsen@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or (at # your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import logging from typing import Optional from gi.repository import Gdk, Gio, GObject, Gtk, Pango from meld.conf import _ from meld.externalhelpers import open_files_external from meld.iohelpers import ( format_home_relative_path, format_parent_relative_path, ) log = logging.getLogger(__name__) @Gtk.Template(resource_path='/org/gnome/meld/ui/path-label.ui') class PathLabel(Gtk.MenuButton): __gtype_name__ = 'PathLabel' MISSING_FILE_NAME: str = _('Unnamed file') full_path_label: Gtk.Entry = Gtk.Template.Child() _gfile: Optional[Gio.File] _parent_gfile: Optional[Gio.File] _path_label: Optional[str] _icon_name: Optional[str] def __get_file(self) -> Optional[Gio.File]: return self._gfile def __set_file(self, file: Optional[Gio.File]) -> None: if file == self._gfile: return try: self._update_paths(self._parent_gfile, file) except ValueError as e: log.warning(f'Error setting GFile: {str(e)}') def __get_parent_file(self) -> Optional[Gio.File]: return self._parent_gfile def __set_parent_file(self, parent_file: Optional[Gio.File]) -> None: if parent_file == self._parent_gfile: return try: self._update_paths(parent_file, self._gfile) except ValueError as e: log.warning(f'Error setting parent GFile: {str(e)}') def __get_path_label(self) -> Optional[str]: return self._path_label def __get_icon_name(self) -> Optional[str]: return self._icon_name def __set_icon_name(self, icon_name: Optional[str]) -> None: if icon_name == self._icon_name: return if icon_name: image = Gtk.Image.new_from_icon_name( icon_name, Gtk.IconSize.BUTTON) self.set_image(image) self.props.always_show_image = True else: self.set_image(None) self.props.always_show_image = False gfile = GObject.Property( type=Gio.File, nick='File being displayed', getter=__get_file, setter=__set_file, ) parent_gfile = GObject.Property( type=Gio.File, nick=( 'Parent folder of the current file being displayed that ' 'determines where the path display will terminate' ), getter=__get_parent_file, setter=__set_parent_file, ) path_label = GObject.Property( type=str, nick='Summarised path label relative to defined parent', getter=__get_path_label, ) icon_name = GObject.Property( type=str, nick='The name of the icon to display', getter=__get_icon_name, setter=__set_icon_name, ) custom_label = GObject.Property( type=str, nick='Custom label override', ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.drag_dest_set( Gtk.DestDefaults.MOTION | Gtk.DestDefaults.HIGHLIGHT | Gtk.DestDefaults.DROP, None, Gdk.DragAction.COPY, ) self.drag_dest_add_uri_targets() self._gfile = None self._parent_gfile = None self._path_label = None self._icon_name = None self.bind_property( 'path_label', self, 'label', GObject.BindingFlags.DEFAULT | GObject.BindingFlags.SYNC_CREATE, self.get_display_label, ) self.bind_property( 'custom_label', self, 'label', GObject.BindingFlags.DEFAULT | GObject.BindingFlags.SYNC_CREATE, self.get_display_label, ) self.bind_property( 'gfile', self.full_path_label, 'text', GObject.BindingFlags.DEFAULT | GObject.BindingFlags.SYNC_CREATE, self.get_display_path, ) action_group = Gio.SimpleActionGroup() actions = ( ('copy-full-path', self.action_copy_full_path), ('open-folder', self.action_open_folder), ) for (name, callback) in actions: action = Gio.SimpleAction.new(name, None) action.connect('activate', callback) action_group.add_action(action) self.insert_action_group('widget', action_group) # GtkButton recreates its GtkLabel child whenever the label # prop changes, so we need this notify callback. self.connect('notify::label', self.label_changed_cb) def label_changed_cb(self, *args): # Our label needs ellipsization to avoid forcing minimum window # sizes for long filenames. This child iteration hack is # required as GtkButton has no label access. for child in self.get_children(): if isinstance(child, Gtk.Label): child.set_ellipsize(Pango.EllipsizeMode.MIDDLE) def get_display_label(self, binding, from_value) -> str: if self.custom_label: return self.custom_label elif self.path_label: return self.path_label else: return self.MISSING_FILE_NAME def get_display_path(self, binding, from_value): if from_value: return from_value.get_parse_name() return '' def _update_paths( self, parent: Optional[Gio.File], descendant: Optional[Gio.File], ) -> None: # If either of the parent or the main gfiles are not set, the # relationship is fine (because it's not yet established). if not parent or not descendant: self._parent_gfile = parent self._gfile = descendant # If we have no parent yet but have a descendant, we'll use # the descendant name as the better-than-nothing label. if descendant: self._path_label = format_home_relative_path(descendant) self.notify('path_label') return descendant_parent = descendant.get_parent() if not descendant_parent: raise ValueError( f'Path {descendant.get_path()} has no parent') descendant_or_equal = bool( parent.equal(descendant_parent) or parent.get_relative_path(descendant_parent), ) if not descendant_or_equal: raise ValueError( f'Path {descendant.get_path()} is not a descendant ' f'of {parent.get_path()}') self._parent_gfile = parent self._gfile = descendant self._path_label = format_parent_relative_path(parent, descendant) self.notify('path_label') def action_copy_full_path(self, *args): if not self.gfile: return path = self.gfile.get_path() or self.gfile.get_uri() clip = Gtk.Clipboard.get_default(Gdk.Display.get_default()) clip.set_text(path, -1) clip.store() def action_open_folder(self, *args): if not self.gfile: return parent = self.gfile.get_parent() if parent: open_files_external(gfiles=[parent])
7,863
Python
.py
200
30.44
76
0.619617
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,843
msgarea.py
GNOME_meld/meld/ui/msgarea.py
# This file is part of the Hotwire Shell user interface. # # Copyright (C) 2007,2008 Colin Walters <walters@verbum.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or (at # your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # Additional modifications made for use in Meld and adaptations for # newer GTK+. # Copyright (C) 2013 Kai Willadsen <kai.willadsen@gmail.com> from typing import Optional from gi.repository import Gtk, Pango from meld.conf import _ def layout_text_and_icon( primary_text: str, secondary_text: Optional[str] = None, icon_name: Optional[str] = None, ): hbox_content = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=8) if icon_name: image = Gtk.Image.new_from_icon_name(icon_name, Gtk.IconSize.DIALOG) image.set_alignment(0.5, 0.5) hbox_content.pack_start(image, False, False, 0) vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6) primary_label = Gtk.Label( label="<b>{}</b>".format(primary_text), wrap=True, wrap_mode=Pango.WrapMode.WORD_CHAR, use_markup=True, xalign=0, can_focus=True, selectable=True, ) vbox.pack_start(primary_label, True, True, 0) if secondary_text: secondary_label = Gtk.Label( "<small>{}</small>".format(secondary_text), wrap=True, wrap_mode=Pango.WrapMode.WORD, use_markup=True, xalign=0, can_focus=True, selectable=True, ) vbox.pack_start(secondary_label, True, True, 0) hbox_content.pack_start(vbox, True, True, 0) hbox_content.show_all() return hbox_content class MsgAreaController(Gtk.Box): __gtype_name__ = "MsgAreaController" def __init__(self): super().__init__() self.__msgarea = None self.__msgid = None self.props.orientation = Gtk.Orientation.HORIZONTAL def has_message(self): return self.__msgarea is not None def get_msg_id(self): return self.__msgid def set_msg_id(self, msgid): self.__msgid = msgid def clear(self): if self.__msgarea is not None: self.remove(self.__msgarea) self.__msgarea.destroy() self.__msgarea = None self.__msgid = None def new_from_text_and_icon( self, primary: str, secondary: Optional[str] = None, icon_name: Optional[str] = None, ): self.clear() msgarea = self.__msgarea = Gtk.InfoBar() content = layout_text_and_icon(primary, secondary, icon_name) content_area = msgarea.get_content_area() content_area.foreach(content_area.remove, None) content_area.add(content) action_area = msgarea.get_action_area() action_area.set_orientation(Gtk.Orientation.VERTICAL) self.pack_start(msgarea, True, True, 0) return msgarea def add_dismissable_msg(self, icon, primary, secondary, close_panes=None): def clear_all(*args): if close_panes: for pane in close_panes: pane.clear() else: self.clear() msgarea = self.new_from_text_and_icon(primary, secondary, icon) msgarea.add_button(_("Hi_de"), Gtk.ResponseType.CLOSE) msgarea.connect("response", clear_all) msgarea.show_all() return msgarea def add_action_msg(self, icon, primary, secondary, action_label, callback): def on_response(msgarea, response_id, *args): self.clear() if response_id == Gtk.ResponseType.ACCEPT: callback() msgarea = self.new_from_text_and_icon(primary, secondary, icon) msgarea.add_button(action_label, Gtk.ResponseType.ACCEPT) msgarea.add_button(_("Hi_de"), Gtk.ResponseType.CLOSE) msgarea.connect("response", on_response) msgarea.show_all() return msgarea
4,507
Python
.py
116
31.413793
79
0.647342
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,844
notebooklabel.py
GNOME_meld/meld/ui/notebooklabel.py
# Copyright (C) 2002-2009 Stephen Kennedy <stevek@gnome.org> # Copyright (C) 2008-2009, 2013, 2019 Kai Willadsen <kai.willadsen@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or (at # your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from gi.repository import Gdk, GObject, Gtk @Gtk.Template(resource_path='/org/gnome/meld/ui/notebook-label.ui') class NotebookLabel(Gtk.EventBox): __gtype_name__ = 'NotebookLabel' label = Gtk.Template.Child() label_text = GObject.Property( type=str, nick='Text of this notebook label', default='', ) page = GObject.Property( type=object, nick='Notebook page for which this is the label', default=None, ) def __init__(self, **kwargs): super().__init__(**kwargs) self.bind_property( 'label-text', self.label, 'label', GObject.BindingFlags.DEFAULT | GObject.BindingFlags.SYNC_CREATE, ) self.bind_property( 'label-text', self, 'tooltip-text', GObject.BindingFlags.DEFAULT | GObject.BindingFlags.SYNC_CREATE, ) @Gtk.Template.Callback() def on_label_button_press_event(self, widget, event): # Middle-click on the tab closes the tab. if event.type == Gdk.EventType.BUTTON_PRESS and event.button == 2: self.page.on_delete_event() @Gtk.Template.Callback() def on_close_button_clicked(self, widget): self.page.on_delete_event()
2,020
Python
.py
48
36.354167
77
0.686894
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,845
notebook.py
GNOME_meld/meld/ui/notebook.py
# Copyright (C) 2015-2019 Kai Willadsen <kai.willadsen@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or (at # your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from gi.repository import Gdk, Gio, GObject, Gtk KEYBINDING_FLAGS = GObject.SignalFlags.RUN_LAST | GObject.SignalFlags.ACTION class MeldNotebook(Gtk.Notebook): """Notebook subclass with tab switch and reordering behaviour MeldNotebook implements some fairly generic tab switching shortcuts and a popup menu for simple tab controls, as well as some Meld-specific tab label handling. """ __gtype_name__ = "MeldNotebook" __gsignals__ = { 'tab-switch': (KEYBINDING_FLAGS, None, (int,)), 'page-label-changed': (0, None, (GObject.TYPE_STRING,)), } # Python 3.4; no bytes formatting css = ( b""" @binding-set TabSwitchBindings { bind "<Alt>1" { "tab-switch" (0) }; bind "<Alt>2" { "tab-switch" (1) }; bind "<Alt>3" { "tab-switch" (2) }; bind "<Alt>4" { "tab-switch" (3) }; bind "<Alt>5" { "tab-switch" (4) }; bind "<Alt>6" { "tab-switch" (5) }; bind "<Alt>7" { "tab-switch" (6) }; bind "<Alt>8" { "tab-switch" (7) }; bind "<Alt>9" { "tab-switch" (8) }; bind "<Alt>0" { "tab-switch" (9) }; } notebook.meld-notebook { -gtk-key-bindings: TabSwitchBindings; } """ ) ui = """ <?xml version="1.0" encoding="UTF-8"?> <interface> <menu id="tab-menu"> <item> <attribute name="label" translatable="yes">Move _Left</attribute> <attribute name="action">popup.tabmoveleft</attribute> </item> <item> <attribute name="label" translatable="yes">Move _Right</attribute> <attribute name="action">popup.tabmoveright</attribute> </item> <item> <attribute name="label" translatable="yes">_Close</attribute> <attribute name="action">win.close</attribute> </item> </menu> </interface> """ provider = Gtk.CssProvider() provider.load_from_data(css) Gtk.StyleContext.add_provider_for_screen( Gdk.Screen.get_default(), provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION, ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.action_group = Gio.SimpleActionGroup() actions = ( ("tabmoveleft", self.on_tab_move_left), ("tabmoveright", self.on_tab_move_right), ) for (name, callback) in actions: action = Gio.SimpleAction.new(name, None) action.connect('activate', callback) self.action_group.add_action(action) self.insert_action_group("popup", self.action_group) builder = Gtk.Builder.new_from_string(self.ui, -1) self.popup_menu = builder.get_object("tab-menu") stylecontext = self.get_style_context() stylecontext.add_class('meld-notebook') self.connect('button-press-event', self.on_button_press_event) self.connect('popup-menu', self.on_popup_menu) self.connect('page-added', self.on_page_added) self.connect('page-removed', self.on_page_removed) def do_tab_switch(self, page_num): self.set_current_page(page_num) def on_popup_menu(self, widget, event=None): self.action_group.lookup_action("tabmoveleft").set_enabled( self.get_current_page() > 0) self.action_group.lookup_action("tabmoveright").set_enabled( self.get_current_page() < self.get_n_pages() - 1) popup = Gtk.Menu.new_from_model(self.popup_menu) popup.attach_to_widget(widget, None) popup.show_all() if event: popup.popup_at_pointer(event) else: popup.popup_at_widget( widget, Gdk.Gravity.NORTH_WEST, Gdk.Gravity.NORTH_WEST, event, ) return True def on_button_press_event(self, widget, event): if (event.triggers_context_menu() and event.type == Gdk.EventType.BUTTON_PRESS): return self.on_popup_menu(widget, event) return False def on_tab_move_left(self, *args): page_num = self.get_current_page() child = self.get_nth_page(page_num) page_num = page_num - 1 if page_num > 0 else 0 self.reorder_child(child, page_num) def on_tab_move_right(self, *args): page_num = self.get_current_page() child = self.get_nth_page(page_num) self.reorder_child(child, page_num + 1) def on_page_added(self, notebook, child, page_num, *args): child.connect("label-changed", self.on_label_changed) self.props.show_tabs = self.get_n_pages() > 1 def on_page_removed(self, notebook, child, page_num, *args): child.disconnect_by_func(self.on_label_changed) self.props.show_tabs = self.get_n_pages() > 1 def on_label_changed(self, page, text: str, tooltip: str) -> None: nbl = self.get_tab_label(page) nbl.props.label_text = text nbl.set_tooltip_text(tooltip) # Only update the window title if the current page is active if self.get_current_page() == self.page_num(page): self.emit('page-label-changed', text) self.child_set_property(page, "menu-label", text)
6,029
Python
.py
139
34.906475
78
0.616513
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,846
cellrenderers.py
GNOME_meld/meld/ui/cellrenderers.py
# Copyright (C) 2016 Kai Willadsen <kai.willadsen@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or (at # your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import datetime from gi.repository import GObject, Gtk class CellRendererDate(Gtk.CellRendererText): __gtype_name__ = "CellRendererDate" #: We use negative 32-bit Unix timestamp to threshold our valid values MIN_TIMESTAMP = -2147483648 DATETIME_FORMAT = "%a %d %b %Y %H:%M:%S" def _format_datetime(self, dt: datetime.datetime) -> str: return dt.strftime(self.DATETIME_FORMAT) def get_timestamp(self): return getattr(self, '_datetime', self.MIN_TIMESTAMP) def set_timestamp(self, value): if value == self.get_timestamp(): return if value <= self.MIN_TIMESTAMP: time_str = '' else: try: mod_datetime = datetime.datetime.fromtimestamp(value) time_str = self._format_datetime(mod_datetime) except Exception: time_str = '' self.props.markup = time_str self._datetime = value timestamp = GObject.Property( type=float, nick="Unix timestamp to display", getter=get_timestamp, setter=set_timestamp, ) class CellRendererISODate(CellRendererDate): __gtype_name__ = "CellRendererISODate" def _format_datetime(self, dt: datetime.datetime) -> str: # Limit our ISO display to seconds (i.e., no milli or # microseconds) for usability return dt.isoformat(timespec="seconds") class CellRendererByteSize(Gtk.CellRendererText): __gtype_name__ = "CellRendererByteSize" def get_bytesize(self): return getattr(self, '_bytesize', -1) def set_bytesize(self, value): if value == self.get_bytesize(): return if value == -1: byte_str = '' else: suffixes = ( 'B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB' ) size = float(value) unit = 0 while size > 1000 and unit < len(suffixes) - 1: size /= 1000 unit += 1 format_str = "%.1f %s" if unit > 0 else "%d %s" byte_str = format_str % (size, suffixes[unit]) self.props.markup = byte_str self._bytesize = value bytesize = GObject.Property( type=GObject.TYPE_INT64, nick="Byte size to display", getter=get_bytesize, setter=set_bytesize, ) class CellRendererFileMode(Gtk.CellRendererText): __gtype_name__ = "CellRendererFileMode" def get_file_mode(self): return getattr(self, '_file_mode', -1) def set_file_mode(self, value): if value == self.get_file_mode(): return if value == -1.0: mode_str = '' else: perms = [] rwx = ((4, 'r'), (2, 'w'), (1, 'x')) for group_index in (6, 3, 0): group = value >> group_index & 7 perms.extend([p if group & i else '-' for i, p in rwx]) mode_str = "".join(perms) self.props.markup = mode_str self._file_mode = value file_mode = GObject.Property( type=int, nick="Byte size to display", getter=get_file_mode, setter=set_file_mode, )
3,919
Python
.py
102
30.186275
74
0.605117
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,847
historyentry.py
GNOME_meld/meld/ui/historyentry.py
# Copyright (C) 2008-2011, 2013 Kai Willadsen <kai.willadsen@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or (at # your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import configparser import os import sys from gi.repository import GLib, GObject, Gtk, Pango # This file started off as a Python translation of: # * gedit/gedit/gedit-history-entry.c # * libgnomeui/libgnomeui/gnome-file-entry.c # roughly based on Colin Walters' Python translation of msgarea.py from Hotwire MIN_ITEM_LEN = 3 HISTORY_ENTRY_HISTORY_LENGTH_DEFAULT = 10 def _remove_item(store, text): if text is None: return False for row in store: if row[1] == text: store.remove(row.iter) return True return False def _clamp_list_store(liststore, max_items): try: # -1 because TreePath counts from 0 it = liststore.get_iter(max_items - 1) except ValueError: return valid = True while valid: valid = liststore.remove(it) class HistoryCombo(Gtk.ComboBox): __gtype_name__ = "HistoryCombo" history_id = GObject.Property( type=str, nick="History ID", blurb="Identifier associated with entry's history store", default=None, flags=GObject.ParamFlags.READWRITE, ) history_length = GObject.Property( type=int, nick="History length", blurb="Number of history items to display in the combo", minimum=1, maximum=20, default=HISTORY_ENTRY_HISTORY_LENGTH_DEFAULT, ) def __init__(self, **kwargs): super().__init__(**kwargs) if sys.platform == "win32": pref_dir = os.path.join(os.getenv("APPDATA"), "Meld") else: pref_dir = os.path.join(GLib.get_user_config_dir(), "meld") if not os.path.exists(pref_dir): os.makedirs(pref_dir) self.history_file = os.path.join(pref_dir, "history.ini") self.config = configparser.RawConfigParser() if os.path.exists(self.history_file): self.config.read(self.history_file, encoding='utf8') self.set_model(Gtk.ListStore(str, str)) rentext = Gtk.CellRendererText() rentext.props.width_chars = 60 rentext.props.ellipsize = Pango.EllipsizeMode.END self.pack_start(rentext, True) self.add_attribute(rentext, 'text', 0) self.connect('notify::history-id', lambda *args: self._load_history()) self.connect('notify::history-length', lambda *args: self._load_history()) def prepend_history(self, text): self._insert_history_item(text, True) def append_history(self, text): self._insert_history_item(text, False) def clear(self): self.get_model().clear() self._save_history() def _insert_history_item(self, text, prepend): if not text or len(text) <= MIN_ITEM_LEN: return store = self.get_model() if not _remove_item(store, text): _clamp_list_store(store, self.props.history_length - 1) row = (text.splitlines()[0], text) if prepend: store.insert(0, row) else: store.append(row) self._save_history() def _load_history(self): section_key = self.props.history_id if section_key is None or not self.config.has_section(section_key): return store = self.get_model() store.clear() messages = sorted(self.config.items(section_key)) for key, message in messages[:self.props.history_length - 1]: message = message.encode('utf8') message = message.decode('unicode-escape') firstline = message.splitlines()[0] store.append((firstline, message)) def _save_history(self): section_key = self.props.history_id if section_key is None: return self.config.remove_section(section_key) self.config.add_section(section_key) for i, row in enumerate(self.get_model()): # This dance is to avoid newline, etc. issues in the ini file message = row[1].encode('unicode-escape') message = message.decode('utf8') self.config.set(section_key, "item%d" % i, message) with open(self.history_file, 'w', encoding='utf8') as f: self.config.write(f)
4,959
Python
.py
123
32.552846
79
0.642946
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,848
statusbar.py
GNOME_meld/meld/ui/statusbar.py
# Copyright (C) 2012-2013 Kai Willadsen <kai.willadsen@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or (at # your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from gi.repository import GObject, Gtk, GtkSource, Pango from meld.conf import _ from meld.ui.bufferselectors import EncodingSelector, SourceLangSelector class MeldStatusMenuButton(Gtk.MenuButton): """Compact menu button with arrow indicator for use in a status bar Implementation based on gedit-status-menu-button.c Copyright (C) 2008 - Jesse van den Kieboom """ __gtype_name__ = "MeldStatusMenuButton" style = b""" * { padding: 1px 8px 2px 4px; border: 0; outline-width: 0; } """ css_provider = Gtk.CssProvider() css_provider.load_from_data(style) def get_label(self): return self._label.get_text() def set_label(self, markup): if markup == self._label.get_text(): return self._label.set_markup(markup) label = GObject.Property( type=str, default=None, getter=get_label, setter=set_label, ) def __init__(self): super().__init__() style_context = self.get_style_context() style_context.add_provider( self.css_provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION) style_context.add_class('flat') # Ideally this would be a template child, but there's still no # Python support for this. label = Gtk.Label( single_line_mode=True, halign=Gtk.Align.START, valign=Gtk.Align.BASELINE, xalign=1.0, ellipsize=Pango.EllipsizeMode.END, ) arrow = Gtk.Image.new_from_icon_name( 'pan-down-symbolic', Gtk.IconSize.SMALL_TOOLBAR) arrow.props.valign = Gtk.Align.BASELINE box = Gtk.Box() box.set_spacing(3) box.add(label) box.add(arrow) box.show_all() self.remove(self.get_child()) self.add(box) self._label = label def set_label_width(self, width): self._label.set_width_chars(width) class MeldStatusBar(Gtk.Statusbar): __gtype_name__ = "MeldStatusBar" __gsignals__ = { 'start-go-to-line': ( GObject.SignalFlags.ACTION, None, tuple()), 'go-to-line': ( GObject.SignalFlags.RUN_FIRST, None, (int,)), 'encoding-changed': ( GObject.SignalFlags.RUN_FIRST, None, (GtkSource.Encoding,)), } cursor_position = GObject.Property( type=object, nick="The position of the cursor displayed in the status bar", default=None, ) source_encoding = GObject.Property( type=GtkSource.Encoding, nick="The file encoding displayed in the status bar", default=GtkSource.Encoding.get_utf8(), ) source_language = GObject.Property( type=GtkSource.Language, nick="The GtkSourceLanguage displayed in the status bar", default=None, ) # Abbreviation for line, column so that it will fit in the status bar _line_column_text = _("Ln {line}, Col {column}") def __init__(self): super().__init__() self.props.margin = 0 self.props.spacing = 6 hbox = self.get_message_area() label = hbox.get_children()[0] hbox.props.spacing = 6 label.props.ellipsize = Pango.EllipsizeMode.NONE hbox.remove(label) hbox.pack_end(label, False, True, 0) def do_realize(self): Gtk.Statusbar.do_realize(self) self.box_box = Gtk.Box( orientation=Gtk.Orientation.HORIZONTAL, spacing=6 ) self.pack_end(self.box_box, False, True, 0) self.box_box.pack_end( self.construct_line_display(), False, True, 0) self.box_box.pack_end( self.construct_highlighting_selector(), False, True, 0) self.box_box.pack_end( self.construct_encoding_selector(), False, True, 0) self.box_box.pack_end( self.construct_display_popover(), False, True, 0) self.box_box.show_all() def construct_line_display(self): # Note that we're receiving one-based line numbers from the # user and storing and emitting zero-base line numbers. def go_to_line_text(text): try: line = int(text) except ValueError: return self.emit('go-to-line', max(0, line - 1)) def line_entry_mapped(entry): line, offset = self.props.cursor_position entry.set_text(str(line + 1)) # This handler causes a failed assertion due to the `position` # out param (see pygobject#12), but we don't need it here. def line_entry_insert_text(entry, new_text, length, position): if not new_text.isdigit(): GObject.signal_stop_emission_by_name(entry, 'insert-text') return def line_entry_changed(entry): go_to_line_text(entry.get_text()) def line_entry_activated(entry): go_to_line_text(entry.get_text()) pop.popdown() entry = Gtk.Entry() entry.set_tooltip_text(_('Line you want to move the cursor to')) entry.set_icon_from_icon_name( Gtk.EntryIconPosition.PRIMARY, 'go-jump-symbolic') entry.set_icon_activatable(Gtk.EntryIconPosition.PRIMARY, False) entry.set_input_purpose(Gtk.InputPurpose.DIGITS) entry.connect('map', line_entry_mapped) entry.connect('insert-text', line_entry_insert_text) entry.connect('changed', line_entry_changed) entry.connect('activate', line_entry_activated) selector = Gtk.Grid() selector.set_border_width(6) selector.add(entry) selector.show_all() pop = Gtk.Popover() pop.set_position(Gtk.PositionType.TOP) pop.add(selector) def format_cursor_position(binding, cursor): line, offset = cursor return self._line_column_text.format( line=line + 1, column=offset + 1) button = MeldStatusMenuButton() self.bind_property( 'cursor_position', button, 'label', GObject.BindingFlags.DEFAULT, format_cursor_position) self.connect('start-go-to-line', lambda *args: button.clicked()) button.set_popover(pop) # Set a label width to avoid other widgets moving on cursor change reasonable_width = len(format_cursor_position(None, (1000, 100))) - 2 button.set_label_width(reasonable_width) button.show() return button def construct_encoding_selector(self): def change_encoding(selector, encoding): self.emit('encoding-changed', encoding) pop.hide() def set_initial_encoding(selector): selector.select_value(self.props.source_encoding) selector = EncodingSelector() selector.connect('encoding-selected', change_encoding) selector.connect('map', set_initial_encoding) pop = Gtk.Popover() pop.set_position(Gtk.PositionType.TOP) pop.add(selector) button = MeldStatusMenuButton() self.bind_property( 'source-encoding', button, 'label', GObject.BindingFlags.DEFAULT | GObject.BindingFlags.SYNC_CREATE, lambda binding, enc: selector.get_value_label(enc)) button.set_popover(pop) button.show() return button def construct_highlighting_selector(self): def change_language(selector, lang): # TODO: Our other GObject properties are expected to be # updated through a bound state from our parent. This is # the only place where we assign to them instead of # emitting a signal, and it makes the class logic as a # whole kind of confusing. self.props.source_language = lang pop.hide() def set_initial_language(selector): selector.select_value(self.props.source_language) selector = SourceLangSelector() selector.connect('language-selected', change_language) selector.connect('map', set_initial_language) pop = Gtk.Popover() pop.set_position(Gtk.PositionType.TOP) pop.add(selector) button = MeldStatusMenuButton() self.bind_property( 'source-language', button, 'label', GObject.BindingFlags.DEFAULT | GObject.BindingFlags.SYNC_CREATE, lambda binding, enc: selector.get_value_label(enc)) button.set_popover(pop) button.show() return button def construct_display_popover(self): builder = Gtk.Builder.new_from_resource( '/org/gnome/meld/ui/statusbar-menu.ui') menu = builder.get_object('statusbar-menu') pop = Gtk.Popover() pop.bind_model(menu, 'view-local') pop.set_position(Gtk.PositionType.TOP) button = MeldStatusMenuButton() # TRANSLATORS: This is the status bar label for a group of settings, # such as text wrapping, show line numbers, whitespace, etc. button.set_label(_('Display')) button.set_popover(pop) button.show() return button
9,885
Python
.py
238
32.546218
77
0.633605
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,849
bufferselectors.py
GNOME_meld/meld/ui/bufferselectors.py
from gi.repository import GObject, Gtk, GtkSource from meld.conf import _ # TODO: Current pygobject support for templates excludes subclassing of # templated classes, which is why we have two near-identical UI files # here, and why we can't subclass Gtk.Grid directly in # FilteredListSelector. class FilteredListSelector: # FilteredListSelector was initially based on gedit's # GeditHighlightModeSelector # Copyright (C) 2013 - Ignacio Casal Quinteiro # Python translation and adaptations # Copyright (C) 2015, 2017 Kai Willadsen <kai.willadsen@gmail.com> __gtype_name__ = 'FilteredListSelector' NAME_COLUMN, VALUE_COLUMN = 0, 1 def __init__(self): super().__init__() self.treeview_selection = self.treeview.get_selection() # FIXME: Should be able to access as a template child, but can't. self.listfilter = self.treeview.get_model() self.liststore = self.listfilter.get_model() self.populate_model() self.filter_string = '' self.entry.connect('changed', self.on_entry_changed) self.listfilter.set_visible_func(self.name_filter) self.entry.connect('activate', self.on_activate) self.treeview.connect('row-activated', self.on_activate) def populate_model(self): raise NotImplementedError def select_value(self, value): if not value: return new_value_getter = getattr(value, self.value_accessor) for row in self.liststore: row_value = row[self.VALUE_COLUMN] if not row_value: continue old_value_getter = getattr(row_value, self.value_accessor) if old_value_getter() != new_value_getter(): continue self.treeview_selection.select_path(row.path) self.treeview.scroll_to_cell(row.path, None, True, 0.5, 0) def name_filter(self, model, it, *args): if not self.filter_string: return True name = model.get_value(it, self.NAME_COLUMN).lower() return self.filter_string.lower() in name def on_entry_changed(self, entry): self.filter_string = entry.get_text() self.listfilter.refilter() first = self.listfilter.get_iter_first() if first: self.treeview_selection.select_iter(first) def on_activate(self, *args): model, it = self.treeview_selection.get_selected() if not it: return value = model.get_value(it, self.VALUE_COLUMN) self.emit(self.change_signal_name, value) # The subclassing here is weird; the Selector must directly subclass # Gtk.Grid; we can't do this on the FilteredListSelector. Likewise, the # Gtk.Template.Child attributes must be per-class, because of how # they're registered by the templating engine. @Gtk.Template(resource_path='/org/gnome/meld/ui/encoding-selector.ui') class EncodingSelector(FilteredListSelector, Gtk.Grid): # The subclassing here is weird; the Selector must directly # subclass Gtk.Grid, or the template building explodes. __gtype_name__ = 'EncodingSelector' __gsignals__ = { 'encoding-selected': ( GObject.SignalFlags.RUN_FIRST | GObject.SignalFlags.ACTION, None, (GtkSource.Encoding,)), } # These exist solely to make subclassing easier. value_accessor = 'get_charset' change_signal_name = 'encoding-selected' entry = Gtk.Template.Child('entry') treeview = Gtk.Template.Child('treeview') def populate_model(self): for enc in GtkSource.Encoding.get_all(): self.liststore.append((self.get_value_label(enc), enc)) def get_value_label(self, enc): return _('{name} ({charset})').format( name=enc.get_name(), charset=enc.get_charset()) # SourceLangSelector was initially based on gedit's # GeditHighlightModeSelector # Copyright (C) 2013 - Ignacio Casal Quinteiro # Python translation and adaptations # Copyright (C) 2015, 2017 Kai Willadsen <kai.willadsen@gmail.com> @Gtk.Template(resource_path='/org/gnome/meld/ui/language-selector.ui') class SourceLangSelector(FilteredListSelector, Gtk.Grid): __gtype_name__ = "SourceLangSelector" __gsignals__ = { 'language-selected': ( GObject.SignalFlags.RUN_FIRST | GObject.SignalFlags.ACTION, None, (GtkSource.Language,)), } # These exist solely to make subclassing easier. value_accessor = 'get_id' change_signal_name = 'language-selected' entry = Gtk.Template.Child('entry') treeview = Gtk.Template.Child('treeview') def populate_model(self): self.liststore.append((_("Plain Text"), None)) manager = GtkSource.LanguageManager.get_default() for lang_id in manager.get_language_ids(): lang = manager.get_language(lang_id) self.liststore.append((lang.get_name(), lang)) def get_value_label(self, lang): if not lang: return _("Plain Text") return lang.get_name()
5,050
Python
.py
111
38.027027
73
0.675372
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,850
recentselector.py
GNOME_meld/meld/ui/recentselector.py
# Copyright (C) 2019 Kai Willadsen <kai.willadsen@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or (at # your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from gi.repository import GObject, Gtk from meld.recent import RecentFiles @Gtk.Template(resource_path='/org/gnome/meld/ui/recent-selector.ui') class RecentSelector(Gtk.Grid): __gtype_name__ = 'RecentSelector' @GObject.Signal( flags=( GObject.SignalFlags.RUN_FIRST | GObject.SignalFlags.ACTION ), arg_types=(str,), ) def open_recent(self, uri: str) -> None: ... recent_chooser = Gtk.Template.Child() search_entry = Gtk.Template.Child() open_button = Gtk.Template.Child() def do_realize(self): self.filter_text = '' self.recent_chooser.set_filter(self.make_recent_filter()) return Gtk.Grid.do_realize(self) def custom_recent_filter_func( self, filter_info: Gtk.RecentFilterInfo) -> bool: """Filter function for Meld-specific files Normal GTK recent filter rules are all OR-ed together to check whether an entry should be shown. This filter instead only ever shows Meld-specific entries, and then filters down from there. """ if filter_info.mime_type != RecentFiles.mime_type: return False if self.filter_text not in filter_info.display_name.lower(): return False return True def make_recent_filter(self) -> Gtk.RecentFilter: recent_filter = Gtk.RecentFilter() recent_filter.add_custom( ( Gtk.RecentFilterFlags.MIME_TYPE | Gtk.RecentFilterFlags.DISPLAY_NAME ), self.custom_recent_filter_func, ) return recent_filter @Gtk.Template.Callback() def on_filter_text_changed(self, *args): self.filter_text = self.search_entry.get_text().lower() # This feels unnecessary, but there's no other good way to get # the RecentChooser to re-evaluate the filter. self.recent_chooser.set_filter(self.make_recent_filter()) @Gtk.Template.Callback() def on_selection_changed(self, *args): have_selection = bool(self.recent_chooser.get_current_uri()) self.open_button.set_sensitive(have_selection) @Gtk.Template.Callback() def on_activate(self, *args): uri = self.recent_chooser.get_current_uri() if uri: self.open_recent.emit(uri) self.get_parent().popdown()
3,084
Python
.py
73
35.09589
71
0.674916
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,851
vcdialogs.py
GNOME_meld/meld/ui/vcdialogs.py
# Copyright (C) 2002-2006 Stephen Kennedy <stevek@gnome.org> # Copyright (C) 2010-2013 Kai Willadsen <kai.willadsen@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or (at # your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import os import textwrap from gi.repository import Gio, GObject, Gtk, Pango from meld.conf import _ from meld.settings import get_meld_settings, settings @Gtk.Template(resource_path='/org/gnome/meld/ui/commit-dialog.ui') class CommitDialog(Gtk.Dialog): __gtype_name__ = "CommitDialog" break_commit_message = GObject.Property(type=bool, default=False) changedfiles = Gtk.Template.Child() textview = Gtk.Template.Child() scrolledwindow1 = Gtk.Template.Child() previousentry = Gtk.Template.Child() def __init__(self, parent): super().__init__() self.set_transient_for(parent.get_toplevel()) selected = parent._get_selected_files() try: to_commit = parent.vc.get_files_to_commit(selected) topdir = parent.vc.root if to_commit: to_commit = ["\t" + s for s in to_commit] else: to_commit = ["\t" + _("No files will be committed")] except NotImplementedError: topdir = os.path.dirname(os.path.commonprefix(selected)) to_commit = ["\t" + s[len(topdir) + 1:] for s in selected] self.changedfiles.set_text("(in %s)\n%s" % (topdir, "\n".join(to_commit))) font = get_meld_settings().font self.textview.modify_font(font) commit_prefill = parent.vc.get_commit_message_prefill() if commit_prefill: buf = self.textview.get_buffer() buf.set_text(commit_prefill) buf.place_cursor(buf.get_start_iter()) # Try and make the textview wide enough for a standard 80-character # commit message. context = self.textview.get_pango_context() metrics = context.get_metrics(None, None) char_width = metrics.get_approximate_char_width() / Pango.SCALE width_request, height_request = self.scrolledwindow1.get_size_request() self.scrolledwindow1.set_size_request(80 * char_width, height_request) settings.bind('vc-show-commit-margin', self.textview, 'show-right-margin', Gio.SettingsBindFlags.DEFAULT) settings.bind('vc-commit-margin', self.textview, 'right-margin-position', Gio.SettingsBindFlags.DEFAULT) settings.bind('vc-break-commit-message', self, 'break-commit-message', Gio.SettingsBindFlags.DEFAULT) self.show_all() def run(self): self.previousentry.set_active(-1) self.textview.grab_focus() response = super().run() msg = None if response == Gtk.ResponseType.OK: show_margin = self.textview.get_show_right_margin() margin = self.textview.get_right_margin_position() buf = self.textview.get_buffer() msg = buf.get_text(*buf.get_bounds(), include_hidden_chars=False) # This is a dependent option because of the margin column if show_margin and self.props.break_commit_message: paragraphs = msg.split("\n\n") msg = "\n\n".join(textwrap.fill(p, margin) for p in paragraphs) if msg.strip(): self.previousentry.prepend_history(msg) self.destroy() return response, msg @Gtk.Template.Callback() def on_previousentry_activate(self, gentry): idx = gentry.get_active() if idx != -1: model = gentry.get_model() buf = self.textview.get_buffer() buf.set_text(model[idx][1]) @Gtk.Template(resource_path='/org/gnome/meld/ui/push-dialog.ui') class PushDialog(Gtk.MessageDialog): __gtype_name__ = "PushDialog" def __init__(self, parent): super().__init__() self.set_transient_for(parent.get_toplevel()) self.show_all() def run(self): # TODO: Ask the VC for a more informative label for what will happen. # In git, this is probably the parsed output of push --dry-run. response = super().run() self.destroy() return response
4,835
Python
.py
103
38.281553
79
0.643798
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,852
listwidget.py
GNOME_meld/meld/ui/listwidget.py
# Copyright (C) 2002-2009 Stephen Kennedy <stevek@gnome.org> # Copyright (C) 2010-2011, 2013, 2018 Kai Willadsen <kai.willadsen@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or (at # your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. class EditableListWidget: """Helper class with behaviour for simple editable lists The entire point of this is to handle simple list item addition, removal, and rearrangement, and the associated sensitivity handling. This requires template children to be bound as: * `treeview` * `remove` * `move_up` * `move_down` """ def setup_sensitivity_handling(self): model = self.treeview.get_model() model.connect("row-inserted", self._update_sensitivity) model.connect("rows-reordered", self._update_sensitivity) self.treeview.get_selection().connect( "changed", self._update_sensitivity) self._update_sensitivity() def _update_sensitivity(self, *args): model, it, path = self._get_selected() if not it: self.remove.set_sensitive(False) self.move_up.set_sensitive(False) self.move_down.set_sensitive(False) else: self.remove.set_sensitive(True) self.move_up.set_sensitive(path > 0) self.move_down.set_sensitive(path < len(model) - 1) def _get_selected(self): model, it = self.treeview.get_selection().get_selected() path = model.get_path(it)[0] if it else None return (model, it, path) def add_entry(self): self.treeview.get_model().append(self.default_entry) def remove_selected_entry(self): model, it, path = self._get_selected() model.remove(it) def move_up_selected_entry(self): model, it, path = self._get_selected() model.swap(it, model.get_iter(path - 1)) def move_down_selected_entry(self): model, it, path = self._get_selected() model.swap(it, model.get_iter(path + 1))
2,558
Python
.py
57
38.403509
77
0.679791
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,853
gladesupport.py
GNOME_meld/meld/ui/gladesupport.py
import meld.actiongutter # noqa: F401 import meld.chunkmap # noqa: F401 import meld.diffgrid # noqa: F401 import meld.linkmap # noqa: F401 import meld.preferences # noqa: F401 import meld.sourceview # noqa: F401 import meld.ui.emblemcellrenderer # noqa: F401 import meld.ui.filebutton # noqa: F401 import meld.ui.historyentry # noqa: F401 import meld.ui.msgarea # noqa: F401 import meld.ui.notebook # noqa: F401 import meld.ui.pathlabel # noqa: F401 import meld.ui.recentselector # noqa: F401 import meld.ui.statusbar # noqa: F401
545
Python
.py
14
37.928571
47
0.774011
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,854
gtkcompat.py
GNOME_meld/meld/ui/gtkcompat.py
# The original C implementation is part of the GTK+ project, under # gtk+/demos/gtk-demo/foreigndrawing.c # # This Python port of portions of the original source code is copyright # (C) 2009-2015 Kai Willadsen <kai.willadsen@gmail.com>, and is released # under the same LGPL version 2 (or later) license. # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library. If not, see <http://www.gnu.org/licenses/>. import logging import re from gi.repository import GObject, Gtk log = logging.getLogger(__name__) def append_element(path, selector): pseudo_classes = [ ('active', Gtk.StateFlags.ACTIVE), ('hover', Gtk.StateFlags.PRELIGHT), ('selected', Gtk.StateFlags.SELECTED), ('disabled', Gtk.StateFlags.INSENSITIVE), ('indeterminate', Gtk.StateFlags.INCONSISTENT), ('focus', Gtk.StateFlags.FOCUSED), ('backdrop', Gtk.StateFlags.BACKDROP), ('dir(ltr)', Gtk.StateFlags.DIR_LTR), ('dir(rtl)', Gtk.StateFlags.DIR_RTL), ('link', Gtk.StateFlags.LINK), ('visited', Gtk.StateFlags.VISITED), ('checked', Gtk.StateFlags.CHECKED), ('drop(active)', Gtk.StateFlags.DROP_ACTIVE) ] toks = [t for t in re.split(r'([#\.:])', selector) if t] elements = [toks[i] + toks[i + 1] for i in range(1, len(toks), 2)] name = toks[0] if name[0].isupper(): gtype = GObject.GType.from_name(name) if gtype == GObject.TYPE_INVALID: log.error('Unknown type name "%s"', name) return path.append_type(gtype) else: # Omit type, we're using name path.append_type(GObject.TYPE_NONE) path.iter_set_object_name(-1, name) for segment in elements: segment_type = segment[0] name = segment[1:] if segment_type == '#': path.iter_set_name(-1, name) break elif segment_type == '.': path.iter_add_class(-1, name) break elif segment_type == ':': for class_name, class_state in pseudo_classes: if name == class_name: path.iter_set_state( -1, path.iter_get_state(-1) | class_state) break else: log.error('Unknown pseudo-class :%s', name) pass break else: assert False def create_context_for_path(path, parent): context = Gtk.StyleContext.new() context.set_path(path) context.set_parent(parent) context.set_state(path.iter_get_state(-1)) return context def get_style(parent, selector): if parent: path = Gtk.WidgetPath.copy(parent.get_path()) else: path = Gtk.WidgetPath.new() append_element(path, selector) return create_context_for_path(path, parent) def query_size(context, width, height): margin = context.get_margin(context.get_state()) border = context.get_border(context.get_state()) padding = context.get_padding(context.get_state()) min_width = context.get_property('min-width', context.get_state()) min_height = context.get_property('min-height', context.get_state()) min_width += ( margin.left + margin.right + border.left + border.right + padding.left + padding.right) min_height += ( margin.top + margin.bottom + border.top + border.bottom + padding.top + padding.bottom) return max(width, min_width), max(height, min_height) def draw_style_common(context, cr, x, y, width, height): margin = context.get_margin(context.get_state()) border = context.get_border(context.get_state()) padding = context.get_padding(context.get_state()) min_width = context.get_property('min-width', context.get_state()) min_height = context.get_property('min-height', context.get_state()) x += margin.left y += margin.top width -= margin.left + margin.right height -= margin.top + margin.bottom width = max(width, min_width) height = max(height, min_height) Gtk.render_background(context, cr, x, y, width, height) Gtk.render_frame(context, cr, x, y, width, height) contents_x = x + border.left + padding.left contents_y = y + border.top + padding.top contents_width = ( width - border.left - border.right - padding.left - padding.right) contents_height = ( height - border.top - border.bottom - padding.top - padding.bottom) return contents_x, contents_y, contents_width, contents_height
5,143
Python
.py
120
36.083333
78
0.642257
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,855
findbar.py
GNOME_meld/meld/ui/findbar.py
# Copyright (C) 2002-2009 Stephen Kennedy <stevek@gnome.org> # Copyright (C) 2012-2014 Kai Willadsen <kai.willadsen@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or (at # your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from typing import ClassVar, Optional from gi.repository import GObject, Gtk, GtkSource @Gtk.Template(resource_path='/org/gnome/meld/ui/findbar.ui') class FindBar(Gtk.Grid): __gtype_name__ = 'FindBar' find_entry = Gtk.Template.Child() find_next_button = Gtk.Template.Child() find_previous_button = Gtk.Template.Child() match_case = Gtk.Template.Child() regex = Gtk.Template.Child() replace_all_button = Gtk.Template.Child() replace_button = Gtk.Template.Child() replace_entry = Gtk.Template.Child() whole_word = Gtk.Template.Child() wrap_box = Gtk.Template.Child() replace_mode = GObject.Property(type=bool, default=False) _cached_search: ClassVar[Optional[str]] = None @GObject.Signal( name='activate-secondary', flags=( GObject.SignalFlags.RUN_FIRST | GObject.SignalFlags.ACTION ), ) def activate_secondary(self) -> None: self._find_text(backwards=True) def __init__(self, parent): super().__init__() self.search_context = None self.notify_id = None self.set_text_view(None) # Create and bind our GtkSourceSearchSettings settings = GtkSource.SearchSettings() self.match_case.bind_property('active', settings, 'case-sensitive') self.whole_word.bind_property('active', settings, 'at-word-boundaries') self.regex.bind_property('active', settings, 'regex-enabled') self.find_entry.bind_property('text', settings, 'search-text') settings.set_wrap_around(True) self.search_settings = settings # Bind visibility and layout for find-and-replace mode self.bind_property('replace_mode', self.replace_entry, 'visible') self.bind_property('replace_mode', self.replace_all_button, 'visible') self.bind_property('replace_mode', self.replace_button, 'visible') self.bind_property( 'replace_mode', self, 'row-spacing', GObject.BindingFlags.DEFAULT, lambda binding, replace_mode: 6 if replace_mode else 0) def hide(self): self.set_text_view(None) self.wrap_box.set_visible(False) Gtk.Widget.hide(self) def update_match_state(self, *args): # Note that -1 here implies that the search is still running no_matches = ( self.search_context.props.occurrences_count == 0 and self.search_settings.props.search_text ) style_context = self.find_entry.get_style_context() if no_matches: style_context.add_class(Gtk.STYLE_CLASS_ERROR) else: style_context.remove_class(Gtk.STYLE_CLASS_ERROR) def set_text_view(self, textview): self.textview = textview if textview is not None: self.search_context = GtkSource.SearchContext.new( textview.get_buffer(), self.search_settings) self.search_context.set_highlight(True) self.notify_id = self.search_context.connect( 'notify::occurrences-count', self.update_match_state) else: if self.notify_id: self.search_context.disconnect(self.notify_id) self.notify_id = None self.search_context = None def start_find(self, *, textview: Gtk.TextView, replace: bool, text: str): self.replace_mode = replace self.set_text_view(textview) if text: self.find_entry.set_text(text) FindBar._cached_search = text elif FindBar._cached_search: self.find_entry.set_text(FindBar._cached_search) self.show() self.find_entry.grab_focus() def start_find_next(self, textview): self.set_text_view(textview) self._find_text() def start_find_previous(self, textview): self.set_text_view(textview) self._find_text(backwards=True) @Gtk.Template.Callback() def on_find_next_button_clicked(self, button): self._find_text() @Gtk.Template.Callback() def on_find_previous_button_clicked(self, button): self._find_text(backwards=True) @Gtk.Template.Callback() def on_replace_button_clicked(self, entry): buf = self.textview.get_buffer() oldsel = buf.get_selection_bounds() match = self._find_text(0) newsel = buf.get_selection_bounds() # Only replace if there is an already-selected match at the cursor if (match and oldsel and oldsel[0].equal(newsel[0]) and oldsel[1].equal(newsel[1])): self.search_context.replace( newsel[0], newsel[1], self.replace_entry.get_text(), -1) self._find_text(0) @Gtk.Template.Callback() def on_replace_all_button_clicked(self, entry): buf = self.textview.get_buffer() saved_insert = buf.create_mark( None, buf.get_iter_at_mark(buf.get_insert()), True) self.search_context.replace_all(self.replace_entry.get_text(), -1) if not saved_insert.get_deleted(): buf.place_cursor(buf.get_iter_at_mark(saved_insert)) self.textview.scroll_to_mark( buf.get_insert(), 0.25, True, 0.5, 0.5) @Gtk.Template.Callback() def on_toggle_replace_button_clicked(self, button): self.replace_mode = not self.replace_mode @Gtk.Template.Callback() def on_find_entry_changed(self, entry): FindBar._cached_search = entry.get_text() self._find_text(0) @Gtk.Template.Callback() def on_stop_search(self, search_entry): self.hide() def _find_text(self, start_offset=1, backwards=False): if not self.textview or not self.search_context: return buf = self.textview.get_buffer() insert = buf.get_iter_at_mark(buf.get_insert()) start, end = buf.get_bounds() self.wrap_box.set_visible(False) if not backwards: insert.forward_chars(start_offset) match, start, end, wrapped = self.search_context.forward(insert) else: match, start, end, wrapped = self.search_context.backward(insert) if match: self.wrap_box.set_visible(wrapped) buf.place_cursor(start) buf.move_mark(buf.get_selection_bound(), end) self.textview.scroll_to_mark( buf.get_insert(), 0.25, True, 0.5, 0.5) return True else: buf.place_cursor(buf.get_iter_at_mark(buf.get_insert())) self.wrap_box.set_visible(False) FindBar.set_css_name('meld-find-bar')
7,384
Python
.py
166
36.018072
79
0.648532
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,856
gtkutil.py
GNOME_meld/meld/ui/gtkutil.py
# Copyright (C) 2023 Kai Willadsen <kai.willadsen@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or (at # your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from gi.repository import Gdk def make_gdk_rgba(red: float, green: float, blue: float, alpha: float) -> Gdk.RGBA: rgba = Gdk.RGBA() rgba.red = red rgba.green = green rgba.blue = blue rgba.alpha = alpha return rgba
938
Python
.py
22
40.409091
83
0.751369
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,857
_vc.py
GNOME_meld/meld/vc/_vc.py
# Copyright (C) 2002-2005 Stephen Kennedy <stevek@gnome.org> # Copyright (C) 2010, 2012-2015 Kai Willadsen <kai.willadsen@gmail.com> # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR # IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES # OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. # IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT # NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF # THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import collections import itertools import os import re import shutil import subprocess import tempfile from typing import ClassVar from gi.repository import Gio, GLib from meld.conf import _ from meld.misc import get_hide_window_startupinfo # ignored, new, normal, ignored changes, # error, placeholder, vc added # vc modified, vc renamed, vc conflict, vc removed # locally removed, end (STATE_IGNORED, STATE_NONE, STATE_NORMAL, STATE_NOCHANGE, STATE_ERROR, STATE_EMPTY, STATE_NEW, STATE_MODIFIED, STATE_RENAMED, STATE_CONFLICT, STATE_REMOVED, STATE_MISSING, STATE_NONEXIST, STATE_SPINNER, STATE_MAX) = list(range(15)) # VC conflict types (CONFLICT_MERGED, CONFLICT_BASE, CONFLICT_LOCAL, CONFLICT_REMOTE, CONFLICT_MAX) = list(range(5)) # These names are used by BZR, and are logically identical. CONFLICT_OTHER = CONFLICT_REMOTE CONFLICT_THIS = CONFLICT_LOCAL conflicts = [_("Merged"), _("Base"), _("Local"), _("Remote")] assert len(conflicts) == CONFLICT_MAX # Lifted from the itertools recipes section def partition(pred, iterable): t1, t2 = itertools.tee(iterable) return (list(itertools.ifilterfalse(pred, t1)), list(itertools.ifilter(pred, t2))) class Entry: # These are labels for possible states of version controlled files; # not all states have a label to avoid visual clutter. state_names = { STATE_IGNORED: _("Ignored"), STATE_NONE: _("Unversioned"), STATE_NORMAL: "", STATE_NOCHANGE: "", STATE_ERROR: _("Error"), STATE_EMPTY: "", STATE_NEW: _("Newly added"), STATE_MODIFIED: _("Modified"), STATE_RENAMED: _("Renamed"), STATE_CONFLICT: "<b>%s</b>" % _("Conflict"), STATE_REMOVED: _("Removed"), STATE_MISSING: _("Missing"), STATE_NONEXIST: _("Not present"), STATE_SPINNER: _("Scanning…"), } def __init__(self, path, name, state, isdir, options=None): self.path = path self.name = name self.state = state self.isdir = isdir if isinstance(options, list): options = ','.join(options) self.options = options def __str__(self): return "<%s:%s %s>" % (self.__class__.__name__, self.path, self.get_status() or "Normal") def __repr__(self): return "%s(%r, %r, %r)" % (self.__class__.__name__, self.name, self.path, self.state) def get_status(self): return self.state_names[self.state] def is_present(self): """Should this Entry actually be present on the file system""" return self.state not in (STATE_REMOVED, STATE_MISSING) @staticmethod def is_modified(entry): return entry.state >= STATE_NEW or ( entry.isdir and (entry.state > STATE_NONE)) @staticmethod def is_normal(entry): return entry.state == STATE_NORMAL @staticmethod def is_nonvc(entry): return entry.state == STATE_NONE or ( entry.isdir and (entry.state > STATE_IGNORED)) @staticmethod def is_ignored(entry): return entry.state == STATE_IGNORED or entry.isdir class Vc: VC_DIR: ClassVar[str] #: Whether to walk the current location's parents to find a #: repository root. Only used in legacy version control systems #: (e.g., old SVN, CVS, RCS). VC_ROOT_WALK: ClassVar[bool] = True def __init__(self, path): # Save the requested comparison location. The location may be a # sub-directory of the repository we are diffing and can be useful in # limiting meld's output to the requested location. # # If the location requested is a file (e.g., a single-file command line # comparison) then the location is set to the containing directory. self.root, self.location = self.is_in_repo(path) if not self.root: raise ValueError self._tree_cache = {} self._tree_meta_cache = {} self._tree_missing_cache = collections.defaultdict(set) def run(self, *args, use_locale_encoding=True): """Return subprocess running VC with `args` at VC's location For example, `git_vc.run('log', '-p')` will run `git log -p` and return the subprocess object. If use_locale_encoding is True, the return value is a unicode text stream with universal newlines. If use_locale_encoding is False, the return value is a binary stream. Note that this runs at the *location*, not at the *root*. """ cmd = (self.CMD,) + args return subprocess.Popen( cmd, cwd=self.location, stdout=subprocess.PIPE, universal_newlines=use_locale_encoding, startupinfo=get_hide_window_startupinfo(), ) def get_files_to_commit(self, paths): """Get a list of files that will be committed from paths paths is a list of paths under the version control system root, which may include directories. The return value must be a list of file paths that would actually be committed given the path argument; specifically this should exclude unchanged files and recursively list files in directories. """ raise NotImplementedError() def get_commit_message_prefill(self): """Get a version-control defined pre-filled commit message This will return a unicode message in situations where the version control system has a (possibly partial) pre-filled message, or None if no such message exists. This method should use pre-filled commit messages wherever provided by the version control system, most commonly these are given in merging, revert or cherry-picking scenarios. """ return None def get_commits_to_push_summary(self): """Return a one-line readable description of unpushed commits This provides a one-line description of what would be pushed by the version control's push action, e.g., "2 unpushed commits in 3 branches". Version control systems that always only push the current branch should not show branch information. """ raise NotImplementedError() def get_valid_actions(self, path_states): """Get the set of valid actions for paths with version states path_states is a list of (path, state) tuples describing paths in the version control system. This will return all valid version control actions that could reasonably be taken on *all* of the paths in path_states. If an individual plugin needs special handling, or doesn't implement all standard actions, this should be overridden. """ valid_actions = set() states = path_states.values() if bool(path_states): valid_actions.add('compare') valid_actions.add('update') # TODO: We can't do this; this shells out for each selection change... # if bool(self.get_commits_to_push()): valid_actions.add('push') non_removeable_states = (STATE_NONE, STATE_IGNORED, STATE_REMOVED) non_revertable_states = (STATE_NONE, STATE_NORMAL, STATE_IGNORED) # TODO: We can't disable this for NORMAL, because folders don't # inherit any state from their children, but committing a folder with # modified children is expected behaviour. if all(s not in (STATE_NONE, STATE_IGNORED) for s in states): valid_actions.add('commit') if all(s not in (STATE_NORMAL, STATE_REMOVED) for s in states): valid_actions.add('add') if all(s == STATE_CONFLICT for s in states): valid_actions.add('resolve') if (all(s not in non_removeable_states for s in states) and self.root not in path_states.keys()): valid_actions.add('remove') if all(s not in non_revertable_states for s in states): valid_actions.add('revert') return valid_actions def get_path_for_repo_file(self, path, commit=None): """Returns a file path for the repository path at commit If *commit* is given, the path returned will point to a copy of the file at *path* at the given commit, as interpreted by the VCS. If *commit* is **None**, the current revision is used. Even if the VCS maintains an on-disk copy of the given path, a temp file with file-at-commit content must be created and its path returned, to avoid destructive editing. The VCS plugin must **not** delete temp files it creates. """ raise NotImplementedError() def get_path_for_conflict(self, path, conflict): """Returns a file path for the conflicted repository path *conflict* is the side of the conflict to be retrieved, and must be one of the CONFLICT_* constants. """ raise NotImplementedError() def refresh_vc_state(self, path=None): """Update cached version control state If a path is provided, for example when a file has been modified and saved in the file comparison view and needs its state refreshed, then only that path will be updated. If no path is provided then the version control tree rooted at its `location` will be recursively refreshed. """ if path is None: self._tree_cache = {} self._tree_missing_cache = collections.defaultdict(set) path = './' self._update_tree_state_cache(path) def get_entries(self, base): parent = Gio.File.new_for_path(base) enumerator = parent.enumerate_children( 'standard::name,standard::display-name,standard::type', Gio.FileQueryInfoFlags.NOFOLLOW_SYMLINKS, None) for file_info in enumerator: if file_info.get_name() == self.VC_DIR: continue gfile = enumerator.get_child(file_info) path = gfile.get_path() name = file_info.get_display_name() state = self._tree_cache.get(path, STATE_NORMAL) meta = self._tree_meta_cache.get(path, "") isdir = file_info.get_file_type() == Gio.FileType.DIRECTORY yield Entry(path, name, state, isdir, options=meta) # Removed entries are not in the filesystem, so must be added here for name in self._tree_missing_cache[base]: path = os.path.join(base, name) state = self._tree_cache.get(path, STATE_NORMAL) # TODO: Ideally we'd know whether this was a folder # or a file. Since it's gone however, only the VC # knows, and may or may not tell us. meta = self._tree_meta_cache.get(path, "") yield Entry(path, name, state, isdir=False, options=meta) def _add_missing_cache_entry(self, path, state): if state in (STATE_REMOVED, STATE_MISSING): folder, name = os.path.split(path) self._tree_missing_cache[folder].add(name) def get_entry(self, path): """Return the entry associated with the given path in this VC If the given path does not correspond to an entry in the VC, this method returns an Entry with the appropriate REMOVED or MISSING state. """ gfile = Gio.File.new_for_path(path) try: file_info = gfile.query_info( 'standard::*', Gio.FileQueryInfoFlags.NOFOLLOW_SYMLINKS, None) name = file_info.get_display_name() isdir = file_info.get_file_type() == Gio.FileType.DIRECTORY except GLib.Error as e: if e.domain != 'g-io-error-quark': raise # Handling for non-existent files (or other IO errors) name = path isdir = False path = gfile.get_path() state = self._tree_cache.get(path, STATE_NORMAL) meta = self._tree_meta_cache.get(path, "") return Entry(path, name, state, isdir, options=meta) @classmethod def is_installed(cls): try: call([cls.CMD]) return True except Exception: return False @classmethod def is_in_repo(cls, path): root = None location = path if os.path.isdir(path) else os.path.dirname(path) if cls.VC_ROOT_WALK: root = cls.find_repo_root(location) elif cls.check_repo_root(location): root = location return root, location @classmethod def check_repo_root(cls, location): return os.path.isdir(os.path.join(location, cls.VC_DIR)) @classmethod def find_repo_root(cls, location): while location: if cls.check_repo_root(location): return location location, old = os.path.dirname(location), location if location == old: break @classmethod def valid_repo(cls, path): """Determine if a directory is a valid repository for this class""" raise NotImplementedError class InvalidVCPath(ValueError): """Raised when a VC module is passed an invalid (or not present) path.""" def __init__(self, vc, path, err): self.vc = vc self.path = path self.error = err def __str__(self): return "%s: Path %s is invalid or not present\nError: %s\n" % \ (self.vc.NAME, self.path, self.error) class InvalidVCRevision(ValueError): """Raised when a VC module is passed a revision spec it can't handle.""" def __init__(self, vc, rev, err): self.vc = vc self.revision = rev self.error = err def __str__(self): return "%s: Doesn't understand or have revision %s\nError: %s\n" % \ (self.vc.NAME, self.revision, self.error) def popen(cmd, cwd=None, use_locale_encoding=True): """Return the stdout output of a given command as a stream. If use_locale_encoding is True, the output is parsed to unicode text stream with universal newlines. If use_locale_encoding is False output is treated as binary stream. """ process = subprocess.Popen( cmd, cwd=cwd, stdout=subprocess.PIPE, universal_newlines=use_locale_encoding, startupinfo=get_hide_window_startupinfo(), ) return process.stdout def call_temp_output(cmd, cwd, file_id='', suffix=None): """Call `cmd` in `cwd` and write the output to a temporary file This returns the name of the temporary file used. It is the caller's responsibility to delete this file. If `file_id` is provided, it is used as part of the temporary file's name, for ease of identification. If `suffix` is provided, it is used as the extension of the temporary file's name. """ process = subprocess.Popen( cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo=get_hide_window_startupinfo(), ) vc_file = process.stdout # Error handling here involves doing nothing; in most cases, the only # sane response is to return an empty temp file. prefix = 'meld-tmp' + ('-' + file_id if file_id else '') with tempfile.NamedTemporaryFile(prefix=prefix, suffix=suffix, delete=False) as f: shutil.copyfileobj(vc_file, f) return f.name # Return the return value of a given command def call(cmd, cwd=None): devnull = open(os.devnull, "wb") return subprocess.call( cmd, cwd=cwd, stdout=devnull, stderr=devnull, startupinfo=get_hide_window_startupinfo(), ) base_re = re.compile( br"^<{7}.*?$\r?\n(?P<local>.*?)" br"^\|{7}.*?$\r?\n(?P<base>.*?)" br"^={7}.*?$\r?\n(?P<remote>.*?)" br"^>{7}.*?$\r?\n", flags=re.DOTALL | re.MULTILINE) def base_from_diff3(merged): return base_re.sub(br"==== BASE ====\n\g<base>==== BASE ====\n", merged)
17,376
Python
.py
376
38.194149
79
0.650934
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,858
cvs.py
GNOME_meld/meld/vc/cvs.py
# Copyright (C) 2002-2005 Stephen Kennedy <stevek@gnome.org> # Copyright (C) 2015 Kai Willadsen <kai.willadsen@gmail.com> # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR # IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES # OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. # IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT # NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF # THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import errno import os import shutil from . import _vc class Vc(_vc.Vc): # CVSNT is a drop-in replacement for CVS; if found, it is used instead CMD = "cvsnt" if shutil.which("cvsnt") else "cvs" NAME = "CVS" VC_DIR = "CVS" VC_ROOT_WALK = False # According to the output of the 'status' command state_map = { "Unknown": _vc.STATE_NONE, "Locally Added": _vc.STATE_NEW, "Up-to-date": _vc.STATE_NORMAL, "!": _vc.STATE_MISSING, "I": _vc.STATE_IGNORED, "Locally Modified": _vc.STATE_MODIFIED, "Locally Removed": _vc.STATE_REMOVED, } def commit(self, runner, files, message): command = [self.CMD, 'commit', '-m', message] runner(command, files, refresh=True, working_dir=self.root) def update(self, runner): command = [self.CMD, 'update'] runner(command, [], refresh=True, working_dir=self.root) def add(self, runner, afiles): # CVS needs to add files together with all the parents # (if those are Unversioned yet) relfiles = [ os.path.relpath(s, self.root) for s in afiles if os.path.isfile(s) ] command = [self.CMD, 'add'] relargs = [] for f1 in relfiles: positions = [i for i, ch in enumerate(f1 + os.sep) if ch == os.sep] arg1 = [f1[:pos] for pos in positions] relargs += arg1 absargs = [os.path.join(self.root, a1) for a1 in relargs] runner(command, absargs, refresh=True, working_dir=self.root) def remove(self, runner, files): command = [self.CMD, 'remove', '-f'] runner(command, files, refresh=True, working_dir=self.root) def revert(self, runner, files): command = [self.CMD, 'update', '-C'] runner(command, files, refresh=True, working_dir=self.root) @classmethod def valid_repo(cls, path): return not _vc.call([cls.CMD, 'ls'], cwd=path) def get_path_for_repo_file(self, path, commit=None): if commit is not None: raise NotImplementedError() if not path.startswith(self.root + os.path.sep): raise _vc.InvalidVCPath(self, path, "Path not in repository") path = path[len(self.root) + 1:] suffix = os.path.splitext(path)[1] args = [self.CMD, "-q", "update", "-p", path] return _vc.call_temp_output(args, cwd=self.root, suffix=suffix) def _find_files(self, path): relfiles = [] loc = os.path.join(self.location, path) for step in os.walk(loc): if not step[0].endswith(self.VC_DIR): ff = [os.path.join(step[0], f1) for f1 in step[2]] relfiles += [os.path.relpath(ff1, loc) for ff1 in ff] return relfiles def _update_tree_state_cache(self, path): """ Update the state of the file(s) at self._tree_cache['path'] """ while 1: try: # Get the status of files path_isdir = os.path.isdir(path) files = self._find_files(path) if path_isdir else [path] # Should suppress stderr here proc = _vc.popen( [self.CMD, "-Q", "status"] + files, cwd=self.location, ) entries = [ li for li in proc.read().splitlines() if li.startswith('File:') ] break except OSError as e: if e.errno != errno.EAGAIN: raise if len(entries) == 0 and os.path.isfile(path): # If we're just updating a single file there's a chance that # it was previously modified, and now has been edited so that # it is un-modified. This will result in an empty 'entries' list, # and self._tree_cache['path'] will still contain stale data. # When this corner case occurs we force self._tree_cache['path'] # to STATE_NORMAL. self._tree_cache[path] = _vc.STATE_NORMAL else: # There are 1 or more [modified] files, parse their state for entry in zip(files, entries): statekey = entry[1].split(':')[-1].strip() name = entry[0].strip() if os.path.basename(name) not in entry[1]: # ? The short filename got from # 'cvs -Q status <path/file>' does not match <file> raise path = os.path.join(self.location, name) state = self.state_map.get(statekey, _vc.STATE_NONE) self._tree_cache[path] = state self._add_missing_cache_entry(path, state) """ # Setting the state of dirs also might be relevant, but not sure # Heuristic to find out the state ('CVS' subdir exists or not) for entry in zip(dirs, [os.path.isdir(os.path.join(d1, self.VC_DIR)) for d1 in dirs]): path = os.path.join(self.location, entry[0]) state = _vc.STATE_NORMAL if entry[1] else _vc.STATE_NONE self._tree_cache[path] = state self._add_missing_cache_entry(path, state) """
6,697
Python
.py
139
38.381295
79
0.601133
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,859
git.py
GNOME_meld/meld/vc/git.py
# Copyright (C) 2002-2005 Stephen Kennedy <stevek@gnome.org> # Copyright (C) 2005 Aaron Bentley <aaron.bentley@utoronto.ca> # Copyright (C) 2007 José Fonseca <j_r_fonseca@yahoo.co.uk> # Copyright (C) 2010-2015 Kai Willadsen <kai.willadsen@gmail.com> # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR # IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES # OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. # IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT # NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF # THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import codecs import errno import io import os import re import shutil import stat import subprocess import tempfile from collections import defaultdict from meld.conf import _, ngettext from . import _vc NULL_SHA = "0000000000000000000000000000000000000000" class Vc(_vc.Vc): CMD = "git" NAME = "Git" VC_DIR = ".git" DIFF_FILES_RE = r":(\d+) (\d+) ([a-z0-9]+) ([a-z0-9]+) ([XADMTU])\t(.*)" DIFF_RE = re.compile(DIFF_FILES_RE) conflict_map = { # These are the arguments for git-show # CONFLICT_MERGED has no git-show argument unfortunately. _vc.CONFLICT_BASE: 1, _vc.CONFLICT_LOCAL: 2, _vc.CONFLICT_REMOTE: 3, } state_map = { "X": _vc.STATE_NONE, # Unknown "A": _vc.STATE_NEW, # New "D": _vc.STATE_REMOVED, # Deleted "M": _vc.STATE_MODIFIED, # Modified "T": _vc.STATE_MODIFIED, # Type-changed "U": _vc.STATE_CONFLICT, # Unmerged } @classmethod def is_installed(cls): try: proc = _vc.popen([cls.CMD, '--version']) assert proc.read().startswith('git version') return True except Exception: return False @classmethod def check_repo_root(cls, location): # Check exists instead of isdir, since .git might be a git-file return os.path.exists(os.path.join(location, cls.VC_DIR)) def get_commits_to_push_summary(self): branch_refs = self.get_commits_to_push() unpushed_branches = len([v for v in branch_refs.values() if v]) unpushed_commits = sum(len(v) for v in branch_refs.values()) if unpushed_commits: if unpushed_branches > 1: # Translators: First element is replaced by translated "%d # unpushed commits", second element is replaced by translated # "%d branches" label = _("{unpushed_commits} in {unpushed_branches}").format( unpushed_commits=ngettext( "%d unpushed commit", "%d unpushed commits", unpushed_commits) % unpushed_commits, unpushed_branches=ngettext( "%d branch", "%d branches", unpushed_branches) % unpushed_branches, ) else: # Translators: These messages cover the case where there is # only one branch, and are not part of another message. label = ngettext( "%d unpushed commit", "%d unpushed commits", unpushed_commits) % (unpushed_commits) else: label = "" return label def get_commits_to_push(self): proc = self.run( "for-each-ref", "--format=%(refname:short) %(upstream:short) %(upstream:trackshort)", "refs/heads") branch_remotes = proc.stdout.read().split("\n")[:-1] branch_revisions = {} for line in branch_remotes: try: branch, remote, track = line.split() except ValueError: continue proc = self.run("rev-list", branch, "^" + remote, "--") revisions = proc.stdout.read().split("\n")[:-1] branch_revisions[branch] = revisions return branch_revisions def get_files_to_commit(self, paths): files = [] for p in paths: if os.path.isdir(p): cached_entries, entries = self._get_modified_files(p) all_entries = set(entries + cached_entries) names = [ self.DIFF_RE.search(e).groups()[5] for e in all_entries ] files.extend(names) else: files.append(os.path.relpath(p, self.root)) return sorted(list(set(files))) def get_commit_message_prefill(self): commit_path = os.path.join(self.root, ".git", "MERGE_MSG") if os.path.exists(commit_path): # If I have to deal with non-ascii, non-UTF8 pregenerated commit # messages, I'm taking up pig farming. with open(commit_path, encoding='utf-8') as f: message = f.read() return "\n".join( line for line in message.splitlines() if not line.startswith("#") ) return None def commit(self, runner, files, message): command = [self.CMD, 'commit', '-m', message] runner(command, files, refresh=True, working_dir=self.root) def update(self, runner): command = [self.CMD, 'pull'] runner(command, [], refresh=True, working_dir=self.root) def push(self, runner): command = [self.CMD, 'push'] runner(command, [], refresh=True, working_dir=self.root) def add(self, runner, files): command = [self.CMD, 'add'] runner(command, files, refresh=True, working_dir=self.root) def remove(self, runner, files): command = [self.CMD, 'rm', '-r'] runner(command, files, refresh=True, working_dir=self.root) def revert(self, runner, files): exists = [f for f in files if os.path.exists(f)] missing = [f for f in files if not os.path.exists(f)] if exists: command = [self.CMD, 'checkout'] runner(command, exists, refresh=True, working_dir=self.root) if missing: command = [self.CMD, 'checkout', 'HEAD'] runner(command, missing, refresh=True, working_dir=self.root) def resolve(self, runner, files): command = [self.CMD, 'add'] runner(command, files, refresh=True, working_dir=self.root) def remerge_with_ancestor(self, local, base, remote, suffix=''): """Reconstruct a mixed merge-plus-base file This method re-merges a given file to get diff3-style conflicts which we can then use to get a file that contains the pre-merged result everywhere that has no conflict, and the common ancestor anywhere there *is* a conflict. """ proc = self.run( "merge-file", "-p", "--diff3", local, base, remote, use_locale_encoding=False) vc_file = io.BytesIO( _vc.base_from_diff3(proc.stdout.read())) prefix = 'meld-tmp-%s-' % _vc.CONFLICT_MERGED with tempfile.NamedTemporaryFile( prefix=prefix, suffix=suffix, delete=False) as f: shutil.copyfileobj(vc_file, f) return f.name, True def get_repo_relative_path(self, path): root_prefix = self.root if self.root == "/" else self.root + os.path.sep if not path.startswith(root_prefix): raise _vc.InvalidVCPath(self, path, "Path not in repository") path = path[len(root_prefix):] if os.name == "nt": path = path.replace("\\", "/") return path def get_path_for_conflict(self, path, conflict): if conflict == _vc.CONFLICT_MERGED: # Special case: no way to get merged result from git directly local, _ = self.get_path_for_conflict(path, _vc.CONFLICT_LOCAL) base, _ = self.get_path_for_conflict(path, _vc.CONFLICT_BASE) remote, _ = self.get_path_for_conflict(path, _vc.CONFLICT_REMOTE) if not (local and base and remote): raise _vc.InvalidVCPath(self, path, "Couldn't access conflict parents") suffix = os.path.splitext(path)[1] filename, is_temp = self.remerge_with_ancestor( local, base, remote, suffix=suffix) for temp_file in (local, base, remote): if os.name == "nt": os.chmod(temp_file, stat.S_IWRITE) os.remove(temp_file) return filename, is_temp repo_path = self.get_repo_relative_path(path) suffix = os.path.splitext(repo_path)[1] args = ["git", "show", ":%s:%s" % (self.conflict_map[conflict], repo_path)] filename = _vc.call_temp_output( args, cwd=self.location, file_id=_vc.conflicts[conflict], suffix=suffix) return filename, True def get_path_for_repo_file(self, path, commit=None): if commit is None: commit = "HEAD" else: raise NotImplementedError() repo_path = self.get_repo_relative_path(path) obj = commit + ":" + repo_path suffix = os.path.splitext(repo_path)[1] args = [self.CMD, "cat-file", "blob", obj] return _vc.call_temp_output(args, cwd=self.root, suffix=suffix) @classmethod def valid_repo(cls, path): # TODO: On Windows, this exit code is wrong under the normal shell; it # appears to be correct under the default git bash shell however. return not _vc.call([cls.CMD, "branch"], cwd=path) def _get_modified_files(self, path): # Update the index to avoid reading stale status information proc = self.run("update-index", "--refresh") try: proc.communicate(timeout=5) except subprocess.TimeoutExpired: proc.terminate() proc.communicate() # Get status differences between the index and the repo HEAD proc = self.run("diff-index", "--cached", "HEAD", "--relative", path) cached_entries = proc.stdout.read().split("\n")[:-1] # Get status differences between the index and files-on-disk proc = self.run("diff-files", "-0", "--relative", path) entries = proc.stdout.read().split("\n")[:-1] # Files can show up in both lists, e.g., if a file is modified, # added to the index and changed again. This is okay, and in # fact the calling logic requires it for staging feedback. return cached_entries, entries def _update_tree_state_cache(self, path): """ Update the state of the file(s) at self._tree_cache['path'] """ while 1: try: cached_entries, entries = self._get_modified_files(path) # Identify ignored files and folders proc = self.run( "ls-files", "--others", "--ignored", "--exclude-standard", "--directory", path) ignored_entries = proc.stdout.read().split("\n")[:-1] # Identify unversioned files proc = self.run( "ls-files", "--others", "--exclude-standard", path) unversioned_entries = proc.stdout.read().split("\n")[:-1] break except OSError as e: if e.errno != errno.EAGAIN: raise def get_real_path(name): name = name.strip() if os.name == 'nt': # Git returns unix-style paths on Windows name = os.path.normpath(name) # Unicode file names and file names containing quotes are # returned by git as quoted strings if name[0] == '"': name = name.encode('latin1') name = codecs.escape_decode(name[1:-1])[0].decode('utf-8') return os.path.abspath( os.path.join(self.location, name)) if not cached_entries and not entries and os.path.isfile(path): # If we're just updating a single file there's a chance that it # was it was previously modified, and now has been edited so that # it is un-modified. This will result in an empty 'entries' list, # and self._tree_cache['path'] will still contain stale data. # When this corner case occurs we force self._tree_cache['path'] # to STATE_NORMAL. self._tree_cache[get_real_path(path)] = _vc.STATE_NORMAL else: tree_meta_cache = defaultdict(list) staged = set() unstaged = set() # We iterate over both cached entries and entries, accumulating # metadata from both, but using the state from entries. for entry in cached_entries + entries: columns = self.DIFF_RE.search(entry).groups() old_mode, new_mode, old_sha, new_sha, statekey, path = columns state = self.state_map.get(statekey.strip(), _vc.STATE_NONE) path = get_real_path(path) self._tree_cache[path] = state # Git entries can't be MISSING; that's just an unstaged REMOVED self._add_missing_cache_entry(path, state) if old_mode != new_mode: msg = _( "Mode changed from {old_mode} to {new_mode}".format( old_mode=old_mode, new_mode=new_mode)) tree_meta_cache[path].append(msg) collection = unstaged if new_sha == NULL_SHA else staged collection.add(path) for path in staged: tree_meta_cache[path].append( _("Partially staged") if path in unstaged else _("Staged")) for path, msgs in tree_meta_cache.items(): self._tree_meta_cache[path] = "; ".join(msgs) for path in ignored_entries: self._tree_cache[get_real_path(path)] = _vc.STATE_IGNORED for path in unversioned_entries: self._tree_cache[get_real_path(path)] = _vc.STATE_NONE
15,007
Python
.py
311
37.263666
97
0.591105
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,860
darcs.py
GNOME_meld/meld/vc/darcs.py
# Copyright (C) 2010-2015 Kai Willadsen <kai.willadsen@gmail.com> # Copyright (C) 2016 Guillaume Hoffmann <guillaumh@gmail.com> # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR # IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES # OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. # IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT # NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF # THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import errno import os import shutil import subprocess import tempfile from collections import defaultdict from . import _vc class Vc(_vc.Vc): # Requires Darcs version >= 2.10.3 # TODO implement get_commits_to_push_summary using `darcs push --dry-run` # Currently `darcs whatsnew` (as of v2.10.3) does not report conflicts # see http://bugs.darcs.net/issue2138 CMD = "darcs" NAME = "Darcs" VC_DIR = "_darcs" state_map = { "a": _vc.STATE_NONE, "A": _vc.STATE_NEW, "M": _vc.STATE_MODIFIED, "M!": _vc.STATE_CONFLICT, "R": _vc.STATE_REMOVED, "F": _vc.STATE_NONEXIST, # previous name of file "T": _vc.STATE_RENAMED, # new name of file } @classmethod def is_installed(cls): try: proc = _vc.popen([cls.CMD, '--version']) # check that version >= 2.10.3 (x, y, z) = proc.read().split(" ", 1)[0].split(".", 2)[:3] assert (x, y, z) >= (2, 10, 3) return True except Exception: return False def commit(self, runner, files, message): command = [self.CMD, 'record', '-a', '-m', message] runner(command, [], refresh=True, working_dir=self.root) def update(self, runner): command = [self.CMD, 'pull', '-a'] runner(command, [], refresh=True, working_dir=self.root) def push(self, runner): command = [self.CMD, 'push', '-a'] runner(command, [], refresh=True, working_dir=self.root) def add(self, runner, files): command = [self.CMD, 'add', '-r'] runner(command, files, refresh=True, working_dir=self.root) def remove(self, runner, files): command = [self.CMD, 'remove', '-r'] runner(command, files, refresh=True, working_dir=self.root) def revert(self, runner, files): command = [self.CMD, 'revert', '-a'] runner(command, files, refresh=True, working_dir=self.root) def get_path_for_repo_file(self, path, commit=None): if commit is not None: raise NotImplementedError() if not path.startswith(self.root + os.path.sep): raise _vc.InvalidVCPath(self, path, "Path not in repository") # `darcs show contents` needs the path before rename if path in self._reverse_rename_cache: path = self._reverse_rename_cache[path] path = path[len(self.root) + 1:] suffix = os.path.splitext(path)[1] process = subprocess.Popen( [self.CMD, "show", "contents", path], cwd=self.root, stdout=subprocess.PIPE, stderr=subprocess.PIPE) with tempfile.NamedTemporaryFile(prefix='meld-tmp', suffix=suffix, delete=False) as f: shutil.copyfileobj(process.stdout, f) return f.name @classmethod def valid_repo(cls, path): return not _vc.call([cls.CMD, "show", "repo", "--no-files"], cwd=path) def _update_tree_state_cache(self, path): # FIXME: currently ignoring 'path' due to darcs's bad # behaviour (= fails) when given "" argument """ Update the state of the file(s) at self._tree_cache['path'] """ while 1: try: proc = _vc.popen( [self.CMD, "whatsnew", "-sl", "--machine-readable"], cwd=self.location) lines = proc.read().split("\n")[:-1] break except OSError as e: if e.errno != errno.EAGAIN: raise # Files can appear twice in the list if were modified and renamed # at once. Darcs first show file moves then modifications. if len(lines) == 0 and os.path.isfile(path): # If we're just updating a single file there's a chance that it # was it was previously modified, and now has been edited so that # it is un-modified. This will result in an empty 'entries' list, # and self._tree_cache['path'] will still contain stale data. # When this corner case occurs we force self._tree_cache['path'] # to STATE_NORMAL. self._tree_cache[path] = _vc.STATE_NORMAL else: tree_cache = defaultdict(int) tree_meta_cache = defaultdict(list) self._rename_cache = rename_cache = {} self._reverse_rename_cache = {} old_name = None for line in lines: # skip empty lines and line starting with "What's new in foo" if (not line.strip()) or line.startswith("What"): continue statekey, name = line.split(" ", 1) name = os.path.normpath(name) if statekey == "F": old_name = name path = os.path.join(self.location, name) if statekey == "T" and old_name: old_path = os.path.join(self.location, old_name) rename_cache[old_path] = path old_name = None state = self.state_map.get(statekey.strip(), _vc.STATE_NONE) tree_cache[path] = state for old, new in rename_cache.items(): self._reverse_rename_cache[new] = old old_name = old[len(self.root) + 1:] new_name = new[len(self.root) + 1:] tree_meta_cache[new] = ("%s âž¡ %s" % (old_name, new_name)) self._tree_cache.update( dict((x, y) for x, y in tree_cache.items())) self._tree_meta_cache = dict(tree_meta_cache)
7,031
Python
.py
146
38.438356
78
0.603617
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,861
__init__.py
GNOME_meld/meld/vc/__init__.py
# Copyright (C) 2002-2005 Stephen Kennedy <stevek@gnome.org> # Copyright (C) 2012 Kai Willadsen <kai.willadsen@gmail.com> # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR # IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES # OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. # IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT # NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF # THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from . import bzr, cvs, darcs, git, mercurial, svn # Tuple of plugins, ordered according to best-guess as to which VC a # user is likely to want by default in a multiple-VC situation. VC_PLUGINS = (git, mercurial, bzr, svn, darcs, cvs) def get_vcs(location): """Pick only the Vcs with the longest repo root Some VC plugins search their repository root by walking the filesystem upwards its root and now that we display multiple VCs in the same directory, we must filter those other repositories that are located in the search path towards "/" as they are not relevant to the user. """ vcs = [] for plugin in VC_PLUGINS: root, location = plugin.Vc.is_in_repo(location) enabled = root is not None vcs.append((plugin.Vc, enabled)) return vcs
2,191
Python
.py
41
49.95122
75
0.75432
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,862
svn.py
GNOME_meld/meld/vc/svn.py
# Copyright (C) 2002-2005 Stephen Kennedy <stevek@gnome.org> # Copyright (C) 2011-2013, 2015 Kai Willadsen <kai.willadsen@gmail.com> # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR # IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES # OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. # IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT # NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF # THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import errno import glob import os import xml.etree.ElementTree as ElementTree from meld.conf import _ from . import _vc #: Simple enum constants for differentiating conflict cases. CONFLICT_TYPE_MERGE, CONFLICT_TYPE_UPDATE = 1, 2 class Vc(_vc.Vc): CMD = "svn" NAME = "Subversion" VC_DIR = ".svn" state_map = { "unversioned": _vc.STATE_NONE, "added": _vc.STATE_NEW, "normal": _vc.STATE_NORMAL, "missing": _vc.STATE_MISSING, "ignored": _vc.STATE_IGNORED, "modified": _vc.STATE_MODIFIED, "deleted": _vc.STATE_REMOVED, "conflicted": _vc.STATE_CONFLICT, } def commit(self, runner, files, message): command = [self.CMD, 'commit', '-m', message] runner(command, files, refresh=True, working_dir=self.root) def update(self, runner): command = [self.CMD, 'update'] runner(command, [], refresh=True, working_dir=self.root) def remove(self, runner, files): command = [self.CMD, 'rm', '--force'] runner(command, files, refresh=True, working_dir=self.root) def revert(self, runner, files): command = [self.CMD, 'revert'] runner(command, files, refresh=True, working_dir=self.root) def resolve(self, runner, files): command = [self.CMD, 'resolve', '--accept=working'] runner(command, files, refresh=True, working_dir=self.root) def get_path_for_repo_file(self, path, commit=None): if commit is None: commit = "BASE" else: raise NotImplementedError() if not path.startswith(self.root + os.path.sep): raise _vc.InvalidVCPath(self, path, "Path not in repository") path = path[len(self.root) + 1:] suffix = os.path.splitext(path)[1] args = [self.CMD, "cat", "-r", commit, path] return _vc.call_temp_output(args, cwd=self.root, suffix=suffix) def get_path_for_conflict(self, path, conflict=None): """ SVN has two types of conflicts: Merge conflicts, which give 3 files: .left.r* (THIS) .working (BASE... although this is a bit debatable) .right.r* (OTHER) Update conflicts which give 3 files: .mine (THIS) .r* (lower - BASE) .r* (higher - OTHER) """ if not path.startswith(self.root + os.path.sep): raise _vc.InvalidVCPath(self, path, "Path not in repository") # If this is merged, we just return the merged output if conflict == _vc.CONFLICT_MERGED: return path, False # First fine what type of conflict this is by looking at the base # we can possibly return straight away! conflict_type = None base = glob.glob('%s.working' % path) if len(base) == 1: # We have a merge conflict conflict_type = CONFLICT_TYPE_MERGE else: base = glob.glob('%s.mine' % path) if len(base) == 1: # We have an update conflict conflict_type = CONFLICT_TYPE_UPDATE if conflict_type is None: raise _vc.InvalidVCPath(self, path, "No known conflict type found") if conflict == _vc.CONFLICT_BASE: return base[0], False elif conflict == _vc.CONFLICT_THIS: if conflict_type == CONFLICT_TYPE_MERGE: return glob.glob('%s.merge-left.r*' % path)[0], False else: return glob.glob('%s.r*' % path)[0], False elif conflict == _vc.CONFLICT_OTHER: if conflict_type == CONFLICT_TYPE_MERGE: return glob.glob('%s.merge-right.r*' % path)[0], False else: return glob.glob('%s.r*' % path)[-1], False raise KeyError("Conflict file does not exist") def add(self, runner, files): # SVN < 1.7 needs to add folders from their immediate parent dirs = [s for s in files if os.path.isdir(s)] files = [s for s in files if os.path.isfile(s)] command = [self.CMD, 'add'] for path in dirs: runner(command, [path], refresh=True, working_dir=os.path.dirname(path)) if files: runner(command, files, refresh=True, working_dir=self.location) @classmethod def _repo_version_support(cls, version): return version >= 12 @classmethod def valid_repo(cls, path): if _vc.call([cls.CMD, "info"], cwd=path): return False root, location = cls.is_in_repo(path) vc_dir = os.path.join(root, cls.VC_DIR) # Check for repository version, trusting format file then entries file repo_version = None for filename in ("format", "entries"): path = os.path.join(vc_dir, filename) if os.path.exists(path): with open(path) as f: repo_version = int(f.readline().strip()) break if not repo_version and os.path.exists(os.path.join(vc_dir, "wc.db")): repo_version = 12 return cls._repo_version_support(repo_version) def _update_tree_state_cache(self, path): while 1: try: # "svn --xml" outputs utf8, even with Windows non-utf8 locale proc = _vc.popen( [self.CMD, "status", "-v", "--xml", path], cwd=self.location, use_locale_encoding=False) tree = ElementTree.parse(proc) break except OSError as e: if e.errno != errno.EAGAIN: raise for target in tree.findall("target") + tree.findall("changelist"): for entry in target.iter(tag="entry"): path = entry.attrib["path"] if not path: continue if not os.path.isabs(path): path = os.path.abspath(os.path.join(self.location, path)) for status in entry.iter(tag="wc-status"): item = status.attrib["item"] if item == "": continue state = self.state_map.get(item, _vc.STATE_NONE) self._tree_cache[path] = state rev = status.attrib.get("revision") rev_label = _("Rev %s") % rev if rev is not None else '' self._tree_meta_cache[path] = rev_label self._add_missing_cache_entry(path, state)
7,923
Python
.py
172
36.098837
79
0.603265
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,863
mercurial.py
GNOME_meld/meld/vc/mercurial.py
# Copyright (C) 2002-2005 Stephen Kennedy <stevek@gnome.org> # Copyright (C) 2015 Kai Willadsen <kai.willadsen@gmail.com> # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR # IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES # OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. # IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT # NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF # THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import errno import os from . import _vc class Vc(_vc.Vc): CMD = "hg" NAME = "Mercurial" VC_DIR = ".hg" state_map = { "?": _vc.STATE_NONE, "A": _vc.STATE_NEW, "C": _vc.STATE_NORMAL, "!": _vc.STATE_MISSING, "I": _vc.STATE_IGNORED, "M": _vc.STATE_MODIFIED, "R": _vc.STATE_REMOVED, } def commit(self, runner, files, message): command = [self.CMD, 'commit', '-m', message] runner(command, files, refresh=True, working_dir=self.root) def update(self, runner): command = [self.CMD, 'pull', '-u'] runner(command, [], refresh=True, working_dir=self.root) def add(self, runner, files): command = [self.CMD, 'add'] runner(command, files, refresh=True, working_dir=self.root) def remove(self, runner, files): command = [self.CMD, 'rm'] runner(command, files, refresh=True, working_dir=self.root) def revert(self, runner, files): command = [self.CMD, 'revert'] runner(command, files, refresh=True, working_dir=self.root) @classmethod def valid_repo(cls, path): return not _vc.call([cls.CMD, "root"], cwd=path) def get_path_for_repo_file(self, path, commit=None): if commit is not None: raise NotImplementedError() if not path.startswith(self.root + os.path.sep): raise _vc.InvalidVCPath(self, path, "Path not in repository") path = path[len(self.root) + 1:] suffix = os.path.splitext(path)[1] args = [self.CMD, "cat", path] return _vc.call_temp_output(args, cwd=self.root, suffix=suffix) def _update_tree_state_cache(self, path): """ Update the state of the file(s) at self._tree_cache['path'] """ while 1: try: # Get the status of modified files proc = _vc.popen([self.CMD, "status", '-A', path], cwd=self.location) entries = proc.read().split("\n")[:-1] # The following command removes duplicate file entries. # Just in case. entries = list(set(entries)) break except OSError as e: if e.errno != errno.EAGAIN: raise if len(entries) == 0 and os.path.isfile(path): # If we're just updating a single file there's a chance that it # was it was previously modified, and now has been edited so that # it is un-modified. This will result in an empty 'entries' list, # and self._tree_cache['path'] will still contain stale data. # When this corner case occurs we force self._tree_cache['path'] # to STATE_NORMAL. self._tree_cache[path] = _vc.STATE_NORMAL else: # There are 1 or more modified files, parse their state for entry in entries: # we might have a space in file name, it should be ignored statekey, name = entry.split(" ", 1) path = os.path.join(self.location, name.strip()) state = self.state_map.get(statekey.strip(), _vc.STATE_NONE) self._tree_cache[path] = state self._add_missing_cache_entry(path, state)
4,685
Python
.py
96
40.166667
78
0.632742
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,864
_null.py
GNOME_meld/meld/vc/_null.py
# Copyright (C) 2002-2005 Stephen Kennedy <stevek@gnome.org> # Copyright (C) 2012-2015 Kai Willadsen <kai.willadsen@gmail.com> # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR # IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES # OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. # IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT # NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF # THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import os import shutil import tempfile from meld.conf import _ from meld.vc import _vc class Vc(_vc.Vc): CMD = None # Translators: This is the displayed name of a version control system # when no version control system is actually found. NAME = _("None") VC_DIR = "." def _update_tree_state_cache(*args): pass def get_path_for_repo_file(self, path, commit=None): suffix = os.path.splitext(path)[1] with tempfile.NamedTemporaryFile( prefix='meld-tmp', suffix=suffix, delete=False) as f: with open(path, 'rb') as vc_file: shutil.copyfileobj(vc_file, f) return f.name
2,034
Python
.py
41
45.853659
75
0.745464
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,865
bzr.py
GNOME_meld/meld/vc/bzr.py
# Copyright (C) 2002-2005 Stephen Kennedy <stevek@gnome.org> # Copyright (C) 2005 Aaron Bentley <aaron.bentley@utoronto.ca> # Copyright (C) 2015 Kai Willadsen <kai.willadsen@gmail.com> # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR # IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES # OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. # IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT # NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF # THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import errno import os import re from collections import defaultdict from . import _vc class Vc(_vc.Vc): CMD = "bzr" CMDARGS = ["--no-aliases", "--no-plugins"] NAME = "Bazaar" VC_DIR = ".bzr" PATCH_INDEX_RE = "^=== modified file '(.*)' (.*)$" CONFLICT_RE = "conflict in (.*)$" RENAMED_RE = "^(.*) => (.*)$" commit_statuses = ( _vc.STATE_MODIFIED, _vc.STATE_RENAMED, _vc.STATE_NEW, _vc.STATE_REMOVED ) conflict_map = { _vc.CONFLICT_BASE: '.BASE', _vc.CONFLICT_OTHER: '.OTHER', _vc.CONFLICT_THIS: '.THIS', _vc.CONFLICT_MERGED: '', } # We use None here to indicate flags that we don't deal with or care about state_1_map = { " ": None, # First status column empty "+": None, # File versioned "-": None, # File unversioned "R": _vc.STATE_RENAMED, # File renamed "?": _vc.STATE_NONE, # File unknown "X": None, # File nonexistent (and unknown to bzr) "C": _vc.STATE_CONFLICT, # File has conflicts "P": None, # Entry for a pending merge (not a file) } state_2_map = { " ": _vc.STATE_NORMAL, # Second status column empty "N": _vc.STATE_NEW, # File created "D": _vc.STATE_REMOVED, # File deleted "K": None, # File kind changed "M": _vc.STATE_MODIFIED, # File modified } state_3_map = { " ": None, "*": _vc.STATE_MODIFIED, "/": _vc.STATE_MODIFIED, "@": _vc.STATE_MODIFIED, } valid_status_re = r'[%s][%s][%s]\s*' % (''.join(state_1_map.keys()), ''.join(state_2_map.keys()), ''.join(state_3_map.keys()),) def add(self, runner, files): fullcmd = [self.CMD] + self.CMDARGS command = [fullcmd, 'add'] runner(command, files, refresh=True, working_dir=self.root) def commit(self, runner, files, message): fullcmd = [self.CMD] + self.CMDARGS command = [fullcmd, 'commit', '-m', message] runner(command, [], refresh=True, working_dir=self.root) def revert(self, runner, files): runner( [self.CMD] + self.CMDARGS + ["revert"] + files, [], refresh=True, working_dir=self.root) def push(self, runner): runner( [self.CMD] + self.CMDARGS + ["push"], [], refresh=True, working_dir=self.root) def update(self, runner): # TODO: Handle checkouts/bound branches by calling # update instead of pull. For now we've replicated existing # functionality, as update will not work for unbound branches. runner( [self.CMD] + self.CMDARGS + ["pull"], [], refresh=True, working_dir=self.root) def resolve(self, runner, files): runner( [self.CMD] + self.CMDARGS + ["resolve"] + files, [], refresh=True, working_dir=self.root) def remove(self, runner, files): runner( [self.CMD] + self.CMDARGS + ["rm"] + files, [], refresh=True, working_dir=self.root) @classmethod def valid_repo(cls, path): return not _vc.call([cls.CMD, "root"], cwd=path) def get_files_to_commit(self, paths): files = [] for p in paths: if os.path.isdir(p): for path, status in self._tree_cache.items(): if status in self.commit_statuses and path.startswith(p): files.append(os.path.relpath(path, self.root)) else: files.append(os.path.relpath(p, self.root)) return sorted(list(set(files))) def _update_tree_state_cache(self, path): # FIXME: This actually clears out state information, because the # current API doesn't have any state outside of _tree_cache. branch_root = _vc.popen( [self.CMD] + self.CMDARGS + ["root", path], cwd=self.location).read().rstrip('\n') entries = [] while 1: try: proc = _vc.popen([self.CMD] + self.CMDARGS + ["status", "-S", "--no-pending", branch_root]) entries = proc.read().split("\n")[:-1] break except OSError as e: if e.errno != errno.EAGAIN: raise tree_cache = defaultdict(set) tree_meta_cache = defaultdict(list) self._rename_cache = rename_cache = {} self._reverse_rename_cache = {} # Files can appear twice in the list if they conflict and were renamed # at once. for entry in entries: meta = [] old_name = None state_string, name = entry[:3], entry[4:].strip() if not re.match(self.valid_status_re, state_string): continue state1 = self.state_1_map.get(state_string[0]) state2 = self.state_2_map.get(state_string[1]) state3 = self.state_3_map.get(state_string[2]) states = {state1, state2, state3} - {None} if _vc.STATE_CONFLICT in states: real_path_match = re.search(self.CONFLICT_RE, name) if real_path_match is not None: name = real_path_match.group(1) if _vc.STATE_RENAMED in states: real_path_match = re.search(self.RENAMED_RE, name) if real_path_match is not None: old_name = real_path_match.group(1) name = real_path_match.group(2) meta.append("%s âž¡ %s" % (old_name, name)) path = os.path.join(branch_root, name) if old_name: old_path = os.path.join(branch_root, old_name) rename_cache[old_path] = path if state3 and state3 is _vc.STATE_MODIFIED: # line = _vc.popen(self.diff_command() + [path]).readline() line = _vc.popen(['bzr', 'diff', path]).readline() executable_match = re.search(self.PATCH_INDEX_RE, line) if executable_match: meta.append(executable_match.group(2)) path = path[:-1] if path.endswith('/') else path tree_cache[path].update(states) tree_meta_cache[path].extend(meta) # Bazaar entries will only be REMOVED in the second state column self._add_missing_cache_entry(path, state2) # Handle any renames now for old, new in rename_cache.items(): if old in tree_cache: tree_cache[new].update(tree_cache[old]) tree_meta_cache[new].extend(tree_meta_cache[old]) del tree_cache[old] del tree_meta_cache[old] self._reverse_rename_cache[new] = old self._tree_cache.update( dict((x, max(y)) for x, y in tree_cache.items())) self._tree_meta_cache = dict(tree_meta_cache) def get_path_for_repo_file(self, path, commit=None): if not path.startswith(self.root + os.path.sep): raise _vc.InvalidVCPath(self, path, "Path not in repository") path = path[len(self.root) + 1:] suffix = os.path.splitext(path)[1] args = [self.CMD, "cat", path] if commit: args.append("-r%s" % commit) return _vc.call_temp_output(args, cwd=self.root, suffix=suffix) def get_path_for_conflict(self, path, conflict): if path in self._reverse_rename_cache and not \ conflict == _vc.CONFLICT_MERGED: path = self._reverse_rename_cache[path] if not path.startswith(self.root + os.path.sep): raise _vc.InvalidVCPath(self, path, "Path not in repository") # bzr paths are all temporary files return "%s%s" % (path, self.conflict_map[conflict]), False
9,448
Python
.py
200
37.12
79
0.580193
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,866
screen.py
pwnieexpress_raspberry_pwn/src/pexpect-2.3/screen.py
"""This implements a virtual screen. This is used to support ANSI terminal emulation. The screen representation and state is implemented in this class. Most of the methods are inspired by ANSI screen control codes. The ANSI class extends this class to add parsing of ANSI escape codes. $Id: screen.py 486 2007-07-13 01:04:16Z noah $ """ import copy NUL = 0 # Fill character; ignored on input. ENQ = 5 # Transmit answerback message. BEL = 7 # Ring the bell. BS = 8 # Move cursor left. HT = 9 # Move cursor to next tab stop. LF = 10 # Line feed. VT = 11 # Same as LF. FF = 12 # Same as LF. CR = 13 # Move cursor to left margin or newline. SO = 14 # Invoke G1 character set. SI = 15 # Invoke G0 character set. XON = 17 # Resume transmission. XOFF = 19 # Halt transmission. CAN = 24 # Cancel escape sequence. SUB = 26 # Same as CAN. ESC = 27 # Introduce a control sequence. DEL = 127 # Fill character; ignored on input. SPACE = chr(32) # Space or blank character. def constrain (n, min, max): """This returns a number, n constrained to the min and max bounds. """ if n < min: return min if n > max: return max return n class screen: """This object maintains the state of a virtual text screen as a rectangluar array. This maintains a virtual cursor position and handles scrolling as characters are added. This supports most of the methods needed by an ANSI text screen. Row and column indexes are 1-based (not zero-based, like arrays). """ def __init__ (self, r=24,c=80): """This initializes a blank scree of the given dimentions.""" self.rows = r self.cols = c self.cur_r = 1 self.cur_c = 1 self.cur_saved_r = 1 self.cur_saved_c = 1 self.scroll_row_start = 1 self.scroll_row_end = self.rows self.w = [ [SPACE] * self.cols for c in range(self.rows)] def __str__ (self): """This returns a printable representation of the screen. The end of each screen line is terminated by a newline. """ return '\n'.join ([ ''.join(c) for c in self.w ]) def dump (self): """This returns a copy of the screen as a string. This is similar to __str__ except that lines are not terminated with line feeds. """ return ''.join ([ ''.join(c) for c in self.w ]) def pretty (self): """This returns a copy of the screen as a string with an ASCII text box around the screen border. This is similar to __str__ except that it adds a box. """ top_bot = '+' + '-'*self.cols + '+\n' return top_bot + '\n'.join(['|'+line+'|' for line in str(self).split('\n')]) + '\n' + top_bot def fill (self, ch=SPACE): self.fill_region (1,1,self.rows,self.cols, ch) def fill_region (self, rs,cs, re,ce, ch=SPACE): rs = constrain (rs, 1, self.rows) re = constrain (re, 1, self.rows) cs = constrain (cs, 1, self.cols) ce = constrain (ce, 1, self.cols) if rs > re: rs, re = re, rs if cs > ce: cs, ce = ce, cs for r in range (rs, re+1): for c in range (cs, ce + 1): self.put_abs (r,c,ch) def cr (self): """This moves the cursor to the beginning (col 1) of the current row. """ self.cursor_home (self.cur_r, 1) def lf (self): """This moves the cursor down with scrolling. """ old_r = self.cur_r self.cursor_down() if old_r == self.cur_r: self.scroll_up () self.erase_line() def crlf (self): """This advances the cursor with CRLF properties. The cursor will line wrap and the screen may scroll. """ self.cr () self.lf () def newline (self): """This is an alias for crlf(). """ self.crlf() def put_abs (self, r, c, ch): """Screen array starts at 1 index.""" r = constrain (r, 1, self.rows) c = constrain (c, 1, self.cols) ch = str(ch)[0] self.w[r-1][c-1] = ch def put (self, ch): """This puts a characters at the current cursor position. """ self.put_abs (self.cur_r, self.cur_c, ch) def insert_abs (self, r, c, ch): """This inserts a character at (r,c). Everything under and to the right is shifted right one character. The last character of the line is lost. """ r = constrain (r, 1, self.rows) c = constrain (c, 1, self.cols) for ci in range (self.cols, c, -1): self.put_abs (r,ci, self.get_abs(r,ci-1)) self.put_abs (r,c,ch) def insert (self, ch): self.insert_abs (self.cur_r, self.cur_c, ch) def get_abs (self, r, c): r = constrain (r, 1, self.rows) c = constrain (c, 1, self.cols) return self.w[r-1][c-1] def get (self): self.get_abs (self.cur_r, self.cur_c) def get_region (self, rs,cs, re,ce): """This returns a list of lines representing the region. """ rs = constrain (rs, 1, self.rows) re = constrain (re, 1, self.rows) cs = constrain (cs, 1, self.cols) ce = constrain (ce, 1, self.cols) if rs > re: rs, re = re, rs if cs > ce: cs, ce = ce, cs sc = [] for r in range (rs, re+1): line = '' for c in range (cs, ce + 1): ch = self.get_abs (r,c) line = line + ch sc.append (line) return sc def cursor_constrain (self): """This keeps the cursor within the screen area. """ self.cur_r = constrain (self.cur_r, 1, self.rows) self.cur_c = constrain (self.cur_c, 1, self.cols) def cursor_home (self, r=1, c=1): # <ESC>[{ROW};{COLUMN}H self.cur_r = r self.cur_c = c self.cursor_constrain () def cursor_back (self,count=1): # <ESC>[{COUNT}D (not confused with down) self.cur_c = self.cur_c - count self.cursor_constrain () def cursor_down (self,count=1): # <ESC>[{COUNT}B (not confused with back) self.cur_r = self.cur_r + count self.cursor_constrain () def cursor_forward (self,count=1): # <ESC>[{COUNT}C self.cur_c = self.cur_c + count self.cursor_constrain () def cursor_up (self,count=1): # <ESC>[{COUNT}A self.cur_r = self.cur_r - count self.cursor_constrain () def cursor_up_reverse (self): # <ESC> M (called RI -- Reverse Index) old_r = self.cur_r self.cursor_up() if old_r == self.cur_r: self.scroll_up() def cursor_force_position (self, r, c): # <ESC>[{ROW};{COLUMN}f """Identical to Cursor Home.""" self.cursor_home (r, c) def cursor_save (self): # <ESC>[s """Save current cursor position.""" self.cursor_save_attrs() def cursor_unsave (self): # <ESC>[u """Restores cursor position after a Save Cursor.""" self.cursor_restore_attrs() def cursor_save_attrs (self): # <ESC>7 """Save current cursor position.""" self.cur_saved_r = self.cur_r self.cur_saved_c = self.cur_c def cursor_restore_attrs (self): # <ESC>8 """Restores cursor position after a Save Cursor.""" self.cursor_home (self.cur_saved_r, self.cur_saved_c) def scroll_constrain (self): """This keeps the scroll region within the screen region.""" if self.scroll_row_start <= 0: self.scroll_row_start = 1 if self.scroll_row_end > self.rows: self.scroll_row_end = self.rows def scroll_screen (self): # <ESC>[r """Enable scrolling for entire display.""" self.scroll_row_start = 1 self.scroll_row_end = self.rows def scroll_screen_rows (self, rs, re): # <ESC>[{start};{end}r """Enable scrolling from row {start} to row {end}.""" self.scroll_row_start = rs self.scroll_row_end = re self.scroll_constrain() def scroll_down (self): # <ESC>D """Scroll display down one line.""" # Screen is indexed from 1, but arrays are indexed from 0. s = self.scroll_row_start - 1 e = self.scroll_row_end - 1 self.w[s+1:e+1] = copy.deepcopy(self.w[s:e]) def scroll_up (self): # <ESC>M """Scroll display up one line.""" # Screen is indexed from 1, but arrays are indexed from 0. s = self.scroll_row_start - 1 e = self.scroll_row_end - 1 self.w[s:e] = copy.deepcopy(self.w[s+1:e+1]) def erase_end_of_line (self): # <ESC>[0K -or- <ESC>[K """Erases from the current cursor position to the end of the current line.""" self.fill_region (self.cur_r, self.cur_c, self.cur_r, self.cols) def erase_start_of_line (self): # <ESC>[1K """Erases from the current cursor position to the start of the current line.""" self.fill_region (self.cur_r, 1, self.cur_r, self.cur_c) def erase_line (self): # <ESC>[2K """Erases the entire current line.""" self.fill_region (self.cur_r, 1, self.cur_r, self.cols) def erase_down (self): # <ESC>[0J -or- <ESC>[J """Erases the screen from the current line down to the bottom of the screen.""" self.erase_end_of_line () self.fill_region (self.cur_r + 1, 1, self.rows, self.cols) def erase_up (self): # <ESC>[1J """Erases the screen from the current line up to the top of the screen.""" self.erase_start_of_line () self.fill_region (self.cur_r-1, 1, 1, self.cols) def erase_screen (self): # <ESC>[2J """Erases the screen with the background color.""" self.fill () def set_tab (self): # <ESC>H """Sets a tab at the current position.""" pass def clear_tab (self): # <ESC>[g """Clears tab at the current position.""" pass def clear_all_tabs (self): # <ESC>[3g """Clears all tabs.""" pass # Insert line Esc [ Pn L # Delete line Esc [ Pn M # Delete character Esc [ Pn P # Scrolling region Esc [ Pn(top);Pn(bot) r
10,402
Python
.py
252
33.242063
101
0.576662
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,867
setup.py
pwnieexpress_raspberry_pwn/src/pexpect-2.3/setup.py
''' $Revision: 485 $ $Date: 2007-07-12 15:23:15 -0700 (Thu, 12 Jul 2007) $ ''' from distutils.core import setup setup (name='pexpect', version='2.3', py_modules=['pexpect', 'pxssh', 'fdpexpect', 'FSM', 'screen', 'ANSI'], description='Pexpect is a pure Python Expect. It allows easy control of other applications.', author='Noah Spurrier', author_email='noah@noah.org', url='http://pexpect.sourceforge.net/', license='MIT license', platforms='UNIX', ) # classifiers = [ # 'Development Status :: 4 - Beta', # 'Environment :: Console', # 'Environment :: Console (Text Based)', # 'Intended Audience :: Developers', # 'Intended Audience :: System Administrators', # 'Intended Audience :: Quality Engineers', # 'License :: OSI Approved :: Python Software Foundation License', # 'Operating System :: POSIX', # 'Operating System :: MacOS :: MacOS X', # 'Programming Language :: Python', # 'Topic :: Software Development', # 'Topic :: Software Development :: Libraries :: Python Modules', # 'Topic :: Software Development :: Quality Assurance', # 'Topic :: Software Development :: Testing', # 'Topic :: System, System :: Archiving :: Packaging, System :: Installation/Setup', # 'Topic :: System :: Shells', # 'Topic :: System :: Software Distribution', # 'Topic :: Terminals, Utilities', # ],
1,452
Python
.py
35
39.457143
97
0.619958
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,868
pexpect.py
pwnieexpress_raspberry_pwn/src/pexpect-2.3/pexpect.py
"""Pexpect is a Python module for spawning child applications and controlling them automatically. Pexpect can be used for automating interactive applications such as ssh, ftp, passwd, telnet, etc. It can be used to a automate setup scripts for duplicating software package installations on different servers. It can be used for automated software testing. Pexpect is in the spirit of Don Libes' Expect, but Pexpect is pure Python. Other Expect-like modules for Python require TCL and Expect or require C extensions to be compiled. Pexpect does not use C, Expect, or TCL extensions. It should work on any platform that supports the standard Python pty module. The Pexpect interface focuses on ease of use so that simple tasks are easy. There are two main interfaces to Pexpect -- the function, run() and the class, spawn. You can call the run() function to execute a command and return the output. This is a handy replacement for os.system(). For example:: pexpect.run('ls -la') The more powerful interface is the spawn class. You can use this to spawn an external child command and then interact with the child by sending lines and expecting responses. For example:: child = pexpect.spawn('scp foo myname@host.example.com:.') child.expect ('Password:') child.sendline (mypassword) This works even for commands that ask for passwords or other input outside of the normal stdio streams. Credits: Noah Spurrier, Richard Holden, Marco Molteni, Kimberley Burchett, Robert Stone, Hartmut Goebel, Chad Schroeder, Erick Tryzelaar, Dave Kirby, Ids vander Molen, George Todd, Noel Taylor, Nicolas D. Cesar, Alexander Gattin, Geoffrey Marshall, Francisco Lourenco, Glen Mabey, Karthik Gurusamy, Fernando Perez, Corey Minyard, Jon Cohen, Guillaume Chazarain, Andrew Ryan, Nick Craig-Wood, Andrew Stone, Jorgen Grahn (Let me know if I forgot anyone.) Free, open source, and all that good stuff. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Pexpect Copyright (c) 2008 Noah Spurrier http://pexpect.sourceforge.net/ $Id: pexpect.py 507 2007-12-27 02:40:52Z noah $ """ try: import os, sys, time import select import string import re import struct import resource import types import pty import tty import termios import fcntl import errno import traceback import signal except ImportError, e: raise ImportError (str(e) + """ A critical module was not found. Probably this operating system does not support it. Pexpect is intended for UNIX-like operating systems.""") __version__ = '2.3' __revision__ = '$Revision: 399 $' __all__ = ['ExceptionPexpect', 'EOF', 'TIMEOUT', 'spawn', 'run', 'which', 'split_command_line', '__version__', '__revision__'] # Exception classes used by this module. class ExceptionPexpect(Exception): """Base class for all exceptions raised by this module. """ def __init__(self, value): self.value = value def __str__(self): return str(self.value) def get_trace(self): """This returns an abbreviated stack trace with lines that only concern the caller. In other words, the stack trace inside the Pexpect module is not included. """ tblist = traceback.extract_tb(sys.exc_info()[2]) #tblist = filter(self.__filter_not_pexpect, tblist) tblist = [item for item in tblist if self.__filter_not_pexpect(item)] tblist = traceback.format_list(tblist) return ''.join(tblist) def __filter_not_pexpect(self, trace_list_item): """This returns True if list item 0 the string 'pexpect.py' in it. """ if trace_list_item[0].find('pexpect.py') == -1: return True else: return False class EOF(ExceptionPexpect): """Raised when EOF is read from a child. This usually means the child has exited.""" class TIMEOUT(ExceptionPexpect): """Raised when a read time exceeds the timeout. """ ##class TIMEOUT_PATTERN(TIMEOUT): ## """Raised when the pattern match time exceeds the timeout. ## This is different than a read TIMEOUT because the child process may ## give output, thus never give a TIMEOUT, but the output ## may never match a pattern. ## """ ##class MAXBUFFER(ExceptionPexpect): ## """Raised when a scan buffer fills before matching an expected pattern.""" def run (command, timeout=-1, withexitstatus=False, events=None, extra_args=None, logfile=None, cwd=None, env=None): """ This function runs the given command; waits for it to finish; then returns all output as a string. STDERR is included in output. If the full path to the command is not given then the path is searched. Note that lines are terminated by CR/LF (\\r\\n) combination even on UNIX-like systems because this is the standard for pseudo ttys. If you set 'withexitstatus' to true, then run will return a tuple of (command_output, exitstatus). If 'withexitstatus' is false then this returns just command_output. The run() function can often be used instead of creating a spawn instance. For example, the following code uses spawn:: from pexpect import * child = spawn('scp foo myname@host.example.com:.') child.expect ('(?i)password') child.sendline (mypassword) The previous code can be replace with the following:: from pexpect import * run ('scp foo myname@host.example.com:.', events={'(?i)password': mypassword}) Examples ======== Start the apache daemon on the local machine:: from pexpect import * run ("/usr/local/apache/bin/apachectl start") Check in a file using SVN:: from pexpect import * run ("svn ci -m 'automatic commit' my_file.py") Run a command and capture exit status:: from pexpect import * (command_output, exitstatus) = run ('ls -l /bin', withexitstatus=1) Tricky Examples =============== The following will run SSH and execute 'ls -l' on the remote machine. The password 'secret' will be sent if the '(?i)password' pattern is ever seen:: run ("ssh username@machine.example.com 'ls -l'", events={'(?i)password':'secret\\n'}) This will start mencoder to rip a video from DVD. This will also display progress ticks every 5 seconds as it runs. For example:: from pexpect import * def print_ticks(d): print d['event_count'], run ("mencoder dvd://1 -o video.avi -oac copy -ovc copy", events={TIMEOUT:print_ticks}, timeout=5) The 'events' argument should be a dictionary of patterns and responses. Whenever one of the patterns is seen in the command out run() will send the associated response string. Note that you should put newlines in your string if Enter is necessary. The responses may also contain callback functions. Any callback is function that takes a dictionary as an argument. The dictionary contains all the locals from the run() function, so you can access the child spawn object or any other variable defined in run() (event_count, child, and extra_args are the most useful). A callback may return True to stop the current run process otherwise run() continues until the next event. A callback may also return a string which will be sent to the child. 'extra_args' is not used by directly run(). It provides a way to pass data to a callback function through run() through the locals dictionary passed to a callback. """ if timeout == -1: child = spawn(command, maxread=2000, logfile=logfile, cwd=cwd, env=env) else: child = spawn(command, timeout=timeout, maxread=2000, logfile=logfile, cwd=cwd, env=env) if events is not None: patterns = events.keys() responses = events.values() else: patterns=None # We assume that EOF or TIMEOUT will save us. responses=None child_result_list = [] event_count = 0 while 1: try: index = child.expect (patterns) if type(child.after) in types.StringTypes: child_result_list.append(child.before + child.after) else: # child.after may have been a TIMEOUT or EOF, so don't cat those. child_result_list.append(child.before) if type(responses[index]) in types.StringTypes: child.send(responses[index]) elif type(responses[index]) is types.FunctionType: callback_result = responses[index](locals()) sys.stdout.flush() if type(callback_result) in types.StringTypes: child.send(callback_result) elif callback_result: break else: raise TypeError ('The callback must be a string or function type.') event_count = event_count + 1 except TIMEOUT, e: child_result_list.append(child.before) break except EOF, e: child_result_list.append(child.before) break child_result = ''.join(child_result_list) if withexitstatus: child.close() return (child_result, child.exitstatus) else: return child_result class spawn (object): """This is the main class interface for Pexpect. Use this class to start and control child applications. """ def __init__(self, command, args=[], timeout=30, maxread=2000, searchwindowsize=None, logfile=None, cwd=None, env=None): """This is the constructor. The command parameter may be a string that includes a command and any arguments to the command. For example:: child = pexpect.spawn ('/usr/bin/ftp') child = pexpect.spawn ('/usr/bin/ssh user@example.com') child = pexpect.spawn ('ls -latr /tmp') You may also construct it with a list of arguments like so:: child = pexpect.spawn ('/usr/bin/ftp', []) child = pexpect.spawn ('/usr/bin/ssh', ['user@example.com']) child = pexpect.spawn ('ls', ['-latr', '/tmp']) After this the child application will be created and will be ready to talk to. For normal use, see expect() and send() and sendline(). Remember that Pexpect does NOT interpret shell meta characters such as redirect, pipe, or wild cards (>, |, or *). This is a common mistake. If you want to run a command and pipe it through another command then you must also start a shell. For example:: child = pexpect.spawn('/bin/bash -c "ls -l | grep LOG > log_list.txt"') child.expect(pexpect.EOF) The second form of spawn (where you pass a list of arguments) is useful in situations where you wish to spawn a command and pass it its own argument list. This can make syntax more clear. For example, the following is equivalent to the previous example:: shell_cmd = 'ls -l | grep LOG > log_list.txt' child = pexpect.spawn('/bin/bash', ['-c', shell_cmd]) child.expect(pexpect.EOF) The maxread attribute sets the read buffer size. This is maximum number of bytes that Pexpect will try to read from a TTY at one time. Setting the maxread size to 1 will turn off buffering. Setting the maxread value higher may help performance in cases where large amounts of output are read back from the child. This feature is useful in conjunction with searchwindowsize. The searchwindowsize attribute sets the how far back in the incomming seach buffer Pexpect will search for pattern matches. Every time Pexpect reads some data from the child it will append the data to the incomming buffer. The default is to search from the beginning of the imcomming buffer each time new data is read from the child. But this is very inefficient if you are running a command that generates a large amount of data where you want to match The searchwindowsize does not effect the size of the incomming data buffer. You will still have access to the full buffer after expect() returns. The logfile member turns on or off logging. All input and output will be copied to the given file object. Set logfile to None to stop logging. This is the default. Set logfile to sys.stdout to echo everything to standard output. The logfile is flushed after each write. Example log input and output to a file:: child = pexpect.spawn('some_command') fout = file('mylog.txt','w') child.logfile = fout Example log to stdout:: child = pexpect.spawn('some_command') child.logfile = sys.stdout The logfile_read and logfile_send members can be used to separately log the input from the child and output sent to the child. Sometimes you don't want to see everything you write to the child. You only want to log what the child sends back. For example:: child = pexpect.spawn('some_command') child.logfile_read = sys.stdout To separately log output sent to the child use logfile_send:: self.logfile_send = fout The delaybeforesend helps overcome a weird behavior that many users were experiencing. The typical problem was that a user would expect() a "Password:" prompt and then immediately call sendline() to send the password. The user would then see that their password was echoed back to them. Passwords don't normally echo. The problem is caused by the fact that most applications print out the "Password" prompt and then turn off stdin echo, but if you send your password before the application turned off echo, then you get your password echoed. Normally this wouldn't be a problem when interacting with a human at a real keyboard. If you introduce a slight delay just before writing then this seems to clear up the problem. This was such a common problem for many users that I decided that the default pexpect behavior should be to sleep just before writing to the child application. 1/20th of a second (50 ms) seems to be enough to clear up the problem. You can set delaybeforesend to 0 to return to the old behavior. Most Linux machines don't like this to be below 0.03. I don't know why. Note that spawn is clever about finding commands on your path. It uses the same logic that "which" uses to find executables. If you wish to get the exit status of the child you must call the close() method. The exit or signal status of the child will be stored in self.exitstatus or self.signalstatus. If the child exited normally then exitstatus will store the exit return code and signalstatus will be None. If the child was terminated abnormally with a signal then signalstatus will store the signal value and exitstatus will be None. If you need more detail you can also read the self.status member which stores the status returned by os.waitpid. You can interpret this using os.WIFEXITED/os.WEXITSTATUS or os.WIFSIGNALED/os.TERMSIG. """ self.STDIN_FILENO = pty.STDIN_FILENO self.STDOUT_FILENO = pty.STDOUT_FILENO self.STDERR_FILENO = pty.STDERR_FILENO self.stdin = sys.stdin self.stdout = sys.stdout self.stderr = sys.stderr self.searcher = None self.ignorecase = False self.before = None self.after = None self.match = None self.match_index = None self.terminated = True self.exitstatus = None self.signalstatus = None self.status = None # status returned by os.waitpid self.flag_eof = False self.pid = None self.child_fd = -1 # initially closed self.timeout = timeout self.delimiter = EOF self.logfile = logfile self.logfile_read = None # input from child (read_nonblocking) self.logfile_send = None # output to send (send, sendline) self.maxread = maxread # max bytes to read at one time into buffer self.buffer = '' # This is the read buffer. See maxread. self.searchwindowsize = searchwindowsize # Anything before searchwindowsize point is preserved, but not searched. # Most Linux machines don't like delaybeforesend to be below 0.03 (30 ms). self.delaybeforesend = 0.05 # Sets sleep time used just before sending data to child. Time in seconds. self.delayafterclose = 0.1 # Sets delay in close() method to allow kernel time to update process status. Time in seconds. self.delayafterterminate = 0.1 # Sets delay in terminate() method to allow kernel time to update process status. Time in seconds. self.softspace = False # File-like object. self.name = '<' + repr(self) + '>' # File-like object. self.encoding = None # File-like object. self.closed = True # File-like object. self.cwd = cwd self.env = env self.__irix_hack = (sys.platform.lower().find('irix')>=0) # This flags if we are running on irix # Solaris uses internal __fork_pty(). All others use pty.fork(). if (sys.platform.lower().find('solaris')>=0) or (sys.platform.lower().find('sunos5')>=0): self.use_native_pty_fork = False else: self.use_native_pty_fork = True # allow dummy instances for subclasses that may not use command or args. if command is None: self.command = None self.args = None self.name = '<pexpect factory incomplete>' else: self._spawn (command, args) def __del__(self): """This makes sure that no system resources are left open. Python only garbage collects Python objects. OS file descriptors are not Python objects, so they must be handled explicitly. If the child file descriptor was opened outside of this class (passed to the constructor) then this does not close it. """ if not self.closed: # It is possible for __del__ methods to execute during the # teardown of the Python VM itself. Thus self.close() may # trigger an exception because os.close may be None. # -- Fernando Perez try: self.close() except AttributeError: pass def __str__(self): """This returns a human-readable string that represents the state of the object. """ s = [] s.append(repr(self)) s.append('version: ' + __version__ + ' (' + __revision__ + ')') s.append('command: ' + str(self.command)) s.append('args: ' + str(self.args)) s.append('searcher: ' + str(self.searcher)) s.append('buffer (last 100 chars): ' + str(self.buffer)[-100:]) s.append('before (last 100 chars): ' + str(self.before)[-100:]) s.append('after: ' + str(self.after)) s.append('match: ' + str(self.match)) s.append('match_index: ' + str(self.match_index)) s.append('exitstatus: ' + str(self.exitstatus)) s.append('flag_eof: ' + str(self.flag_eof)) s.append('pid: ' + str(self.pid)) s.append('child_fd: ' + str(self.child_fd)) s.append('closed: ' + str(self.closed)) s.append('timeout: ' + str(self.timeout)) s.append('delimiter: ' + str(self.delimiter)) s.append('logfile: ' + str(self.logfile)) s.append('logfile_read: ' + str(self.logfile_read)) s.append('logfile_send: ' + str(self.logfile_send)) s.append('maxread: ' + str(self.maxread)) s.append('ignorecase: ' + str(self.ignorecase)) s.append('searchwindowsize: ' + str(self.searchwindowsize)) s.append('delaybeforesend: ' + str(self.delaybeforesend)) s.append('delayafterclose: ' + str(self.delayafterclose)) s.append('delayafterterminate: ' + str(self.delayafterterminate)) return '\n'.join(s) def _spawn(self,command,args=[]): """This starts the given command in a child process. This does all the fork/exec type of stuff for a pty. This is called by __init__. If args is empty then command will be parsed (split on spaces) and args will be set to parsed arguments. """ # The pid and child_fd of this object get set by this method. # Note that it is difficult for this method to fail. # You cannot detect if the child process cannot start. # So the only way you can tell if the child process started # or not is to try to read from the file descriptor. If you get # EOF immediately then it means that the child is already dead. # That may not necessarily be bad because you may haved spawned a child # that performs some task; creates no stdout output; and then dies. # If command is an int type then it may represent a file descriptor. if type(command) == type(0): raise ExceptionPexpect ('Command is an int type. If this is a file descriptor then maybe you want to use fdpexpect.fdspawn which takes an existing file descriptor instead of a command string.') if type (args) != type([]): raise TypeError ('The argument, args, must be a list.') if args == []: self.args = split_command_line(command) self.command = self.args[0] else: self.args = args[:] # work with a copy self.args.insert (0, command) self.command = command command_with_path = which(self.command) if command_with_path is None: raise ExceptionPexpect ('The command was not found or was not executable: %s.' % self.command) self.command = command_with_path self.args[0] = self.command self.name = '<' + ' '.join (self.args) + '>' assert self.pid is None, 'The pid member should be None.' assert self.command is not None, 'The command member should not be None.' if self.use_native_pty_fork: try: self.pid, self.child_fd = pty.fork() except OSError, e: raise ExceptionPexpect('Error! pty.fork() failed: ' + str(e)) else: # Use internal __fork_pty self.pid, self.child_fd = self.__fork_pty() if self.pid == 0: # Child try: self.child_fd = sys.stdout.fileno() # used by setwinsize() self.setwinsize(24, 80) except: # Some platforms do not like setwinsize (Cygwin). # This will cause problem when running applications that # are very picky about window size. # This is a serious limitation, but not a show stopper. pass # Do not allow child to inherit open file descriptors from parent. max_fd = resource.getrlimit(resource.RLIMIT_NOFILE)[0] for i in range (3, max_fd): try: os.close (i) except OSError: pass # I don't know why this works, but ignoring SIGHUP fixes a # problem when trying to start a Java daemon with sudo # (specifically, Tomcat). signal.signal(signal.SIGHUP, signal.SIG_IGN) if self.cwd is not None: os.chdir(self.cwd) if self.env is None: os.execv(self.command, self.args) else: os.execvpe(self.command, self.args, self.env) # Parent self.terminated = False self.closed = False def __fork_pty(self): """This implements a substitute for the forkpty system call. This should be more portable than the pty.fork() function. Specifically, this should work on Solaris. Modified 10.06.05 by Geoff Marshall: Implemented __fork_pty() method to resolve the issue with Python's pty.fork() not supporting Solaris, particularly ssh. Based on patch to posixmodule.c authored by Noah Spurrier:: http://mail.python.org/pipermail/python-dev/2003-May/035281.html """ parent_fd, child_fd = os.openpty() if parent_fd < 0 or child_fd < 0: raise ExceptionPexpect, "Error! Could not open pty with os.openpty()." pid = os.fork() if pid < 0: raise ExceptionPexpect, "Error! Failed os.fork()." elif pid == 0: # Child. os.close(parent_fd) self.__pty_make_controlling_tty(child_fd) os.dup2(child_fd, 0) os.dup2(child_fd, 1) os.dup2(child_fd, 2) if child_fd > 2: os.close(child_fd) else: # Parent. os.close(child_fd) return pid, parent_fd def __pty_make_controlling_tty(self, tty_fd): """This makes the pseudo-terminal the controlling tty. This should be more portable than the pty.fork() function. Specifically, this should work on Solaris. """ child_name = os.ttyname(tty_fd) # Disconnect from controlling tty if still connected. fd = os.open("/dev/tty", os.O_RDWR | os.O_NOCTTY); if fd >= 0: os.close(fd) os.setsid() # Verify we are disconnected from controlling tty try: fd = os.open("/dev/tty", os.O_RDWR | os.O_NOCTTY); if fd >= 0: os.close(fd) raise ExceptionPexpect, "Error! We are not disconnected from a controlling tty." except: # Good! We are disconnected from a controlling tty. pass # Verify we can open child pty. fd = os.open(child_name, os.O_RDWR); if fd < 0: raise ExceptionPexpect, "Error! Could not open child pty, " + child_name else: os.close(fd) # Verify we now have a controlling tty. fd = os.open("/dev/tty", os.O_WRONLY) if fd < 0: raise ExceptionPexpect, "Error! Could not open controlling tty, /dev/tty" else: os.close(fd) def fileno (self): # File-like object. """This returns the file descriptor of the pty for the child. """ return self.child_fd def close (self, force=True): # File-like object. """This closes the connection with the child application. Note that calling close() more than once is valid. This emulates standard Python behavior with files. Set force to True if you want to make sure that the child is terminated (SIGKILL is sent if the child ignores SIGHUP and SIGINT). """ if not self.closed: self.flush() os.close (self.child_fd) time.sleep(self.delayafterclose) # Give kernel time to update process status. if self.isalive(): if not self.terminate(force): raise ExceptionPexpect ('close() could not terminate the child using terminate()') self.child_fd = -1 self.closed = True #self.pid = None def flush (self): # File-like object. """This does nothing. It is here to support the interface for a File-like object. """ pass def isatty (self): # File-like object. """This returns True if the file descriptor is open and connected to a tty(-like) device, else False. """ return os.isatty(self.child_fd) def waitnoecho (self, timeout=-1): """This waits until the terminal ECHO flag is set False. This returns True if the echo mode is off. This returns False if the ECHO flag was not set False before the timeout. This can be used to detect when the child is waiting for a password. Usually a child application will turn off echo mode when it is waiting for the user to enter a password. For example, instead of expecting the "password:" prompt you can wait for the child to set ECHO off:: p = pexpect.spawn ('ssh user@example.com') p.waitnoecho() p.sendline(mypassword) If timeout is None then this method to block forever until ECHO flag is False. """ if timeout == -1: timeout = self.timeout if timeout is not None: end_time = time.time() + timeout while True: if not self.getecho(): return True if timeout < 0 and timeout is not None: return False if timeout is not None: timeout = end_time - time.time() time.sleep(0.1) def getecho (self): """This returns the terminal echo mode. This returns True if echo is on or False if echo is off. Child applications that are expecting you to enter a password often set ECHO False. See waitnoecho(). """ attr = termios.tcgetattr(self.child_fd) if attr[3] & termios.ECHO: return True return False def setecho (self, state): """This sets the terminal echo mode on or off. Note that anything the child sent before the echo will be lost, so you should be sure that your input buffer is empty before you call setecho(). For example, the following will work as expected:: p = pexpect.spawn('cat') p.sendline ('1234') # We will see this twice (once from tty echo and again from cat). p.expect (['1234']) p.expect (['1234']) p.setecho(False) # Turn off tty echo p.sendline ('abcd') # We will set this only once (echoed by cat). p.sendline ('wxyz') # We will set this only once (echoed by cat) p.expect (['abcd']) p.expect (['wxyz']) The following WILL NOT WORK because the lines sent before the setecho will be lost:: p = pexpect.spawn('cat') p.sendline ('1234') # We will see this twice (once from tty echo and again from cat). p.setecho(False) # Turn off tty echo p.sendline ('abcd') # We will set this only once (echoed by cat). p.sendline ('wxyz') # We will set this only once (echoed by cat) p.expect (['1234']) p.expect (['1234']) p.expect (['abcd']) p.expect (['wxyz']) """ self.child_fd attr = termios.tcgetattr(self.child_fd) if state: attr[3] = attr[3] | termios.ECHO else: attr[3] = attr[3] & ~termios.ECHO # I tried TCSADRAIN and TCSAFLUSH, but these were inconsistent # and blocked on some platforms. TCSADRAIN is probably ideal if it worked. termios.tcsetattr(self.child_fd, termios.TCSANOW, attr) def read_nonblocking (self, size = 1, timeout = -1): """This reads at most size characters from the child application. It includes a timeout. If the read does not complete within the timeout period then a TIMEOUT exception is raised. If the end of file is read then an EOF exception will be raised. If a log file was set using setlog() then all data will also be written to the log file. If timeout is None then the read may block indefinitely. If timeout is -1 then the self.timeout value is used. If timeout is 0 then the child is polled and if there was no data immediately ready then this will raise a TIMEOUT exception. The timeout refers only to the amount of time to read at least one character. This is not effected by the 'size' parameter, so if you call read_nonblocking(size=100, timeout=30) and only one character is available right away then one character will be returned immediately. It will not wait for 30 seconds for another 99 characters to come in. This is a wrapper around os.read(). It uses select.select() to implement the timeout. """ if self.closed: raise ValueError ('I/O operation on closed file in read_nonblocking().') if timeout == -1: timeout = self.timeout # Note that some systems such as Solaris do not give an EOF when # the child dies. In fact, you can still try to read # from the child_fd -- it will block forever or until TIMEOUT. # For this case, I test isalive() before doing any reading. # If isalive() is false, then I pretend that this is the same as EOF. if not self.isalive(): r,w,e = self.__select([self.child_fd], [], [], 0) # timeout of 0 means "poll" if not r: self.flag_eof = True raise EOF ('End Of File (EOF) in read_nonblocking(). Braindead platform.') elif self.__irix_hack: # This is a hack for Irix. It seems that Irix requires a long delay before checking isalive. # This adds a 2 second delay, but only when the child is terminated. r, w, e = self.__select([self.child_fd], [], [], 2) if not r and not self.isalive(): self.flag_eof = True raise EOF ('End Of File (EOF) in read_nonblocking(). Pokey platform.') r,w,e = self.__select([self.child_fd], [], [], timeout) if not r: if not self.isalive(): # Some platforms, such as Irix, will claim that their processes are alive; # then timeout on the select; and then finally admit that they are not alive. self.flag_eof = True raise EOF ('End of File (EOF) in read_nonblocking(). Very pokey platform.') else: raise TIMEOUT ('Timeout exceeded in read_nonblocking().') if self.child_fd in r: try: s = os.read(self.child_fd, size) except OSError, e: # Linux does this self.flag_eof = True raise EOF ('End Of File (EOF) in read_nonblocking(). Exception style platform.') if s == '': # BSD style self.flag_eof = True raise EOF ('End Of File (EOF) in read_nonblocking(). Empty string style platform.') if self.logfile is not None: self.logfile.write (s) self.logfile.flush() if self.logfile_read is not None: self.logfile_read.write (s) self.logfile_read.flush() return s raise ExceptionPexpect ('Reached an unexpected state in read_nonblocking().') def read (self, size = -1): # File-like object. """This reads at most "size" bytes from the file (less if the read hits EOF before obtaining size bytes). If the size argument is negative or omitted, read all data until EOF is reached. The bytes are returned as a string object. An empty string is returned when EOF is encountered immediately. """ if size == 0: return '' if size < 0: self.expect (self.delimiter) # delimiter default is EOF return self.before # I could have done this more directly by not using expect(), but # I deliberately decided to couple read() to expect() so that # I would catch any bugs early and ensure consistant behavior. # It's a little less efficient, but there is less for me to # worry about if I have to later modify read() or expect(). # Note, it's OK if size==-1 in the regex. That just means it # will never match anything in which case we stop only on EOF. cre = re.compile('.{%d}' % size, re.DOTALL) index = self.expect ([cre, self.delimiter]) # delimiter default is EOF if index == 0: return self.after ### self.before should be ''. Should I assert this? return self.before def readline (self, size = -1): # File-like object. """This reads and returns one entire line. A trailing newline is kept in the string, but may be absent when a file ends with an incomplete line. Note: This readline() looks for a \\r\\n pair even on UNIX because this is what the pseudo tty device returns. So contrary to what you may expect you will receive the newline as \\r\\n. An empty string is returned when EOF is hit immediately. Currently, the size argument is mostly ignored, so this behavior is not standard for a file-like object. If size is 0 then an empty string is returned. """ if size == 0: return '' index = self.expect (['\r\n', self.delimiter]) # delimiter default is EOF if index == 0: return self.before + '\r\n' else: return self.before def __iter__ (self): # File-like object. """This is to support iterators over a file-like object. """ return self def next (self): # File-like object. """This is to support iterators over a file-like object. """ result = self.readline() if result == "": raise StopIteration return result def readlines (self, sizehint = -1): # File-like object. """This reads until EOF using readline() and returns a list containing the lines thus read. The optional "sizehint" argument is ignored. """ lines = [] while True: line = self.readline() if not line: break lines.append(line) return lines def write(self, s): # File-like object. """This is similar to send() except that there is no return value. """ self.send (s) def writelines (self, sequence): # File-like object. """This calls write() for each element in the sequence. The sequence can be any iterable object producing strings, typically a list of strings. This does not add line separators There is no return value. """ for s in sequence: self.write (s) def send(self, s): """This sends a string to the child process. This returns the number of bytes written. If a log file was set then the data is also written to the log. """ time.sleep(self.delaybeforesend) if self.logfile is not None: self.logfile.write (s) self.logfile.flush() if self.logfile_send is not None: self.logfile_send.write (s) self.logfile_send.flush() c = os.write(self.child_fd, s) return c def sendline(self, s=''): """This is like send(), but it adds a line feed (os.linesep). This returns the number of bytes written. """ n = self.send(s) n = n + self.send (os.linesep) return n def sendcontrol(self, char): """This sends a control character to the child such as Ctrl-C or Ctrl-D. For example, to send a Ctrl-G (ASCII 7):: child.sendcontrol('g') See also, sendintr() and sendeof(). """ char = char.lower() a = ord(char) if a>=97 and a<=122: a = a - ord('a') + 1 return self.send (chr(a)) d = {'@':0, '`':0, '[':27, '{':27, '\\':28, '|':28, ']':29, '}': 29, '^':30, '~':30, '_':31, '?':127} if char not in d: return 0 return self.send (chr(d[char])) def sendeof(self): """This sends an EOF to the child. This sends a character which causes the pending parent output buffer to be sent to the waiting child program without waiting for end-of-line. If it is the first character of the line, the read() in the user program returns 0, which signifies end-of-file. This means to work as expected a sendeof() has to be called at the beginning of a line. This method does not send a newline. It is the responsibility of the caller to ensure the eof is sent at the beginning of a line. """ ### Hmmm... how do I send an EOF? ###C if ((m = write(pty, *buf, p - *buf)) < 0) ###C return (errno == EWOULDBLOCK) ? n : -1; #fd = sys.stdin.fileno() #old = termios.tcgetattr(fd) # remember current state #attr = termios.tcgetattr(fd) #attr[3] = attr[3] | termios.ICANON # ICANON must be set to recognize EOF #try: # use try/finally to ensure state gets restored # termios.tcsetattr(fd, termios.TCSADRAIN, attr) # if hasattr(termios, 'CEOF'): # os.write (self.child_fd, '%c' % termios.CEOF) # else: # # Silly platform does not define CEOF so assume CTRL-D # os.write (self.child_fd, '%c' % 4) #finally: # restore state # termios.tcsetattr(fd, termios.TCSADRAIN, old) if hasattr(termios, 'VEOF'): char = termios.tcgetattr(self.child_fd)[6][termios.VEOF] else: # platform does not define VEOF so assume CTRL-D char = chr(4) self.send(char) def sendintr(self): """This sends a SIGINT to the child. It does not require the SIGINT to be the first character on a line. """ if hasattr(termios, 'VINTR'): char = termios.tcgetattr(self.child_fd)[6][termios.VINTR] else: # platform does not define VINTR so assume CTRL-C char = chr(3) self.send (char) def eof (self): """This returns True if the EOF exception was ever raised. """ return self.flag_eof def terminate(self, force=False): """This forces a child process to terminate. It starts nicely with SIGHUP and SIGINT. If "force" is True then moves onto SIGKILL. This returns True if the child was terminated. This returns False if the child could not be terminated. """ if not self.isalive(): return True try: self.kill(signal.SIGHUP) time.sleep(self.delayafterterminate) if not self.isalive(): return True self.kill(signal.SIGCONT) time.sleep(self.delayafterterminate) if not self.isalive(): return True self.kill(signal.SIGINT) time.sleep(self.delayafterterminate) if not self.isalive(): return True if force: self.kill(signal.SIGKILL) time.sleep(self.delayafterterminate) if not self.isalive(): return True else: return False return False except OSError, e: # I think there are kernel timing issues that sometimes cause # this to happen. I think isalive() reports True, but the # process is dead to the kernel. # Make one last attempt to see if the kernel is up to date. time.sleep(self.delayafterterminate) if not self.isalive(): return True else: return False def wait(self): """This waits until the child exits. This is a blocking call. This will not read any data from the child, so this will block forever if the child has unread output and has terminated. In other words, the child may have printed output then called exit(); but, technically, the child is still alive until its output is read. """ if self.isalive(): pid, status = os.waitpid(self.pid, 0) else: raise ExceptionPexpect ('Cannot wait for dead child process.') self.exitstatus = os.WEXITSTATUS(status) if os.WIFEXITED (status): self.status = status self.exitstatus = os.WEXITSTATUS(status) self.signalstatus = None self.terminated = True elif os.WIFSIGNALED (status): self.status = status self.exitstatus = None self.signalstatus = os.WTERMSIG(status) self.terminated = True elif os.WIFSTOPPED (status): raise ExceptionPexpect ('Wait was called for a child process that is stopped. This is not supported. Is some other process attempting job control with our child pid?') return self.exitstatus def isalive(self): """This tests if the child process is running or not. This is non-blocking. If the child was terminated then this will read the exitstatus or signalstatus of the child. This returns True if the child process appears to be running or False if not. It can take literally SECONDS for Solaris to return the right status. """ if self.terminated: return False if self.flag_eof: # This is for Linux, which requires the blocking form of waitpid to get # status of a defunct process. This is super-lame. The flag_eof would have # been set in read_nonblocking(), so this should be safe. waitpid_options = 0 else: waitpid_options = os.WNOHANG try: pid, status = os.waitpid(self.pid, waitpid_options) except OSError, e: # No child processes if e[0] == errno.ECHILD: raise ExceptionPexpect ('isalive() encountered condition where "terminated" is 0, but there was no child process. Did someone else call waitpid() on our process?') else: raise e # I have to do this twice for Solaris. I can't even believe that I figured this out... # If waitpid() returns 0 it means that no child process wishes to # report, and the value of status is undefined. if pid == 0: try: pid, status = os.waitpid(self.pid, waitpid_options) ### os.WNOHANG) # Solaris! except OSError, e: # This should never happen... if e[0] == errno.ECHILD: raise ExceptionPexpect ('isalive() encountered condition that should never happen. There was no child process. Did someone else call waitpid() on our process?') else: raise e # If pid is still 0 after two calls to waitpid() then # the process really is alive. This seems to work on all platforms, except # for Irix which seems to require a blocking call on waitpid or select, so I let read_nonblocking # take care of this situation (unfortunately, this requires waiting through the timeout). if pid == 0: return True if pid == 0: return True if os.WIFEXITED (status): self.status = status self.exitstatus = os.WEXITSTATUS(status) self.signalstatus = None self.terminated = True elif os.WIFSIGNALED (status): self.status = status self.exitstatus = None self.signalstatus = os.WTERMSIG(status) self.terminated = True elif os.WIFSTOPPED (status): raise ExceptionPexpect ('isalive() encountered condition where child process is stopped. This is not supported. Is some other process attempting job control with our child pid?') return False def kill(self, sig): """This sends the given signal to the child application. In keeping with UNIX tradition it has a misleading name. It does not necessarily kill the child unless you send the right signal. """ # Same as os.kill, but the pid is given for you. if self.isalive(): os.kill(self.pid, sig) def compile_pattern_list(self, patterns): """This compiles a pattern-string or a list of pattern-strings. Patterns must be a StringType, EOF, TIMEOUT, SRE_Pattern, or a list of those. Patterns may also be None which results in an empty list (you might do this if waiting for an EOF or TIMEOUT condition without expecting any pattern). This is used by expect() when calling expect_list(). Thus expect() is nothing more than:: cpl = self.compile_pattern_list(pl) return self.expect_list(cpl, timeout) If you are using expect() within a loop it may be more efficient to compile the patterns first and then call expect_list(). This avoid calls in a loop to compile_pattern_list():: cpl = self.compile_pattern_list(my_pattern) while some_condition: ... i = self.expect_list(clp, timeout) ... """ if patterns is None: return [] if type(patterns) is not types.ListType: patterns = [patterns] compile_flags = re.DOTALL # Allow dot to match \n if self.ignorecase: compile_flags = compile_flags | re.IGNORECASE compiled_pattern_list = [] for p in patterns: if type(p) in types.StringTypes: compiled_pattern_list.append(re.compile(p, compile_flags)) elif p is EOF: compiled_pattern_list.append(EOF) elif p is TIMEOUT: compiled_pattern_list.append(TIMEOUT) elif type(p) is type(re.compile('')): compiled_pattern_list.append(p) else: raise TypeError ('Argument must be one of StringTypes, EOF, TIMEOUT, SRE_Pattern, or a list of those type. %s' % str(type(p))) return compiled_pattern_list def expect(self, pattern, timeout = -1, searchwindowsize=None): """This seeks through the stream until a pattern is matched. The pattern is overloaded and may take several types. The pattern can be a StringType, EOF, a compiled re, or a list of any of those types. Strings will be compiled to re types. This returns the index into the pattern list. If the pattern was not a list this returns index 0 on a successful match. This may raise exceptions for EOF or TIMEOUT. To avoid the EOF or TIMEOUT exceptions add EOF or TIMEOUT to the pattern list. That will cause expect to match an EOF or TIMEOUT condition instead of raising an exception. If you pass a list of patterns and more than one matches, the first match in the stream is chosen. If more than one pattern matches at that point, the leftmost in the pattern list is chosen. For example:: # the input is 'foobar' index = p.expect (['bar', 'foo', 'foobar']) # returns 1 ('foo') even though 'foobar' is a "better" match Please note, however, that buffering can affect this behavior, since input arrives in unpredictable chunks. For example:: # the input is 'foobar' index = p.expect (['foobar', 'foo']) # returns 0 ('foobar') if all input is available at once, # but returs 1 ('foo') if parts of the final 'bar' arrive late After a match is found the instance attributes 'before', 'after' and 'match' will be set. You can see all the data read before the match in 'before'. You can see the data that was matched in 'after'. The re.MatchObject used in the re match will be in 'match'. If an error occurred then 'before' will be set to all the data read so far and 'after' and 'match' will be None. If timeout is -1 then timeout will be set to the self.timeout value. A list entry may be EOF or TIMEOUT instead of a string. This will catch these exceptions and return the index of the list entry instead of raising the exception. The attribute 'after' will be set to the exception type. The attribute 'match' will be None. This allows you to write code like this:: index = p.expect (['good', 'bad', pexpect.EOF, pexpect.TIMEOUT]) if index == 0: do_something() elif index == 1: do_something_else() elif index == 2: do_some_other_thing() elif index == 3: do_something_completely_different() instead of code like this:: try: index = p.expect (['good', 'bad']) if index == 0: do_something() elif index == 1: do_something_else() except EOF: do_some_other_thing() except TIMEOUT: do_something_completely_different() These two forms are equivalent. It all depends on what you want. You can also just expect the EOF if you are waiting for all output of a child to finish. For example:: p = pexpect.spawn('/bin/ls') p.expect (pexpect.EOF) print p.before If you are trying to optimize for speed then see expect_list(). """ compiled_pattern_list = self.compile_pattern_list(pattern) return self.expect_list(compiled_pattern_list, timeout, searchwindowsize) def expect_list(self, pattern_list, timeout = -1, searchwindowsize = -1): """This takes a list of compiled regular expressions and returns the index into the pattern_list that matched the child output. The list may also contain EOF or TIMEOUT (which are not compiled regular expressions). This method is similar to the expect() method except that expect_list() does not recompile the pattern list on every call. This may help if you are trying to optimize for speed, otherwise just use the expect() method. This is called by expect(). If timeout==-1 then the self.timeout value is used. If searchwindowsize==-1 then the self.searchwindowsize value is used. """ return self.expect_loop(searcher_re(pattern_list), timeout, searchwindowsize) def expect_exact(self, pattern_list, timeout = -1, searchwindowsize = -1): """This is similar to expect(), but uses plain string matching instead of compiled regular expressions in 'pattern_list'. The 'pattern_list' may be a string; a list or other sequence of strings; or TIMEOUT and EOF. This call might be faster than expect() for two reasons: string searching is faster than RE matching and it is possible to limit the search to just the end of the input buffer. This method is also useful when you don't want to have to worry about escaping regular expression characters that you want to match.""" if type(pattern_list) in types.StringTypes or pattern_list in (TIMEOUT, EOF): pattern_list = [pattern_list] return self.expect_loop(searcher_string(pattern_list), timeout, searchwindowsize) def expect_loop(self, searcher, timeout = -1, searchwindowsize = -1): """This is the common loop used inside expect. The 'searcher' should be an instance of searcher_re or searcher_string, which describes how and what to search for in the input. See expect() for other arguments, return value and exceptions. """ self.searcher = searcher if timeout == -1: timeout = self.timeout if timeout is not None: end_time = time.time() + timeout if searchwindowsize == -1: searchwindowsize = self.searchwindowsize try: incoming = self.buffer freshlen = len(incoming) while True: # Keep reading until exception or return. index = searcher.search(incoming, freshlen, searchwindowsize) if index >= 0: self.buffer = incoming[searcher.end : ] self.before = incoming[ : searcher.start] self.after = incoming[searcher.start : searcher.end] self.match = searcher.match self.match_index = index return self.match_index # No match at this point if timeout < 0 and timeout is not None: raise TIMEOUT ('Timeout exceeded in expect_any().') # Still have time left, so read more data c = self.read_nonblocking (self.maxread, timeout) freshlen = len(c) time.sleep (0.0001) incoming = incoming + c if timeout is not None: timeout = end_time - time.time() except EOF, e: self.buffer = '' self.before = incoming self.after = EOF index = searcher.eof_index if index >= 0: self.match = EOF self.match_index = index return self.match_index else: self.match = None self.match_index = None raise EOF (str(e) + '\n' + str(self)) except TIMEOUT, e: self.buffer = incoming self.before = incoming self.after = TIMEOUT index = searcher.timeout_index if index >= 0: self.match = TIMEOUT self.match_index = index return self.match_index else: self.match = None self.match_index = None raise TIMEOUT (str(e) + '\n' + str(self)) except: self.before = incoming self.after = None self.match = None self.match_index = None raise def getwinsize(self): """This returns the terminal window size of the child tty. The return value is a tuple of (rows, cols). """ TIOCGWINSZ = getattr(termios, 'TIOCGWINSZ', 1074295912L) s = struct.pack('HHHH', 0, 0, 0, 0) x = fcntl.ioctl(self.fileno(), TIOCGWINSZ, s) return struct.unpack('HHHH', x)[0:2] def setwinsize(self, r, c): """This sets the terminal window size of the child tty. This will cause a SIGWINCH signal to be sent to the child. This does not change the physical window size. It changes the size reported to TTY-aware applications like vi or curses -- applications that respond to the SIGWINCH signal. """ # Check for buggy platforms. Some Python versions on some platforms # (notably OSF1 Alpha and RedHat 7.1) truncate the value for # termios.TIOCSWINSZ. It is not clear why this happens. # These platforms don't seem to handle the signed int very well; # yet other platforms like OpenBSD have a large negative value for # TIOCSWINSZ and they don't have a truncate problem. # Newer versions of Linux have totally different values for TIOCSWINSZ. # Note that this fix is a hack. TIOCSWINSZ = getattr(termios, 'TIOCSWINSZ', -2146929561) if TIOCSWINSZ == 2148037735L: # L is not required in Python >= 2.2. TIOCSWINSZ = -2146929561 # Same bits, but with sign. # Note, assume ws_xpixel and ws_ypixel are zero. s = struct.pack('HHHH', r, c, 0, 0) fcntl.ioctl(self.fileno(), TIOCSWINSZ, s) def interact(self, escape_character = chr(29), input_filter = None, output_filter = None): """This gives control of the child process to the interactive user (the human at the keyboard). Keystrokes are sent to the child process, and the stdout and stderr output of the child process is printed. This simply echos the child stdout and child stderr to the real stdout and it echos the real stdin to the child stdin. When the user types the escape_character this method will stop. The default for escape_character is ^]. This should not be confused with ASCII 27 -- the ESC character. ASCII 29 was chosen for historical merit because this is the character used by 'telnet' as the escape character. The escape_character will not be sent to the child process. You may pass in optional input and output filter functions. These functions should take a string and return a string. The output_filter will be passed all the output from the child process. The input_filter will be passed all the keyboard input from the user. The input_filter is run BEFORE the check for the escape_character. Note that if you change the window size of the parent the SIGWINCH signal will not be passed through to the child. If you want the child window size to change when the parent's window size changes then do something like the following example:: import pexpect, struct, fcntl, termios, signal, sys def sigwinch_passthrough (sig, data): s = struct.pack("HHHH", 0, 0, 0, 0) a = struct.unpack('hhhh', fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ , s)) global p p.setwinsize(a[0],a[1]) p = pexpect.spawn('/bin/bash') # Note this is global and used in sigwinch_passthrough. signal.signal(signal.SIGWINCH, sigwinch_passthrough) p.interact() """ # Flush the buffer. self.stdout.write (self.buffer) self.stdout.flush() self.buffer = '' mode = tty.tcgetattr(self.STDIN_FILENO) tty.setraw(self.STDIN_FILENO) try: self.__interact_copy(escape_character, input_filter, output_filter) finally: tty.tcsetattr(self.STDIN_FILENO, tty.TCSAFLUSH, mode) def __interact_writen(self, fd, data): """This is used by the interact() method. """ while data != '' and self.isalive(): n = os.write(fd, data) data = data[n:] def __interact_read(self, fd): """This is used by the interact() method. """ return os.read(fd, 1000) def __interact_copy(self, escape_character = None, input_filter = None, output_filter = None): """This is used by the interact() method. """ while self.isalive(): r,w,e = self.__select([self.child_fd, self.STDIN_FILENO], [], []) if self.child_fd in r: data = self.__interact_read(self.child_fd) if output_filter: data = output_filter(data) if self.logfile is not None: self.logfile.write (data) self.logfile.flush() os.write(self.STDOUT_FILENO, data) if self.STDIN_FILENO in r: data = self.__interact_read(self.STDIN_FILENO) if input_filter: data = input_filter(data) i = data.rfind(escape_character) if i != -1: data = data[:i] self.__interact_writen(self.child_fd, data) break self.__interact_writen(self.child_fd, data) def __select (self, iwtd, owtd, ewtd, timeout=None): """This is a wrapper around select.select() that ignores signals. If select.select raises a select.error exception and errno is an EINTR error then it is ignored. Mainly this is used to ignore sigwinch (terminal resize). """ # if select() is interrupted by a signal (errno==EINTR) then # we loop back and enter the select() again. if timeout is not None: end_time = time.time() + timeout while True: try: return select.select (iwtd, owtd, ewtd, timeout) except select.error, e: if e[0] == errno.EINTR: # if we loop back we have to subtract the amount of time we already waited. if timeout is not None: timeout = end_time - time.time() if timeout < 0: return ([],[],[]) else: # something else caused the select.error, so this really is an exception raise ############################################################################## # The following methods are no longer supported or allowed. def setmaxread (self, maxread): """This method is no longer supported or allowed. I don't like getters and setters without a good reason. """ raise ExceptionPexpect ('This method is no longer supported or allowed. Just assign a value to the maxread member variable.') def setlog (self, fileobject): """This method is no longer supported or allowed. """ raise ExceptionPexpect ('This method is no longer supported or allowed. Just assign a value to the logfile member variable.') ############################################################################## # End of spawn class ############################################################################## class searcher_string (object): """This is a plain string search helper for the spawn.expect_any() method. Attributes: eof_index - index of EOF, or -1 timeout_index - index of TIMEOUT, or -1 After a successful match by the search() method the following attributes are available: start - index into the buffer, first byte of match end - index into the buffer, first byte after match match - the matching string itself """ def __init__(self, strings): """This creates an instance of searcher_string. This argument 'strings' may be a list; a sequence of strings; or the EOF or TIMEOUT types. """ self.eof_index = -1 self.timeout_index = -1 self._strings = [] for n, s in zip(range(len(strings)), strings): if s is EOF: self.eof_index = n continue if s is TIMEOUT: self.timeout_index = n continue self._strings.append((n, s)) def __str__(self): """This returns a human-readable string that represents the state of the object.""" ss = [ (ns[0],' %d: "%s"' % ns) for ns in self._strings ] ss.append((-1,'searcher_string:')) if self.eof_index >= 0: ss.append ((self.eof_index,' %d: EOF' % self.eof_index)) if self.timeout_index >= 0: ss.append ((self.timeout_index,' %d: TIMEOUT' % self.timeout_index)) ss.sort() ss = zip(*ss)[1] return '\n'.join(ss) def search(self, buffer, freshlen, searchwindowsize=None): """This searches 'buffer' for the first occurence of one of the search strings. 'freshlen' must indicate the number of bytes at the end of 'buffer' which have not been searched before. It helps to avoid searching the same, possibly big, buffer over and over again. See class spawn for the 'searchwindowsize' argument. If there is a match this returns the index of that string, and sets 'start', 'end' and 'match'. Otherwise, this returns -1. """ absurd_match = len(buffer) first_match = absurd_match # 'freshlen' helps a lot here. Further optimizations could # possibly include: # # using something like the Boyer-Moore Fast String Searching # Algorithm; pre-compiling the search through a list of # strings into something that can scan the input once to # search for all N strings; realize that if we search for # ['bar', 'baz'] and the input is '...foo' we need not bother # rescanning until we've read three more bytes. # # Sadly, I don't know enough about this interesting topic. /grahn for index, s in self._strings: if searchwindowsize is None: # the match, if any, can only be in the fresh data, # or at the very end of the old data offset = -(freshlen+len(s)) else: # better obey searchwindowsize offset = -searchwindowsize n = buffer.find(s, offset) if n >= 0 and n < first_match: first_match = n best_index, best_match = index, s if first_match == absurd_match: return -1 self.match = best_match self.start = first_match self.end = self.start + len(self.match) return best_index class searcher_re (object): """This is regular expression string search helper for the spawn.expect_any() method. Attributes: eof_index - index of EOF, or -1 timeout_index - index of TIMEOUT, or -1 After a successful match by the search() method the following attributes are available: start - index into the buffer, first byte of match end - index into the buffer, first byte after match match - the re.match object returned by a succesful re.search """ def __init__(self, patterns): """This creates an instance that searches for 'patterns' Where 'patterns' may be a list or other sequence of compiled regular expressions, or the EOF or TIMEOUT types.""" self.eof_index = -1 self.timeout_index = -1 self._searches = [] for n, s in zip(range(len(patterns)), patterns): if s is EOF: self.eof_index = n continue if s is TIMEOUT: self.timeout_index = n continue self._searches.append((n, s)) def __str__(self): """This returns a human-readable string that represents the state of the object.""" ss = [ (n,' %d: re.compile("%s")' % (n,str(s.pattern))) for n,s in self._searches] ss.append((-1,'searcher_re:')) if self.eof_index >= 0: ss.append ((self.eof_index,' %d: EOF' % self.eof_index)) if self.timeout_index >= 0: ss.append ((self.timeout_index,' %d: TIMEOUT' % self.timeout_index)) ss.sort() ss = zip(*ss)[1] return '\n'.join(ss) def search(self, buffer, freshlen, searchwindowsize=None): """This searches 'buffer' for the first occurence of one of the regular expressions. 'freshlen' must indicate the number of bytes at the end of 'buffer' which have not been searched before. See class spawn for the 'searchwindowsize' argument. If there is a match this returns the index of that string, and sets 'start', 'end' and 'match'. Otherwise, returns -1.""" absurd_match = len(buffer) first_match = absurd_match # 'freshlen' doesn't help here -- we cannot predict the # length of a match, and the re module provides no help. if searchwindowsize is None: searchstart = 0 else: searchstart = max(0, len(buffer)-searchwindowsize) for index, s in self._searches: match = s.search(buffer, searchstart) if match is None: continue n = match.start() if n < first_match: first_match = n the_match = match best_index = index if first_match == absurd_match: return -1 self.start = first_match self.match = the_match self.end = self.match.end() return best_index def which (filename): """This takes a given filename; tries to find it in the environment path; then checks if it is executable. This returns the full path to the filename if found and executable. Otherwise this returns None.""" # Special case where filename already contains a path. if os.path.dirname(filename) != '': if os.access (filename, os.X_OK): return filename if not os.environ.has_key('PATH') or os.environ['PATH'] == '': p = os.defpath else: p = os.environ['PATH'] # Oddly enough this was the one line that made Pexpect # incompatible with Python 1.5.2. #pathlist = p.split (os.pathsep) pathlist = string.split (p, os.pathsep) for path in pathlist: f = os.path.join(path, filename) if os.access(f, os.X_OK): return f return None def split_command_line(command_line): """This splits a command line into a list of arguments. It splits arguments on spaces, but handles embedded quotes, doublequotes, and escaped characters. It's impossible to do this with a regular expression, so I wrote a little state machine to parse the command line. """ arg_list = [] arg = '' # Constants to name the states we can be in. state_basic = 0 state_esc = 1 state_singlequote = 2 state_doublequote = 3 state_whitespace = 4 # The state of consuming whitespace between commands. state = state_basic for c in command_line: if state == state_basic or state == state_whitespace: if c == '\\': # Escape the next character state = state_esc elif c == r"'": # Handle single quote state = state_singlequote elif c == r'"': # Handle double quote state = state_doublequote elif c.isspace(): # Add arg to arg_list if we aren't in the middle of whitespace. if state == state_whitespace: None # Do nothing. else: arg_list.append(arg) arg = '' state = state_whitespace else: arg = arg + c state = state_basic elif state == state_esc: arg = arg + c state = state_basic elif state == state_singlequote: if c == r"'": state = state_basic else: arg = arg + c elif state == state_doublequote: if c == r'"': state = state_basic else: arg = arg + c if arg != '': arg_list.append(arg) return arg_list # vi:ts=4:sw=4:expandtab:ft=python:
75,937
Python
.py
1,500
40.182667
205
0.617702
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,869
pxssh.py
pwnieexpress_raspberry_pwn/src/pexpect-2.3/pxssh.py
"""This class extends pexpect.spawn to specialize setting up SSH connections. This adds methods for login, logout, and expecting the shell prompt. $Id: pxssh.py 487 2007-08-29 22:33:29Z noah $ """ from pexpect import * import pexpect import time __all__ = ['ExceptionPxssh', 'pxssh'] # Exception classes used by this module. class ExceptionPxssh(ExceptionPexpect): """Raised for pxssh exceptions. """ class pxssh (spawn): """This class extends pexpect.spawn to specialize setting up SSH connections. This adds methods for login, logout, and expecting the shell prompt. It does various tricky things to handle many situations in the SSH login process. For example, if the session is your first login, then pxssh automatically accepts the remote certificate; or if you have public key authentication setup then pxssh won't wait for the password prompt. pxssh uses the shell prompt to synchronize output from the remote host. In order to make this more robust it sets the shell prompt to something more unique than just $ or #. This should work on most Borne/Bash or Csh style shells. Example that runs a few commands on a remote server and prints the result:: import pxssh import getpass try: s = pxssh.pxssh() hostname = raw_input('hostname: ') username = raw_input('username: ') password = getpass.getpass('password: ') s.login (hostname, username, password) s.sendline ('uptime') # run a command s.prompt() # match the prompt print s.before # print everything before the prompt. s.sendline ('ls -l') s.prompt() print s.before s.sendline ('df') s.prompt() print s.before s.logout() except pxssh.ExceptionPxssh, e: print "pxssh failed on login." print str(e) Note that if you have ssh-agent running while doing development with pxssh then this can lead to a lot of confusion. Many X display managers (xdm, gdm, kdm, etc.) will automatically start a GUI agent. You may see a GUI dialog box popup asking for a password during development. You should turn off any key agents during testing. The 'force_password' attribute will turn off public key authentication. This will only work if the remote SSH server is configured to allow password logins. Example of using 'force_password' attribute:: s = pxssh.pxssh() s.force_password = True hostname = raw_input('hostname: ') username = raw_input('username: ') password = getpass.getpass('password: ') s.login (hostname, username, password) """ def __init__ (self, timeout=30, maxread=2000, searchwindowsize=None, logfile=None, cwd=None, env=None): spawn.__init__(self, None, timeout=timeout, maxread=maxread, searchwindowsize=searchwindowsize, logfile=logfile, cwd=cwd, env=env) self.name = '<pxssh>' #SUBTLE HACK ALERT! Note that the command to set the prompt uses a #slightly different string than the regular expression to match it. This #is because when you set the prompt the command will echo back, but we #don't want to match the echoed command. So if we make the set command #slightly different than the regex we eliminate the problem. To make the #set command different we add a backslash in front of $. The $ doesn't #need to be escaped, but it doesn't hurt and serves to make the set #prompt command different than the regex. # used to match the command-line prompt self.UNIQUE_PROMPT = "\[PEXPECT\][\$\#] " self.PROMPT = self.UNIQUE_PROMPT # used to set shell command-line prompt to UNIQUE_PROMPT. self.PROMPT_SET_SH = "PS1='[PEXPECT]\$ '" self.PROMPT_SET_CSH = "set prompt='[PEXPECT]\$ '" self.SSH_OPTS = "-o'RSAAuthentication=no' -o 'PubkeyAuthentication=no'" # Disabling X11 forwarding gets rid of the annoying SSH_ASKPASS from # displaying a GUI password dialog. I have not figured out how to # disable only SSH_ASKPASS without also disabling X11 forwarding. # Unsetting SSH_ASKPASS on the remote side doesn't disable it! Annoying! #self.SSH_OPTS = "-x -o'RSAAuthentication=no' -o 'PubkeyAuthentication=no'" self.force_password = False self.auto_prompt_reset = True def levenshtein_distance(self, a,b): """This calculates the Levenshtein distance between a and b. """ n, m = len(a), len(b) if n > m: a,b = b,a n,m = m,n current = range(n+1) for i in range(1,m+1): previous, current = current, [i]+[0]*n for j in range(1,n+1): add, delete = previous[j]+1, current[j-1]+1 change = previous[j-1] if a[j-1] != b[i-1]: change = change + 1 current[j] = min(add, delete, change) return current[n] def synch_original_prompt (self): """This attempts to find the prompt. Basically, press enter and record the response; press enter again and record the response; if the two responses are similar then assume we are at the original prompt. """ # All of these timing pace values are magic. # I came up with these based on what seemed reliable for # connecting to a heavily loaded machine I have. # If latency is worse than these values then this will fail. self.read_nonblocking(size=10000,timeout=1) # GAS: Clear out the cache before getting the prompt time.sleep(0.1) self.sendline() time.sleep(0.5) x = self.read_nonblocking(size=1000,timeout=1) time.sleep(0.1) self.sendline() time.sleep(0.5) a = self.read_nonblocking(size=1000,timeout=1) time.sleep(0.1) self.sendline() time.sleep(0.5) b = self.read_nonblocking(size=1000,timeout=1) ld = self.levenshtein_distance(a,b) len_a = len(a) if len_a == 0: return False if float(ld)/len_a < 0.4: return True return False ### TODO: This is getting messy and I'm pretty sure this isn't perfect. ### TODO: I need to draw a flow chart for this. def login (self,server,username,password='',terminal_type='ansi',original_prompt=r"[#$]",login_timeout=10,port=None,auto_prompt_reset=True): """This logs the user into the given server. It uses the 'original_prompt' to try to find the prompt right after login. When it finds the prompt it immediately tries to reset the prompt to something more easily matched. The default 'original_prompt' is very optimistic and is easily fooled. It's more reliable to try to match the original prompt as exactly as possible to prevent false matches by server strings such as the "Message Of The Day". On many systems you can disable the MOTD on the remote server by creating a zero-length file called "~/.hushlogin" on the remote server. If a prompt cannot be found then this will not necessarily cause the login to fail. In the case of a timeout when looking for the prompt we assume that the original prompt was so weird that we could not match it, so we use a few tricks to guess when we have reached the prompt. Then we hope for the best and blindly try to reset the prompt to something more unique. If that fails then login() raises an ExceptionPxssh exception. In some situations it is not possible or desirable to reset the original prompt. In this case, set 'auto_prompt_reset' to False to inhibit setting the prompt to the UNIQUE_PROMPT. Remember that pxssh uses a unique prompt in the prompt() method. If the original prompt is not reset then this will disable the prompt() method unless you manually set the PROMPT attribute. """ ssh_options = '-q' if self.force_password: ssh_options = ssh_options + ' ' + self.SSH_OPTS if port is not None: ssh_options = ssh_options + ' -p %s'%(str(port)) cmd = "ssh %s -l %s %s" % (ssh_options, username, server) # This does not distinguish between a remote server 'password' prompt # and a local ssh 'passphrase' prompt (for unlocking a private key). spawn._spawn(self, cmd) i = self.expect(["(?i)are you sure you want to continue connecting", original_prompt, "(?i)(?:password)|(?:passphrase for key)", "(?i)permission denied", "(?i)terminal type", TIMEOUT, "(?i)connection closed by remote host"], timeout=login_timeout) # First phase if i==0: # New certificate -- always accept it. # This is what you get if SSH does not have the remote host's # public key stored in the 'known_hosts' cache. self.sendline("yes") i = self.expect(["(?i)are you sure you want to continue connecting", original_prompt, "(?i)(?:password)|(?:passphrase for key)", "(?i)permission denied", "(?i)terminal type", TIMEOUT]) if i==2: # password or passphrase self.sendline(password) i = self.expect(["(?i)are you sure you want to continue connecting", original_prompt, "(?i)(?:password)|(?:passphrase for key)", "(?i)permission denied", "(?i)terminal type", TIMEOUT]) if i==4: self.sendline(terminal_type) i = self.expect(["(?i)are you sure you want to continue connecting", original_prompt, "(?i)(?:password)|(?:passphrase for key)", "(?i)permission denied", "(?i)terminal type", TIMEOUT]) # Second phase if i==0: # This is weird. This should not happen twice in a row. self.close() raise ExceptionPxssh ('Weird error. Got "are you sure" prompt twice.') elif i==1: # can occur if you have a public key pair set to authenticate. ### TODO: May NOT be OK if expect() got tricked and matched a false prompt. pass elif i==2: # password prompt again # For incorrect passwords, some ssh servers will # ask for the password again, others return 'denied' right away. # If we get the password prompt again then this means # we didn't get the password right the first time. self.close() raise ExceptionPxssh ('password refused') elif i==3: # permission denied -- password was bad. self.close() raise ExceptionPxssh ('permission denied') elif i==4: # terminal type again? WTF? self.close() raise ExceptionPxssh ('Weird error. Got "terminal type" prompt twice.') elif i==5: # Timeout #This is tricky... I presume that we are at the command-line prompt. #It may be that the shell prompt was so weird that we couldn't match #it. Or it may be that we couldn't log in for some other reason. I #can't be sure, but it's safe to guess that we did login because if #I presume wrong and we are not logged in then this should be caught #later when I try to set the shell prompt. pass elif i==6: # Connection closed by remote host self.close() raise ExceptionPxssh ('connection closed') else: # Unexpected self.close() raise ExceptionPxssh ('unexpected login response') if not self.synch_original_prompt(): self.close() raise ExceptionPxssh ('could not synchronize with original prompt') # We appear to be in. # set shell prompt to something unique. if auto_prompt_reset: if not self.set_unique_prompt(): self.close() raise ExceptionPxssh ('could not set shell prompt\n'+self.before) return True def logout (self): """This sends exit to the remote shell. If there are stopped jobs then this automatically sends exit twice. """ self.sendline("exit") index = self.expect([EOF, "(?i)there are stopped jobs"]) if index==1: self.sendline("exit") self.expect(EOF) self.close() def prompt (self, timeout=20): """This matches the shell prompt. This is little more than a short-cut to the expect() method. This returns True if the shell prompt was matched. This returns False if there was a timeout. Note that if you called login() with auto_prompt_reset set to False then you should have manually set the PROMPT attribute to a regex pattern for matching the prompt. """ i = self.expect([self.PROMPT, TIMEOUT], timeout=timeout) if i==1: return False return True def set_unique_prompt (self): """This sets the remote prompt to something more unique than # or $. This makes it easier for the prompt() method to match the shell prompt unambiguously. This method is called automatically by the login() method, but you may want to call it manually if you somehow reset the shell prompt. For example, if you 'su' to a different user then you will need to manually reset the prompt. This sends shell commands to the remote host to set the prompt, so this assumes the remote host is ready to receive commands. Alternatively, you may use your own prompt pattern. Just set the PROMPT attribute to a regular expression that matches it. In this case you should call login() with auto_prompt_reset=False; then set the PROMPT attribute. After that the prompt() method will try to match your prompt pattern.""" self.sendline ("unset PROMPT_COMMAND") self.sendline (self.PROMPT_SET_SH) # sh-style i = self.expect ([TIMEOUT, self.PROMPT], timeout=10) if i == 0: # csh-style self.sendline (self.PROMPT_SET_CSH) i = self.expect ([TIMEOUT, self.PROMPT], timeout=10) if i == 0: return False return True # vi:ts=4:sw=4:expandtab:ft=python:
14,565
Python
.py
266
44.680451
255
0.638127
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,870
fdpexpect.py
pwnieexpress_raspberry_pwn/src/pexpect-2.3/fdpexpect.py
"""This is like pexpect, but will work on any file descriptor that you pass it. So you are reponsible for opening and close the file descriptor. $Id: fdpexpect.py 505 2007-12-26 21:33:50Z noah $ """ from pexpect import * import os __all__ = ['fdspawn'] class fdspawn (spawn): """This is like pexpect.spawn but allows you to supply your own open file descriptor. For example, you could use it to read through a file looking for patterns, or to control a modem or serial device. """ def __init__ (self, fd, args=[], timeout=30, maxread=2000, searchwindowsize=None, logfile=None): """This takes a file descriptor (an int) or an object that support the fileno() method (returning an int). All Python file-like objects support fileno(). """ ### TODO: Add better handling of trying to use fdspawn in place of spawn ### TODO: (overload to allow fdspawn to also handle commands as spawn does. if type(fd) != type(0) and hasattr(fd, 'fileno'): fd = fd.fileno() if type(fd) != type(0): raise ExceptionPexpect ('The fd argument is not an int. If this is a command string then maybe you want to use pexpect.spawn.') try: # make sure fd is a valid file descriptor os.fstat(fd) except OSError: raise ExceptionPexpect, 'The fd argument is not a valid file descriptor.' self.args = None self.command = None spawn.__init__(self, None, args, timeout, maxread, searchwindowsize, logfile) self.child_fd = fd self.own_fd = False self.closed = False self.name = '<file descriptor %d>' % fd def __del__ (self): return def close (self): if self.child_fd == -1: return if self.own_fd: self.close (self) else: self.flush() os.close(self.child_fd) self.child_fd = -1 self.closed = True def isalive (self): """This checks if the file descriptor is still valid. If os.fstat() does not raise an exception then we assume it is alive. """ if self.child_fd == -1: return False try: os.fstat(self.child_fd) return True except: return False def terminate (self, force=False): raise ExceptionPexpect ('This method is not valid for file descriptors.') def kill (self, sig): return
2,488
Python
.py
58
34.241379
139
0.618869
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,871
FSM.py
pwnieexpress_raspberry_pwn/src/pexpect-2.3/FSM.py
#!/usr/bin/env python """This module implements a Finite State Machine (FSM). In addition to state this FSM also maintains a user defined "memory". So this FSM can be used as a Push-down Automata (PDA) since a PDA is a FSM + memory. The following describes how the FSM works, but you will probably also need to see the example function to understand how the FSM is used in practice. You define an FSM by building tables of transitions. For a given input symbol the process() method uses these tables to decide what action to call and what the next state will be. The FSM has a table of transitions that associate: (input_symbol, current_state) --> (action, next_state) Where "action" is a function you define. The symbols and states can be any objects. You use the add_transition() and add_transition_list() methods to add to the transition table. The FSM also has a table of transitions that associate: (current_state) --> (action, next_state) You use the add_transition_any() method to add to this transition table. The FSM also has one default transition that is not associated with any specific input_symbol or state. You use the set_default_transition() method to set the default transition. When an action function is called it is passed a reference to the FSM. The action function may then access attributes of the FSM such as input_symbol, current_state, or "memory". The "memory" attribute can be any object that you want to pass along to the action functions. It is not used by the FSM itself. For parsing you would typically pass a list to be used as a stack. The processing sequence is as follows. The process() method is given an input_symbol to process. The FSM will search the table of transitions that associate: (input_symbol, current_state) --> (action, next_state) If the pair (input_symbol, current_state) is found then process() will call the associated action function and then set the current state to the next_state. If the FSM cannot find a match for (input_symbol, current_state) it will then search the table of transitions that associate: (current_state) --> (action, next_state) If the current_state is found then the process() method will call the associated action function and then set the current state to the next_state. Notice that this table lacks an input_symbol. It lets you define transitions for a current_state and ANY input_symbol. Hence, it is called the "any" table. Remember, it is always checked after first searching the table for a specific (input_symbol, current_state). For the case where the FSM did not match either of the previous two cases the FSM will try to use the default transition. If the default transition is defined then the process() method will call the associated action function and then set the current state to the next_state. This lets you define a default transition as a catch-all case. You can think of it as an exception handler. There can be only one default transition. Finally, if none of the previous cases are defined for an input_symbol and current_state then the FSM will raise an exception. This may be desirable, but you can always prevent this just by defining a default transition. Noah Spurrier 20020822 """ class ExceptionFSM(Exception): """This is the FSM Exception class.""" def __init__(self, value): self.value = value def __str__(self): return `self.value` class FSM: """This is a Finite State Machine (FSM). """ def __init__(self, initial_state, memory=None): """This creates the FSM. You set the initial state here. The "memory" attribute is any object that you want to pass along to the action functions. It is not used by the FSM. For parsing you would typically pass a list to be used as a stack. """ # Map (input_symbol, current_state) --> (action, next_state). self.state_transitions = {} # Map (current_state) --> (action, next_state). self.state_transitions_any = {} self.default_transition = None self.input_symbol = None self.initial_state = initial_state self.current_state = self.initial_state self.next_state = None self.action = None self.memory = memory def reset (self): """This sets the current_state to the initial_state and sets input_symbol to None. The initial state was set by the constructor __init__(). """ self.current_state = self.initial_state self.input_symbol = None def add_transition (self, input_symbol, state, action=None, next_state=None): """This adds a transition that associates: (input_symbol, current_state) --> (action, next_state) The action may be set to None in which case the process() method will ignore the action and only set the next_state. The next_state may be set to None in which case the current state will be unchanged. You can also set transitions for a list of symbols by using add_transition_list(). """ if next_state is None: next_state = state self.state_transitions[(input_symbol, state)] = (action, next_state) def add_transition_list (self, list_input_symbols, state, action=None, next_state=None): """This adds the same transition for a list of input symbols. You can pass a list or a string. Note that it is handy to use string.digits, string.whitespace, string.letters, etc. to add transitions that match character classes. The action may be set to None in which case the process() method will ignore the action and only set the next_state. The next_state may be set to None in which case the current state will be unchanged. """ if next_state is None: next_state = state for input_symbol in list_input_symbols: self.add_transition (input_symbol, state, action, next_state) def add_transition_any (self, state, action=None, next_state=None): """This adds a transition that associates: (current_state) --> (action, next_state) That is, any input symbol will match the current state. The process() method checks the "any" state associations after it first checks for an exact match of (input_symbol, current_state). The action may be set to None in which case the process() method will ignore the action and only set the next_state. The next_state may be set to None in which case the current state will be unchanged. """ if next_state is None: next_state = state self.state_transitions_any [state] = (action, next_state) def set_default_transition (self, action, next_state): """This sets the default transition. This defines an action and next_state if the FSM cannot find the input symbol and the current state in the transition list and if the FSM cannot find the current_state in the transition_any list. This is useful as a final fall-through state for catching errors and undefined states. The default transition can be removed by setting the attribute default_transition to None. """ self.default_transition = (action, next_state) def get_transition (self, input_symbol, state): """This returns (action, next state) given an input_symbol and state. This does not modify the FSM state, so calling this method has no side effects. Normally you do not call this method directly. It is called by process(). The sequence of steps to check for a defined transition goes from the most specific to the least specific. 1. Check state_transitions[] that match exactly the tuple, (input_symbol, state) 2. Check state_transitions_any[] that match (state) In other words, match a specific state and ANY input_symbol. 3. Check if the default_transition is defined. This catches any input_symbol and any state. This is a handler for errors, undefined states, or defaults. 4. No transition was defined. If we get here then raise an exception. """ if self.state_transitions.has_key((input_symbol, state)): return self.state_transitions[(input_symbol, state)] elif self.state_transitions_any.has_key (state): return self.state_transitions_any[state] elif self.default_transition is not None: return self.default_transition else: raise ExceptionFSM ('Transition is undefined: (%s, %s).' % (str(input_symbol), str(state)) ) def process (self, input_symbol): """This is the main method that you call to process input. This may cause the FSM to change state and call an action. This method calls get_transition() to find the action and next_state associated with the input_symbol and current_state. If the action is None then the action is not called and only the current state is changed. This method processes one complete input symbol. You can process a list of symbols (or a string) by calling process_list(). """ self.input_symbol = input_symbol (self.action, self.next_state) = self.get_transition (self.input_symbol, self.current_state) if self.action is not None: self.action (self) self.current_state = self.next_state self.next_state = None def process_list (self, input_symbols): """This takes a list and sends each element to process(). The list may be a string or any iterable object. """ for s in input_symbols: self.process (s) ############################################################################## # The following is an example that demonstrates the use of the FSM class to # process an RPN expression. Run this module from the command line. You will # get a prompt > for input. Enter an RPN Expression. Numbers may be integers. # Operators are * / + - Use the = sign to evaluate and print the expression. # For example: # # 167 3 2 2 * * * 1 - = # # will print: # # 2003 ############################################################################## import sys, os, traceback, optparse, time, string # # These define the actions. # Note that "memory" is a list being used as a stack. # def BeginBuildNumber (fsm): fsm.memory.append (fsm.input_symbol) def BuildNumber (fsm): s = fsm.memory.pop () s = s + fsm.input_symbol fsm.memory.append (s) def EndBuildNumber (fsm): s = fsm.memory.pop () fsm.memory.append (int(s)) def DoOperator (fsm): ar = fsm.memory.pop() al = fsm.memory.pop() if fsm.input_symbol == '+': fsm.memory.append (al + ar) elif fsm.input_symbol == '-': fsm.memory.append (al - ar) elif fsm.input_symbol == '*': fsm.memory.append (al * ar) elif fsm.input_symbol == '/': fsm.memory.append (al / ar) def DoEqual (fsm): print str(fsm.memory.pop()) def Error (fsm): print 'That does not compute.' print str(fsm.input_symbol) def main(): """This is where the example starts and the FSM state transitions are defined. Note that states are strings (such as 'INIT'). This is not necessary, but it makes the example easier to read. """ f = FSM ('INIT', []) # "memory" will be used as a stack. f.set_default_transition (Error, 'INIT') f.add_transition_any ('INIT', None, 'INIT') f.add_transition ('=', 'INIT', DoEqual, 'INIT') f.add_transition_list (string.digits, 'INIT', BeginBuildNumber, 'BUILDING_NUMBER') f.add_transition_list (string.digits, 'BUILDING_NUMBER', BuildNumber, 'BUILDING_NUMBER') f.add_transition_list (string.whitespace, 'BUILDING_NUMBER', EndBuildNumber, 'INIT') f.add_transition_list ('+-*/', 'INIT', DoOperator, 'INIT') print print 'Enter an RPN Expression.' print 'Numbers may be integers. Operators are * / + -' print 'Use the = sign to evaluate and print the expression.' print 'For example: ' print ' 167 3 2 2 * * * 1 - =' inputstr = raw_input ('> ') f.process_list(inputstr) if __name__ == '__main__': try: start_time = time.time() parser = optparse.OptionParser(formatter=optparse.TitledHelpFormatter(), usage=globals()['__doc__'], version='$Id: FSM.py 490 2007-12-07 15:46:24Z noah $') parser.add_option ('-v', '--verbose', action='store_true', default=False, help='verbose output') (options, args) = parser.parse_args() if options.verbose: print time.asctime() main() if options.verbose: print time.asctime() if options.verbose: print 'TOTAL TIME IN MINUTES:', if options.verbose: print (time.time() - start_time) / 60.0 sys.exit(0) except KeyboardInterrupt, e: # Ctrl-C raise e except SystemExit, e: # sys.exit() raise e except Exception, e: print 'ERROR, UNEXPECTED EXCEPTION' print str(e) traceback.print_exc() os._exit(1)
13,318
Python
.py
253
46.16996
163
0.675445
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,872
ANSI.py
pwnieexpress_raspberry_pwn/src/pexpect-2.3/ANSI.py
"""This implements an ANSI terminal emulator as a subclass of screen. $Id: ANSI.py 491 2007-12-16 20:04:57Z noah $ """ # references: # http://www.retards.org/terminals/vt102.html # http://vt100.net/docs/vt102-ug/contents.html # http://vt100.net/docs/vt220-rm/ # http://www.termsys.demon.co.uk/vtansi.htm import screen import FSM import copy import string def Emit (fsm): screen = fsm.memory[0] screen.write_ch(fsm.input_symbol) def StartNumber (fsm): fsm.memory.append (fsm.input_symbol) def BuildNumber (fsm): ns = fsm.memory.pop() ns = ns + fsm.input_symbol fsm.memory.append (ns) def DoBackOne (fsm): screen = fsm.memory[0] screen.cursor_back () def DoBack (fsm): count = int(fsm.memory.pop()) screen = fsm.memory[0] screen.cursor_back (count) def DoDownOne (fsm): screen = fsm.memory[0] screen.cursor_down () def DoDown (fsm): count = int(fsm.memory.pop()) screen = fsm.memory[0] screen.cursor_down (count) def DoForwardOne (fsm): screen = fsm.memory[0] screen.cursor_forward () def DoForward (fsm): count = int(fsm.memory.pop()) screen = fsm.memory[0] screen.cursor_forward (count) def DoUpReverse (fsm): screen = fsm.memory[0] screen.cursor_up_reverse() def DoUpOne (fsm): screen = fsm.memory[0] screen.cursor_up () def DoUp (fsm): count = int(fsm.memory.pop()) screen = fsm.memory[0] screen.cursor_up (count) def DoHome (fsm): c = int(fsm.memory.pop()) r = int(fsm.memory.pop()) screen = fsm.memory[0] screen.cursor_home (r,c) def DoHomeOrigin (fsm): c = 1 r = 1 screen = fsm.memory[0] screen.cursor_home (r,c) def DoEraseDown (fsm): screen = fsm.memory[0] screen.erase_down() def DoErase (fsm): arg = int(fsm.memory.pop()) screen = fsm.memory[0] if arg == 0: screen.erase_down() elif arg == 1: screen.erase_up() elif arg == 2: screen.erase_screen() def DoEraseEndOfLine (fsm): screen = fsm.memory[0] screen.erase_end_of_line() def DoEraseLine (fsm): screen = fsm.memory[0] if arg == 0: screen.end_of_line() elif arg == 1: screen.start_of_line() elif arg == 2: screen.erase_line() def DoEnableScroll (fsm): screen = fsm.memory[0] screen.scroll_screen() def DoCursorSave (fsm): screen = fsm.memory[0] screen.cursor_save_attrs() def DoCursorRestore (fsm): screen = fsm.memory[0] screen.cursor_restore_attrs() def DoScrollRegion (fsm): screen = fsm.memory[0] r2 = int(fsm.memory.pop()) r1 = int(fsm.memory.pop()) screen.scroll_screen_rows (r1,r2) def DoMode (fsm): screen = fsm.memory[0] mode = fsm.memory.pop() # Should be 4 # screen.setReplaceMode () def Log (fsm): screen = fsm.memory[0] fsm.memory = [screen] fout = open ('log', 'a') fout.write (fsm.input_symbol + ',' + fsm.current_state + '\n') fout.close() class term (screen.screen): """This is a placeholder. In theory I might want to add other terminal types. """ def __init__ (self, r=24, c=80): screen.screen.__init__(self, r,c) class ANSI (term): """This class encapsulates a generic terminal. It filters a stream and maintains the state of a screen object. """ def __init__ (self, r=24,c=80): term.__init__(self,r,c) #self.screen = screen (24,80) self.state = FSM.FSM ('INIT',[self]) self.state.set_default_transition (Log, 'INIT') self.state.add_transition_any ('INIT', Emit, 'INIT') self.state.add_transition ('\x1b', 'INIT', None, 'ESC') self.state.add_transition_any ('ESC', Log, 'INIT') self.state.add_transition ('(', 'ESC', None, 'G0SCS') self.state.add_transition (')', 'ESC', None, 'G1SCS') self.state.add_transition_list ('AB012', 'G0SCS', None, 'INIT') self.state.add_transition_list ('AB012', 'G1SCS', None, 'INIT') self.state.add_transition ('7', 'ESC', DoCursorSave, 'INIT') self.state.add_transition ('8', 'ESC', DoCursorRestore, 'INIT') self.state.add_transition ('M', 'ESC', DoUpReverse, 'INIT') self.state.add_transition ('>', 'ESC', DoUpReverse, 'INIT') self.state.add_transition ('<', 'ESC', DoUpReverse, 'INIT') self.state.add_transition ('=', 'ESC', None, 'INIT') # Selects application keypad. self.state.add_transition ('#', 'ESC', None, 'GRAPHICS_POUND') self.state.add_transition_any ('GRAPHICS_POUND', None, 'INIT') self.state.add_transition ('[', 'ESC', None, 'ELB') # ELB means Escape Left Bracket. That is ^[[ self.state.add_transition ('H', 'ELB', DoHomeOrigin, 'INIT') self.state.add_transition ('D', 'ELB', DoBackOne, 'INIT') self.state.add_transition ('B', 'ELB', DoDownOne, 'INIT') self.state.add_transition ('C', 'ELB', DoForwardOne, 'INIT') self.state.add_transition ('A', 'ELB', DoUpOne, 'INIT') self.state.add_transition ('J', 'ELB', DoEraseDown, 'INIT') self.state.add_transition ('K', 'ELB', DoEraseEndOfLine, 'INIT') self.state.add_transition ('r', 'ELB', DoEnableScroll, 'INIT') self.state.add_transition ('m', 'ELB', None, 'INIT') self.state.add_transition ('?', 'ELB', None, 'MODECRAP') self.state.add_transition_list (string.digits, 'ELB', StartNumber, 'NUMBER_1') self.state.add_transition_list (string.digits, 'NUMBER_1', BuildNumber, 'NUMBER_1') self.state.add_transition ('D', 'NUMBER_1', DoBack, 'INIT') self.state.add_transition ('B', 'NUMBER_1', DoDown, 'INIT') self.state.add_transition ('C', 'NUMBER_1', DoForward, 'INIT') self.state.add_transition ('A', 'NUMBER_1', DoUp, 'INIT') self.state.add_transition ('J', 'NUMBER_1', DoErase, 'INIT') self.state.add_transition ('K', 'NUMBER_1', DoEraseLine, 'INIT') self.state.add_transition ('l', 'NUMBER_1', DoMode, 'INIT') ### It gets worse... the 'm' code can have infinite number of ### number;number;number before it. I've never seen more than two, ### but the specs say it's allowed. crap! self.state.add_transition ('m', 'NUMBER_1', None, 'INIT') ### LED control. Same problem as 'm' code. self.state.add_transition ('q', 'NUMBER_1', None, 'INIT') # \E[?47h appears to be "switch to alternate screen" # \E[?47l restores alternate screen... I think. self.state.add_transition_list (string.digits, 'MODECRAP', StartNumber, 'MODECRAP_NUM') self.state.add_transition_list (string.digits, 'MODECRAP_NUM', BuildNumber, 'MODECRAP_NUM') self.state.add_transition ('l', 'MODECRAP_NUM', None, 'INIT') self.state.add_transition ('h', 'MODECRAP_NUM', None, 'INIT') #RM Reset Mode Esc [ Ps l none self.state.add_transition (';', 'NUMBER_1', None, 'SEMICOLON') self.state.add_transition_any ('SEMICOLON', Log, 'INIT') self.state.add_transition_list (string.digits, 'SEMICOLON', StartNumber, 'NUMBER_2') self.state.add_transition_list (string.digits, 'NUMBER_2', BuildNumber, 'NUMBER_2') self.state.add_transition_any ('NUMBER_2', Log, 'INIT') self.state.add_transition ('H', 'NUMBER_2', DoHome, 'INIT') self.state.add_transition ('f', 'NUMBER_2', DoHome, 'INIT') self.state.add_transition ('r', 'NUMBER_2', DoScrollRegion, 'INIT') ### It gets worse... the 'm' code can have infinite number of ### number;number;number before it. I've never seen more than two, ### but the specs say it's allowed. crap! self.state.add_transition ('m', 'NUMBER_2', None, 'INIT') ### LED control. Same problem as 'm' code. self.state.add_transition ('q', 'NUMBER_2', None, 'INIT') def process (self, c): self.state.process(c) def process_list (self, l): self.write(l) def write (self, s): for c in s: self.process(c) def flush (self): pass def write_ch (self, ch): """This puts a character at the current cursor position. cursor position if moved forward with wrap-around, but no scrolling is done if the cursor hits the lower-right corner of the screen. """ #\r and \n both produce a call to crlf(). ch = ch[0] if ch == '\r': # self.crlf() return if ch == '\n': self.crlf() return if ch == chr(screen.BS): self.cursor_back() self.put_abs(self.cur_r, self.cur_c, ' ') return if ch not in string.printable: fout = open ('log', 'a') fout.write ('Nonprint: ' + str(ord(ch)) + '\n') fout.close() return self.put_abs(self.cur_r, self.cur_c, ch) old_r = self.cur_r old_c = self.cur_c self.cursor_forward() if old_c == self.cur_c: self.cursor_down() if old_r != self.cur_r: self.cursor_home (self.cur_r, 1) else: self.scroll_up () self.cursor_home (self.cur_r, 1) self.erase_line() # def test (self): # # import sys # write_text = 'I\'ve got a ferret sticking up my nose.\n' + \ # '(He\'s got a ferret sticking up his nose.)\n' + \ # 'How it got there I can\'t tell\n' + \ # 'But now it\'s there it hurts like hell\n' + \ # 'And what is more it radically affects my sense of smell.\n' + \ # '(His sense of smell.)\n' + \ # 'I can see a bare-bottomed mandril.\n' + \ # '(Slyly eyeing his other nostril.)\n' + \ # 'If it jumps inside there too I really don\'t know what to do\n' + \ # 'I\'ll be the proud posessor of a kind of nasal zoo.\n' + \ # '(A nasal zoo.)\n' + \ # 'I\'ve got a ferret sticking up my nose.\n' + \ # '(And what is worst of all it constantly explodes.)\n' + \ # '"Ferrets don\'t explode," you say\n' + \ # 'But it happened nine times yesterday\n' + \ # 'And I should know for each time I was standing in the way.\n' + \ # 'I\'ve got a ferret sticking up my nose.\n' + \ # '(He\'s got a ferret sticking up his nose.)\n' + \ # 'How it got there I can\'t tell\n' + \ # 'But now it\'s there it hurts like hell\n' + \ # 'And what is more it radically affects my sense of smell.\n' + \ # '(His sense of smell.)' # self.fill('.') # self.cursor_home() # for c in write_text: # self.write_ch (c) # print str(self) # #if __name__ == '__main__': # t = ANSI(6,65) # t.test()
10,842
Python
.py
262
35.164122
99
0.596381
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,873
chess.py
pwnieexpress_raspberry_pwn/src/pexpect-2.3/examples/chess.py
#!/usr/bin/env python '''This demonstrates controlling a screen oriented application (curses). It starts two instances of gnuchess and then pits them against each other. ''' import pexpect import string import ANSI REGEX_MOVE = '(?:[a-z]|\x1b\[C)(?:[0-9]|\x1b\[C)(?:[a-z]|\x1b\[C)(?:[0-9]|\x1b\[C)' REGEX_MOVE_PART = '(?:[0-9]|\x1b\[C)(?:[a-z]|\x1b\[C)(?:[0-9]|\x1b\[C)' class Chess: def __init__(self, engine = "/usr/local/bin/gnuchess -a -h 1"): self.child = pexpect.spawn (engine) self.term = ANSI.ANSI () self.child.expect ('Chess') if self.child.after != 'Chess': raise IOError, 'incompatible chess program' self.term.process_list (self.before) self.term.process_list (self.after) self.last_computer_move = '' def read_until_cursor (self, r,c) while 1: self.child.read(1, 60) self.term.process (c) if self.term.cur_r == r and self.term.cur_c == c: return 1 def do_first_move (self, move): self.child.expect ('Your move is') self.child.sendline (move) self.term.process_list (self.before) self.term.process_list (self.after) return move def do_move (self, move): read_until_cursor (19,60) #self.child.expect ('\[19;60H') self.child.sendline (move) print 'do_move' move return move def get_first_computer_move (self): self.child.expect ('My move is') self.child.expect (REGEX_MOVE) # print '', self.child.after return self.child.after def get_computer_move (self): print 'Here' i = self.child.expect (['\[17;59H', '\[17;58H']) print i if i == 0: self.child.expect (REGEX_MOVE) if len(self.child.after) < 4: self.child.after = self.child.after + self.last_computer_move[3] if i == 1: self.child.expect (REGEX_MOVE_PART) self.child.after = self.last_computer_move[0] + self.child.after print '', self.child.after self.last_computer_move = self.child.after return self.child.after def switch (self): self.child.sendline ('switch') def set_depth (self, depth): self.child.sendline ('depth') self.child.expect ('depth=') self.child.sendline ('%d' % depth) def quit(self): self.child.sendline ('quit') import sys, os print 'Starting...' white = Chess() white.child.echo = 1 white.child.expect ('Your move is') white.set_depth(2) white.switch() move_white = white.get_first_computer_move() print 'first move white:', move_white white.do_move ('e7e5') move_white = white.get_computer_move() print 'move white:', move_white white.do_move ('f8c5') move_white = white.get_computer_move() print 'move white:', move_white white.do_move ('b8a6') move_white = white.get_computer_move() print 'move white:', move_white sys.exit(1) black = Chess() white = Chess() white.child.expect ('Your move is') white.switch() move_white = white.get_first_computer_move() print 'first move white:', move_white black.do_first_move (move_white) move_black = black.get_first_computer_move() print 'first move black:', move_black white.do_move (move_black) done = 0 while not done: move_white = white.get_computer_move() print 'move white:', move_white black.do_move (move_white) move_black = black.get_computer_move() print 'move black:', move_black white.do_move (move_black) print 'tail of loop' g.quit()
3,417
Python
.py
103
28.893204
83
0.665341
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,874
python.py
pwnieexpress_raspberry_pwn/src/pexpect-2.3/examples/python.py
#!/usr/bin/env python """This starts the python interpreter; captures the startup message; then gives the user interactive control over the session. Why? For fun... """ # Don't do this unless you like being John Malkovich # c = pexpect.spawn ('/usr/bin/env python ./python.py') import pexpect c = pexpect.spawn ('/usr/bin/env python') c.expect ('>>>') print 'And now for something completely different...' f = lambda s:s and f(s[1:])+s[0] # Makes a function to reverse a string. print f(c.before) print 'Yes, it\'s python, but it\'s backwards.' print print 'Escape character is \'^]\'.' print c.after, c.interact() c.kill(1) print 'is alive:', c.isalive()
660
Python
.py
18
35.444444
79
0.719436
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,875
uptime.py
pwnieexpress_raspberry_pwn/src/pexpect-2.3/examples/uptime.py
#!/usr/bin/env python """This displays uptime information using uptime. This is redundant, but it demonstrates expecting for a regular expression that uses subgroups. $Id: uptime.py 489 2007-11-28 23:40:34Z noah $ """ import pexpect import re # There are many different styles of uptime results. I try to parse them all. Yeee! # Examples from different machines: # [x86] Linux 2.4 (Redhat 7.3) # 2:06pm up 63 days, 18 min, 3 users, load average: 0.32, 0.08, 0.02 # [x86] Linux 2.4.18-14 (Redhat 8.0) # 3:07pm up 29 min, 1 user, load average: 2.44, 2.51, 1.57 # [PPC - G4] MacOS X 10.1 SERVER Edition # 2:11PM up 3 days, 13:50, 3 users, load averages: 0.01, 0.00, 0.00 # [powerpc] Darwin v1-58.corefa.com 8.2.0 Darwin Kernel Version 8.2.0 # 10:35 up 18:06, 4 users, load averages: 0.52 0.47 0.36 # [Sparc - R220] Sun Solaris (8) # 2:13pm up 22 min(s), 1 user, load average: 0.02, 0.01, 0.01 # [x86] Linux 2.4.18-14 (Redhat 8) # 11:36pm up 4 days, 17:58, 1 user, load average: 0.03, 0.01, 0.00 # AIX jwdir 2 5 0001DBFA4C00 # 09:43AM up 23:27, 1 user, load average: 0.49, 0.32, 0.23 # OpenBSD box3 2.9 GENERIC#653 i386 # 6:08PM up 4 days, 22:26, 1 user, load averages: 0.13, 0.09, 0.08 # This parses uptime output into the major groups using regex group matching. p = pexpect.spawn ('uptime') p.expect('up\s+(.*?),\s+([0-9]+) users?,\s+load averages?: ([0-9]+\.[0-9][0-9]),?\s+([0-9]+\.[0-9][0-9]),?\s+([0-9]+\.[0-9][0-9])') duration, users, av1, av5, av15 = p.match.groups() # The duration is a little harder to parse because of all the different # styles of uptime. I'm sure there is a way to do this all at once with # one single regex, but I bet it would be hard to read and maintain. # If anyone wants to send me a version using a single regex I'd be happy to see it. days = '0' hours = '0' mins = '0' if 'day' in duration: p.match = re.search('([0-9]+)\s+day',duration) days = str(int(p.match.group(1))) if ':' in duration: p.match = re.search('([0-9]+):([0-9]+)',duration) hours = str(int(p.match.group(1))) mins = str(int(p.match.group(2))) if 'min' in duration: p.match = re.search('([0-9]+)\s+min',duration) mins = str(int(p.match.group(1))) # Print the parsed fields in CSV format. print 'days, hours, minutes, users, cpu avg 1 min, cpu avg 5 min, cpu avg 15 min' print '%s, %s, %s, %s, %s, %s, %s' % (days, hours, mins, users, av1, av5, av15)
2,413
Python
.py
49
47.510204
131
0.660017
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,876
bd_client.py
pwnieexpress_raspberry_pwn/src/pexpect-2.3/examples/bd_client.py
#!/usr/bin/env python """This is a very simple client for the backdoor daemon. This is intended more for testing rather than normal use. See bd_serv.py """ import socket import sys, time, select def recv_wrapper(s): r,w,e = select.select([s.fileno()],[],[], 2) if not r: return '' #cols = int(s.recv(4)) #rows = int(s.recv(4)) cols = 80 rows = 24 packet_size = cols * rows * 2 # double it for good measure return s.recv(packet_size) #HOST = '' #'localhost' # The remote host #PORT = 1664 # The same port as used by the server s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) s.connect(sys.argv[1])#(HOST, PORT)) time.sleep(1) #s.setblocking(0) #s.send('COMMAND' + '\x01' + sys.argv[1]) s.send(':sendline ' + sys.argv[2]) print recv_wrapper(s) s.close() sys.exit() #while True: # data = recv_wrapper(s) # if data == '': # break # sys.stdout.write (data) # sys.stdout.flush() #s.close()
957
Python
.py
33
26.636364
78
0.647443
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,877
fix_cvs_files.py
pwnieexpress_raspberry_pwn/src/pexpect-2.3/examples/fix_cvs_files.py
#!/usr/bin/env python """This is for cleaning up binary files improperly added to CVS. This script scans the given path to find binary files; checks with CVS to see if the sticky options are set to -kb; finally if sticky options are not -kb then uses 'cvs admin' to set the -kb option. This script ignores CVS directories, symbolic links, and files not known under CVS control (cvs status is 'Unknown'). Run this on a CHECKED OUT module sandbox, not on the repository itself. After if fixes the sticky options on any files you should manually do a 'cvs commit' to accept the changes. Then be sure to have all users do a 'cvs up -A' to update the Sticky Option status. Noah Spurrier 20030426 """ import os, sys, time import pexpect VERBOSE = 1 def is_binary (filename): """Assume that any file with a character where the 8th bit is set is binary. """ fin = open(filename, 'rb') wholething = fin.read() fin.close() for c in wholething: if ord(c) & 0x80: return 1 return 0 def is_kb_sticky (filename): """This checks if 'cvs status' reports '-kb' for Sticky options. If the Sticky Option status is '-ks' then this returns 1. If the status is 'Unknown' then it returns 1. Otherwise 0 is returned. """ try: s = pexpect.spawn ('cvs status %s' % filename) i = s.expect (['Sticky Options:\s*(.*)\r\n', 'Status: Unknown']) if i==1 and VERBOSE: print 'File not part of CVS repository:', filename return 1 # Pretend it's OK. if s.match.group(1) == '-kb': return 1 s = None except: print 'Something went wrong trying to run external cvs command.' print ' cvs status %s' % filename print 'The cvs command returned:' print s.before return 0 def cvs_admin_kb (filename): """This uses 'cvs admin' to set the '-kb' sticky option. """ s = pexpect.run ('cvs admin -kb %s' % filename) # There is a timing issue. If I run 'cvs admin' too quickly # cvs sometimes has trouble obtaining the directory lock. time.sleep(1) def walk_and_clean_cvs_binaries (arg, dirname, names): """This contains the logic for processing files. This is the os.path.walk callback. This skips dirnames that end in CVS. """ if len(dirname)>3 and dirname[-3:]=='CVS': return for n in names: fullpath = os.path.join (dirname, n) if os.path.isdir(fullpath) or os.path.islink(fullpath): continue if is_binary(fullpath): if not is_kb_sticky (fullpath): if VERBOSE: print fullpath cvs_admin_kb (fullpath) def main (): if len(sys.argv) == 1: root = '.' else: root = sys.argv[1] os.path.walk (root, walk_and_clean_cvs_binaries, None) if __name__ == '__main__': main ()
2,649
Python
.py
73
33.493151
79
0.709362
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,878
bd_serv.py
pwnieexpress_raspberry_pwn/src/pexpect-2.3/examples/bd_serv.py
#!/usr/bin/env python """Back door shell server This exposes an shell terminal on a socket. --hostname : sets the remote host name to open an ssh connection to. --username : sets the user name to login with --password : (optional) sets the password to login with --port : set the local port for the server to listen on --watch : show the virtual screen after each client request """ # Having the password on the command line is not a good idea, but # then this entire project is probably not the most security concious thing # I've ever built. This should be considered an experimental tool -- at best. import pxssh, pexpect, ANSI import time, sys, os, getopt, getpass, traceback, threading, socket def exit_with_usage(exit_code=1): print globals()['__doc__'] os._exit(exit_code) class roller (threading.Thread): """This runs a function in a loop in a thread.""" def __init__(self, interval, function, args=[], kwargs={}): """The interval parameter defines time between each call to the function. """ threading.Thread.__init__(self) self.interval = interval self.function = function self.args = args self.kwargs = kwargs self.finished = threading.Event() def cancel(self): """Stop the roller.""" self.finished.set() def run(self): while not self.finished.isSet(): # self.finished.wait(self.interval) self.function(*self.args, **self.kwargs) def endless_poll (child, prompt, screen, refresh_timeout=0.1): """This keeps the screen updated with the output of the child. This runs in a separate thread. See roller(). """ #child.logfile_read = screen try: s = child.read_nonblocking(4000, 0.1) screen.write(s) except: pass #while True: # #child.prompt (timeout=refresh_timeout) # try: # #child.read_nonblocking(1,timeout=refresh_timeout) # child.read_nonblocking(4000, 0.1) # except: # pass def daemonize (stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'): '''This forks the current process into a daemon. Almost none of this is necessary (or advisable) if your daemon is being started by inetd. In that case, stdin, stdout and stderr are all set up for you to refer to the network connection, and the fork()s and session manipulation should not be done (to avoid confusing inetd). Only the chdir() and umask() steps remain as useful. References: UNIX Programming FAQ 1.7 How do I get my program to act like a daemon? http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16 Advanced Programming in the Unix Environment W. Richard Stevens, 1992, Addison-Wesley, ISBN 0-201-56317-7. The stdin, stdout, and stderr arguments are file names that will be opened and be used to replace the standard file descriptors in sys.stdin, sys.stdout, and sys.stderr. These arguments are optional and default to /dev/null. Note that stderr is opened unbuffered, so if it shares a file with stdout then interleaved output may not appear in the order that you expect. ''' # Do first fork. try: pid = os.fork() if pid > 0: sys.exit(0) # Exit first parent. except OSError, e: sys.stderr.write ("fork #1 failed: (%d) %s\n" % (e.errno, e.strerror) ) sys.exit(1) # Decouple from parent environment. os.chdir("/") os.umask(0) os.setsid() # Do second fork. try: pid = os.fork() if pid > 0: sys.exit(0) # Exit second parent. except OSError, e: sys.stderr.write ("fork #2 failed: (%d) %s\n" % (e.errno, e.strerror) ) sys.exit(1) # Now I am a daemon! # Redirect standard file descriptors. si = open(stdin, 'r') so = open(stdout, 'a+') se = open(stderr, 'a+', 0) os.dup2(si.fileno(), sys.stdin.fileno()) os.dup2(so.fileno(), sys.stdout.fileno()) os.dup2(se.fileno(), sys.stderr.fileno()) # I now return as the daemon return 0 def add_cursor_blink (response, row, col): i = (row-1) * 80 + col return response[:i]+'<img src="http://www.noah.org/cursor.gif">'+response[i:] def main (): try: optlist, args = getopt.getopt(sys.argv[1:], 'h?d', ['help','h','?', 'hostname=', 'username=', 'password=', 'port=', 'watch']) except Exception, e: print str(e) exit_with_usage() command_line_options = dict(optlist) options = dict(optlist) # There are a million ways to cry for help. These are but a few of them. if [elem for elem in command_line_options if elem in ['-h','--h','-?','--?','--help']]: exit_with_usage(0) hostname = "127.0.0.1" port = 1664 username = os.getenv('USER') password = "" daemon_mode = False if '-d' in options: daemon_mode = True if '--watch' in options: watch_mode = True else: watch_mode = False if '--hostname' in options: hostname = options['--hostname'] if '--port' in options: port = int(options['--port']) if '--username' in options: username = options['--username'] print "Login for %s@%s:%s" % (username, hostname, port) if '--password' in options: password = options['--password'] else: password = getpass.getpass('password: ') if daemon_mode: print "daemonizing server" daemonize() #daemonize('/dev/null','/tmp/daemon.log','/tmp/daemon.log') sys.stdout.write ('server started with pid %d\n' % os.getpid() ) virtual_screen = ANSI.ANSI (24,80) child = pxssh.pxssh() child.login (hostname, username, password) print 'created shell. command line prompt is', child.PROMPT #child.sendline ('stty -echo') #child.setecho(False) virtual_screen.write (child.before) virtual_screen.write (child.after) if os.path.exists("/tmp/mysock"): os.remove("/tmp/mysock") s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) localhost = '127.0.0.1' s.bind('/tmp/mysock') os.chmod('/tmp/mysock',0777) print 'Listen' s.listen(1) print 'Accept' #s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #localhost = '127.0.0.1' #s.bind((localhost, port)) #print 'Listen' #s.listen(1) r = roller (0.01, endless_poll, (child, child.PROMPT, virtual_screen)) r.start() print "screen poll updater started in background thread" sys.stdout.flush() try: while True: conn, addr = s.accept() print 'Connected by', addr data = conn.recv(1024) if data[0]!=':': cmd = ':sendline' arg = data.strip() else: request = data.split(' ', 1) if len(request)>1: cmd = request[0].strip() arg = request[1].strip() else: cmd = request[0].strip() if cmd == ':exit': r.cancel() break elif cmd == ':sendline': child.sendline (arg) #child.prompt(timeout=2) time.sleep(0.2) shell_window = str(virtual_screen) elif cmd == ':send' or cmd==':xsend': if cmd==':xsend': arg = arg.decode("hex") child.send (arg) time.sleep(0.2) shell_window = str(virtual_screen) elif cmd == ':cursor': shell_window = '%x%x' % (virtual_screen.cur_r, virtual_screen.cur_c) elif cmd == ':refresh': shell_window = str(virtual_screen) response = [] response.append (shell_window) #response = add_cursor_blink (response, row, col) sent = conn.send('\n'.join(response)) if watch_mode: print '\n'.join(response) if sent < len (response): print "Sent is too short. Some data was cut off." conn.close() finally: r.cancel() print "cleaning up socket" s.close() if os.path.exists("/tmp/mysock"): os.remove("/tmp/mysock") print "done!" def pretty_box (rows, cols, s): """This puts an ASCII text box around the given string, s. """ top_bot = '+' + '-'*cols + '+\n' return top_bot + '\n'.join(['|'+line+'|' for line in s.split('\n')]) + '\n' + top_bot def error_response (msg): response = [] response.append ("""All commands start with : :{REQUEST} {ARGUMENT} {REQUEST} may be one of the following: :sendline: Run the ARGUMENT followed by a line feed. :send : send the characters in the ARGUMENT without a line feed. :refresh : Use to catch up the screen with the shell if state gets out of sync. Example: :sendline ls -l You may also leave off :command and it will be assumed. Example: ls -l is equivalent to: :sendline ls -l """) response.append (msg) return '\n'.join(response) def parse_host_connect_string (hcs): """This parses a host connection string in the form username:password@hostname:port. All fields are options expcet hostname. A dictionary is returned with all four keys. Keys that were not included are set to empty strings ''. Note that if your password has the '@' character then you must backslash escape it. """ if '@' in hcs: p = re.compile (r'(?P<username>[^@:]*)(:?)(?P<password>.*)(?!\\)@(?P<hostname>[^:]*):?(?P<port>[0-9]*)') else: p = re.compile (r'(?P<username>)(?P<password>)(?P<hostname>[^:]*):?(?P<port>[0-9]*)') m = p.search (hcs) d = m.groupdict() d['password'] = d['password'].replace('\\@','@') return d if __name__ == "__main__": try: start_time = time.time() print time.asctime() main() print time.asctime() print "TOTAL TIME IN MINUTES:", print (time.time() - start_time) / 60.0 except Exception, e: print str(e) tb_dump = traceback.format_exc() print str(tb_dump)
10,268
Python
.py
262
31.641221
133
0.599396
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,879
rippy.py
pwnieexpress_raspberry_pwn/src/pexpect-2.3/examples/rippy.py
#!/usr/bin/env python """Rippy! This script helps to convert video from one format to another. This is useful for ripping DVD to mpeg4 video (XviD, DivX). Features: * automatic crop detection * mp3 audio compression with resampling options * automatic bitrate calculation based on desired target size * optional interlace removal, b/w video optimization, video scaling Run the script with no arguments to start with interactive prompts: rippy.py Run the script with the filename of a config to start automatic mode: rippy.py rippy.conf After Rippy is finished it saves the current configuation in a file called 'rippy.conf' in the local directoy. This can be used to rerun process using the exact same settings by passing the filename of the conf file as an argument to Rippy. Rippy will read the options from the file instead of asking you for options interactively. So if you run rippy with 'dry_run=1' then you can run the process again later using the 'rippy.conf' file. Don't forget to edit 'rippy.conf' to set 'dry_run=0'! If you run rippy with 'dry_run' and 'verbose' true then the output generated is valid command line commands. you could (in theory) cut-and-paste the commands to a shell prompt. You will need to tweak some values such as crop area and bit rate because these cannot be calculated in a dry run. This is useful if you want to get an idea of what Rippy plans to do. For all the trouble that Rippy goes through to calculate the best bitrate for a desired target video size it sometimes fails to get it right. Sometimes the final video size will differ more than you wanted from the desired size, but if you are really motivated and have a lot of time on your hands then you can run Rippy again with a manually calculated bitrate. After all compression is done the first time Rippy will recalculate the bitrate to give you the nearly exact bitrate that would have worked. You can then edit the 'rippy.conf' file; set the video_bitrate with this revised bitrate; and then run Rippy all over again. There is nothing like 4-pass video compression to get it right! Actually, this could be done in three passes since I don't need to do the second pass compression before I calculate the revised bitrate. I'm also considering an enhancement where Rippy would compress ten spread out chunks, 1-minute in length to estimate the bitrate. Free, open source, and all that good stuff. Rippy Copyright (c) 2006 Noah Spurrier Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Noah Spurrier $Id: rippy.py 498 2007-12-17 13:44:19Z noah $ """ import sys, os, re, math, stat, getopt, traceback, types, time import pexpect __version__ = '1.2' __revision__ = '$Revision: 11 $' __all__ = ['main', __version__, __revision__] GLOBAL_LOGFILE_NAME = "rippy_%d.log" % os.getpid() GLOBAL_LOGFILE = open (GLOBAL_LOGFILE_NAME, "wb") ############################################################################### # This giant section defines the prompts and defaults used in interactive mode. ############################################################################### # Python dictionaries are unordered, so # I have this list that maintains the order of the keys. prompts_key_order = ( 'verbose_flag', 'dry_run_flag', 'video_source_filename', 'video_chapter', 'video_final_filename', 'video_length', 'video_aspect_ratio', 'video_scale', 'video_encode_passes', 'video_codec', 'video_fourcc_override', 'video_bitrate', 'video_bitrate_overhead', 'video_target_size', 'video_crop_area', 'video_deinterlace_flag', 'video_gray_flag', 'subtitle_id', 'audio_id', 'audio_codec', 'audio_raw_filename', 'audio_volume_boost', 'audio_sample_rate', 'audio_bitrate', #'audio_lowpass_filter', 'delete_tmp_files_flag' ) # # The 'prompts' dictionary holds all the messages shown to the user in # interactive mode. The 'prompts' dictionary schema is defined as follows: # prompt_key : ( default value, prompt string, help string, level of difficulty (0,1,2) ) # prompts = { 'video_source_filename':("dvd://1", 'video source filename?', """This is the filename of the video that you want to convert from. It can be any file that mencoder supports. You can also choose a DVD device using the dvd://1 syntax. Title 1 is usually the main title on a DVD.""",0), 'video_chapter':("none",'video chapter?',"""This is the chapter number. Usually disks such as TV series seasons will be divided into chapters. Maybe be set to none.""",0), 'video_final_filename':("video_final.avi", "video final filename?", """This is the name of the final video.""",0), 'audio_raw_filename':("audiodump.wav", "audio raw filename?", """This is the audio raw PCM filename. This is prior to compression. Note that mplayer automatically names this audiodump.wav, so don't change this.""",1000), #'audio_compressed_filename':("audiodump.mp3","Audio compressed filename?", """This is the name of the compressed audio that will be mixed #into the final video. Normally you don't need to change this.""",2), 'video_length':("none","video length in seconds?","""This sets the length of the video in seconds. This is used to estimate the bitrate for a target video file size. Set to 'calc' to have Rippy calculate the length. Set to 'none' if you don't want rippy to estimate the bitrate -- you will have to manually specify bitrate.""",1), 'video_aspect_ratio':("calc","aspect ratio?","""This sets the aspect ratio of the video. Most DVDs are 16/9 or 4/3.""",1), 'video_scale':("none","video scale?","""This scales the video to the given output size. The default is to do no scaling. You may type in a resolution such as 320x240 or you may use presets. qntsc: 352x240 (NTSC quarter screen) qpal: 352x288 (PAL quarter screen) ntsc: 720x480 (standard NTSC) pal: 720x576 (standard PAL) sntsc: 640x480 (square pixel NTSC) spal: 768x576 (square pixel PAL)""",1), 'video_codec':("mpeg4","video codec?","""This is the video compression to use. This is passed directly to mencoder, so any format that it recognizes should work. For XviD or DivX use mpeg4. Almost all MS Windows systems support wmv2 out of the box. Some common codecs include: mjpeg, h263, h263p, h264, mpeg4, msmpeg4, wmv1, wmv2, mpeg1video, mpeg2video, huffyuv, ffv1. """,2), 'audio_codec':("mp3","audio codec?","""This is the audio compression to use. This is passed directly to mencoder, so any format that it recognizes will work. Some common codecs include: mp3, mp2, aac, pcm See mencoder manual for details.""",2), 'video_fourcc_override':("XVID","force fourcc code?","""This forces the fourcc codec to the given value. XVID is safest for Windows. The following are common fourcc values: FMP4 - This is the mencoder default. This is the "real" value. XVID - used by Xvid (safest) DX50 - MP4S - Microsoft""",2), 'video_encode_passes':("1","number of encode passes?","""This sets how many passes to use to encode the video. You can choose 1 or 2. Using two pases takes twice as long as one pass, but produces a better quality video. I found that the improvement is not that impressive.""",1), 'verbose_flag':("Y","verbose output?","""This sets verbose output. If true then all commands and arguments are printed before they are run. This is useful to see exactly how commands are run.""",1), 'dry_run_flag':("N","dry run?","""This sets 'dry run' mode. If true then commands are not run. This is useful if you want to see what would the script would do.""",1), 'video_bitrate':("calc","video bitrate?","""This sets the video bitrate. This overrides video_target_size. Set to 'calc' to automatically estimate the bitrate based on the video final target size. If you set video_length to 'none' then you will have to specify this video_bitrate.""",1), 'video_target_size':("737280000","video final target size?","""This sets the target video size that you want to end up with. This is over-ridden by video_bitrate. In other words, if you specify video_bitrate then video_target_size is ignored. Due to the unpredictable nature of VBR compression the final video size may not exactly match. The following are common CDR sizes: 180MB CDR (21 minutes) holds 193536000 bytes 550MB CDR (63 minutes) holds 580608000 bytes 650MB CDR (74 minutes) holds 681984000 bytes 700MB CDR (80 minutes) holds 737280000 bytes""",0), 'video_bitrate_overhead':("1.0","bitrate overhead factor?","""Adjust this value if you want to leave more room for other files such as subtitle files. If you specify video_bitrate then this value is ignored.""",2), 'video_crop_area':("detect","crop area?","""This sets the crop area to remove black bars from the top or sides of the video. This helps save space. Set to 'detect' to automatically detect the crop area. Set to 'none' to not crop the video. Normally you don't need to change this.""",1), 'video_deinterlace_flag':("N","is the video interlaced?","""This sets the deinterlace flag. If set then mencoder will be instructed to filter out interlace artifacts (using '-vf pp=md').""",1), 'video_gray_flag':("N","is the video black and white (gray)?","""This improves output for black and white video.""",1), 'subtitle_id':("None","Subtitle ID stream?","""This selects the subtitle stream to extract from the source video. Normally, 0 is the English subtitle stream for a DVD. Subtitles IDs with higher numbers may be other languages.""",1), 'audio_id':("128","audio ID stream?","""This selects the audio stream to extract from the source video. If your source is a VOB file (DVD) then stream IDs start at 128. Normally, 128 is the main audio track for a DVD. Tracks with higher numbers may be other language dubs or audio commentary.""",1), 'audio_sample_rate':("32000","audio sample rate (Hz) 48000, 44100, 32000, 24000, 12000","""This sets the rate at which the compressed audio will be resampled. DVD audio is 48 kHz whereas music CDs use 44.1 kHz. The higher the sample rate the more space the audio track will take. That will leave less space for video. 32 kHz is a good trade-off if you are trying to fit a video onto a CD.""",1), 'audio_bitrate':("96","audio bitrate (kbit/s) 192, 128, 96, 64?","""This sets the bitrate for MP3 audio compression. The higher the bitrate the more space the audio track will take. That will leave less space for video. Most people find music to be acceptable at 128 kBitS. 96 kBitS is a good trade-off if you are trying to fit a video onto a CD.""",1), 'audio_volume_boost':("none","volume dB boost?","""Many DVDs have very low audio volume. This sets an audio volume boost in Decibels. Values of 6 to 10 usually adjust quiet DVDs to a comfortable level.""",1), #'audio_lowpass_filter':("16","audio lowpass filter (kHz)?","""This sets the low-pass filter for the audio. #Normally this should be half of the audio sample rate. #This improves audio compression and quality. #Normally you don't need to change this.""",1), 'delete_tmp_files_flag':("N","delete temporary files when finished?","""If Y then %s, audio_raw_filename, and 'divx2pass.log' will be deleted at the end."""%GLOBAL_LOGFILE_NAME,1) } ############################################################################## # This is the important convert control function ############################################################################## def convert (options): """This is the heart of it all -- this performs an end-to-end conversion of a video from one format to another. It requires a dictionary of options. The conversion process will also add some keys to the dictionary such as length of the video and crop area. The dictionary is returned. This options dictionary could be used again to repeat the convert process (it is also saved to rippy.conf as text). """ if options['subtitle_id'] is not None: print "# extract subtitles" apply_smart (extract_subtitles, options) else: print "# do not extract subtitles." # Optimization # I really only need to calculate the exact video length if the user # selected 'calc' for video_bitrate # or # selected 'detect' for video_crop_area. if options['video_bitrate']=='calc' or options['video_crop_area']=='detect': # As strange as it seems, the only reliable way to calculate the length # of a video (in seconds) is to extract the raw, uncompressed PCM audio stream # and then calculate the length of that. This is because MP4 video is VBR, so # you cannot get exact time based on compressed size. if options['video_length']=='calc': print "# extract PCM raw audio to %s" % (options['audio_raw_filename']) apply_smart (extract_audio, options) options['video_length'] = apply_smart (get_length, options) print "# Length of raw audio file : %d seconds (%0.2f minutes)" % (options['video_length'], float(options['video_length'])/60.0) if options['video_bitrate']=='calc': options['video_bitrate'] = options['video_bitrate_overhead'] * apply_smart (calc_video_bitrate, options) print "# video bitrate : " + str(options['video_bitrate']) if options['video_crop_area']=='detect': options['video_crop_area'] = apply_smart (crop_detect, options) print "# crop area : " + str(options['video_crop_area']) print "# compression estimate" print apply_smart (compression_estimate, options) print "# compress video" apply_smart (compress_video, options) 'audio_volume_boost', print "# delete temporary files:", if options['delete_tmp_files_flag']: print "yes" apply_smart (delete_tmp_files, options) else: print "no" # Finish by saving options to rippy.conf and # calclating if final_size is less than target_size. o = ["# options used to create video\n"] video_actual_size = get_filesize (options['video_final_filename']) if options['video_target_size'] != 'none': revised_bitrate = calculate_revised_bitrate (options['video_bitrate'], options['video_target_size'], video_actual_size) o.append("# revised video_bitrate : %d\n" % revised_bitrate) for k,v in options.iteritems(): o.append (" %30s : %s\n" % (k, v)) print '# '.join(o) fout = open("rippy.conf","wb").write(''.join(o)) print "# final actual video size = %d" % video_actual_size if options['video_target_size'] != 'none': if video_actual_size > options['video_target_size']: print "# FINAL VIDEO SIZE IS GREATER THAN DESIRED TARGET" print "# final video size is %d bytes over target size" % (video_actual_size - options['video_target_size']) else: print "# final video size is %d bytes under target size" % (options['video_target_size'] - video_actual_size) print "# If you want to run the entire compression process all over again" print "# to get closer to the target video size then trying using a revised" print "# video_bitrate of %d" % revised_bitrate return options ############################################################################## def exit_with_usage(exit_code=1): print globals()['__doc__'] print 'version:', globals()['__version__'] sys.stdout.flush() os._exit(exit_code) def check_missing_requirements (): """This list of missing requirements (mencoder, mplayer, lame, and mkvmerge). Returns None if all requirements are in the execution path. """ missing = [] if pexpect.which("mencoder") is None: missing.append("mencoder") if pexpect.which("mplayer") is None: missing.append("mplayer") #if pexpect.which("lame") is None: # missing.append("lame") #if pexpect.which("mkvmerge") is None: # missing.append("mkvmerge") if len(missing)==0: return None return missing def input_option (message, default_value="", help=None, level=0, max_level=0): """This is a fancy raw_input function. If the user enters '?' then the contents of help is printed. The 'level' and 'max_level' are used to adjust which advanced options are printed. 'max_level' is the level of options that the user wants to see. 'level' is the level of difficulty for this particular option. If this level is <= the max_level the user wants then the message is printed and user input is allowed; otherwise, the default value is returned automatically without user input. """ if default_value != '': message = "%s [%s] " % (message, default_value) if level > max_level: return default_value while 1: user_input = raw_input (message) if user_input=='?': print help elif user_input=='': return default_value else: break return user_input def progress_callback (d=None): """This callback simply prints a dot to show activity. This is used when running external commands with pexpect.run. """ sys.stdout.write (".") sys.stdout.flush() def run(cmd): global GLOBAL_LOGFILE print >>GLOBAL_LOGFILE, cmd (command_output, exitstatus) = pexpect.run(cmd, events={pexpect.TIMEOUT:progress_callback}, timeout=5, withexitstatus=True, logfile=GLOBAL_LOGFILE) if exitstatus != 0: print "RUN FAILED. RETURNED EXIT STATUS:", exitstatus print >>GLOBAL_LOGFILE, "RUN FAILED. RETURNED EXIT STATUS:", exitstatus return (command_output, exitstatus) def apply_smart (func, args): """This is similar to func(**args), but this won't complain about extra keys in 'args'. This ignores keys in 'args' that are not required by 'func'. This passes None to arguments that are not defined in 'args'. That's fine for arguments with a default valeue, but that's a bug for required arguments. I should probably raise a TypeError. The func parameter can be a function reference or a string. If it is a string then it is converted to a function reference. """ if type(func) is type(''): if func in globals(): func = globals()[func] else: raise NameError("name '%s' is not defined" % func) if hasattr(func,'im_func'): # Handle case when func is a class method. func = func.im_func argcount = func.func_code.co_argcount required_args = dict([(k,args.get(k)) for k in func.func_code.co_varnames[:argcount]]) return func(**required_args) def count_unique (items): """This takes a list and returns a sorted list of tuples with a count of each unique item in the list. Example 1: count_unique(['a','b','c','a','c','c','a','c','c']) returns: [(5,'c'), (3,'a'), (1,'b')] Example 2 -- get the most frequent item in a list: count_unique(['a','b','c','a','c','c','a','c','c'])[0][1] returns: 'c' """ stats = {} for i in items: if i in stats: stats[i] = stats[i] + 1 else: stats[i] = 1 stats = [(v, k) for k, v in stats.items()] stats.sort() stats.reverse() return stats def calculate_revised_bitrate (video_bitrate, video_target_size, video_actual_size): """This calculates a revised video bitrate given the video_bitrate used, the actual size that resulted, and the video_target_size. This can be used if you want to compress the video all over again in an attempt to get closer to the video_target_size. """ return int(math.floor(video_bitrate * (float(video_target_size) / float(video_actual_size)))) def get_aspect_ratio (video_source_filename): """This returns the aspect ratio of the original video. This is usualy 1.78:1(16/9) or 1.33:1(4/3). This function is very lenient. It basically guesses 16/9 whenever it cannot figure out the aspect ratio. """ cmd = "mplayer '%s' -vo png -ao null -frames 1" % video_source_filename (command_output, exitstatus) = run(cmd) ar = re.findall("Movie-Aspect is ([0-9]+\.?[0-9]*:[0-9]+\.?[0-9]*)", command_output) if len(ar)==0: return '16/9' if ar[0] == '1.78:1': return '16/9' if ar[0] == '1.33:1': return '4/3' return '16/9' #idh = re.findall("ID_VIDEO_HEIGHT=([0-9]+)", command_output) #if len(idw)==0 or len(idh)==0: # print 'WARNING!' # print 'Could not get aspect ration. Assuming 1.78:1 (16/9).' # return 1.78 #return float(idw[0])/float(idh[0]) #ID_VIDEO_WIDTH=720 #ID_VIDEO_HEIGHT=480 #Movie-Aspect is 1.78:1 - prescaling to correct movie aspect. def get_aid_list (video_source_filename): """This returns a list of audio ids in the source video file. TODO: Also extract ID_AID_nnn_LANG to associate language. Not all DVDs include this. """ cmd = "mplayer '%s' -vo null -ao null -frames 0 -identify" % video_source_filename (command_output, exitstatus) = run(cmd) idl = re.findall("ID_AUDIO_ID=([0-9]+)", command_output) idl.sort() return idl def get_sid_list (video_source_filename): """This returns a list of subtitle ids in the source video file. TODO: Also extract ID_SID_nnn_LANG to associate language. Not all DVDs include this. """ cmd = "mplayer '%s' -vo null -ao null -frames 0 -identify" % video_source_filename (command_output, exitstatus) = run(cmd) idl = re.findall("ID_SUBTITLE_ID=([0-9]+)", command_output) idl.sort() return idl def extract_audio (video_source_filename, audio_id=128, verbose_flag=0, dry_run_flag=0): """This extracts the given audio_id track as raw uncompressed PCM from the given source video. Note that mplayer always saves this to audiodump.wav. At this time there is no way to set the output audio name. """ #cmd = "mplayer %(video_source_filename)s -vc null -vo null -aid %(audio_id)s -ao pcm:fast -noframedrop" % locals() cmd = "mplayer -quiet '%(video_source_filename)s' -vc dummy -vo null -aid %(audio_id)s -ao pcm:fast -noframedrop" % locals() if verbose_flag: print cmd if not dry_run_flag: run(cmd) print def extract_subtitles (video_source_filename, subtitle_id=0, verbose_flag=0, dry_run_flag=0): """This extracts the given subtitle_id track as VOBSUB format from the given source video. """ cmd = "mencoder -quiet '%(video_source_filename)s' -o /dev/null -nosound -ovc copy -vobsubout subtitles -vobsuboutindex 0 -sid %(subtitle_id)s" % locals() if verbose_flag: print cmd if not dry_run_flag: run(cmd) print def get_length (audio_raw_filename): """This attempts to get the length of the media file (length is time in seconds). This should not be confused with size (in bytes) of the file data. This is best used on a raw PCM AUDIO file because mplayer cannot get an accurate time for many compressed video and audio formats -- notably MPEG4 and MP3. Weird... This returns -1 if it cannot get the length of the given file. """ cmd = "mplayer %s -vo null -ao null -frames 0 -identify" % audio_raw_filename (command_output, exitstatus) = run(cmd) idl = re.findall("ID_LENGTH=([0-9.]*)", command_output) idl.sort() if len(idl) != 1: print "ERROR: cannot get length of raw audio file." print "command_output of mplayer identify:" print command_output print "parsed command_output:" print str(idl) return -1 return float(idl[0]) def get_filesize (filename): """This returns the number of bytes a file takes on storage.""" return os.stat(filename)[stat.ST_SIZE] def calc_video_bitrate (video_target_size, audio_bitrate, video_length, extra_space=0, dry_run_flag=0): """This gives an estimate of the video bitrate necessary to fit the final target size. This will take into account room to fit the audio and extra space if given (for container overhead or whatnot). video_target_size is in bytes, audio_bitrate is bits per second (96, 128, 256, etc.) ASSUMING CBR, video_length is in seconds, extra_space is in bytes. a 180MB CDR (21 minutes) holds 193536000 bytes. a 550MB CDR (63 minutes) holds 580608000 bytes. a 650MB CDR (74 minutes) holds 681984000 bytes. a 700MB CDR (80 minutes) holds 737280000 bytes. """ if dry_run_flag: return -1 if extra_space is None: extra_space = 0 #audio_size = os.stat(audio_compressed_filename)[stat.ST_SIZE] audio_size = (audio_bitrate * video_length * 1000) / 8.0 video_target_size = video_target_size - audio_size - extra_space return (int)(calc_video_kbitrate (video_target_size, video_length)) def calc_video_kbitrate (target_size, length_secs): """Given a target byte size free for video data, this returns the bitrate in kBit/S. For mencoder vbitrate 1 kBit = 1000 Bits -- not 1024 bits. target_size = bitrate * 1000 * length_secs / 8 target_size = bitrate * 125 * length_secs bitrate = target_size/(125*length_secs) """ return int(target_size / (125.0 * length_secs)) def crop_detect (video_source_filename, video_length, dry_run_flag=0): """This attempts to figure out the best crop for the given video file. Basically it runs crop detect for 10 seconds on five different places in the video. It picks the crop area that was most often detected. """ skip = int(video_length/9) # offset to skip (-ss option in mencoder) sample_length = 10 cmd1 = "mencoder '%s' -quiet -ss %d -endpos %d -o /dev/null -nosound -ovc lavc -vf cropdetect" % (video_source_filename, skip, sample_length) cmd2 = "mencoder '%s' -quiet -ss %d -endpos %d -o /dev/null -nosound -ovc lavc -vf cropdetect" % (video_source_filename, 2*skip, sample_length) cmd3 = "mencoder '%s' -quiet -ss %d -endpos %d -o /dev/null -nosound -ovc lavc -vf cropdetect" % (video_source_filename, 4*skip, sample_length) cmd4 = "mencoder '%s' -quiet -ss %d -endpos %d -o /dev/null -nosound -ovc lavc -vf cropdetect" % (video_source_filename, 6*skip, sample_length) cmd5 = "mencoder '%s' -quiet -ss %d -endpos %d -o /dev/null -nosound -ovc lavc -vf cropdetect" % (video_source_filename, 8*skip, sample_length) if dry_run_flag: return "0:0:0:0" (command_output1, exitstatus1) = run(cmd1) (command_output2, exitstatus2) = run(cmd2) (command_output3, exitstatus3) = run(cmd3) (command_output4, exitstatus4) = run(cmd4) (command_output5, exitstatus5) = run(cmd5) idl = re.findall("-vf crop=([0-9]+:[0-9]+:[0-9]+:[0-9]+)", command_output1) idl = idl + re.findall("-vf crop=([0-9]+:[0-9]+:[0-9]+:[0-9]+)", command_output2) idl = idl + re.findall("-vf crop=([0-9]+:[0-9]+:[0-9]+:[0-9]+)", command_output3) idl = idl + re.findall("-vf crop=([0-9]+:[0-9]+:[0-9]+:[0-9]+)", command_output4) idl = idl + re.findall("-vf crop=([0-9]+:[0-9]+:[0-9]+:[0-9]+)", command_output5) items_count = count_unique(idl) return items_count[0][1] def build_compression_command (video_source_filename, video_final_filename, video_target_size, audio_id=128, video_bitrate=1000, video_codec='mpeg4', audio_codec='mp3', video_fourcc_override='FMP4', video_gray_flag=0, video_crop_area=None, video_aspect_ratio='16/9', video_scale=None, video_encode_passes=2, video_deinterlace_flag=0, audio_volume_boost=None, audio_sample_rate=None, audio_bitrate=None, seek_skip=None, seek_length=None, video_chapter=None): #Notes:For DVD, VCD, and SVCD use acodec=mp2 and vcodec=mpeg2video: #mencoder movie.avi -o movie.VOB -ovc lavc -oac lavc -lavcopts acodec=mp2:abitrate=224:vcodec=mpeg2video:vbitrate=2000 # # build video filter (-vf) argument # video_filter = '' if video_crop_area and video_crop_area.lower()!='none': video_filter = video_filter + 'crop=%s' % video_crop_area if video_deinterlace_flag: if video_filter != '': video_filter = video_filter + ',' video_filter = video_filter + 'pp=md' if video_scale and video_scale.lower()!='none': if video_filter != '': video_filter = video_filter + ',' video_filter = video_filter + 'scale=%s' % video_scale # optional video rotation -- were you holding your camera sideways? #if video_filter != '': # video_filter = video_filter + ',' #video_filter = video_filter + 'rotate=2' if video_filter != '': video_filter = '-vf ' + video_filter # # build chapter argument # if video_chapter is not None: chapter = '-chapter %d-%d' %(video_chapter,video_chapter) else: chapter = '' # chapter = '-chapter 2-2' # # build audio_filter argument # audio_filter = '' if audio_sample_rate: if audio_filter != '': audio_filter = audio_filter + ',' audio_filter = audio_filter + 'lavcresample=%s' % audio_sample_rate if audio_volume_boost is not None: if audio_filter != '': audio_filter = audio_filter + ',' audio_filter = audio_filter + 'volume=%0.1f:1'%audio_volume_boost if audio_filter != '': audio_filter = '-af ' + audio_filter # #if audio_sample_rate: # audio_filter = ('-srate %d ' % audio_sample_rate) + audio_filter # # build lavcopts argument # #lavcopts = '-lavcopts vcodec=%s:vbitrate=%d:mbd=2:aspect=%s:acodec=%s:abitrate=%d:vpass=1' % (video_codec,video_bitrate,audio_codec,audio_bitrate) lavcopts = '-lavcopts vcodec=%(video_codec)s:vbitrate=%(video_bitrate)d:mbd=2:aspect=%(video_aspect_ratio)s:acodec=%(audio_codec)s:abitrate=%(audio_bitrate)d:vpass=1' % (locals()) if video_gray_flag: lavcopts = lavcopts + ':gray' seek_filter = '' if seek_skip is not None: seek_filter = '-ss %s' % (str(seek_skip)) if seek_length is not None: seek_filter = seek_filter + ' -endpos %s' % (str(seek_length)) cmd = "mencoder -quiet -info comment='Arkivist' '%(video_source_filename)s' %(seek_filter)s %(chapter)s -aid %(audio_id)s -o '%(video_final_filename)s' -ffourcc %(video_fourcc_override)s -ovc lavc -oac lavc %(lavcopts)s %(video_filter)s %(audio_filter)s" % locals() return cmd def compression_estimate (video_length, video_source_filename, video_final_filename, video_target_size, audio_id=128, video_bitrate=1000, video_codec='mpeg4', audio_codec='mp3', video_fourcc_override='FMP4', video_gray_flag=0, video_crop_area=None, video_aspect_ratio='16/9', video_scale=None, video_encode_passes=2, video_deinterlace_flag=0, audio_volume_boost=None, audio_sample_rate=None, audio_bitrate=None): """This attempts to figure out the best compression ratio for a given set of compression options. """ # TODO Need to account for AVI overhead. skip = int(video_length/9) # offset to skip (-ss option in mencoder) sample_length = 10 cmd1 = build_compression_command (video_source_filename, "compression_test_1.avi", video_target_size, audio_id, video_bitrate, video_codec, audio_codec, video_fourcc_override, video_gray_flag, video_crop_area, video_aspect_ratio, video_scale, video_encode_passes, video_deinterlace_flag, audio_volume_boost, audio_sample_rate, audio_bitrate, skip, sample_length) cmd2 = build_compression_command (video_source_filename, "compression_test_2.avi", video_target_size, audio_id, video_bitrate, video_codec, audio_codec, video_fourcc_override, video_gray_flag, video_crop_area, video_aspect_ratio, video_scale, video_encode_passes, video_deinterlace_flag, audio_volume_boost, audio_sample_rate, audio_bitrate, skip*2, sample_length) cmd3 = build_compression_command (video_source_filename, "compression_test_3.avi", video_target_size, audio_id, video_bitrate, video_codec, audio_codec, video_fourcc_override, video_gray_flag, video_crop_area, video_aspect_ratio, video_scale, video_encode_passes, video_deinterlace_flag, audio_volume_boost, audio_sample_rate, audio_bitrate, skip*4, sample_length) cmd4 = build_compression_command (video_source_filename, "compression_test_4.avi", video_target_size, audio_id, video_bitrate, video_codec, audio_codec, video_fourcc_override, video_gray_flag, video_crop_area, video_aspect_ratio, video_scale, video_encode_passes, video_deinterlace_flag, audio_volume_boost, audio_sample_rate, audio_bitrate, skip*6, sample_length) cmd5 = build_compression_command (video_source_filename, "compression_test_5.avi", video_target_size, audio_id, video_bitrate, video_codec, audio_codec, video_fourcc_override, video_gray_flag, video_crop_area, video_aspect_ratio, video_scale, video_encode_passes, video_deinterlace_flag, audio_volume_boost, audio_sample_rate, audio_bitrate, skip*8, sample_length) run(cmd1) run(cmd2) run(cmd3) run(cmd4) run(cmd5) size = get_filesize ("compression_test_1.avi")+get_filesize ("compression_test_2.avi")+get_filesize ("compression_test_3.avi")+get_filesize ("compression_test_4.avi")+get_filesize ("compression_test_5.avi") return (size / 5.0) def compress_video (video_source_filename, video_final_filename, video_target_size, audio_id=128, video_bitrate=1000, video_codec='mpeg4', audio_codec='mp3', video_fourcc_override='FMP4', video_gray_flag=0, video_crop_area=None, video_aspect_ratio='16/9', video_scale=None, video_encode_passes=2, video_deinterlace_flag=0, audio_volume_boost=None, audio_sample_rate=None, audio_bitrate=None, seek_skip=None, seek_length=None, video_chapter=None, verbose_flag=0, dry_run_flag=0): """This compresses the video and audio of the given source video filename to the transcoded filename. This does a two-pass compression (I'm assuming mpeg4, I should probably make this smarter for other formats). """ # # do the first pass video compression # #cmd = "mencoder -quiet '%(video_source_filename)s' -ss 65 -endpos 20 -aid %(audio_id)s -o '%(video_final_filename)s' -ffourcc %(video_fourcc_override)s -ovc lavc -oac lavc %(lavcopts)s %(video_filter)s %(audio_filter)s" % locals() cmd = build_compression_command (video_source_filename, video_final_filename, video_target_size, audio_id, video_bitrate, video_codec, audio_codec, video_fourcc_override, video_gray_flag, video_crop_area, video_aspect_ratio, video_scale, video_encode_passes, video_deinterlace_flag, audio_volume_boost, audio_sample_rate, audio_bitrate, seek_skip, seek_length, video_chapter) if verbose_flag: print cmd if not dry_run_flag: run(cmd) print # If not doing two passes then return early. if video_encode_passes!='2': return if verbose_flag: video_actual_size = get_filesize (video_final_filename) if video_actual_size > video_target_size: print "=======================================================" print "WARNING!" print "First pass compression resulted in" print "actual file size greater than target size." print "Second pass will be too big." print "=======================================================" # # do the second pass video compression # cmd = cmd.replace ('vpass=1', 'vpass=2') if verbose_flag: print cmd if not dry_run_flag: run(cmd) print return def compress_audio (audio_raw_filename, audio_compressed_filename, audio_lowpass_filter=None, audio_sample_rate=None, audio_bitrate=None, verbose_flag=0, dry_run_flag=0): """This is depricated. This compresses the raw audio file to the compressed audio filename. """ cmd = 'lame -h --athaa-sensitivity 1' # --cwlimit 11" if audio_lowpass_filter: cmd = cmd + ' --lowpass ' + audio_lowpass_filter if audio_bitrate: #cmd = cmd + ' --abr ' + audio_bitrate cmd = cmd + ' --cbr -b ' + audio_bitrate if audio_sample_rate: cmd = cmd + ' --resample ' + audio_sample_rate cmd = cmd + ' ' + audio_raw_filename + ' ' + audio_compressed_filename if verbose_flag: print cmd if not dry_run_flag: (command_output, exitstatus) = run(cmd) print if exitstatus != 0: raise Exception('ERROR: lame failed to compress raw audio file.') def mux (video_final_filename, video_transcoded_filename, audio_compressed_filename, video_container_format, verbose_flag=0, dry_run_flag=0): """This is depricated. I used to use a three-pass encoding where I would mix the audio track separately, but this never worked very well (loss of audio sync).""" if video_container_format.lower() == 'mkv': # Matroska mux_mkv (video_final_filename, video_transcoded_filename, audio_compressed_filename, verbose_flag, dry_run_flag) if video_container_format.lower() == 'avi': mux_avi (video_final_filename, video_transcoded_filename, audio_compressed_filename, verbose_flag, dry_run_flag) def mux_mkv (video_final_filename, video_transcoded_filename, audio_compressed_filename, verbose_flag=0, dry_run_flag=0): """This is depricated.""" cmd = 'mkvmerge -o %s --noaudio %s %s' % (video_final_filename, video_transcoded_filename, audio_compressed_filename) if verbose_flag: print cmd if not dry_run_flag: run(cmd) print def mux_avi (video_final_filename, video_transcoded_filename, audio_compressed_filename, verbose_flag=0, dry_run_flag=0): """This is depricated.""" cmd = "mencoder -quiet -oac copy -ovc copy -o '%s' -audiofile %s '%s'" % (video_final_filename, audio_compressed_filename, video_transcoded_filename) if verbose_flag: print cmd if not dry_run_flag: run(cmd) print def delete_tmp_files (audio_raw_filename, verbose_flag=0, dry_run_flag=0): global GLOBAL_LOGFILE_NAME file_list = ' '.join([GLOBAL_LOGFILE_NAME, 'divx2pass.log', audio_raw_filename ]) cmd = 'rm -f ' + file_list if verbose_flag: print cmd if not dry_run_flag: run(cmd) print ############################################################################## # This is the interactive Q&A that is used if a conf file was not given. ############################################################################## def interactive_convert (): global prompts, prompts_key_order print globals()['__doc__'] print print "==============================================" print " Enter '?' at any question to get extra help." print "==============================================" print # Ask for the level of options the user wants. # A lot of code just to print a string! level_sort = {0:'', 1:'', 2:''} for k in prompts: level = prompts[k][3] if level < 0 or level > 2: continue level_sort[level] += " " + prompts[k][1] + "\n" level_sort_string = "This sets the level for advanced options prompts. Set 0 for simple, 1 for advanced, or 2 for expert.\n" level_sort_string += "[0] Basic options:\n" + str(level_sort[0]) + "\n" level_sort_string += "[1] Advanced options:\n" + str(level_sort[1]) + "\n" level_sort_string += "[2] Expert options:\n" + str(level_sort[2]) c = input_option("Prompt level (0, 1, or 2)?", "1", level_sort_string) max_prompt_level = int(c) options = {} for k in prompts_key_order: if k == 'video_aspect_ratio': guess_aspect = get_aspect_ratio(options['video_source_filename']) options[k] = input_option (prompts[k][1], guess_aspect, prompts[k][2], prompts[k][3], max_prompt_level) elif k == 'audio_id': aid_list = get_aid_list (options['video_source_filename']) default_id = '128' if max_prompt_level>=prompts[k][3]: if len(aid_list) > 1: print "This video has more than one audio stream. The following stream audio IDs were found:" for aid in aid_list: print " " + aid default_id = aid_list[0] else: print "WARNING!" print "Rippy was unable to get the list of audio streams from this video." print "If reading directly from a DVD then the DVD device might be busy." print "Using a default setting of stream id 128 (main audio on most DVDs)." default_id = '128' options[k] = input_option (prompts[k][1], default_id, prompts[k][2], prompts[k][3], max_prompt_level) elif k == 'subtitle_id': sid_list = get_sid_list (options['video_source_filename']) default_id = 'None' if max_prompt_level>=prompts[k][3]: if len(sid_list) > 0: print "This video has one or more subtitle streams. The following stream subtitle IDs were found:" for sid in sid_list: print " " + sid #default_id = sid_list[0] default_id = prompts[k][0] else: print "WARNING!" print "Unable to get the list of subtitle streams from this video. It may have none." print "Setting default to None." default_id = 'None' options[k] = input_option (prompts[k][1], default_id, prompts[k][2], prompts[k][3], max_prompt_level) elif k == 'audio_lowpass_filter': lowpass_default = "%.1f" % (math.floor(float(options['audio_sample_rate']) / 2.0)) options[k] = input_option (prompts[k][1], lowpass_default, prompts[k][2], prompts[k][3], max_prompt_level) elif k == 'video_bitrate': if options['video_length'].lower() == 'none': options[k] = input_option (prompts[k][1], '1000', prompts[k][2], prompts[k][3], max_prompt_level) else: options[k] = input_option (prompts[k][1], prompts[k][0], prompts[k][2], prompts[k][3], max_prompt_level) else: # don't bother asking for video_target_size or video_bitrate_overhead if video_bitrate was set if (k=='video_target_size' or k=='video_bitrate_overhead') and options['video_bitrate']!='calc': continue # don't bother with crop area if video length is none if k == 'video_crop_area' and options['video_length'].lower() == 'none': options['video_crop_area'] = 'none' continue options[k] = input_option (prompts[k][1], prompts[k][0], prompts[k][2], prompts[k][3], max_prompt_level) #options['video_final_filename'] = options['video_final_filename'] + "." + options['video_container_format'] print "==========================================================================" print "Ready to Rippy!" print print "The following options will be used:" for k,v in options.iteritems(): print "%27s : %s" % (k, v) print c = input_option("Continue?", "Y") c = c.strip().lower() if c[0] != 'y': print "Exiting..." os._exit(1) return options def clean_options (d): """This validates and cleans up the options dictionary. After reading options interactively or from a conf file we need to make sure that the values make sense and are converted to the correct type. 1. Any key with "_flag" in it becomes a boolean True or False. 2. Values are normalized ("No", "None", "none" all become "none"; "Calcluate", "c", "CALC" all become "calc"). 3. Certain values are converted from string to int. 4. Certain combinations of options are invalid or override each other. This is a rather annoying function, but then so it most cleanup work. """ for k in d: d[k] = d[k].strip() # convert all flag options to 0 or 1 if '_flag' in k: if type(d[k]) is types.StringType: if d[k].strip().lower()[0] in 'yt1': #Yes, True, 1 d[k] = 1 else: d[k] = 0 d['video_bitrate'] = d['video_bitrate'].lower() if d['video_bitrate'][0]=='c': d['video_bitrate']='calc' else: d['video_bitrate'] = int(float(d['video_bitrate'])) try: d['video_target_size'] = int(d['video_target_size']) # shorthand magic numbers get automatically expanded if d['video_target_size'] == 180: d['video_target_size'] = 193536000 elif d['video_target_size'] == 550: d['video_target_size'] = 580608000 elif d['video_target_size'] == 650: d['video_target_size'] = 681984000 elif d['video_target_size'] == 700: d['video_target_size'] = 737280000 except: d['video_target_size'] = 'none' try: d['video_chapter'] = int(d['video_chapter']) except: d['video_chapter'] = None try: d['subtitle_id'] = int(d['subtitle_id']) except: d['subtitle_id'] = None try: d['video_bitrate_overhead'] = float(d['video_bitrate_overhead']) except: d['video_bitrate_overhead'] = -1.0 d['audio_bitrate'] = int(d['audio_bitrate']) d['audio_sample_rate'] = int(d['audio_sample_rate']) d['audio_volume_boost'] = d['audio_volume_boost'].lower() if d['audio_volume_boost'][0]=='n': d['audio_volume_boost'] = None else: d['audio_volume_boost'] = d['audio_volume_boost'].replace('db','') d['audio_volume_boost'] = float(d['audio_volume_boost']) # assert (d['video_bitrate']=='calc' and d['video_target_size']!='none') # or (d['video_bitrate']!='calc' and d['video_target_size']=='none') d['video_scale'] = d['video_scale'].lower() if d['video_scale'][0]=='n': d['video_scale']='none' else: al = re.findall("([0-9]+).*?([0-9]+)", d['video_scale']) d['video_scale']=al[0][0]+':'+al[0][1] d['video_crop_area'] = d['video_crop_area'].lower() if d['video_crop_area'][0]=='n': d['video_crop_area']='none' d['video_length'] = d['video_length'].lower() if d['video_length'][0]=='c': d['video_length']='calc' elif d['video_length'][0]=='n': d['video_length']='none' else: d['video_length'] = int(float(d['video_length'])) if d['video_length']==0: d['video_length'] = 'none' assert (not (d['video_length']=='none' and d['video_bitrate']=='calc')) return d def main (): try: optlist, args = getopt.getopt(sys.argv[1:], 'h?', ['help','h','?']) except Exception, e: print str(e) exit_with_usage() command_line_options = dict(optlist) # There are a million ways to cry for help. These are but a few of them. if [elem for elem in command_line_options if elem in ['-h','--h','-?','--?','--help']]: exit_with_usage(0) missing = check_missing_requirements() if missing is not None: print print "==========================================================================" print "ERROR!" print "Some required external commands are missing." print "please install the following packages:" print str(missing) print "==========================================================================" print c = input_option("Continue?", "Y") c = c.strip().lower() if c[0] != 'y': print "Exiting..." os._exit(1) if len(args) > 0: # cute one-line string-to-dictionary parser (two-lines if you count this comment): options = dict(re.findall('([^: \t\n]*)\s*:\s*(".*"|[^ \t\n]*)', file(args[0]).read())) options = clean_options(options) convert (options) else: options = interactive_convert () options = clean_options(options) convert (options) print "# Done!" if __name__ == "__main__": try: start_time = time.time() print time.asctime() main() print time.asctime() print "TOTAL TIME IN MINUTES:", print (time.time() - start_time) / 60.0 except Exception, e: tb_dump = traceback.format_exc() print "==========================================================================" print "ERROR -- Unexpected exception in script." print str(e) print str(tb_dump) print "==========================================================================" print >>GLOBAL_LOGFILE, "==========================================================================" print >>GLOBAL_LOGFILE, "ERROR -- Unexpected exception in script." print >>GLOBAL_LOGFILE, str(e) print >>GLOBAL_LOGFILE, str(tb_dump) print >>GLOBAL_LOGFILE, "==========================================================================" exit_with_usage(3)
49,801
Python
.py
903
49.179402
478
0.653153
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,880
hive.py
pwnieexpress_raspberry_pwn/src/pexpect-2.3/examples/hive.py
#!/usr/bin/env python """hive -- Hive Shell This lets you ssh to a group of servers and control them as if they were one. Each command you enter is sent to each host in parallel. The response of each host is collected and printed. In normal synchronous mode Hive will wait for each host to return the shell command line prompt. The shell prompt is used to sync output. Example: $ hive.py --sameuser --samepass host1.example.com host2.example.net username: myusername password: connecting to host1.example.com - OK connecting to host2.example.net - OK targetting hosts: 192.168.1.104 192.168.1.107 CMD (? for help) > uptime ======================================================================= host1.example.com ----------------------------------------------------------------------- uptime 23:49:55 up 74 days, 5:14, 2 users, load average: 0.15, 0.05, 0.01 ======================================================================= host2.example.net ----------------------------------------------------------------------- uptime 23:53:02 up 1 day, 13:36, 2 users, load average: 0.50, 0.40, 0.46 ======================================================================= Other Usage Examples: 1. You will be asked for your username and password for each host. hive.py host1 host2 host3 ... hostN 2. You will be asked once for your username and password. This will be used for each host. hive.py --sameuser --samepass host1 host2 host3 ... hostN 3. Give a username and password on the command-line: hive.py user1:pass2@host1 user2:pass2@host2 ... userN:passN@hostN You can use an extended host notation to specify username, password, and host instead of entering auth information interactively. Where you would enter a host name use this format: username:password@host This assumes that ':' is not part of the password. If your password contains a ':' then you can use '\\:' to indicate a ':' and '\\\\' to indicate a single '\\'. Remember that this information will appear in the process listing. Anyone on your machine can see this auth information. This is not secure. This is a crude script that begs to be multithreaded. But it serves its purpose. Noah Spurrier $Id: hive.py 509 2008-01-05 21:27:47Z noah $ """ # TODO add feature to support username:password@host combination # TODO add feature to log each host output in separate file import sys, os, re, optparse, traceback, types, time, getpass import pexpect, pxssh import readline, atexit #histfile = os.path.join(os.environ["HOME"], ".hive_history") #try: # readline.read_history_file(histfile) #except IOError: # pass #atexit.register(readline.write_history_file, histfile) CMD_HELP="""Hive commands are preceded by a colon : (just think of vi). :target name1 name2 name3 ... set list of hosts to target commands :target all reset list of hosts to target all hosts in the hive. :to name command send a command line to the named host. This is similar to :target, but sends only one command and does not change the list of targets for future commands. :sync set mode to wait for shell prompts after commands are run. This is the default. When Hive first logs into a host it sets a special shell prompt pattern that it can later look for to synchronize output of the hosts. If you 'su' to another user then it can upset the synchronization. If you need to run something like 'su' then use the following pattern: CMD (? for help) > :async CMD (? for help) > sudo su - root CMD (? for help) > :prompt CMD (? for help) > :sync :async set mode to not expect command line prompts (see :sync). Afterwards commands are send to target hosts, but their responses are not read back until :sync is run. This is useful to run before commands that will not return with the special shell prompt pattern that Hive uses to synchronize. :refresh refresh the display. This shows the last few lines of output from all hosts. This is similar to resync, but does not expect the promt. This is useful for seeing what hosts are doing during long running commands. :resync This is similar to :sync, but it does not change the mode. It looks for the prompt and thus consumes all input from all targetted hosts. :prompt force each host to reset command line prompt to the special pattern used to synchronize all the hosts. This is useful if you 'su' to a different user where Hive would not know the prompt to match. :send my text This will send the 'my text' wihtout a line feed to the targetted hosts. This output of the hosts is not automatically synchronized. :control X This will send the given control character to the targetted hosts. For example, ":control c" will send ASCII 3. :exit This will exit the hive shell. """ def login (args, cli_username=None, cli_password=None): # I have to keep a separate list of host names because Python dicts are not ordered. # I want to keep the same order as in the args list. host_names = [] hive_connect_info = {} hive = {} # build up the list of connection information (hostname, username, password, port) for host_connect_string in args: hcd = parse_host_connect_string (host_connect_string) hostname = hcd['hostname'] port = hcd['port'] if port == '': port = None if len(hcd['username']) > 0: username = hcd['username'] elif cli_username is not None: username = cli_username else: username = raw_input('%s username: ' % hostname) if len(hcd['password']) > 0: password = hcd['password'] elif cli_password is not None: password = cli_password else: password = getpass.getpass('%s password: ' % hostname) host_names.append(hostname) hive_connect_info[hostname] = (hostname, username, password, port) # build up the list of hive connections using the connection information. for hostname in host_names: print 'connecting to', hostname try: fout = file("log_"+hostname, "w") hive[hostname] = pxssh.pxssh() hive[hostname].login(*hive_connect_info[hostname]) print hive[hostname].before hive[hostname].logfile = fout print '- OK' except Exception, e: print '- ERROR', print str(e) print 'Skipping', hostname hive[hostname] = None return host_names, hive def main (): global options, args, CMD_HELP if options.sameuser: cli_username = raw_input('username: ') else: cli_username = None if options.samepass: cli_password = getpass.getpass('password: ') else: cli_password = None host_names, hive = login(args, cli_username, cli_password) synchronous_mode = True target_hostnames = host_names[:] print 'targetting hosts:', ' '.join(target_hostnames) while True: cmd = raw_input('CMD (? for help) > ') cmd = cmd.strip() if cmd=='?' or cmd==':help' or cmd==':h': print CMD_HELP continue elif cmd==':refresh': refresh (hive, target_hostnames, timeout=0.5) for hostname in target_hostnames: if hive[hostname] is None: print '/=============================================================================' print '| ' + hostname + ' is DEAD' print '\\-----------------------------------------------------------------------------' else: print '/=============================================================================' print '| ' + hostname print '\\-----------------------------------------------------------------------------' print hive[hostname].before print '==============================================================================' continue elif cmd==':resync': resync (hive, target_hostnames, timeout=0.5) for hostname in target_hostnames: if hive[hostname] is None: print '/=============================================================================' print '| ' + hostname + ' is DEAD' print '\\-----------------------------------------------------------------------------' else: print '/=============================================================================' print '| ' + hostname print '\\-----------------------------------------------------------------------------' print hive[hostname].before print '==============================================================================' continue elif cmd==':sync': synchronous_mode = True resync (hive, target_hostnames, timeout=0.5) continue elif cmd==':async': synchronous_mode = False continue elif cmd==':prompt': for hostname in target_hostnames: try: if hive[hostname] is not None: hive[hostname].set_unique_prompt() except Exception, e: print "Had trouble communicating with %s, so removing it from the target list." % hostname print str(e) hive[hostname] = None continue elif cmd[:5] == ':send': cmd, txt = cmd.split(None,1) for hostname in target_hostnames: try: if hive[hostname] is not None: hive[hostname].send(txt) except Exception, e: print "Had trouble communicating with %s, so removing it from the target list." % hostname print str(e) hive[hostname] = None continue elif cmd[:3] == ':to': cmd, hostname, txt = cmd.split(None,2) if hive[hostname] is None: print '/=============================================================================' print '| ' + hostname + ' is DEAD' print '\\-----------------------------------------------------------------------------' continue try: hive[hostname].sendline (txt) hive[hostname].prompt(timeout=2) print '/=============================================================================' print '| ' + hostname print '\\-----------------------------------------------------------------------------' print hive[hostname].before except Exception, e: print "Had trouble communicating with %s, so removing it from the target list." % hostname print str(e) hive[hostname] = None continue elif cmd[:7] == ':expect': cmd, pattern = cmd.split(None,1) print 'looking for', pattern try: for hostname in target_hostnames: if hive[hostname] is not None: hive[hostname].expect(pattern) print hive[hostname].before except Exception, e: print "Had trouble communicating with %s, so removing it from the target list." % hostname print str(e) hive[hostname] = None continue elif cmd[:7] == ':target': target_hostnames = cmd.split()[1:] if len(target_hostnames) == 0 or target_hostnames[0] == all: target_hostnames = host_names[:] print 'targetting hosts:', ' '.join(target_hostnames) continue elif cmd == ':exit' or cmd == ':q' or cmd == ':quit': break elif cmd[:8] == ':control' or cmd[:5] == ':ctrl' : cmd, c = cmd.split(None,1) if ord(c)-96 < 0 or ord(c)-96 > 255: print '/=============================================================================' print '| Invalid character. Must be [a-zA-Z], @, [, ], \\, ^, _, or ?' print '\\-----------------------------------------------------------------------------' continue for hostname in target_hostnames: try: if hive[hostname] is not None: hive[hostname].sendcontrol(c) except Exception, e: print "Had trouble communicating with %s, so removing it from the target list." % hostname print str(e) hive[hostname] = None continue elif cmd == ':esc': for hostname in target_hostnames: if hive[hostname] is not None: hive[hostname].send(chr(27)) continue # # Run the command on all targets in parallel # for hostname in target_hostnames: try: if hive[hostname] is not None: hive[hostname].sendline (cmd) except Exception, e: print "Had trouble communicating with %s, so removing it from the target list." % hostname print str(e) hive[hostname] = None # # print the response for each targeted host. # if synchronous_mode: for hostname in target_hostnames: try: if hive[hostname] is None: print '/=============================================================================' print '| ' + hostname + ' is DEAD' print '\\-----------------------------------------------------------------------------' else: hive[hostname].prompt(timeout=2) print '/=============================================================================' print '| ' + hostname print '\\-----------------------------------------------------------------------------' print hive[hostname].before except Exception, e: print "Had trouble communicating with %s, so removing it from the target list." % hostname print str(e) hive[hostname] = None print '==============================================================================' def refresh (hive, hive_names, timeout=0.5): """This waits for the TIMEOUT on each host. """ # TODO This is ideal for threading. for hostname in hive_names: hive[hostname].expect([pexpect.TIMEOUT,pexpect.EOF],timeout=timeout) def resync (hive, hive_names, timeout=2, max_attempts=5): """This waits for the shell prompt for each host in an effort to try to get them all to the same state. The timeout is set low so that hosts that are already at the prompt will not slow things down too much. If a prompt match is made for a hosts then keep asking until it stops matching. This is a best effort to consume all input if it printed more than one prompt. It's kind of kludgy. Note that this will always introduce a delay equal to the timeout for each machine. So for 10 machines with a 2 second delay you will get AT LEAST a 20 second delay if not more. """ # TODO This is ideal for threading. for hostname in hive_names: for attempts in xrange(0, max_attempts): if not hive[hostname].prompt(timeout=timeout): break def parse_host_connect_string (hcs): """This parses a host connection string in the form username:password@hostname:port. All fields are options expcet hostname. A dictionary is returned with all four keys. Keys that were not included are set to empty strings ''. Note that if your password has the '@' character then you must backslash escape it. """ if '@' in hcs: p = re.compile (r'(?P<username>[^@:]*)(:?)(?P<password>.*)(?!\\)@(?P<hostname>[^:]*):?(?P<port>[0-9]*)') else: p = re.compile (r'(?P<username>)(?P<password>)(?P<hostname>[^:]*):?(?P<port>[0-9]*)') m = p.search (hcs) d = m.groupdict() d['password'] = d['password'].replace('\\@','@') return d if __name__ == '__main__': try: start_time = time.time() parser = optparse.OptionParser(formatter=optparse.TitledHelpFormatter(), usage=globals()['__doc__'], version='$Id: hive.py 509 2008-01-05 21:27:47Z noah $',conflict_handler="resolve") parser.add_option ('-v', '--verbose', action='store_true', default=False, help='verbose output') parser.add_option ('--samepass', action='store_true', default=False, help='Use same password for each login.') parser.add_option ('--sameuser', action='store_true', default=False, help='Use same username for each login.') (options, args) = parser.parse_args() if len(args) < 1: parser.error ('missing argument') if options.verbose: print time.asctime() main() if options.verbose: print time.asctime() if options.verbose: print 'TOTAL TIME IN MINUTES:', if options.verbose: print (time.time() - start_time) / 60.0 sys.exit(0) except KeyboardInterrupt, e: # Ctrl-C raise e except SystemExit, e: # sys.exit() raise e except Exception, e: print 'ERROR, UNEXPECTED EXCEPTION' print str(e) traceback.print_exc() os._exit(1)
18,065
Python
.py
373
38.302949
191
0.525169
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,881
sshls.py
pwnieexpress_raspberry_pwn/src/pexpect-2.3/examples/sshls.py
#!/usr/bin/env python """This runs 'ls -l' on a remote host using SSH. At the prompts enter hostname, user, and password. $Id: sshls.py 489 2007-11-28 23:40:34Z noah $ """ import pexpect import getpass, os def ssh_command (user, host, password, command): """This runs a command on the remote host. This could also be done with the pxssh class, but this demonstrates what that class does at a simpler level. This returns a pexpect.spawn object. This handles the case when you try to connect to a new host and ssh asks you if you want to accept the public key fingerprint and continue connecting. """ ssh_newkey = 'Are you sure you want to continue connecting' child = pexpect.spawn('ssh -l %s %s %s'%(user, host, command)) i = child.expect([pexpect.TIMEOUT, ssh_newkey, 'password: ']) if i == 0: # Timeout print 'ERROR!' print 'SSH could not login. Here is what SSH said:' print child.before, child.after return None if i == 1: # SSH does not have the public key. Just accept it. child.sendline ('yes') child.expect ('password: ') i = child.expect([pexpect.TIMEOUT, 'password: ']) if i == 0: # Timeout print 'ERROR!' print 'SSH could not login. Here is what SSH said:' print child.before, child.after return None child.sendline(password) return child def main (): host = raw_input('Hostname: ') user = raw_input('User: ') password = getpass.getpass('Password: ') child = ssh_command (user, host, password, '/bin/ls -l') child.expect(pexpect.EOF) print child.before if __name__ == '__main__': try: main() except Exception, e: print str(e) traceback.print_exc() os._exit(1)
1,796
Python
.py
46
33.152174
79
0.646552
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,882
passmass.py
pwnieexpress_raspberry_pwn/src/pexpect-2.3/examples/passmass.py
#!/usr/bin/env python """Change passwords on the named machines. passmass host1 host2 host3 . . . Note that login shell prompt on remote machine must end in # or $. """ import pexpect import sys, getpass USAGE = '''passmass host1 host2 host3 . . .''' COMMAND_PROMPT = '[$#] ' TERMINAL_PROMPT = r'Terminal type\?' TERMINAL_TYPE = 'vt100' SSH_NEWKEY = r'Are you sure you want to continue connecting \(yes/no\)\?' def login(host, user, password): child = pexpect.spawn('ssh -l %s %s'%(user, host)) fout = file ("LOG.TXT","wb") child.setlog (fout) i = child.expect([pexpect.TIMEOUT, SSH_NEWKEY, '[Pp]assword: ']) if i == 0: # Timeout print 'ERROR!' print 'SSH could not login. Here is what SSH said:' print child.before, child.after sys.exit (1) if i == 1: # SSH does not have the public key. Just accept it. child.sendline ('yes') child.expect ('[Pp]assword: ') child.sendline(password) # Now we are either at the command prompt or # the login process is asking for our terminal type. i = child.expect (['Permission denied', TERMINAL_PROMPT, COMMAND_PROMPT]) if i == 0: print 'Permission denied on host:', host sys.exit (1) if i == 1: child.sendline (TERMINAL_TYPE) child.expect (COMMAND_PROMPT) return child # (current) UNIX password: def change_password(child, user, oldpassword, newpassword): child.sendline('passwd') i = child.expect(['[Oo]ld [Pp]assword', '.current.*password', '[Nn]ew [Pp]assword']) # Root does not require old password, so it gets to bypass the next step. if i == 0 or i == 1: child.sendline(oldpassword) child.expect('[Nn]ew [Pp]assword') child.sendline(newpassword) i = child.expect(['[Nn]ew [Pp]assword', '[Rr]etype', '[Rr]e-enter']) if i == 0: print 'Host did not like new password. Here is what it said...' print child.before child.send (chr(3)) # Ctrl-C child.sendline('') # This should tell remote passwd command to quit. return child.sendline(newpassword) def main(): if len(sys.argv) <= 1: print USAGE return 1 user = raw_input('Username: ') password = getpass.getpass('Current Password: ') newpassword = getpass.getpass('New Password: ') newpasswordconfirm = getpass.getpass('Confirm New Password: ') if newpassword != newpasswordconfirm: print 'New Passwords do not match.' return 1 for host in sys.argv[1:]: child = login(host, user, password) if child == None: print 'Could not login to host:', host continue print 'Changing password on host:', host change_password(child, user, password, newpassword) child.expect(COMMAND_PROMPT) child.sendline('exit') if __name__ == '__main__': try: main() except pexpect.ExceptionPexpect, e: print str(e)
2,960
Python
.py
76
32.894737
88
0.638328
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,883
chess3.py
pwnieexpress_raspberry_pwn/src/pexpect-2.3/examples/chess3.py
#!/usr/bin/env python '''This demonstrates controlling a screen oriented application (curses). It starts two instances of gnuchess and then pits them against each other. ''' import pexpect import string import ANSI REGEX_MOVE = '(?:[a-z]|\x1b\[C)(?:[0-9]|\x1b\[C)(?:[a-z]|\x1b\[C)(?:[0-9]|\x1b\[C)' REGEX_MOVE_PART = '(?:[0-9]|\x1b\[C)(?:[a-z]|\x1b\[C)(?:[0-9]|\x1b\[C)' class Chess: def __init__(self, engine = "/usr/local/bin/gnuchess -a -h 1"): self.child = pexpect.spawn (engine) self.term = ANSI.ANSI () # self.child.expect ('Chess') # if self.child.after != 'Chess': # raise IOError, 'incompatible chess program' # self.term.process_list (self.before) # self.term.process_list (self.after) self.last_computer_move = '' def read_until_cursor (self, r,c): fout = open ('log','a') while 1: k = self.child.read(1, 10) self.term.process (k) fout.write ('(r,c):(%d,%d)\n' %(self.term.cur_r, self.term.cur_c)) fout.flush() if self.term.cur_r == r and self.term.cur_c == c: fout.close() return 1 sys.stdout.write (k) sys.stdout.flush() def do_scan (self): fout = open ('log','a') while 1: c = self.child.read(1,10) self.term.process (c) fout.write ('(r,c):(%d,%d)\n' %(self.term.cur_r, self.term.cur_c)) fout.flush() sys.stdout.write (c) sys.stdout.flush() def do_move (self, move): self.read_until_cursor (19,60) self.child.sendline (move) return move def get_computer_move (self): print 'Here' i = self.child.expect (['\[17;59H', '\[17;58H']) print i if i == 0: self.child.expect (REGEX_MOVE) if len(self.child.after) < 4: self.child.after = self.child.after + self.last_computer_move[3] if i == 1: self.child.expect (REGEX_MOVE_PART) self.child.after = self.last_computer_move[0] + self.child.after print '', self.child.after self.last_computer_move = self.child.after return self.child.after def switch (self): self.child.sendline ('switch') def set_depth (self, depth): self.child.sendline ('depth') self.child.expect ('depth=') self.child.sendline ('%d' % depth) def quit(self): self.child.sendline ('quit') import sys, os print 'Starting...' white = Chess() white.do_move('b2b4') white.read_until_cursor (19,60) c1 = white.term.get_abs(17,58) c2 = white.term.get_abs(17,59) c3 = white.term.get_abs(17,60) c4 = white.term.get_abs(17,61) fout = open ('log','a') fout.write ('Computer:%s%s%s%s\n' %(c1,c2,c3,c4)) fout.close() white.do_move('c2c4') white.read_until_cursor (19,60) c1 = white.term.get_abs(17,58) c2 = white.term.get_abs(17,59) c3 = white.term.get_abs(17,60) c4 = white.term.get_abs(17,61) fout = open ('log','a') fout.write ('Computer:%s%s%s%s\n' %(c1,c2,c3,c4)) fout.close() white.do_scan () #white.do_move ('b8a6') #move_white = white.get_computer_move() #print 'move white:', move_white sys.exit(1) black = Chess() white = Chess() white.child.expect ('Your move is') white.switch() move_white = white.get_first_computer_move() print 'first move white:', move_white black.do_first_move (move_white) move_black = black.get_first_computer_move() print 'first move black:', move_black white.do_move (move_black) done = 0 while not done: move_white = white.get_computer_move() print 'move white:', move_white black.do_move (move_white) move_black = black.get_computer_move() print 'move black:', move_black white.do_move (move_black) print 'tail of loop' g.quit()
3,777
Python
.py
112
28.419643
83
0.615958
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,884
monitor.py
pwnieexpress_raspberry_pwn/src/pexpect-2.3/examples/monitor.py
#!/usr/bin/env python """ This runs a sequence of commands on a remote host using SSH. It runs a simple system checks such as uptime and free to monitor the state of the remote host. ./monitor.py [-s server_hostname] [-u username] [-p password] -s : hostname of the remote server to login to. -u : username to user for login. -p : Password to user for login. Example: This will print information about the given host: ./monitor.py -s www.example.com -u mylogin -p mypassword It works like this: Login via SSH (This is the hardest part). Run and parse 'uptime'. Run 'iostat'. Run 'vmstat'. Run 'netstat' Run 'free'. Exit the remote host. """ import os, sys, time, re, getopt, getpass import traceback import pexpect # # Some constants. # COMMAND_PROMPT = '[#$] ' ### This is way too simple for industrial use -- we will change is ASAP. TERMINAL_PROMPT = '(?i)terminal type\?' TERMINAL_TYPE = 'vt100' # This is the prompt we get if SSH does not have the remote host's public key stored in the cache. SSH_NEWKEY = '(?i)are you sure you want to continue connecting' def exit_with_usage(): print globals()['__doc__'] os._exit(1) def main(): global COMMAND_PROMPT, TERMINAL_PROMPT, TERMINAL_TYPE, SSH_NEWKEY ###################################################################### ## Parse the options, arguments, get ready, etc. ###################################################################### try: optlist, args = getopt.getopt(sys.argv[1:], 'h?s:u:p:', ['help','h','?']) except Exception, e: print str(e) exit_with_usage() options = dict(optlist) if len(args) > 1: exit_with_usage() if [elem for elem in options if elem in ['-h','--h','-?','--?','--help']]: print "Help:" exit_with_usage() if '-s' in options: host = options['-s'] else: host = raw_input('hostname: ') if '-u' in options: user = options['-u'] else: user = raw_input('username: ') if '-p' in options: password = options['-p'] else: password = getpass.getpass('password: ') # # Login via SSH # child = pexpect.spawn('ssh -l %s %s'%(user, host)) i = child.expect([pexpect.TIMEOUT, SSH_NEWKEY, COMMAND_PROMPT, '(?i)password']) if i == 0: # Timeout print 'ERROR! could not login with SSH. Here is what SSH said:' print child.before, child.after print str(child) sys.exit (1) if i == 1: # In this case SSH does not have the public key cached. child.sendline ('yes') child.expect ('(?i)password') if i == 2: # This may happen if a public key was setup to automatically login. # But beware, the COMMAND_PROMPT at this point is very trivial and # could be fooled by some output in the MOTD or login message. pass if i == 3: child.sendline(password) # Now we are either at the command prompt or # the login process is asking for our terminal type. i = child.expect ([COMMAND_PROMPT, TERMINAL_PROMPT]) if i == 1: child.sendline (TERMINAL_TYPE) child.expect (COMMAND_PROMPT) # # Set command prompt to something more unique. # COMMAND_PROMPT = "\[PEXPECT\]\$ " child.sendline ("PS1='[PEXPECT]\$ '") # In case of sh-style i = child.expect ([pexpect.TIMEOUT, COMMAND_PROMPT], timeout=10) if i == 0: print "# Couldn't set sh-style prompt -- trying csh-style." child.sendline ("set prompt='[PEXPECT]\$ '") i = child.expect ([pexpect.TIMEOUT, COMMAND_PROMPT], timeout=10) if i == 0: print "Failed to set command prompt using sh or csh style." print "Response was:" print child.before sys.exit (1) # Now we should be at the command prompt and ready to run some commands. print '---------------------------------------' print 'Report of commands run on remote host.' print '---------------------------------------' # Run uname. child.sendline ('uname -a') child.expect (COMMAND_PROMPT) print child.before if 'linux' in child.before.lower(): LINUX_MODE = 1 else: LINUX_MODE = 0 # Run and parse 'uptime'. child.sendline ('uptime') child.expect('up\s+(.*?),\s+([0-9]+) users?,\s+load averages?: ([0-9]+\.[0-9][0-9]),?\s+([0-9]+\.[0-9][0-9]),?\s+([0-9]+\.[0-9][0-9])') duration, users, av1, av5, av15 = child.match.groups() days = '0' hours = '0' mins = '0' if 'day' in duration: child.match = re.search('([0-9]+)\s+day',duration) days = str(int(child.match.group(1))) if ':' in duration: child.match = re.search('([0-9]+):([0-9]+)',duration) hours = str(int(child.match.group(1))) mins = str(int(child.match.group(2))) if 'min' in duration: child.match = re.search('([0-9]+)\s+min',duration) mins = str(int(child.match.group(1))) print print 'Uptime: %s days, %s users, %s (1 min), %s (5 min), %s (15 min)' % ( duration, users, av1, av5, av15) child.expect (COMMAND_PROMPT) # Run iostat. child.sendline ('iostat') child.expect (COMMAND_PROMPT) print child.before # Run vmstat. child.sendline ('vmstat') child.expect (COMMAND_PROMPT) print child.before # Run free. if LINUX_MODE: child.sendline ('free') # Linux systems only. child.expect (COMMAND_PROMPT) print child.before # Run df. child.sendline ('df') child.expect (COMMAND_PROMPT) print child.before # Run lsof. child.sendline ('lsof') child.expect (COMMAND_PROMPT) print child.before # # Run netstat # child.sendline ('netstat') # child.expect (COMMAND_PROMPT) # print child.before # # Run MySQL show status. # child.sendline ('mysql -p -e "SHOW STATUS;"') # child.expect (PASSWORD_PROMPT_MYSQL) # child.sendline (password_mysql) # child.expect (COMMAND_PROMPT) # print # print child.before # Now exit the remote host. child.sendline ('exit') index = child.expect([pexpect.EOF, "(?i)there are stopped jobs"]) if index==1: child.sendline("exit") child.expect(EOF) if __name__ == "__main__": try: main() except Exception, e: print str(e) traceback.print_exc() os._exit(1)
6,478
Python
.py
181
29.955801
139
0.588733
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,885
chess2.py
pwnieexpress_raspberry_pwn/src/pexpect-2.3/examples/chess2.py
#!/usr/bin/env python '''This demonstrates controlling a screen oriented application (curses). It starts two instances of gnuchess and then pits them against each other. ''' import pexpect import string import ANSI import sys, os, time class Chess: def __init__(self, engine = "/usr/local/bin/gnuchess -a -h 1"): self.child = pexpect.spawn (engine) self.term = ANSI.ANSI () #self.child.expect ('Chess') #if self.child.after != 'Chess': # raise IOError, 'incompatible chess program' #self.term.process_list (self.child.before) #self.term.process_list (self.child.after) self.last_computer_move = '' def read_until_cursor (self, r,c, e=0): '''Eventually something like this should move into the screen class or a subclass. Maybe a combination of pexpect and screen... ''' fout = open ('log','a') while self.term.cur_r != r or self.term.cur_c != c: try: k = self.child.read(1, 10) except Exception, e: print 'EXCEPTION, (r,c):(%d,%d)\n' %(self.term.cur_r, self.term.cur_c) sys.stdout.flush() self.term.process (k) fout.write ('(r,c):(%d,%d)\n' %(self.term.cur_r, self.term.cur_c)) fout.flush() if e: sys.stdout.write (k) sys.stdout.flush() if self.term.cur_r == r and self.term.cur_c == c: fout.close() return 1 print 'DIDNT EVEN HIT.' fout.close() return 1 def expect_region (self): '''This is another method that would be moved into the screen class. ''' pass def do_scan (self): fout = open ('log','a') while 1: c = self.child.read(1,10) self.term.process (c) fout.write ('(r,c):(%d,%d)\n' %(self.term.cur_r, self.term.cur_c)) fout.flush() sys.stdout.write (c) sys.stdout.flush() def do_move (self, move, e = 0): time.sleep(1) self.read_until_cursor (19,60, e) self.child.sendline (move) def wait (self, color): while 1: r = self.term.get_region (14,50,14,60)[0] r = r.strip() if r == color: return time.sleep (1) def parse_computer_move (self, s): i = s.find ('is: ') cm = s[i+3:i+9] return cm def get_computer_move (self, e = 0): time.sleep(1) self.read_until_cursor (19,60, e) time.sleep(1) r = self.term.get_region (17,50,17,62)[0] cm = self.parse_computer_move (r) return cm def switch (self): print 'switching' self.child.sendline ('switch') def set_depth (self, depth): self.child.sendline ('depth') self.child.expect ('depth=') self.child.sendline ('%d' % depth) def quit(self): self.child.sendline ('quit') def LOG (s): print s sys.stdout.flush () fout = open ('moves.log', 'a') fout.write (s + '\n') fout.close() print 'Starting...' black = Chess() white = Chess() white.read_until_cursor (19,60,1) white.switch() done = 0 while not done: white.wait ('Black') move_white = white.get_computer_move(1) LOG ( 'move white:'+ move_white ) black.do_move (move_white) black.wait ('White') move_black = black.get_computer_move() LOG ( 'move black:'+ move_black ) white.do_move (move_black, 1) g.quit()
4,026
Python
.py
108
25.027778
90
0.494457
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,886
ftp.py
pwnieexpress_raspberry_pwn/src/pexpect-2.3/examples/ftp.py
#!/usr/bin/env python """This demonstrates an FTP "bookmark". This connects to an ftp site; does a few ftp stuff; and then gives the user interactive control over the session. In this case the "bookmark" is to a directory on the OpenBSD ftp server. It puts you in the i386 packages directory. You can easily modify this for other sites. """ import pexpect import sys child = pexpect.spawn('ftp ftp.openbsd.org') child.expect('(?i)name .*: ') child.sendline('anonymous') child.expect('(?i)password') child.sendline('pexpect@sourceforge.net') child.expect('ftp> ') child.sendline('cd /pub/OpenBSD/3.7/packages/i386') child.expect('ftp> ') child.sendline('bin') child.expect('ftp> ') child.sendline('prompt') child.expect('ftp> ') child.sendline('pwd') child.expect('ftp> ') print("Escape character is '^]'.\n") sys.stdout.write (child.after) sys.stdout.flush() child.interact() # Escape character defaults to ^] # At this point this script blocks until the user presses the escape character # or until the child exits. The human user and the child should be talking # to each other now. # At this point the script is running again. print 'Left interactve mode.' # The rest is not strictly necessary. This just demonstrates a few functions. # This makes sure the child is dead; although it would be killed when Python exits. if child.isalive(): child.sendline('bye') # Try to ask ftp child to exit. child.close() # Print the final state of the child. Normally isalive() should be FALSE. if child.isalive(): print 'Child did not exit gracefully.' else: print 'Child exited gracefully.'
1,604
Python
.py
41
37.585366
83
0.756583
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,887
script.py
pwnieexpress_raspberry_pwn/src/pexpect-2.3/examples/script.py
#!/usr/bin/env python """This spawns a sub-shell (bash) and gives the user interactive control. The entire shell session is logged to a file called script.log. This behaves much like the classic BSD command 'script'. ./script.py [-a] [-c command] {logfilename} logfilename : This is the name of the log file. Default is script.log. -a : Append to log file. Default is to overwrite log file. -c : spawn command. Default is to spawn the sh shell. Example: This will start a bash shell and append to the log named my_session.log: ./script.py -a -c bash my_session.log """ import os, sys, time, getopt import signal, fcntl, termios, struct import traceback import pexpect global_pexpect_instance = None # Used by signal handler def exit_with_usage(): print globals()['__doc__'] os._exit(1) def main(): ###################################################################### # Parse the options, arguments, get ready, etc. ###################################################################### try: optlist, args = getopt.getopt(sys.argv[1:], 'h?ac:', ['help','h','?']) except Exception, e: print str(e) exit_with_usage() options = dict(optlist) if len(args) > 1: exit_with_usage() if [elem for elem in options if elem in ['-h','--h','-?','--?','--help']]: print "Help:" exit_with_usage() if len(args) == 1: script_filename = args[0] else: script_filename = "script.log" if '-a' in options: fout = file (script_filename, "ab") else: fout = file (script_filename, "wb") if '-c' in options: command = options['-c'] else: command = "sh" # Begin log with date/time in the form CCCCyymm.hhmmss fout.write ('# %4d%02d%02d.%02d%02d%02d \n' % time.localtime()[:-3]) ###################################################################### # Start the interactive session ###################################################################### p = pexpect.spawn(command) p.logfile = fout global global_pexpect_instance global_pexpect_instance = p signal.signal(signal.SIGWINCH, sigwinch_passthrough) print "Script recording started. Type ^] (ASCII 29) to escape from the script shell." p.interact(chr(29)) fout.close() return 0 def sigwinch_passthrough (sig, data): # Check for buggy platforms (see pexpect.setwinsize()). if 'TIOCGWINSZ' in dir(termios): TIOCGWINSZ = termios.TIOCGWINSZ else: TIOCGWINSZ = 1074295912 # assume s = struct.pack ("HHHH", 0, 0, 0, 0) a = struct.unpack ('HHHH', fcntl.ioctl(sys.stdout.fileno(), TIOCGWINSZ , s)) global global_pexpect_instance global_pexpect_instance.setwinsize(a[0],a[1]) if __name__ == "__main__": try: main() except SystemExit, e: raise e except Exception, e: print "ERROR" print str(e) traceback.print_exc() os._exit(1)
3,028
Python
.py
81
31.716049
89
0.576038
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,888
ssh_session.py
pwnieexpress_raspberry_pwn/src/pexpect-2.3/examples/ssh_session.py
# # Eric S. Raymond # # Greatly modified by Nigel W. Moriarty # April 2003 # from pexpect import * import os, sys import getpass import time class ssh_session: "Session with extra state including the password to be used." def __init__(self, user, host, password=None, verbose=0): self.user = user self.host = host self.verbose = verbose self.password = password self.keys = [ 'authenticity', 'assword:', '@@@@@@@@@@@@', 'Command not found.', EOF, ] self.f = open('ssh.out','w') def __repr__(self): outl = 'class :'+self.__class__.__name__ for attr in self.__dict__: if attr == 'password': outl += '\n\t'+attr+' : '+'*'*len(self.password) else: outl += '\n\t'+attr+' : '+str(getattr(self, attr)) return outl def __exec(self, command): "Execute a command on the remote host. Return the output." child = spawn(command, #timeout=10, ) if self.verbose: sys.stderr.write("-> " + command + "\n") seen = child.expect(self.keys) self.f.write(str(child.before) + str(child.after)+'\n') if seen == 0: child.sendline('yes') seen = child.expect(self.keys) if seen == 1: if not self.password: self.password = getpass.getpass('Remote password: ') child.sendline(self.password) child.readline() time.sleep(5) # Added to allow the background running of remote process if not child.isalive(): seen = child.expect(self.keys) if seen == 2: lines = child.readlines() self.f.write(lines) if self.verbose: sys.stderr.write("<- " + child.before + "|\n") try: self.f.write(str(child.before) + str(child.after)+'\n') except: pass self.f.close() return child.before def ssh(self, command): return self.__exec("ssh -l %s %s \"%s\"" \ % (self.user,self.host,command)) def scp(self, src, dst): return self.__exec("scp %s %s@%s:%s" \ % (src, session.user, session.host, dst)) def exists(self, file): "Retrieve file permissions of specified remote file." seen = self.ssh("/bin/ls -ld %s" % file) if string.find(seen, "No such file") > -1: return None # File doesn't exist else: return seen.split()[0] # Return permission field of listing.
2,817
Python
.py
78
24.769231
86
0.50389
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,889
df.py
pwnieexpress_raspberry_pwn/src/pexpect-2.3/examples/df.py
#!/usr/bin/env python """This collects filesystem capacity info using the 'df' command. Tuples of filesystem name and percentage are stored in a list. A simple report is printed. Filesystems over 95% capacity are highlighted. Note that this does not parse filesystem names after the first space, so names with spaces in them will be truncated. This will produce ambiguous results for automount filesystems on Apple OSX. """ import pexpect child = pexpect.spawn ('df') # parse 'df' output into a list. pattern = "\n(\S+).*?([0-9]+)%" filesystem_list = [] for dummy in range (0, 1000): i = child.expect ([pattern, pexpect.EOF]) if i == 0: filesystem_list.append (child.match.groups()) else: break # Print report print for m in filesystem_list: s = "Filesystem %s is at %s%%" % (m[0], m[1]) # highlight filesystems over 95% capacity if int(m[1]) > 95: s = '! ' + s else: s = ' ' + s print s
959
Python
.py
28
30.75
79
0.678919
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,890
ssh_tunnel.py
pwnieexpress_raspberry_pwn/src/pexpect-2.3/examples/ssh_tunnel.py
#!/usr/bin/env python """This starts an SSH tunnel to a given host. If the SSH process ever dies then this script will detect that and restart it. I use this under Cygwin to keep open encrypted tunnels to port 25 (SMTP), port 143 (IMAP4), and port 110 (POP3). I set my mail client to talk to localhost and I keep this script running in the background. Note that this is a rather stupid script at the moment because it just looks to see if any ssh process is running. It should really make sure that our specific ssh process is running. The problem is that ssh is missing a very useful feature. It has no way to report the process id of the background daemon that it creates with the -f command. This would be a really useful script if I could figure a way around this problem. """ import pexpect import getpass import time # SMTP:25 IMAP4:143 POP3:110 tunnel_command = 'ssh -C -N -f -L 25:127.0.0.1:25 -L 143:127.0.0.1:143 -L 110:127.0.0.1:110 %(user)@%(host)' host = raw_input('Hostname: ') user = raw_input('Username: ') X = getpass.getpass('Password: ') def get_process_info (): # This seems to work on both Linux and BSD, but should otherwise be considered highly UNportable. ps = pexpect.run ('ps ax -O ppid') pass def start_tunnel (): try: ssh_tunnel = pexpect.spawn (tunnel_command % globals()) ssh_tunnel.expect ('password:') time.sleep (0.1) ssh_tunnel.sendline (X) time.sleep (60) # Cygwin is slow to update process status. ssh_tunnel.expect (pexpect.EOF) except Exception, e: print str(e) def main (): while True: ps = pexpect.spawn ('ps') time.sleep (1) index = ps.expect (['/usr/bin/ssh', pexpect.EOF, pexpect.TIMEOUT]) if index == 2: print 'TIMEOUT in ps command...' print str(ps) time.sleep (13) if index == 1: print time.asctime(), print 'restarting tunnel' start_tunnel () time.sleep (11) print 'tunnel OK' else: # print 'tunnel OK' time.sleep (7) if __name__ == '__main__': main () # This was for older SSH versions that didn't have -f option #tunnel_command = 'ssh -C -n -L 25:%(host)s:25 -L 110:%(host)s:110 %(user)s@%(host)s -f nothing.sh' #nothing_script = """#!/bin/sh #while true; do sleep 53; done #"""
2,390
Python
.py
59
35.067797
108
0.655306
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,891
topip.py
pwnieexpress_raspberry_pwn/src/pexpect-2.3/examples/topip.py
#!/usr/bin/env python """ This runs netstat on a local or remote server. It calculates some simple statistical information on the number of external inet connections. It groups by IP address. This can be used to detect if one IP address is taking up an excessive number of connections. It can also send an email alert if a given IP address exceeds a threshold between runs of the script. This script can be used as a drop-in Munin plugin or it can be used stand-alone from cron. I used this on a busy web server that would sometimes get hit with denial of service attacks. This made it easy to see if a script was opening many multiple connections. A typical browser would open fewer than 10 connections at once. A script might open over 100 simultaneous connections. ./topip.py [-s server_hostname] [-u username] [-p password] {-a from_addr,to_addr} {-n N} {-v} {--ipv6} -s : hostname of the remote server to login to. -u : username to user for login. -p : password to user for login. -n : print stddev for the the number of the top 'N' ipaddresses. -v : verbose - print stats and list of top ipaddresses. -a : send alert if stddev goes over 20. -l : to log message to /var/log/topip.log --ipv6 : this parses netstat output that includes ipv6 format. Note that this actually only works with ipv4 addresses, but for versions of netstat that print in ipv6 format. --stdev=N : Where N is an integer. This sets the trigger point for alerts and logs. Default is to trigger if max value is above 5 standard deviations. Example: This will print stats for the top IP addresses connected to the given host: ./topip.py -s www.example.com -u mylogin -p mypassword -n 10 -v This will send an alert email if the maxip goes over the stddev trigger value and the the current top ip is the same as the last top ip (/tmp/topip.last): ./topip.py -s www.example.com -u mylogin -p mypassword -n 10 -v -a alert@example.com,user@example.com This will print the connection stats for the localhost in Munin format: ./topip.py Noah Spurrier $Id: topip.py 489 2007-11-28 23:40:34Z noah $ """ import pexpect, pxssh # See http://pexpect.sourceforge.net/ import os, sys, time, re, getopt, pickle, getpass, smtplib import traceback from pprint import pprint TOPIP_LOG_FILE = '/var/log/topip.log' TOPIP_LAST_RUN_STATS = '/var/run/topip.last' def exit_with_usage(): print globals()['__doc__'] os._exit(1) def stats(r): """This returns a dict of the median, average, standard deviation, min and max of the given sequence. >>> from topip import stats >>> print stats([5,6,8,9]) {'med': 8, 'max': 9, 'avg': 7.0, 'stddev': 1.5811388300841898, 'min': 5} >>> print stats([1000,1006,1008,1014]) {'med': 1008, 'max': 1014, 'avg': 1007.0, 'stddev': 5.0, 'min': 1000} >>> print stats([1,3,4,5,18,16,4,3,3,5,13]) {'med': 4, 'max': 18, 'avg': 6.8181818181818183, 'stddev': 5.6216817577237475, 'min': 1} >>> print stats([1,3,4,5,18,16,4,3,3,5,13,14,5,6,7,8,7,6,6,7,5,6,4,14,7]) {'med': 6, 'max': 18, 'avg': 7.0800000000000001, 'stddev': 4.3259218670706474, 'min': 1} """ total = sum(r) avg = float(total)/float(len(r)) sdsq = sum([(i-avg)**2 for i in r]) s = list(r) s.sort() return dict(zip(['med', 'avg', 'stddev', 'min', 'max'] , (s[len(s)//2], avg, (sdsq/len(r))**.5, min(r), max(r)))) def send_alert (message, subject, addr_from, addr_to, smtp_server='localhost'): """This sends an email alert. """ message = 'From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n' % (addr_from, addr_to, subject) + message server = smtplib.SMTP(smtp_server) server.sendmail(addr_from, addr_to, message) server.quit() def main(): ###################################################################### ## Parse the options, arguments, etc. ###################################################################### try: optlist, args = getopt.getopt(sys.argv[1:], 'h?valqs:u:p:n:', ['help','h','?','ipv6','stddev=']) except Exception, e: print str(e) exit_with_usage() options = dict(optlist) munin_flag = False if len(args) > 0: if args[0] == 'config': print 'graph_title Netstat Connections per IP' print 'graph_vlabel Socket connections per IP' print 'connections_max.label max' print 'connections_max.info Maximum number of connections per IP' print 'connections_avg.label avg' print 'connections_avg.info Average number of connections per IP' print 'connections_stddev.label stddev' print 'connections_stddev.info Standard deviation' return 0 elif args[0] != '': print args, len(args) return 0 exit_with_usage() if [elem for elem in options if elem in ['-h','--h','-?','--?','--help']]: print 'Help:' exit_with_usage() if '-s' in options: hostname = options['-s'] else: # if host was not specified then assume localhost munin plugin. munin_flag = True hostname = 'localhost' # If localhost then don't ask for username/password. if hostname != 'localhost' and hostname != '127.0.0.1': if '-u' in options: username = options['-u'] else: username = raw_input('username: ') if '-p' in options: password = options['-p'] else: password = getpass.getpass('password: ') else: use_localhost = True if '-l' in options: log_flag = True else: log_flag = False if '-n' in options: average_n = int(options['-n']) else: average_n = None if '-v' in options: verbose = True else: verbose = False if '-a' in options: alert_flag = True (alert_addr_from, alert_addr_to) = tuple(options['-a'].split(',')) else: alert_flag = False if '--ipv6' in options: ipv6_flag = True else: ipv6_flag = False if '--stddev' in options: stddev_trigger = float(options['--stddev']) else: stddev_trigger = 5 if ipv6_flag: netstat_pattern = '(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+::ffff:(\S+):(\S+)\s+.*?\r' else: netstat_pattern = '(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(?:::ffff:)*(\S+):(\S+)\s+.*?\r' #netstat_pattern = '(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+):(\S+)\s+.*?\r' # run netstat (either locally or via SSH). if use_localhost: p = pexpect.spawn('netstat -n -t') PROMPT = pexpect.TIMEOUT else: p = pxssh.pxssh() p.login(hostname, username, password) p.sendline('netstat -n -t') PROMPT = p.PROMPT # loop through each matching netstat_pattern and put the ip address in the list. ip_list = {} try: while 1: i = p.expect([PROMPT, netstat_pattern]) if i == 0: break k = p.match.groups()[4] if k in ip_list: ip_list[k] = ip_list[k] + 1 else: ip_list[k] = 1 except: pass # remove a few common, uninteresting addresses from the dictionary. ip_list = dict([ (key,value) for key,value in ip_list.items() if '192.168.' not in key]) ip_list = dict([ (key,value) for key,value in ip_list.items() if '127.0.0.1' not in key]) # sort dict by value (count) #ip_list = sorted(ip_list.iteritems(),lambda x,y:cmp(x[1], y[1]),reverse=True) ip_list = ip_list.items() if len(ip_list) < 1: if verbose: print 'Warning: no networks connections worth looking at.' return 0 ip_list.sort(lambda x,y:cmp(y[1],x[1])) # generate some stats for the ip addresses found. if average_n <= 1: average_n = None s = stats(zip(*ip_list[0:average_n])[1]) # The * unary operator treats the list elements as arguments s['maxip'] = ip_list[0] # print munin-style or verbose results for the stats. if munin_flag: print 'connections_max.value', s['max'] print 'connections_avg.value', s['avg'] print 'connections_stddev.value', s['stddev'] return 0 if verbose: pprint (s) print pprint (ip_list[0:average_n]) # load the stats from the last run. try: last_stats = pickle.load(file(TOPIP_LAST_RUN_STATS)) except: last_stats = {'maxip':None} if s['maxip'][1] > (s['stddev'] * stddev_trigger) and s['maxip']==last_stats['maxip']: if verbose: print 'The maxip has been above trigger for two consecutive samples.' if alert_flag: if verbose: print 'SENDING ALERT EMAIL' send_alert(str(s), 'ALERT on %s' % hostname, alert_addr_from, alert_addr_to) if log_flag: if verbose: print 'LOGGING THIS EVENT' fout = file(TOPIP_LOG_FILE,'a') #dts = time.strftime('%Y:%m:%d:%H:%M:%S', time.localtime()) dts = time.asctime() fout.write ('%s - %d connections from %s\n' % (dts,s['maxip'][1],str(s['maxip'][0]))) fout.close() # save state to TOPIP_LAST_RUN_STATS try: pickle.dump(s, file(TOPIP_LAST_RUN_STATS,'w')) os.chmod (TOPIP_LAST_RUN_STATS, 0664) except: pass # p.logout() if __name__ == '__main__': try: main() sys.exit(0) except SystemExit, e: raise e except Exception, e: print str(e) traceback.print_exc() os._exit(1)
9,640
Python
.py
228
35.175439
117
0.596821
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,892
astat.py
pwnieexpress_raspberry_pwn/src/pexpect-2.3/examples/astat.py
#!/usr/bin/env python """This runs Apache Status on the remote host and returns the number of requests per second. ./astat.py [-s server_hostname] [-u username] [-p password] -s : hostname of the remote server to login to. -u : username to user for login. -p : Password to user for login. Example: This will print information about the given host: ./astat.py -s www.example.com -u mylogin -p mypassword """ import os, sys, time, re, getopt, getpass import traceback import pexpect, pxssh def exit_with_usage(): print globals()['__doc__'] os._exit(1) def main(): ###################################################################### ## Parse the options, arguments, get ready, etc. ###################################################################### try: optlist, args = getopt.getopt(sys.argv[1:], 'h?s:u:p:', ['help','h','?']) except Exception, e: print str(e) exit_with_usage() options = dict(optlist) if len(args) > 1: exit_with_usage() if [elem for elem in options if elem in ['-h','--h','-?','--?','--help']]: print "Help:" exit_with_usage() if '-s' in options: hostname = options['-s'] else: hostname = raw_input('hostname: ') if '-u' in options: username = options['-u'] else: username = raw_input('username: ') if '-p' in options: password = options['-p'] else: password = getpass.getpass('password: ') # # Login via SSH # p = pxssh.pxssh() p.login(hostname, username, password) p.sendline('apachectl status') p.expect('([0-9]+\.[0-9]+)\s*requests/sec') requests_per_second = p.match.groups()[0] p.logout() print requests_per_second if __name__ == "__main__": try: main() except Exception, e: print str(e) traceback.print_exc() os._exit(1)
1,930
Python
.py
60
26.533333
92
0.548491
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,893
replay.py
pwnieexpress_raspberry_pwn/src/aircrack-ng-1.2-rc1/test/replay.py
#!/usr/bin/env python import sys from scapy import * import pcapy from impacket.ImpactDecoder import * try: conf.verb=0 except NameError: # Scapy v2 from scapy.all import * conf.verb=0 if len(sys.argv) != 2: print "Usage: ./replay.py <iface>" sys.exit(1) interface=sys.argv[1] max_bytes = 2048 promiscuous = False read_timeout = 100 # in milliseconds packet_limit = -1 # infinite pc = pcapy.open_live(interface, max_bytes, promiscuous, read_timeout) def recv_pkts(hdr, data): replay = True if data[11] == "\xFF": return # separate ethernet header and ieee80211 packet raw_header = data[:11] + "\xFF" + data[12:14] header = Ether(raw_header) try: # end of separation packet = Dot11(data[14:]) except struct.error: # Ignore unpack errors on short packages return # manipulate/drop/insert dot11 packet print packet.summary() # end of manipulation # construct packet and replay if replay == True: data = header/packet sendp(data, iface=interface) pc.loop(packet_limit, recv_pkts) # capture packets
1,136
Python
.py
41
23.243902
69
0.679926
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,894
dcrack.py
pwnieexpress_raspberry_pwn/src/aircrack-ng-1.2-rc1/scripts/dcrack.py
#!/usr/bin/python import sys import os import subprocess import random import time import sqlite3 import threading import hashlib import gzip import json import datetime import re if sys.version_info[0] >= 3: from socketserver import ThreadingTCPServer from urllib.request import urlopen, URLError from urllib.parse import urlparse, parse_qs from http.client import HTTPConnection from http.server import SimpleHTTPRequestHandler else: from SocketServer import ThreadingTCPServer from urllib2 import urlopen, URLError from urlparse import urlparse, parse_qs from httplib import HTTPConnection from SimpleHTTPServer import SimpleHTTPRequestHandler bytes = lambda a, b : a port = 1337 url = None cid = None tls = threading.local() nets = {} cracker = None class ServerHandler(SimpleHTTPRequestHandler): def do_GET(s): result = s.do_req(s.path) if not result: return s.send_response(200) s.send_header("Content-type", "text/plain") s.end_headers() s.wfile.write(bytes(result, "UTF-8")) def do_POST(s): if ("dict" in s.path): s.do_upload_dict() if ("cap" in s.path): s.do_upload_cap() s.send_response(200) s.send_header("Content-type", "text/plain") s.end_headers() s.wfile.write(bytes("OK", "UTF-8")) def do_upload_dict(s): con = get_con() f = "dcrack-dict" c = f + ".gz" o = open(c, "wb") cl = int(s.headers['Content-Length']) o.write(s.rfile.read(cl)) o.close() decompress(f) sha1 = hashlib.sha1() x = open(f, "rb") sha1.update(x.read()) x.close() h = sha1.hexdigest() x = open(f, "rb") for i, l in enumerate(x): pass i = i + 1 x.close() n = "%s-%s.txt" % (f, h) os.rename(f, n) os.rename(c, "%s.gz" % n) c = con.cursor() c.execute("INSERT into dict values (?, ?, 0)", (h, i)) con.commit() def do_upload_cap(s): cl = int(s.headers['Content-Length']) f = open("dcrack.cap.tmp.gz", "wb") f.write(s.rfile.read(cl)) f.close() decompress("dcrack.cap.tmp") os.rename("dcrack.cap.tmp.gz", "dcrack.cap.gz") os.rename("dcrack.cap.tmp", "dcrack.cap") def do_req(s, path): con = get_con() c = con.cursor() c.execute("""DELETE from clients where (strftime('%s', datetime()) - strftime('%s', last)) > 300""") con.commit() if ("ping" in path): return s.do_ping(path) if ("getwork" in path): return s.do_getwork(path) if ("dict" in path and "status" in path): return s.do_dict_status(path) if ("dict" in path and "set" in path): return s.do_dict_set(path) if ("dict" in path): return s.get_dict(path) if ("net" in path and "/crack" in path): return s.do_crack(path) if ("net" in path and "result" in path): return s.do_result(path) if ("cap" in path): return s.get_cap(path) if ("status" in path): return s.get_status() if ("remove" in path): return s.remove(path) return "error" def remove(s, path): con = get_con() p = path.split("/") n = p[4].upper() c = con.cursor() c.execute("DELETE from nets where bssid = ?", (n,)) con.commit() c.execute("DELETE from work where net = ?", (n,)) con.commit() return "OK" def get_status(s): con = get_con() c = con.cursor() c.execute("SELECT * from clients") clients = [] for r in c.fetchall(): clients.append(r['speed']) nets = [] c.execute("SELECT * from dict where current = 1") dic = c.fetchone() c.execute("SELECT * from nets") for r in c.fetchall(): n = { "bssid" : r['bssid'] } if r['pass']: n["pass"] = r['pass'] if r['state'] != 2: n["tot"] = dic["lines"] did = 0 cur = con.cursor() cur.execute("""SELECT * from work where net = ? and dict = ? and state = 2""", (n['bssid'], dic['id'])) for row in cur.fetchall(): did += row['end'] - row['start'] n["did"] = did nets.append(n) d = { "clients" : clients, "nets" : nets } return json.dumps(d) def do_result_pass(s, net, pw): con = get_con() pf = "dcrack-pass.txt" f = open(pf, "w") f.write(pw) f.write("\n") f.close() cmd = ["aircrack-ng", "-w", pf, "-b", net, "-q", "dcrack.cap"] p = subprocess.Popen(cmd, stdout=subprocess.PIPE, \ stdin=subprocess.PIPE) res = p.communicate()[0] res = str(res) os.remove(pf) if not "KEY FOUND" in res: return "error" s.net_done(net) c = con.cursor() c.execute("UPDATE nets set pass = ? where bssid = ?", \ (pw, net)) con.commit() return "OK" def net_done(s, net): con = get_con() c = con.cursor() c.execute("UPDATE nets set state = 2 where bssid = ?", (net,)) c.execute("DELETE from work where net = ?", (net,)) con.commit() def do_result(s, path): con = get_con() p = path.split("/") n = p[4].upper() x = urlparse(path) qs = parse_qs(x.query) if "pass" in qs: return s.do_result_pass(n, qs['pass'][0]) wl = qs['wl'][0] c = con.cursor() c.execute("SELECT * from nets where bssid = ?", (n,)) r = c.fetchone() if r and r['state'] == 2: return "Already done" c.execute("""UPDATE work set state = 2 where net = ? and dict = ? and start = ? and end = ?""", (n, wl, qs['start'][0], qs['end'][0])) con.commit() if c.rowcount == 0: c.execute("""INSERT into work values (NULL, ?, ?, ?, ?, datetime(), 2)""", (n, wl, qs['start'][0], qs['end'][0])) con.commit() # check status c.execute("""SELECT * from work where net = ? and dict = ? and state = 2 order by start""", (n, wl)) i = 0 r = c.fetchall() for row in r: if i == row['start']: i = row['end'] else: break c.execute("SELECT * from dict where id = ? and lines = ?", (wl, i)) r = c.fetchone() if r: s.net_done(n) return "OK" def get_cap(s, path): return s.serve_file("dcrack.cap.gz") def get_dict(s, path): p = path.split("/") n = p[4] fn = "dcrack-dict-%s.txt.gz" % n return s.serve_file(fn) def serve_file(s, fn): s.send_response(200) s.send_header("Content-type", "application/x-gzip") s.end_headers() # XXX openat f = open(fn, "rb") s.wfile.write(f.read()) f.close() return None def do_crack(s, path): con = get_con() p = path.split("/") n = p[4].upper() c = con.cursor() c.execute("INSERT into nets values (?, NULL, 1)", (n,)) con.commit() return "OK" def do_dict_set(s, path): con = get_con() p = path.split("/") h = p[4] c = con.cursor() c.execute("UPDATE dict set current = 0") c.execute("UPDATE dict set current = 1 where id = ?", (h,)) con.commit() return "OK" def do_ping(s, path): con = get_con() p = path.split("/") cid = p[4] x = urlparse(path) qs = parse_qs(x.query) speed = qs['speed'][0] c = con.cursor() c.execute("SELECT * from clients where id = ?", (cid,)) r = c.fetchall() if (not r): c.execute("INSERT into clients values (?, ?, datetime())", (cid, int(speed))) else: c.execute("""UPDATE clients set speed = ?, last = datetime() where id = ?""", (int(speed), cid)) con.commit() return "60" def try_network(s, net, d): con = get_con() c = con.cursor() c.execute("""SELECT * from work where net = ? and dict = ? order by start""", (net['bssid'], d['id'])) r = c.fetchall() s = 5000000 i = 0 found = False for row in r: if found: if i + s > row['start']: s = row['start'] - i break if (i >= row['start'] and i <= row['end']): i = row['end'] else: found = True if i + s > d['lines']: s = d['lines'] - i if s == 0: return None c.execute("INSERT into work values (NULL, ?, ?, ?, ?, datetime(), 1)", (net['bssid'], d['id'], i, i + s)) con.commit() crack = { "net" : net['bssid'], \ "dict" : d['id'], \ "start" : i, \ "end" : i + s } j = json.dumps(crack) return j def do_getwork(s, path): con = get_con() c = con.cursor() c.execute("""DELETE from work where ((strftime('%s', datetime()) - strftime('%s', last)) > 3600) and state = 1""") con.commit() c.execute("SELECT * from dict where current = 1") d = c.fetchone() c.execute("SELECT * from nets where state = 1") r = c.fetchall() for row in r: res = s.try_network(row, d) if res: return res # try some old stuff c.execute("""select * from work where state = 1 order by last limit 1""") res = c.fetchone() if res: c.execute("DELETE from work where id = ?", (res['id'],)) for row in r: res = s.try_network(row, d) if res: return res res = { "interval" : "60" } return json.dumps(res) def do_dict_status(s, path): p = path.split("/") d = p[4] try: f = open("dcrack-dict-%s.txt" % d) f.close() return "OK" except: return "NO" def create_db(): con = get_con() c = con.cursor() c.execute("""create table clients (id varchar(255), speed integer, last datetime)""") c.execute("""create table dict (id varchar(255), lines integer, current boolean)""") c.execute("""create table nets (bssid varchar(255), pass varchar(255), state integer)""") c.execute("""create table work (id integer primary key, net varchar(255), dict varchar(255), start integer, end integer, last datetime, state integer)""") def connect_db(): con = sqlite3.connect('dcrack.db') con.row_factory = sqlite3.Row return con def get_con(): global tls try: return tls.con except: tls.con = connect_db() return tls.con def init_db(): con = get_con() c = con.cursor() try: c.execute("SELECT * from clients") except: create_db() def server(): init_db() server_class = ThreadingTCPServer httpd = server_class(('', port), ServerHandler) print("Starting server") httpd.serve_forever() def usage(): print("""dcrack v0.3 Usage: dcrack.py [MODE] server Runs coordinator client <server addr> Runs cracker cmd <server addr> [CMD] Sends a command to server [CMD] can be: dict <file> cap <file> crack <bssid> remove <bssid> status""") exit(1) def get_speed(): print("Getting speed") p = subprocess.Popen(["aircrack-ng", "-S"], stdout=subprocess.PIPE) speed = p.stdout.readline() speed = speed.split() speed = speed[len(speed) - 2] return int(speed) def get_cid(): return random.getrandbits(64) def do_ping(speed): global url, cid u = url + "client/" + str(cid) + "/ping?speed=" + str(speed) stuff = urlopen(u).read() interval = int(stuff) return interval def pinger(speed): while True: interval = try_ping(speed) time.sleep(interval) def try_ping(speed): while True: try: return do_ping(speed) except URLError: print("Conn refused (pinger)") time.sleep(60) def get_work(): global url, cid, cracker u = url + "client/" + str(cid) + "/getwork" stuff = urlopen(u).read() stuff = stuff.decode("utf-8") crack = json.loads(stuff) if "interval" in crack: print("Waiting") return int(crack['interval']) wl = setup_dict(crack) cap = get_cap(crack) print("Cracking") cmd = ["aircrack-ng", "-w", wl, "-b", crack['net'], "-q", cap] p = subprocess.Popen(cmd, stdout=subprocess.PIPE, \ stdin=subprocess.PIPE) cracker = p res = p.communicate()[0] res = str(res) cracker = None if ("not in dictionary" in res): print("No luck") u = "%snet/%s/result?wl=%s&start=%d&end=%d&found=0" % \ (url, crack['net'], crack['dict'], \ crack['start'], crack['end']) stuff = urlopen(u).read() elif "KEY FOUND" in res: pw = re.sub("^.*\[ ", "", res) i = pw.rfind(" ]") if i == -1: raise BaseException("Can't parse output") pw = pw[:i] print("Key for %s is %s" % (crack['net'], pw)) u = "%snet/%s/result?pass=%s" % (url, crack['net'], pw) stuff = urlopen(u).read() return 0 def decompress(fn): f = gzip.open(fn + ".gz") o = open(fn, "wb") o.writelines(f) o.close() f.close() def setup_dict(crack): global url d = crack['dict'] fn = "dcrack-client-dict-%s.txt" % d try: f = open(fn) f.close() except: print("Downloading dictionary %s" % d) u = "%sdict/%s" % (url, d) stuff = urlopen(u) f = open(fn + ".gz", "wb") f.write(stuff.read()) f.close() print("Uncompressing dictionary") decompress(fn) sha1 = hashlib.sha1() f = open(fn, "rb") sha1.update(f.read()) f.close() h = sha1.hexdigest() if h != d: print("bad dictionary") exit(1) s = "dcrack-client-dict-%s-%d:%d.txt" \ % (d, crack['start'], crack['end']) try: f = open(s) f.close() except: print("Splitting dict %s" % s) f = open(fn, "rb") o = open(s, "wb") for i, l in enumerate(f): if i >= crack['end']: break if i >= crack['start']: o.write(l) f.close() o.close() return s def get_cap(crack): global url, nets fn = "dcrack-client.cap" bssid = crack['net'].upper() if bssid in nets: return fn try: f = open(fn, "rb") f.close() check_cap(fn, bssid) except: pass if bssid in nets: return fn print("Downloading cap") u = "%scap/%s" % (url, bssid) stuff = urlopen(u) f = open(fn + ".gz", "wb") f.write(stuff.read()) f.close() print("Uncompressing cap") decompress(fn) nets = {} check_cap(fn, bssid) if bssid not in nets: raise BaseException("Can't find net %s" % bssid) return fn def process_cap(fn): global nets nets = {} print("Processing cap") p = subprocess.Popen(["aircrack-ng", fn], stdout=subprocess.PIPE, \ stdin=subprocess.PIPE) found = False while True: line = p.stdout.readline() try: line = line.decode("utf-8") except: line = str(line) if "1 handshake" in line: found = True parts = line.split() b = parts[1].upper() # print("BSSID [%s]" % b) nets[b] = True if (found and line == "\n"): break p.stdin.write(bytes("1\n", "utf-8")) p.communicate() def check_cap(fn, bssid): global nets cmd = ["aircrack-ng", "-b", bssid, fn] p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE) res = p.communicate()[0] res = str(res) if "No matching network found" not in res: nets[bssid] = True def worker(): while True: interval = get_work() time.sleep(interval) def set_url(): global url, port if len(sys.argv) < 3: print("Provide server addr") usage() host = sys.argv[2] if not ":" in host: host = "%s:%d" % (host, port) url = "http://" + host + "/" + "dcrack/" def client(): global cid, cracker, url set_url() url += "worker/" speed = get_speed() print("Speed", speed) cid = get_cid() print("CID", cid) try_ping(speed) t = threading.Thread(target=pinger, args=(speed,)) t.start() while True: try: do_client() break except URLError: print("Conn refused") time.sleep(60) def do_client(): try: worker() except KeyboardInterrupt: if cracker: cracker.kill() print("one more time...") def upload_file(url, f): x = urlparse(url) c = HTTPConnection(x.netloc) # XXX not quite HTTP form f = open(f, "rb") c.request("POST", x.path, f) res = c.getresponse() stuff = res.read() c.close() f.close() return stuff def compress_file(f): i = open(f, "rb") o = gzip.open(f + ".gz", "wb") o.writelines(i) o.close() i.close() def send_dict(): global url if len(sys.argv) < 5: print("Need dict") usage() d = sys.argv[4] print("Calculating dictionary hash for %s" % d) sha1 = hashlib.sha1() f = open(d, "rb") sha1.update(f.read()) f.close() h = sha1.hexdigest() print("Hash is %s" % h) u = url + "dict/" + h + "/status" stuff = urlopen(u).read() if "NO" in str(stuff): u = url + "dict/create" print("Compressing dictionary") compress_file(d) print("Uploading dictionary") upload_file(u, d + ".gz") print("Setting dictionary to %s" % d) u = url + "dict/" + h + "/set" stuff = urlopen(u).read() def send_cap(): global url if len(sys.argv) < 5: print("Need cap") usage() cap = sys.argv[4] print("Cleaning cap %s" % cap) subprocess.Popen(["wpaclean", cap + ".clean", cap], \ stderr=subprocess.STDOUT, stdout=subprocess.PIPE).communicate()[0] print("Compressing cap") compress_file(cap + ".clean") u = url + "cap/create" upload_file(u, cap + ".clean.gz") def cmd_crack(): net_cmd("crack") def net_cmd(op): global url if len(sys.argv) < 5: print("Need BSSID") usage() bssid = sys.argv[4] print("%s %s" % (op, bssid)) u = "%snet/%s/%s" % (url, bssid, op) stuff = urlopen(u).read() def cmd_remove(): net_cmd("remove") def cmd_status(): u = "%sstatus" % url stuff = urlopen(u).read() stuff = json.loads(stuff.decode("utf-8")) # print(stuff) # print("=============") i = 0 speed = 0 for c in stuff['clients']: i += 1 speed += c print("Clients\t%d\nSpeed\t%d\n" % (i, speed)) need = 0 for n in stuff['nets']: out = n['bssid'] + " " if "pass" in n: out += n['pass'] elif "did" in n: did = int(float(n['did']) / float(n['tot']) * 100.0) out += str(did) + "%" need += n['tot'] - n['did'] else: out += "-" print(out) if need != 0: print("\nKeys left %d" % need) if speed != 0: s = int(float(need) / float(speed)) sec = datetime.timedelta(seconds=s) d = datetime.datetime(1,1,1) + sec print("ETA %dh %dm" % (d.hour, d.minute)) def do_cmd(): global url set_url() url += "cmd/" if len(sys.argv) < 4: print("Need CMD") usage() cmd = sys.argv[3] if "dict" in cmd: send_dict() elif "cap" in cmd: send_cap() elif "crack" in cmd: cmd_crack() elif "status" in cmd: cmd_status() elif "remove" in cmd: cmd_remove() else: print("Unknown cmd %s" % cmd) usage() def main(): if len(sys.argv) < 2: usage() cmd = sys.argv[1] if cmd == "server": server() elif cmd == "client": client() elif cmd == "cmd": do_cmd() else: print("Unknown cmd", cmd) usage() exit(0) if __name__ == "__main__": main()
17,795
Python
.py
723
21.419087
73
0.618477
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,895
setup.py
pwnieexpress_raspberry_pwn/src/aircrack-ng-1.2-rc1/scripts/airdrop-ng/setup.py
#!/usr/bin/env python # This file is Copyright David Francos Cuartero, licensed under the GPL2 license. from distutils.core import setup import os setup(name='airdrop-ng', version='1.1', description='Rule based Deauth Tool', author='TheX1le', console = [{"script": "airdrop-ng" }], url='http://aircrack-ng.org', license='GPL2', classifiers=[ 'Development Status :: 4 - Beta', ], packages=['airdrop'], scripts=['airdrop-ng'], )
488
Python
.py
15
27.466667
81
0.645435
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,896
libDumpParse.py
pwnieexpress_raspberry_pwn/src/aircrack-ng-1.2-rc1/scripts/airdrop-ng/airdrop/libDumpParse.py
#!/usr/bin/python #airodump parsing lib #returns in an array of client and Ap information #part of the airdrop-ng project from sys import exit as Exit class airDumpParse: def parser(self,file): """ One Function to call to parse a file and return the information """ fileOpenResults = self.airDumpOpen(file) parsedResults = self.airDumpParse(fileOpenResults) capr = self.clientApChannelRelationship(parsedResults) rtrnList = [capr,parsedResults] return rtrnList def airDumpOpen(self,file): """ Takes one argument (the input file) and opens it for reading Returns a list full of data """ try: openedFile = open(file, "r") except IOError: print "Error Airodump File",file,"does not exist" Exit(1) data = openedFile.xreadlines() cleanedData = [] for line in data: cleanedData.append(line.rstrip()) openedFile.close() return cleanedData def airDumpParse(self,cleanedDump): """ Function takes parsed dump file list and does some more cleaning. Returns a list of 2 dictionaries (Clients and APs) """ try: #some very basic error handeling to make sure they are loading up the correct file try: apStart = cleanedDump.index('BSSID, First time seen, Last time seen, Channel, Speed, Privacy, Power, # beacons, # data, LAN IP, ESSID') except Exception: apStart = cleanedDump.index('BSSID, First time seen, Last time seen, channel, Speed, Privacy, Cipher, Authentication, Power, # beacons, # IV, LAN IP, ID-length, ESSID, Key') del cleanedDump[apStart] #remove the first line of text with the headings try: stationStart = cleanedDump.index('Station MAC, First time seen, Last time seen, Power, # packets, BSSID, Probed ESSIDs') except Exception: stationStart = cleanedDump.index('Station MAC, First time seen, Last time seen, Power, # packets, BSSID, ESSID') except Exception: print "You Seem to have provided an improper input file please make sure you are loading an airodump txt file and not a pcap" Exit(1) del cleanedDump[stationStart] #Remove the heading line clientList = cleanedDump[stationStart:] #Splits all client data into its own list del cleanedDump[stationStart:] #The remaining list is all of the AP information apDict = self.apTag(cleanedDump) clientDict = self.clientTag(clientList) resultDicts = [clientDict,apDict] #Put both dictionaries into a list return resultDicts def apTag(self,devices): """ Create a ap dictionary with tags of the data type on an incoming list """ dict = {} for entry in devices: ap = {} string_list = entry.split(',') #sorry for the clusterfuck but i swear it all makse sense this is builiding a dic from our list so we dont have to do postion calls later len(string_list) if len(string_list) == 15: ap = {"bssid":string_list[0].replace(' ',''), "fts":string_list[1], "lts":string_list[2], "channel":string_list[3].replace(' ',''), "speed":string_list[4], "privacy":string_list[5].replace(' ',''), "cipher":string_list[6], "auth":string_list[7], "power":string_list[8], "beacons":string_list[9], "iv":string_list[10], "ip":string_list[11], "id":string_list[12], "essid":string_list[13][1:], "key":string_list[14]} elif len(string_list) == 11: ap = {"bssid":string_list[0].replace(' ',''), "fts":string_list[1], "lts":string_list[2], "channel":string_list[3].replace(' ',''), "speed":string_list[4], "privacy":string_list[5].replace(' ',''), "power":string_list[6], "beacons":string_list[7], "data":string_list[8], "ip":string_list[9], "essid":string_list[10][1:]} if len(ap) != 0: dict[string_list[0]] = ap return dict def clientTag(self,devices): """ Create a client dictionary with tags of the data type on an incoming list """ dict = {} for entry in devices: client = {} string_list = entry.split(',') if len(string_list) >= 7: client = {"station":string_list[0].replace(' ',''), "fts":string_list[1], "lts":string_list[2], "power":string_list[3], "packets":string_list[4], "bssid":string_list[5].replace(' ',''), "probe":string_list[6:][0:]} if len(client) != 0: dict[string_list[0]] = client return dict def clientApChannelRelationship(self,data): """ parse the dic for the relationships of client to ap """ clients = data[0] AP = data[1] NA = [] #create a var to keep the not associdated clients NAP = [] #create a var to keep track of associated clients to AP's we cant see apCount = {} #count number of Aps dict is faster the list stored as BSSID:number of essids apClient = {} #dict that stores bssid and clients as a nested list for key in (clients): mac = clients[key] #mac is the MAC address of the client if mac["bssid"] != ' (notassociated) ': #one line of of our dictionary of clients if AP.has_key(mac["bssid"]): # if it is check to see its an AP we can see and have info on if apClient.has_key(mac["bssid"]): apClient[mac["bssid"]].extend([key]) #if key exists append new client else: apClient[mac["bssid"]] = [key] #create new key and append the client else: NAP.append(key) # stores the clients that are talking to an access point we cant see else: NA.append(key) #stores the lines of the not assocated AP's in a list return apClient
5,413
Python
.py
137
35.408759
177
0.687833
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,897
__init__.py
pwnieexpress_raspberry_pwn/src/aircrack-ng-1.2-rc1/scripts/airdrop-ng/airdrop/__init__.py
import os, sys class bcolors: """ class for using colored text """ HEADER = '\033[95m' #pink OKBLUE = '\033[94m' #blue OKGREEN = '\033[92m' #green WARNING = '\033[93m' #yellow FAIL = '\033[91m' #red ENDC = '\033[0m' #white def disable(self): """ fucntion to disable colored text """ self.HEADER = '' self.OKBLUE = '' self.OKGREEN = '' self.WARNING = '' self.FAIL = '' self.ENDC = '' encoding = sys.getfilesystemencoding() if hasattr(sys, 'frozen'): install_dir = os.path.abspath(os.path.dirname(unicode(sys.executable, encoding))) install_dir = os.path.abspath(os.path.dirname(unicode(__file__, encoding))) try: os.mkdir(install_dir + "/support") except: pass
803
Python
.py
29
21.965517
85
0.582361
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,898
libOuiParse.py
pwnieexpress_raspberry_pwn/src/aircrack-ng-1.2-rc1/scripts/airdrop-ng/airdrop/libOuiParse.py
#!/usr/bin/env python __author__ = 'Ben "TheX1le" Smith, Marfi' __email__ = 'thex1le@gmail.com' __website__= '' __date__ = '09/19/09' __version__ = '2009.11.23' __file__ = 'ouiParse.py' __data__ = 'a class for dealing with the oui txt file' """ ######################################## # # This program and its support programs are free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation; version 2. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # ######################################### """ from airdrop import install_dir import re import urllib2 import urllib import sys import os class macOUI_lookup: """ A class for deaing with OUIs and deterimining device type """ def __init__(self,oui=None,GetFile=False): """ generate the two dictionaries and return them """ aircrackOUI = None self.OUI_PATH = ["/etc/aircrack-ng/airodump-ng-oui.txt", "/usr/local/etc/aircrack-ng/airodump-ng-oui.txt", "/usr/share/aircrack-ng/airodump-ng-oui.txt", "/usr/share/misc/oui.txt", "/etc/manuf/oui.txt", "/usr/share/wireshark/wireshark/manuf/oui.txt", "/usr/share/wireshark/manuf/oui.txt"] # append any oui paths provided by program using lib to list if oui != None: self.OUI_PATH.append(oui) for PATH in self.OUI_PATH: if os.path.isfile(PATH): aircrackOUI=PATH if aircrackOUI == None: # default aircrackOUI=self.OUI_PATH[1] #a poor fix where if we have no file it trys to download it self.ouiTxtUrl = "http://standards.ieee.org/regauth/oui/oui.txt" self.ouiUnPath = install_dir#path to oui.txt if module is installed self.ouiInPath = install_dir + '/support/' #path to oui.txt if module is not installed self.ouiTxt = aircrackOUI self.ouiRaw = self.ouiOpen() self.oui_company = self.ouiParse() #dict where oui's are the keys to company names self.company_oui = self.companyParse() #dict where company name is the key to oui's def compKeyChk(self,name): """ check for valid company name key """ compMatch = re.compile(name,re.I) if self.company_oui.has_key(name): return True for key in self.company_oui.keys(): if compMatch.search(key) is not None: return True return False def ouiKeyChk(self,name): """ check for a valid oui prefix """ if self.oui_company.has_key(name): return True else: return False def lookup_OUI(self,mac): """ Lookup a oui and return the company name """ if self.ouiKeyChk(mac) is not False: return self.oui_company[mac][0] else: return False def lookup_company(self,companyLst): """ look up a company name and return their OUI's """ oui = [] if type(companyLst).__name__ == "list": for name in companyLst: compMatch = re.compile(name,re.I) if self.company_oui.has_key(name): oui.extend(self.company_oui[name]) else: for key in self.company_oui: if compMatch.search(key) is not None: oui.extend(self.company_oui[key]) elif type(companyLst).__name__ == "str": if self.company_oui.has_key(companyLst): oui = self.company_oui[companyLst] else: compMatch = re.compile(companyLst,re.I) for key in self.company_oui: if compMatch.search(key) is not None: oui.extend(self.company_oui[key]) #return the oui for that key return oui def ouiOpen(self): """ open the file and read it in """ ouiFile = open(self.ouiTxt, "r") text = ouiFile.readlines() #text = ouiFile.read() return text def ouiParse(self): """ generate a oui to company lookup dict """ HexOui= {} Hex = re.compile('.*(hex).*') #matches the following example "00-00-00 (hex)\t\tXEROX CORPORATION" ouiLines = self.ouiRaw for line in ouiLines: if Hex.search(line) != None: #return the matched text and build a list out of it lineList = Hex.search(line).group().replace("\t"," ").split(" ") #build a dict in the format of mac:company name HexOui[lineList[0].replace("-",":")] = [lineList[2]] return HexOui def companyParse(self): """ generate a company to oui lookup dict """ company_oui = {} for oui in self.oui_company: if company_oui.has_key(self.oui_company[oui][0]): company_oui[self.oui_company[oui][0]].append(oui) else: company_oui[self.oui_company[oui][0]] = [oui] return company_oui if __name__ == "__main__": import pdb # for testing x = macOUI_lookup() pdb.set_trace()
5,665
Python
.py
150
28.153333
104
0.569508
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,899
uninstall.py
pwnieexpress_raspberry_pwn/src/aircrack-ng-1.2-rc1/scripts/airdrop-ng/old-installers/uninstall.py
#!/usr/bin/env python __author__ = "Marfi" __version__ = "?" from os import system, geteuid from sys import exit if geteuid() != 0: print "airdrop-ng must be root. Please \n'su' or 'sudo -i' and run again. \nExiting..." exit(1) yno = raw_input ("You shouldn't need this. Remove? (y/n): ") if yno == "y": print "Removing man entry and airdrop-ng..." system ("sudo rm /usr/share/man/man1/airdrop-ng.1") system ("sudo rm /usr/bin/airdrop-ng") system ("sudo rm -r /usr/lib/airdrop-ng") else: print "Exiting..." exit()
525
Python
.py
17
29.294118
88
0.667984
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)