Debian Codegraph @

lib/diffview.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 #
3 # QBrz - Qt frontend to Breezy commands
4 # Copyright (C) 2007 Lukáš Lalinský <[email protected]om>
5 #
6 # This program is free software; you can redistribute it and/or
7 # modify it under the terms of the GNU General Public License
8 # as published by the Free Software Foundation; either version 2
9 # of the License, or (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19
20 from PyQt5 import QtCore, QtGui, QtWidgets
21
22 import re
23 from patiencediff import PatienceSequenceMatcher as SequenceMatcher
24 from breezy.plugins.qbrz.lib.i18n import gettext
25 from breezy.plugins.qbrz.lib.util import (
26 file_extension,
27 format_timestamp,
28 get_qbrz_config,
29 get_monospace_font,
30 get_tab_width_pixels,
31 )
32 from breezy.trace import mutter
33 from breezy.plugins.qbrz.lib.syntaxhighlighter import (
34 CachedTTypeFormater,
35 split_tokens_at_lines,
36 )
37 from breezy.plugins.qbrz.lib.widgets.texteditaccessory import (
38 GuideBarPanel, GBAR_LEFT, GBAR_RIGHT
39 )
40
41 have_pygments = True
42 try:
43 from pygments import lex
44 from pygments.util import ClassNotFound
45 from pygments.lexers import get_lexer_for_filename
46 except ImportError:
47 have_pygments = False
48
49 colors = {
50 'delete': [QtGui.QColor(255, 160, 180), QtGui.QColor(200, 60, 90)],
51 'insert': [QtGui.QColor(180, 255, 180), QtGui.QColor(80, 210, 80)],
52 'replace': [QtGui.QColor(206, 226, 250), QtGui.QColor(90, 130, 180)],
53 'blank': [QtGui.QColor(240, 240, 240), QtGui.QColor(171, 171, 171)],
54 'dummy': [QtGui.QColor(0, 0, 0, 0), QtGui.QColor(0, 0, 0, 0)],
55 }
56 # The background color of the replacement text in a replacement group.
57 interline_changes_background = QtGui.QColor(180, 210, 250)
58
59 # load user-defined color mapping from configuration file.
60
61 # For each kind, there can be two entries in the configuration file,
62 # under the [QDIFF COLORS] section:
63 # kind_bound -- the color of the boundary of the rectangle this kind refers to.
64 # kind_fill -- the color of the filling of that same rectangle.
65
66 config = get_qbrz_config()
67 component_dict = {0:'fill', 1:'bound'}
68 for key in colors.keys():
69 for comp in [0,1]:
70 color = None
71 try:
72 color = config.get_color(key + '_' + component_dict[comp], 'QDIFF COLORS')
73 except ValueError as msg:
74 # error handling.
75 mutter(str(msg))
76 if color is not None:
77 colors[key][comp] = color
78
79
80 # Get a user-defined replacement text background
81 try:
82 new_interline_bg = config.get_color('interline_changes_background',
83 'QDIFF COLORS')
84 if new_interline_bg is not None:
85 interline_changes_background = new_interline_bg
86 except ValueError as msg:
87 mutter(str(msg))
88
89 brushes = {}
90 for kind, cols in list(colors.items()):
91 brushes[kind] = (QtGui.QBrush(cols[0]), QtGui.QBrush(cols[1]))
92
93
94 class DiffSourceView(QtWidgets.QTextBrowser):
95 resized = QtCore.pyqtSignal()
96 # RJL added for qt5
97 documentChangeFinished = QtCore.pyqtSignal()
98
99 def __init__(self, parent=None):
100 QtWidgets.QTextBrowser.__init__(self, parent)
101 self.setLineWrapMode(QtWidgets.QTextEdit.NoWrap)
102 self.clear()
103 self.scrollbar = None
104 self.changes = []
105 self.infoBlocks = []
106
107 def clear(self):
108 self.changes = []
109 self.infoBlocks = []
110
111 def resizeEvent(self, event):
112 QtWidgets.QTextBrowser.resizeEvent(self, event)
113 self.resized.emit()
114
115 def paintEvent(self, event):
116 w = self.width()
117 y = self.verticalScrollBar().value()
118 painter = QtGui.QPainter(self.viewport())
119 painter.setClipRect(event.rect())
120 bot = event.rect().bottom()
121 top = event.rect().top()
122 pen = QtGui.QPen(QtCore.Qt.black)
123 pen.setWidth(2)
124 painter.setPen(pen)
125 for block_y in self.infoBlocks:
126 block_y = int(block_y - y)
127 if block_y < top:
128 continue
129 if block_y > bot:
130 break
131 painter.drawLine(0, block_y, w, block_y)
132
133 pen.setWidth(1)
134 for y_top, y_bot, kind in self.changes:
135 y_top = int(y_top - y)
136 y_bot = int(y_bot - y)
137 if y_top < top and y_bot < top:
138 continue
139 if y_top > bot and y_bot > bot:
140 break
141 painter.fillRect(0, y_top, w, y_bot - y_top, brushes[kind][0])
142 painter.setPen(colors[kind][1])
143 painter.drawLine(0, y_top, w, y_top)
144 painter.drawLine(0, y_bot - 1, w, y_bot - 1)
145 del painter
146 QtWidgets.QTextBrowser.paintEvent(self, event)
147
148 # def wheelEvent(self, event):
149 # if event.orientation() == QtCore.Qt.Vertical and self.scrollbar:
150 # self.scrollbar.wheelEvent(event)
151 # else:
152 # QtWidgets.QTextBrowser.wheelEvent(self, event)
153
154 def wheelEvent(self, event):
155 # RJLRJL orientation is no longer in qt5, so replaed with angleDelta().y() > 0
156 if event.angleDelta().y() > 0 and self.scrollbar:
157 self.scrollbar.wheelEvent(event)
158 else:
159 QtWidgets.QTextBrowser.wheelEvent(self, event)
160
161
162 class DiffViewHandle(QtWidgets.QSplitterHandle):
163
164 def __init__(self, parent=None):
165 QtWidgets.QSplitterHandle.__init__(self, QtCore.Qt.Horizontal, parent)
166 self.scrollbar = None
167 self.view = parent
168 self.changes = []
169 self.infoBlocks = []
170 self.clear()
171
172 def clear(self):
173 self.changes = []
174 self.infoBlocks = []
175
176 def paintEvent(self, event):
177 painter = QtGui.QPainter(self)
178 painter.setClipRect(event.rect())
179 frame = QtWidgets.QApplication.style().pixelMetric(QtWidgets.QStyle.PM_DefaultFrameWidth)
180 ly = self.view.browsers[0].verticalScrollBar().value() - frame
181 ry = self.view.browsers[1].verticalScrollBar().value() - frame
182 w = self.width()
183 h = self.height()
184 painter.setRenderHints(QtGui.QPainter.Antialiasing, True)
185
186 curve_factor = 16
187
188 def create_line(ly, ry, right_to_left=False):
189 """
190 Create path which represents upper or lower line of change marker.
191 """
192 line = QtGui.QPainterPath()
193 if not right_to_left:
194 line.moveTo(0, ly)
195 line.cubicTo(curve_factor, ly, w - curve_factor, ry, w, ry)
196 else:
197 line.moveTo(w, ry)
198 line.cubicTo(w - curve_factor, ry, curve_factor, ly, 0, ly)
199 return line
200
201 pen = QtGui.QPen(QtCore.Qt.black)
202 pen.setWidth(2)
203 painter.setPen(pen)
204 for block_ly, block_ry in self.infoBlocks:
205 block_ly -= ly
206 block_ry -= ry
207 if block_ly < 0 and block_ry < 0:
208 continue
209 if block_ly > h and block_ry > h:
210 break
211
212 painter.drawPath(create_line(block_ly, block_ry))
213
214 for ly_top, ly_bot, ry_top, ry_bot, kind in self.changes:
215 ly_top -= ly
216 ly_bot -= ly + 1
217 ry_top -= ry
218 ry_bot -= ry + 1
219
220 if ly_top < 0 and ly_bot < 0 and ry_top < 0 and ry_bot < 0:
221 continue
222 if ly_top > h and ly_bot > h and ry_top > h and ry_bot > h:
223 break
224
225 upper_line = create_line(ly_top, ry_top)
226 lower_line = create_line(ly_bot, ry_bot, True)
227
228 region = QtGui.QPainterPath()
229 region.moveTo(0, ly_top)
230 region.connectPath(upper_line)
231 region.lineTo(w, ry_bot)
232 region.connectPath(lower_line)
233 region.closeSubpath()
234
235 painter.fillPath(region, brushes[kind][0])
236 painter.setPen(colors[kind][1])
237 for path, aa in zip((upper_line, lower_line),
238 (ly_top != ry_top, ly_bot != ry_bot)):
239 painter.setRenderHints(QtGui.QPainter.Antialiasing, aa)
240 painter.drawPath(path)
241 del painter
242
243 def wheelEvent(self, event):
244 # RJL orientation is now obsolete
245 # if event.orientation() == QtCore.Qt.Vertical:
246 # angleDelta().y() provides the angle through which the common
247 # vertical mouse wheel was rotated since the previous event.
248 # angleDelta().x() provides the angle through which the horizontal
249 # mouse wheel was rotated, if the mouse has a horizontal wheel;
250 # otherwise it stays at zero.
251 # We'll be vertical if y_delta is non-zero x_delta is zero...
252 if event.angleDelta().y() and not event.angleDelta().x():
253 self.view.scrollbar.wheelEvent(event)
254 else:
255 QtWidgets.QSplitterHandle.wheelEvent(self, event)
256
257
258 class SidebySideDiffView(QtWidgets.QFrame):
259 def __init__(self, parent=None):
260 QtWidgets.QFrame.__init__(self, parent)
261 hbox = QtWidgets.QHBoxLayout(self)
262 hbox.setContentsMargins(0, 0, 0, 0)
263 hbox.setSpacing(0)
264 self.view = _SidebySideDiffView(parent)
265 self.browsers = self.view.browsers
266 hbox.addWidget(self.view)
267 hbox.addWidget(self.view.scrollbar)
268
269 def __getattr__(self, name):
270 """Delegate unknown methods to internal diffview."""
271 return getattr(self.view, name)
272
273
274 SYNC_POSITION = 0.4
275
276
277 class SidebySideDiffViewScrollBar(QtWidgets.QScrollBar):
278 def __init__(self, handle, browsers):
279 QtWidgets.QScrollBar.__init__(self)
280 self.handle = handle
281 self.browsers = browsers
282 self.total_length = 0
283 self.changes = []
284 self.complete = False
285
286 for b in browsers:
287 b.scrollbar = self
288
289 for i, scbar in enumerate([self] + [b.verticalScrollBar() for b in browsers]):
290 scbar.valueChanged[int].connect(lambda value, target=i : self.scrolled(target))
291
292 browsers[0].resized.connect(self.adjust_range)
293 self.setSingleStep(browsers[0].verticalScrollBar().singleStep())
294 self.adjust_range()
295 self.syncing = False
296 self.gap_with_left = 0
297
298 def clear(self):
299 self.gap_with_left = 0
300 self.total_length = 0
301 self.changes = []
302
303 def set_complete(self, complete):
304 if self.complete != complete:
305 self.complete = complete
306 self.clear()
307
308 def adjust_range(self):
309 page_step = self.browsers[0].verticalScrollBar().pageStep()
310 self.setPageStep(page_step)
311 self.setRange(0, int(self.total_length - page_step + 4))
312 self.setVisible(self.total_length > page_step)
313
314 def get_position_info(self, target):
315 """
316 Get position info should scroll to.
317 target: 0 is self, 1 is left browser, 2 is right browser
318 """
319 basis_y = self.height() * SYNC_POSITION
320 if target == 0:
321 scbar = self
322 changes = self.changes
323 else:
324 b = self.browsers[target - 1]
325 scbar, changes = b.verticalScrollBar(), b.changes
326
327 if not self.complete:
328 return 'exact', scbar.value()
329 else:
330 value = scbar.value() + basis_y
331 prev = (0, 0, None)
332 for i, ch in enumerate(changes):
333 if value <= ch[1]:
334 if ch[0] <= value:
335 ratio = float(value - ch[0]) / (ch[1] - ch[0])
336 return 'in', i, ratio
337 else:
338 offset = value - prev[1]
339 return 'after', i - 1, offset
340 break
341 else:
342 prev = ch
343 else:
344 offset = value - prev[1]
345 return 'after', len(self.changes) - 1, offset
346
347 def scroll_to(self, target: int, position):
348 """
349 Scroll to specified position.
350 target: 0 is self, 1 is left browser, 2 is right browser
351 """
352 basis_y: float = self.height() * SYNC_POSITION
353 if target == 0:
354 scbar, changes = self, self.changes
355 else:
356 b = self.browsers[target - 1]
357 scbar, changes = b.verticalScrollBar(), b.changes
358 if position[0] == 'exact':
359 scbar.setValue(position[1])
360 elif position[0] == 'in':
361 change_idx, ratio = position[1:]
362 start, end = changes[change_idx][:2]
363 # scbar.setValue(start + float(end - start) * ratio - basis_y)
364 scbar.setValue(int(start + float(end - start) * ratio - basis_y))
365 else:
366 change_idx, offset = position[1:]
367 if change_idx < 0:
368 start = 0
369 else:
370 start = changes[change_idx][1]
371 # scbar.setValue(start + offset - basis_y)
372 scbar.setValue(int(start + offset - basis_y))
373
374 def scrolled(self, target):
375 if self.syncing:
376 return
377 try:
378 self.syncing = True
379 position = self.get_position_info(target)
380 for t in range(3):
381 if t != target:
382 self.scroll_to(t, position)
383 self.handle.update()
384 finally:
385 self.syncing = False
386
387 def append_change(self, l_top, l_bot, r_top, r_bot, kind):
388 if not self.complete:
389 return
390 changes = self.changes
391 height = max(l_bot - l_top, r_bot - r_top)
392 top = l_top + self.gap_with_left
393 changes.append((top, top + height, kind))
394 self.gap_with_left = top + height - l_bot
395
396 def fix_document_length(self, cursors):
397 if not self.complete:
398 scbar = self.browsers[0].verticalScrollBar()
399 self.total_length = scbar.maximum() + scbar.pageStep()
400 else:
401 l = cursors[0].block().layout()
402 self.total_length = l.position().y() + l.boundingRect().height() + self.gap_with_left
403 self.adjust_range()
404
405
406 def setup_guidebar_entries(gb):
407 gb.add_entry('title', QtGui.QColor(80, 80, 80), -1)
408 for tag in ('delete', 'insert', 'replace'):
409 gb.add_entry(tag, colors[tag][0], 0)
410
411
412 class _SidebySideDiffView(QtWidgets.QSplitter):
413 """Widget to show differences in side-by-side format."""
414
415 def __init__(self, parent=None):
416 QtWidgets.QSplitter.__init__(self, QtCore.Qt.Horizontal, parent)
417 self.setHandleWidth(30)
418 self.complete = False
419
420 titleFont = QtGui.QFont(self.font())
421 titleFont.setPointSizeF(titleFont.pointSizeF() * 140 / 100)
422 titleFont.setBold(True)
423
424 self.monospacedFont = get_monospace_font()
425 metadataFont = QtGui.QFont(self.font())
426 metadataFont.setPointSizeF(titleFont.pointSizeF() * 70 / 100)
427 metadataLabelFont = QtGui.QFont(metadataFont)
428 metadataLabelFont.setBold(True)
429
430 self.monospacedFormat = QtGui.QTextCharFormat()
431 self.monospacedFormat.setFont(self.monospacedFont)
432 self.ttype_formater = CachedTTypeFormater(QtGui.QTextCharFormat(self.monospacedFormat))
433 self.background = self.monospacedFormat.background()
434
435 self.titleFormat = QtGui.QTextCharFormat()
436 self.titleFormat.setFont(titleFont)
437 self.metadataFormat = QtGui.QTextCharFormat()
438 self.metadataFormat.setFont(metadataFont)
439 self.metadataLabelFormat = QtGui.QTextCharFormat()
440 self.metadataLabelFormat.setFont(metadataLabelFont)
441
442 self.docs = (QtGui.QTextDocument(), QtGui.QTextDocument())
443 self.browsers = (DiffSourceView(self), DiffSourceView(self))
444
445 self.guidebar_panels = [
446 GuideBarPanel(b, align=a)
447 for (b, a) in zip(self.browsers, (GBAR_LEFT, GBAR_RIGHT))
448 ]
449 for g in self.guidebar_panels:
450 setup_guidebar_entries(g.bar)
451
452 self.reset_guidebar_data()
453
454 for b in self.browsers:
455 b.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
456
457 self.cursors = [QtGui.QTextCursor(doc) for doc in self.docs]
458
459 for i, (panel, doc, cursor) in enumerate(zip(self.guidebar_panels,
460 self.docs, self.cursors)):
461 doc.setUndoRedoEnabled(False)
462 doc.setDefaultFont(self.monospacedFont)
463
464 panel.edit.setDocument(doc)
465 self.addWidget(panel)
466 self.setCollapsible(i, False)
467
468 char_format = QtGui.QTextCharFormat()
469 char_format.setAnchorNames(["top"])
470 cursor.insertText("", char_format)
471
472 self.scrollbar = SidebySideDiffViewScrollBar(self.handle(1), self.browsers)
473
474 self.ignoreUpdate = False
475 self.browsers[0].horizontalScrollBar().valueChanged[int].connect(self.syncHorizontalSlider1)
476 self.browsers[1].horizontalScrollBar().valueChanged[int].connect(self.syncHorizontalSlider2)
477
478 self.rewinded = False
479
480 self.lastModifiedLabel = gettext('Last modified:')
481 self.statusLabel = gettext('Status:')
482 self.kindLabel = gettext('Kind:')
483 self.propertiesLabel = gettext('Properties:')
484
485 self.image_exts = ['.'+str(i)
486 for i in QtGui.QImageReader.supportedImageFormats()]
487
488 config = get_qbrz_config()
489 self.show_intergroup_colors = config.get_option("diff_show_intergroup_colors") in ("True", "1")
490
491 def setTabStopWidths(self, pixels):
492 for (pixel_width, browser) in zip(pixels, self.browsers):
493 browser.setTabStopWidth(pixel_width)
494
495 def reset_guidebar_data(self):
496 self.guidebar_data = [
497 dict(title=[], delete=[], insert=[], replace=[]), # for left view
498 dict(title=[], delete=[], insert=[], replace=[]), # for right view
499 ]
500
501 def clear(self):
502 self.browsers[0].clear()
503 self.browsers[1].clear()
504 self.handle(1).clear()
505 self.scrollbar.clear()
506 for doc in self.docs:
507 doc.clear()
508 self.reset_guidebar_data()
509 self.update()
510
511 def set_complete(self, complete):
512 if self.complete != complete:
513 self.complete = complete
514 self.clear()
515 self.scrollbar.set_complete(complete)
516
517 def append_diff(self, paths, file_id, kind, status, dates,
518 present, binary, lines, groups, data, properties_changed):
519 cursors = self.cursors
520
521 guidebar_data = self.guidebar_data
522
523 for i in range(2):
524 cursor = cursors[i]
525 guidebar_data[i]['title'].append((cursor.block().blockNumber(), 2))
526 cursor.beginEditBlock()
527 cursor.insertText(paths[i] or " ", self.titleFormat) # None or " " => " "
528 cursor.insertBlock()
529 if present[i]:
530 cursor.insertText(self.lastModifiedLabel, self.metadataLabelFormat)
531 cursor.insertText(" %s, " % format_timestamp(dates[i]), self.metadataFormat)
532 cursor.insertText(self.statusLabel, self.metadataLabelFormat)
533 cursor.insertText(" %s, " % gettext(status), self.metadataFormat)
534 cursor.insertText(self.kindLabel, self.metadataLabelFormat)
535 cursor.insertText(" %s" % gettext(kind[i]), self.metadataFormat)
536 if properties_changed:
537 cursor.insertText(", ", self.metadataFormat)
538 cursor.insertText(self.propertiesLabel, self.metadataLabelFormat)
539 cursor.insertText(" ", self.metadataFormat)
540 cursor.insertText(", ".join([p[i] for p in properties_changed]), self.metadataFormat)
541 else:
542 cursor.insertText(" ", self.metadataFormat)
543 cursor.insertBlock()
544
545 infoBlocks = (cursors[0].block().layout(),
546 cursors[1].block().layout())
547 changes = []
548
549 if not binary:
550 for cursor in cursors:
551 cursor.setCharFormat(self.monospacedFormat)
552 cursor.insertBlock()
553
554 def fix_last_line(lines):
555 """Fix last line if there is no new line.
556
557 @param lines: list of lines
558 @return: original lines if lastline is OK,
559 or new list with fixed last line.
560 """
561 if lines:
562 last = lines[-1]
563 if last and last[-1] not in ('\r', '\n'):
564 lines = lines[:-1] + [last+'\n']
565 return lines
566
567 lines = [fix_last_line(l) for l in lines]
568 if have_pygments:
569 use_pygments = True
570 try:
571 def getTokens(p, d, path):
572 if not p:
573 return []
574 lexer = get_lexer_for_filename(path, stripnl=False)
575 tokens = []
576 for token in split_tokens_at_lines(lex(d, lexer)):
577 tokens.append(token)
578 if len(token) % 100 == 0:
579 QtCore.QCoreApplication.processEvents()
580 return tokens
581
582 display_lines = [getTokens(p, d, path)
583 for p, d, path in zip(present, data, paths)]
584 except ClassNotFound:
585 use_pygments = False
586 display_lines = lines
587 else:
588 use_pygments = False
589 display_lines = lines
590
591 def insertLine(cursor, line):
592 if use_pygments:
593 for ttype, value in line:
594 ttype_format = self.ttype_formater.format(ttype)
595 modifyFormatForTag(ttype_format, "equal")
596 cursor.insertText(value, ttype_format)
597 else:
598 cursor.insertText(line)
599
600 def insertIxs(ixs):
601 for cursor, line, ix in zip(cursors, display_lines, ixs):
602 for l in line[ix[0]:ix[1]]:
603 insertLine(cursor, l)
604
605 def modifyFormatForTag(type_format, tag):
606 if tag == "replace":
607 type_format.setBackground(interline_changes_background)
608 elif tag == "equal":
609 type_format.setBackground(self.background)
610 elif self.show_intergroup_colors:
611 type_format.setBackground(brushes[tag][0])
612 else:
613 type_format.setBackground(interline_changes_background)
614
615 split_words = re.compile(r"\w+|\n\r|\r\n|\W")
616
617 def insertIxsWithChangesHighlighted(ixs):
618 texts = ["".join(l[ix[0]:ix[1]]) for l, ix in zip(lines, ixs)]
619 if use_pygments:
620 # This is what the pygments lexer does, so we need to do the
621 # same incase we have \r\n line endings.
622 texts = ["\n".join(t.splitlines()) for t in texts]
623
624 texts = [split_words.findall(t) for t in texts]
625
626 if use_pygments:
627 groups = ([], [])
628 for tag, i0, i1, j0, j1 in SequenceMatcher(None,
629 tuple(texts[0]),
630 tuple(texts[1]),
631 ).get_opcodes():
632 groups[0].append((tag, len("".join(texts[0][i0:i1]))))
633 groups[1].append((tag, len("".join(texts[1][j0:j1]))))
634 for cursor, ls, ix, g in zip(cursors, display_lines, ixs, groups):
635 tag, n = g.pop(0)
636 for l in ls[ix[0]:ix[1]]:
637 for ttype, value in l:
638 while value:
639 ttype_format = self.ttype_formater.format(ttype)
640 modifyFormatForTag(ttype_format, tag)
641 t = value[0:n]
642 cursor.insertText(t, ttype_format)
643 value = value[len(t):]
644 n -= len(t)
645 if n <= 0:
646 if g:
647 tag, n = g.pop(0)
648 else:
649 # why would this happen?????
650 tag = 'equal'
651 n = len(value)
652 else:
653 for tag, i0, i1, j0, j1 in SequenceMatcher(None,
654 tuple(texts[0]),
655 tuple(texts[1]),
656 ).get_opcodes():
657 ttype_format = QtGui.QTextCharFormat()
658 ttype_format.setFont(self.monospacedFont)
659 modifyFormatForTag(ttype_format, tag)
660
661 cursors[0].insertText("".join(texts[0][i0:i1]),ttype_format)
662 cursors[1].insertText("".join(texts[1][j0:j1]),ttype_format)
663
664 for cursor in cursors:
665 cursor.setCharFormat (self.monospacedFormat)
666
667 for i, group in enumerate(groups):
668 if i > 0:
669 y_top = [cursor.block().layout() for cursor in self.cursors]
670 for cursor in cursors:
671 cursor.insertBlock()
672 t_bot = [cursor.block().layout() for cursor in self.cursors]
673 changes.append((y_top[0], t_bot[0], y_top[1], t_bot[1], 'blank'))
674 linediff = 0
675 for g in group:
676 tag = g[0]
677 # indexes
678 ixs = ((g[1], g[2]), (g[3], g[4]))
679 n = [ix[1]-ix[0] for ix in ixs]
680 if tag == "equal":
681 insertIxs(ixs)
682 else:
683 y_top = [cursor.block().layout() for cursor in self.cursors]
684 g_top = [cursor.block().blockNumber() for cursor in self.cursors]
685 if tag == "replace":
686 insertIxsWithChangesHighlighted(ixs)
687 else:
688 insertIxs(ixs)
689 linediff += n[0] - n[1]
690 y_bot = [cursor.block().layout() for cursor in self.cursors]
691 changes.append((y_top[0], y_bot[0], y_top[1], y_bot[1], tag))
692
693 g_bot = [cursor.block().blockNumber() for cursor in self.cursors]
694 for data, top, bot in zip(guidebar_data, g_top, g_bot):
695 data[tag].append((top, bot - top))
696
697 if linediff == 0:
698 continue
699 if not self.complete:
700 if linediff < 0:
701 i0 = group[-1][2]
702 i1 = i0 - linediff
703 exlines = display_lines[0][i0:i1]
704 linediff = -linediff - len(exlines)
705 cursor = cursors[0]
706 else:
707 j0 = group[-1][4]
708 j1 = j0 + linediff
709 exlines = display_lines[1][j0:j1]
710 linediff = linediff - len(exlines)
711 cursor = cursors[1]
712 for l in exlines:
713 insertLine(cursor, l)
714
715 if i % 100 == 0:
716 QtCore.QCoreApplication.processEvents()
717 else:
718 y_top = [cursor.block().layout() for cursor in self.cursors]
719 heights = [0,0]
720 is_images = [False, False]
721 for i in range(2):
722 if present[i]:
723 ext = file_extension(paths[i]).lower()
724 if ext in self.image_exts:
725 is_images[i] = True
726 image = QtGui.QImage()
727 image.loadFromData(data[i])
728 heights[i] = image.height()
729 self.docs[i].addResource(QtGui.QTextDocument.ImageResource,
730 QtCore.QUrl(file_id),
731 image)
732
733 max_height = max(heights)
734 for i, cursor in enumerate(self.cursors):
735 block_format = QtGui.QTextBlockFormat()
736 block_format.setBottomMargin((max_height - heights[i])/2)
737 block_format.setTopMargin((max_height - heights[i])/2)
738 cursor.insertBlock(block_format)
739 if present[i]:
740 if is_images[i]:
741 cursor.insertImage(file_id)
742 else:
743 cursor.insertText(gettext('[binary file (%d bytes)]') % len(data[i]))
744 else:
745 cursor.insertText(" ")
746 cursor.insertBlock(QtGui.QTextBlockFormat())
747 y_bot = [cursor.block().layout() for cursor in self.cursors]
748 changes.append((y_top[0], y_bot[0], y_top[1], y_bot[1], 'dummy'))
749
750 for cursor in cursors:
751 cursor.endEditBlock()
752 cursor.insertText("\n")
753 y_top = [cursor.block().layout() for cursor in self.cursors]
754 if not self.complete:
755 maxy = max([l.position().y() for l in y_top])
756 for cursor in cursors:
757 block_format = QtGui.QTextBlockFormat()
758 block_format.setBottomMargin(maxy-cursor.block().layout().position().y())
759 cursor.setBlockFormat(block_format)
760 cursor.insertBlock(QtGui.QTextBlockFormat())
761
762 l_block = infoBlocks[0].position().y()
763 r_block = infoBlocks[1].position().y()
764 self.browsers[0].infoBlocks.append(l_block)
765 self.browsers[1].infoBlocks.append(r_block)
766 self.handle(1).infoBlocks.append((l_block, r_block))
767
768 for (ly_top, ly_bot, ry_top, ry_bot, kind) in changes:
769 ly_top = ly_top.position().y() - 1
770 ly_bot = ly_bot.position().y() + 1
771 ry_top = ry_top.position().y() - 1
772 ry_bot = ry_bot.position().y() + 1
773 self.scrollbar.append_change(ly_top, ly_bot, ry_top, ry_bot, kind)
774 self.browsers[0].changes.append((ly_top, ly_bot, kind))
775 self.browsers[1].changes.append((ry_top, ry_bot, kind))
776 self.handle(1).changes.append((ly_top, ly_bot, ry_top, ry_bot, kind))
777 self.scrollbar.fix_document_length(cursors)
778
779 # check horizontal scrollbars and force both if scrollbar visible only at one side
780 if (self.browsers[0].horizontalScrollBar().isVisible()
781 or self.browsers[1].horizontalScrollBar().isVisible()):
782 self.browsers[0].setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
783 self.browsers[1].setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
784
785 self.update_guidebar()
786 self.update()
787
788 def rewind(self):
789 if not self.rewinded:
790 self.rewinded = True
791 self.browsers[0].scrollToAnchor("top")
792 self.browsers[1].scrollToAnchor("top")
793
794 def _syncSliders(self, slider1, slider2, value):
795 m = slider1.maximum()
796 if m:
797 value = slider2.minimum() + slider2.maximum() * (value - slider1.minimum()) / m
798 self.ignoreUpdate = True
799 slider2.setValue(int(value))
800 self.ignoreUpdate = False
801
802 def syncHorizontalSlider1(self, value):
803 if not self.ignoreUpdate:
804 slider1 = self.browsers[0].horizontalScrollBar()
805 slider2 = self.browsers[1].horizontalScrollBar()
806 self._syncSliders(slider1, slider2, value)
807 self.handle(1).update()
808
809 def syncHorizontalSlider2(self, value):
810 if not self.ignoreUpdate:
811 slider1 = self.browsers[0].horizontalScrollBar()
812 slider2 = self.browsers[1].horizontalScrollBar()
813 self._syncSliders(slider2, slider1, value)
814 self.handle(1).update()
815
816 def createHandle(self):
817 return DiffViewHandle(self)
818
819 def update_guidebar(self):
820 for gb, data in zip(self.guidebar_panels, self.guidebar_data):
821 gb.bar.update_data(**data)
822
823
824 class SimpleDiffView(GuideBarPanel):
825 def __init__(self, parent):
826 self.view = _SimpleDiffView(parent)
827 GuideBarPanel.__init__(self, self.view, parent=parent)
828 setup_guidebar_entries(self)
829
830 def append_diff(self, *args, **kwargs):
831 self.view.append_diff(*args, **kwargs)
832 self.update_data(**self.view.guidebar_data)
833
834 def __getattr__(self, name):
835 """Delegate unknown methods to internal diffview."""
836 return getattr(self.view, name)
837
838
839 class _SimpleDiffView(QtWidgets.QTextBrowser):
840 """Widget to show differences in unidiff format."""
841 documentChangeFinished = QtCore.pyqtSignal()
842
843 def __init__(self, parent=None):
844 QtWidgets.QTextBrowser.__init__(self, parent)
845 self.doc = QtGui.QTextDocument(parent)
846 self.doc.setUndoRedoEnabled(False)
847 self.setDocument(self.doc)
848 option = self.doc.defaultTextOption()
849 option.setWrapMode(QtGui.QTextOption.NoWrap)
850 self.doc.setDefaultTextOption(option)
851 self.rewinded = False
852 self.cursor = QtGui.QTextCursor(self.doc)
853 char_format = QtGui.QTextCharFormat()
854 char_format.setAnchorNames(["top"])
855 self.cursor.insertText("", char_format)
856 monospacedFont = get_monospace_font()
857 self.monospacedFormat = QtGui.QTextCharFormat()
858 self.monospacedFormat.setFont(monospacedFont)
859
860 self.monospacedInsertFormat = QtGui.QTextCharFormat(self.monospacedFormat)
861 self.monospacedInsertFormat.setForeground(QtGui.QColor(0, 136, 11))
862 self.monospacedDeleteFormat = QtGui.QTextCharFormat(self.monospacedFormat)
863 self.monospacedDeleteFormat.setForeground(QtGui.QColor(204, 0, 0))
864
865 monospacedBoldFont = QtGui.QFont(monospacedFont)
866 monospacedBoldFont.setBold(True)
867
868 monospacedItalicFont = QtGui.QFont(monospacedFont)
869 monospacedItalicFont.setItalic(True)
870
871 self.monospacedBoldInsertFormat = QtGui.QTextCharFormat(self.monospacedInsertFormat)
872 self.monospacedBoldInsertFormat.setFont(monospacedBoldFont)
873 self.monospacedBoldDeleteFormat = QtGui.QTextCharFormat(self.monospacedDeleteFormat)
874 self.monospacedBoldDeleteFormat.setFont(monospacedBoldFont)
875
876 self.monospacedHeaderFormat = QtGui.QTextCharFormat()
877 self.monospacedHeaderFormat.setFont(monospacedBoldFont)
878 self.monospacedHeaderFormat.setBackground(QtGui.QColor(246, 245, 238))
879 self.monospacedHeaderFormat.setForeground(QtGui.QColor(117, 117, 117))
880
881 self.monospacedHunkFormat = QtGui.QTextCharFormat()
882 self.monospacedHunkFormat.setFont(monospacedItalicFont)
883 self.monospacedHunkFormat.setForeground(QtGui.QColor(153, 30, 199))
884
885 self.reset_guidebar_data()
886
887 def rewind(self):
888 if not self.rewinded:
889 self.rewinded = True
890 self.scrollToAnchor("top")
891
892 def set_complete(self, complete):
893 self.clear()
894
895 def append_diff(self, paths, file_id, kind, status, dates, present, binary, lines, groups, data, properties_changed):
896 guidebar_data = self.guidebar_data
897 guidebar_data['title'].append((self.cursor.block().blockNumber(), 2))
898 self.cursor.beginEditBlock()
899 path_info = paths[1] or paths[0]
900 if status in ('renamed', 'renamed and modified'):
901 path_info = paths[0] + ' => ' + paths[1]
902 kind_info = kind[0] or kind[1]
903 self.cursor.insertText("=== %s %s %s" % (gettext(status),
904 gettext(kind_info), path_info),
905 self.monospacedHeaderFormat)
906 if properties_changed:
907 prop_str = []
908 for pair in properties_changed:
909 if None not in pair:
910 prop_str.append("%s to %s" % pair)
911 if prop_str:
912 self.cursor.insertText(" (properties changed: %s)" % (", ".join(prop_str)))
913 self.cursor.insertText("\n")
914
915 # GNU Patch uses the epoch date to detect files that are being added
916 # or removed in a diff.
917 EPOCH_DATE = '1970-01-01 00:00:00 +0000'
918 for i in range(2):
919 if present[i]:
920 dates[i] = timestamp.format_patch_date(dates[i])
921 else:
922 paths[i] = paths[(i+1)%2]
923 dates[i] = EPOCH_DATE
924
925 if not binary:
926 self.cursor.insertText('--- %s\t%s\n' % (paths[0], dates[0]), self.monospacedBoldInsertFormat)
927 self.cursor.insertText('+++ %s\t%s\n' % (paths[1], dates[1]), self.monospacedBoldDeleteFormat)
928
929 def fix_last_line(lines):
930 """Fix last line if there is no new line.
931
932 @param lines: original list of lines
933 @return: lines if lastline is OK,
934 or new list with fixed last line.
935 """
936 if lines:
937 last = lines[-1]
938 if last and last[-1] not in ('\r', '\n'):
939 last += ('\n' + gettext('\\ No newline at end of file') + '\n')
940 lines = lines[:-1] + [last]
941 return lines
942
943 a = fix_last_line(lines[0])
944 b = fix_last_line(lines[1])
945
946 for i, group in enumerate(groups):
947 if group:
948 i0, i1, j0, j1 = \
949 group[0][1], group[-1][2], group[0][3], group[-1][4]
950 self.cursor.insertText(
951 "@@ -%d,%d +%d,%d @@\n" % (i0+1, i1-i0, j0+1, j1-j0), self.monospacedHunkFormat)
952 for tag, i0, i1, j0, j1 in group:
953 if tag == "equal":
954 text = "".join(" " + l for l in a[i0:i1])
955 self.cursor.insertText(text, self.monospacedFormat)
956 else:
957 start = self.cursor.block().blockNumber()
958 text = "".join("-" + l for l in a[i0:i1])
959 self.cursor.insertText(text, self.monospacedDeleteFormat)
960 text = "".join("+" + l for l in b[j0:j1])
961 self.cursor.insertText(text, self.monospacedInsertFormat)
962 end = self.cursor.block().blockNumber()
963 guidebar_data[tag].append((start, end - start))
964 else:
965 self.cursor.insertText("Binary files %s %s and %s %s differ\n" % (paths[0], dates[0], paths[1], dates[1]))
966 self.cursor.insertText("\n")
967 self.cursor.endEditBlock()
968 self.update()
969
970 def clear(self):
971 QtWidgets.QTextBrowser.clear(self)
972 self.reset_guidebar_data()
973
974 def reset_guidebar_data(self):
975 self.guidebar_data = dict(title=[], delete=[], insert=[], replace=[])