Debian Codegraph @

lib/annotate.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 #
3 # QBrz - Qt frontend to Breezy commands
4 # Copyright (C) 2006 Lukáš Lalinský <[email protected]om>
5 # Copyright (C) 2005 Dan Loda <[email protected]>
6 # Copyright (C) 2009 Gary van der Merwe <[email protected]>
7 #
8 # This program is free software; you can redistribute it and/or
9 # modify it under the terms of the GNU General Public License
10 # as published by the Free Software Foundation; either version 2
11 # of the License, or (at your option) any later version.
12 #
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with this program; if not, write to the Free Software
20 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21
22 # TODO:
23 # - better annotate algorithm on packs
24
25 import sys, time, hashlib
26 from itertools import groupby
27 from PyQt5 import QtCore, QtGui, QtWidgets
28
29 from breezy.revision import CURRENT_REVISION
30
31 from breezy.plugins.qbrz.lib.i18n import gettext
32 from breezy.plugins.qbrz.lib.util import (
33 BTN_CLOSE,
34 QBzrWindow,
35 ToolBarThrobberWidget,
36 get_apparent_author_name,
37 get_icon,
38 get_monospace_font,
39 get_set_encoding,
40 get_set_tab_width_chars,
41 get_tab_width_pixels,
42 runs_in_loading_queue,
43 )
44 from breezy.plugins.qbrz.lib.widgets.toolbars import FindToolbar
45 from breezy.plugins.qbrz.lib.widgets.texteditaccessory import (
46 GuideBarPanel, setup_guidebar_for_find
47 )
48 from breezy.plugins.qbrz.lib.uifactory import ui_current_widget
49 from breezy.plugins.qbrz.lib.trace import reports_exception
50 from breezy.plugins.qbrz.lib.logwidget import LogList
51 from breezy.plugins.qbrz.lib.lazycachedrevloader import (load_revisions,
52 cached_revisions)
53 from breezy.plugins.qbrz.lib.texteditannotate import (AnnotateBarBase,
54 AnnotateEditerFrameBase)
55 from breezy.lazy_import import lazy_import
56 lazy_import(globals(), '''
57 from breezy.config import parse_username
58 from breezy.workingtree import WorkingTree
59 from breezy.revisiontree import RevisionTree
60 from breezy.plugins.qbrz.lib.revisionmessagebrowser import LogListRevisionMessageBrowser
61 from breezy.plugins.qbrz.lib.encoding_selector import EncodingMenuSelector
62 from breezy.plugins.qbrz.lib.widgets.tab_width_selector import TabWidthMenuSelector
63 from breezy.plugins.qbrz.lib.syntaxhighlighter import highlight_document
64 from breezy.plugins.qbrz.lib.revtreeview import paint_revno, get_text_color
65 from breezy.plugins.qbrz.lib import logmodel
66 from breezy.plugins.qbrz.lib.loggraphviz import BranchInfo
67 from patiencediff import PatienceSequenceMatcher as SequenceMatcher
68 ''')
69
70
71 class AnnotateBar(AnnotateBarBase):
72
73 def __init__(self, edit, parent, get_revno):
74 super(AnnotateBar, self).__init__(edit, parent)
75
76 self.get_revno = get_revno
77 self.annotate = None
78 self.rev_colors = {}
79 self._highlight_revids = set()
80 self.highlight_lines = []
81
82 self.splitter = None
83 self.adjustWidth(1, 999)
84
85 edit.cursorPositionChanged.connect(self.edit_cursorPositionChanged)
86 self.show_current_line = False
87
88 def get_highlight_revids(self):
89 return self._highlight_revids
90
91 def set_highlight_revids(self, value):
92 if self._highlight_revids == value:
93 return
94
95 self._highlight_revids = value
96 self.update_highlight_lines()
97
98 def update_highlight_lines(self):
99 self.highlight_lines = []
100 if not self.annotate:
101 return
102 lines = [i for i, (revno, istop) in enumerate(self.annotate)
103 if revno in self._highlight_revids]
104
105 # Convert [0,1,2,5,6,9,14,15,16,17] to [(0,3),(5,2),(9,1),(14,4)]
106 def summarize(lines):
107 for k, g in groupby(enumerate(lines), key=lambda x:x[1]-x[0]):
108 yield [line for i, line in g]
109 self.highlight_lines = [(x[0], len(x)) for x in summarize(lines)]
110
111 highlight_revids = property(get_highlight_revids, set_highlight_revids)
112
113 def edit_cursorPositionChanged(self):
114 self.show_current_line = True
115
116 def adjustWidth(self, lines, max_revno):
117 fm = self.fontMetrics()
118 text_margin = self.style().pixelMetric(QtWidgets.QStyle.PM_FocusFrameHMargin, None, self) + 1
119
120 self.line_number_width = fm.width(str(lines))
121 self.line_number_width += (text_margin * 2)
122
123 self.revno_width = fm.width(str(max_revno)+".8.88")
124 self.max_mainline_digits = len(str(max_revno))
125 self.revno_width += (text_margin * 2)
126
127 if self.splitter:
128 if 0: self.splitter = QtWidgets.QSplitter
129 width = (self.line_number_width + self.revno_width +
130 fm.width("Joe I have a Long Name"))
131 self.splitter.setSizes([width, 1000])
132
133 self.setMinimumWidth(self.line_number_width + self.revno_width)
134
135 def paint_line(self, painter, rect, line_number, is_current):
136 fm = self.fontMetrics()
137 painter.save()
138 if is_current and self.show_current_line:
139 style = self.style()
140 option = QtWidgets.QStyleOptionViewItem()
141 option.initFrom(self)
142 option.state = option.state | QtWidgets.QStyle.State_Selected
143 option.rect = rect.toRect()
144 painter.fillRect(rect, QtGui.QBrush(option.palette.highlight()))
145 style.drawPrimitive(QtWidgets.QStyle.PE_PanelItemViewItem, option, painter, self)
146
147 painter.setPen(get_text_color(option, style))
148 elif self.annotate and line_number-1 < len(self.annotate):
149 revid, is_top = self.annotate[line_number - 1]
150 if revid in self.rev_colors:
151 painter.fillRect(rect, self.rev_colors[revid])
152
153 text_margin = self.style().pixelMetric(QtWidgets.QStyle.PM_FocusFrameHMargin, None, self) + 1
154
155 if 0: rect = QtCore.QRect
156 line_number_rect = QtCore.QRect(*map(int, [
157 rect.left() + text_margin,
158 rect.top(),
159 self.line_number_width - (2 * text_margin),
160 rect.height()]))
161
162 painter.drawText(line_number_rect, QtCore.Qt.AlignRight, str(line_number))
163
164 if self.annotate and line_number-1 < len(self.annotate):
165 revid, is_top = self.annotate[line_number - 1]
166 if is_top:
167 if revid in self._highlight_revids:
168 font = painter.font()
169 font.setBold(True)
170 painter.setFont(font)
171
172 revno_rect = QtCore.QRect(*map(int, [
173 rect.left() + self.line_number_width + text_margin,
174 rect.top(),
175 self.revno_width - (2 * text_margin),
176 rect.height()]))
177 paint_revno(painter, revno_rect, str(self.get_revno(revid)), self.max_mainline_digits)
178
179 if revid in cached_revisions:
180 rev = cached_revisions[revid]
181 author_rect = QtCore.QRect(*map(int, [
182 rect.left() + self.line_number_width
183 + self.revno_width + text_margin,
184 rect.top(),
185 rect.right() - revno_rect.right() - (2 * text_margin),
186 rect.height()]))
187 author = get_apparent_author_name(rev)
188 if fm.width(author) > author_rect.width():
189 author= fm.elidedText(author, QtCore.Qt.ElideRight, author_rect.width())
190 painter.drawText(author_rect, 0, author)
191 painter.restore()
192
193
194 class AnnotatedTextEdit(QtWidgets.QPlainTextEdit):
195 annotate = None
196 rev_colors = {}
197 # RJLRJL: added for Qt5
198 documentChangeFinished = QtCore.pyqtSignal()
199
200 def paintEvent(self, event):
201 if self.annotate:
202 block = self.firstVisibleBlock()
203 painter = QtGui.QPainter(self.viewport())
204 painter.setClipRect(event.rect())
205
206 line_count = block.blockNumber()
207 # Iterate over all visible text blocks in the document.
208 while block.isValid():
209 line_count += 1
210 # Check if the position of the block is out side of the visible
211 # area.
212 rect = self.blockBoundingGeometry(block)
213 rect = rect.translated(self.contentOffset())
214
215 if not block.isVisible() or rect.top() >= event.rect().bottom():
216 break
217
218 if line_count - 1 >= len(self.annotate):
219 break
220
221 revid, is_top = self.annotate[line_count - 1]
222 if revid in self.rev_colors:
223 painter.fillRect(rect, self.rev_colors[revid])
224
225 block = block.next()
226 del painter
227 QtWidgets.QPlainTextEdit.paintEvent(self, event)
228
229 def get_positions(self):
230 """Returns the charator positons for the selection start,
231 selection end, center of the viewport, an the number of lines from
232 the top of the viewport to the center of the viewport."""
233 old_cursor = self.textCursor()
234 old_center = self.cursorForPosition(QtCore.QPoint(0, self.height() / 2))
235 lines_to_center = (old_center.block().blockNumber() - self.verticalScrollBar().value())
236
237 return (old_cursor.selectionStart(), old_cursor.selectionEnd(), old_center.position()) , lines_to_center
238
239 def set_positions(self, new_positions, lines_to_center):
240 new_start, new_end, new_center = new_positions
241 if new_center:
242 new_center_cursor = QtGui.QTextCursor(self.document())
243 new_center_cursor.setPosition(new_center)
244 new_scroll = new_center_cursor.block().blockNumber() - lines_to_center
245 self.verticalScrollBar().setValue(new_scroll)
246
247 new_selection_cursor = QtGui.QTextCursor(self.document())
248 new_selection_cursor.movePosition(QtGui.QTextCursor.Right, QtGui.QTextCursor.MoveAnchor, new_start)
249 new_selection_cursor.movePosition(QtGui.QTextCursor.Right, QtGui.QTextCursor.KeepAnchor, new_end - new_start)
250 self.setTextCursor(new_selection_cursor)
251
252
253 class AnnotateWindow(QBzrWindow):
254 documentChangeFinished = QtCore.pyqtSignal()
255
256 def __init__(self, branch, working_tree, annotate_tree, path, fileId,
257 encoding=None, parent=None, ui_mode=True, no_graph=False,
258 loader=None, loader_args=None, activate_line=None):
259 QBzrWindow.__init__(self, [gettext("Annotate"), gettext("Loading...")], parent, ui_mode=ui_mode)
260 self.restoreSize("annotate", (780, 680))
261
262 self.activate_line_after_load = activate_line
263
264 self.windows = []
265
266 self.branch = branch
267 self.annotate_tree = annotate_tree
268 self.working_tree = working_tree
269 if (self.working_tree is None and isinstance(annotate_tree, WorkingTree)):
270 self.working_tree = annotate_tree
271
272 self.no_graph = no_graph
273 self.old_lines = None
274
275 self.fileId = fileId
276 self.path = path
277 self.encoding = encoding
278 self.loader_func = loader
279 self.loader_args = loader_args
280
281 self.throbber = ToolBarThrobberWidget(self)
282
283 self.text_edit_frame = AnnotateEditerFrameBase(self)
284 self.text_edit = AnnotatedTextEdit(self)
285 self.text_edit.setFrameStyle(QtWidgets.QFrame.NoFrame)
286 self.text_edit.setTextInteractionFlags(QtCore.Qt.TextSelectableByMouse | QtCore.Qt.TextSelectableByKeyboard)
287 self.text_edit.setLineWrapMode(QtWidgets.QPlainTextEdit.NoWrap)
288
289 self.text_edit.document().setDefaultFont(get_monospace_font())
290
291 self.guidebar_panel = GuideBarPanel(self.text_edit, parent=self)
292 self.guidebar_panel.add_entry('annotate', QtGui.QColor(255, 160, 180))
293 self.annotate_bar = AnnotateBar(self.text_edit, self, self.get_revno)
294 annotate_spliter = QtWidgets.QSplitter(QtCore.Qt.Horizontal, self)
295 annotate_spliter.addWidget(self.annotate_bar)
296 annotate_spliter.addWidget(self.guidebar_panel)
297 self.annotate_bar.splitter = annotate_spliter
298 self.text_edit_frame.hbox.addWidget(annotate_spliter)
299
300 self.text_edit.cursorPositionChanged.connect(self.edit_cursorPositionChanged)
301 self.annotate_bar.cursorPositionChanged.connect(self.edit_cursorPositionChanged)
302 self.text_edit.documentChangeFinished.connect(self.edit_documentChangeFinished)
303
304 self.log_list = AnnotateLogList(self.processEvents, self.throbber, self)
305 self.log_list.header().hideSection(logmodel.COL_DATE)
306 self.log_list.parent_annotate_window = self
307 self.log_branch_loaded = False
308
309 self.log_list.selectionModel().selectionChanged[QtCore.QItemSelection, QtCore.QItemSelection].connect(self.log_list_selectionChanged)
310
311 self.message = LogListRevisionMessageBrowser(self.log_list, self)
312
313 self.encoding_selector = EncodingMenuSelector(self.encoding, gettext("Encoding"), self._on_encoding_changed)
314
315 hsplitter = QtWidgets.QSplitter(QtCore.Qt.Horizontal)
316 hsplitter.addWidget(self.log_list)
317 hsplitter.addWidget(self.message)
318
319 hsplitter.setStretchFactor(0, 2)
320 hsplitter.setStretchFactor(1, 2)
321
322 splitter = QtWidgets.QSplitter(QtCore.Qt.Vertical)
323 splitter.addWidget(self.text_edit_frame)
324 splitter.addWidget(hsplitter)
325
326 splitter.setStretchFactor(0, 5)
327 splitter.setStretchFactor(1, 2)
328
329 vbox = QtWidgets.QVBoxLayout(self.centralwidget)
330 #vbox.addWidget(self.toolbar)
331 vbox.addWidget(splitter)
332 self.text_edit.setFocus()
333
334 self.show_find = QtWidgets.QAction(get_icon("edit-find"), gettext("Find"), self)
335 self.show_find.setShortcuts(QtGui.QKeySequence.Find)
336 self.show_find.setCheckable(True)
337
338 self.show_goto_line = QtWidgets.QAction(get_icon("go-jump"), gettext("Goto Line"), self)
339 self.show_goto_line.setShortcuts((QtCore.Qt.CTRL + QtCore.Qt.Key_L,))
340 self.show_goto_line.setCheckable(True)
341
342 show_view_menu = QtWidgets.QAction(get_icon("document-properties"), gettext("&View Options"), self)
343 view_menu = QtWidgets.QMenu(gettext('View Options'), self)
344 show_view_menu.setMenu(view_menu)
345
346 word_wrap = QtWidgets.QAction(gettext("Word Wrap"), self)
347 word_wrap.setCheckable(True)
348 word_wrap.toggled [bool].connect(self.word_wrap_toggle)
349
350 def setTabStopWidth(tw):
351 self.text_edit.setTabStopWidth(get_tab_width_pixels(tab_width_chars=tw))
352 get_set_tab_width_chars(branch=self.branch,tab_width_chars=tw)
353 self.tab_width_selector = TabWidthMenuSelector(get_set_tab_width_chars(branch=branch), gettext("Tab Width"), setTabStopWidth)
354
355 view_menu.addMenu(self.tab_width_selector)
356 view_menu.addMenu(self.encoding_selector)
357 view_menu.addAction(word_wrap)
358
359 toolbar = self.addToolBar(gettext("Annotate"))
360 toolbar.setMovable (False)
361 toolbar.setToolButtonStyle(QtCore.Qt.ToolButtonTextBesideIcon)
362
363 #self.toolbar.setToolButtonStyle(QtCore.Qt.ToolButtonTextBesideIcon)
364 toolbar.addAction(self.show_find)
365 toolbar.addAction(self.show_goto_line)
366 toolbar.addAction(show_view_menu)
367 toolbar.widgetForAction(show_view_menu).setPopupMode(QtWidgets.QToolButton.InstantPopup)
368
369 spacer = QtWidgets.QWidget()
370 spacer.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
371 toolbar.addWidget(spacer)
372 toolbar.addWidget(self.throbber)
373
374 self.addToolBarBreak()
375
376 self.find_toolbar = FindToolbar(self, self.text_edit, self.show_find)
377 self.find_toolbar.hide()
378 self.addToolBar(self.find_toolbar)
379 self.show_find.toggled [bool].connect(self.show_find_toggle)
380 setup_guidebar_for_find(self.guidebar_panel, self.find_toolbar, index=1)
381
382 self.goto_line_toolbar = GotoLineToolbar(self, self.show_goto_line)
383 self.goto_line_toolbar.hide()
384 self.addToolBar(self.goto_line_toolbar)
385
386 self.show_goto_line.toggled [bool].connect(self.show_goto_line_toggle)
387
388 self.__hashes = {}
389
390 def show(self):
391 QBzrWindow.show(self)
392 # RJL 2023 - the singleShot causes problems, so just run the load
393 # QtCore.QTimer.singleShot(0, self.initial_load)
394 self.initial_load()
395
396 @runs_in_loading_queue
397 @ui_current_widget
398 @reports_exception()
399 def initial_load(self):
400 """Called to perform the initial load of the form. Enables a
401 throbber window, then loads the branches etc if they weren't specified
402 in our constructor.
403 """
404 self.throbber.show()
405 try:
406 if self.loader_func is not None:
407 (self.branch,
408 self.annotate_tree,
409 self.working_tree,
410 self.path, self.fileId) = self.loader_func(*self.loader_args)
411 self.loader_func = self.loader_args = None # kill extra refs...
412 QtCore.QCoreApplication.processEvents()
413 self.encoding = get_set_encoding(self.encoding, self.branch)
414 self.encoding_selector.encoding = self.encoding
415 with self.branch.lock_read():
416 self.set_annotate_title()
417 self.annotate(self.annotate_tree, self.fileId, self.path)
418 finally:
419 self.throbber.hide()
420 QtCore.QTimer.singleShot(1, self._activate_line)
421
422 def _activate_line(self):
423 # [bialix 2012/09/14] I have to use QtCore.QTimer.singleShot because
424 # otherwise the line with uncommitted changes is not highlighted
425 # properly: nothing appears in the revision message browser at all.
426 # I didn't find the reason behind it, shame on me.
427 n = self.activate_line_after_load
428 self.activate_line_after_load = None # clear the line number just in case
429 if n:
430 if n == 1:
431 # [bialix 2012/09/13] actually after loading annotation
432 # document implictly sets current position to the first line.
433 # So we're unable to change position to 1st line.
434 # Make a hack: select 2nd line, and then actually select 1st one.
435 self.go_to_line(2)
436 self.go_to_line(n)
437
438 def set_annotate_title(self):
439 # and update the title to show we are done.
440 if isinstance(self.annotate_tree, RevisionTree):
441 revno = self.get_revno(self.annotate_tree.get_revision_id())
442 if revno:
443 self.set_title_and_icon([gettext("Annotate"), self.path, gettext("Revision %s") % revno])
444 return
445
446 self.set_title_and_icon([gettext("Annotate"), self.path])
447
448 def get_revno(self, revid):
449 gv = self.log_list.log_model.graph_viz
450 if (gv and
451 revid in gv.revid_rev):
452 return gv.revid_rev[revid].revno_str
453 return ""
454
455 def annotate(self, annotate_tree, fileId, path):
456 self.now = time.time()
457 self.rev_indexes = {}
458 last_revid = None
459 lines = []
460 annotate = []
461 ordered_revids = []
462
463 self.processEvents()
464 for revid, text in annotate_tree.annotate_iter(path):
465 if revid == CURRENT_REVISION:
466 revid = CURRENT_REVISION + annotate_tree.basedir.encode("utf-8")
467
468 text = text.decode(self.encoding, 'replace')
469
470 lines.append(text)
471
472 text = text.rstrip()
473 if revid not in self.rev_indexes:
474 self.rev_indexes[revid]=[]
475 ordered_revids.append(revid)
476 self.rev_indexes[revid].append(len(annotate))
477
478 is_top = last_revid != revid
479 last_revid = revid
480
481 annotate.append((revid, is_top))
482 if len(annotate) % 100 == 0:
483 self.processEvents()
484 annotate.append((None, False)) # because the view has one more line
485
486 new_positions = None
487 if self.old_lines:
488 # Try keep the scroll, and selection stable.
489 old_positions, lines_to_center = self.text_edit.get_positions()
490 new_positions = self.translate_positions(self.old_lines, lines, old_positions)
491
492 self.text_edit.annotate = None
493 self.text_edit.setPlainText("".join(lines))
494 if new_positions:
495 self.text_edit.set_positions(new_positions, lines_to_center)
496
497 self.old_lines = lines
498 self.annotate_bar.adjustWidth(len(lines), 999)
499 self.annotate_bar.annotate = annotate
500 self.text_edit.annotate = annotate
501 self.annotate_bar.show_current_line = False
502
503 self.text_edit.documentChangeFinished.emit()
504
505 self.processEvents()
506
507 just_loaded_log = False
508 if not self.log_branch_loaded:
509 self.log_branch_loaded = True
510 bi = BranchInfo('', self.working_tree, self.branch)
511 self.log_list.load((bi,), bi, [self.fileId], self.no_graph, logmodel.WithWorkingTreeGraphVizLoader)
512
513 gv = self.log_list.log_model.graph_viz
514 self.annotate_bar.adjustWidth(len(lines), gv.revisions[0].revno_sequence[0])
515
516 just_loaded_log = True
517
518 # Show the revisions the we know about from the annotate.
519 filter = self.log_list.log_model.file_id_filter
520 changed_revs = []
521 for revid in list(self.rev_indexes.keys()):
522 rev = gv.revid_rev[revid]
523 filter.filter_file_id[rev.index] = True
524 changed_revs.append(rev)
525 filter.filter_changed_callback(changed_revs, last_call=True)
526
527 self.processEvents()
528 highlight_document(self.text_edit, path)
529 self.processEvents()
530 load_revisions(ordered_revids, self.branch.repository, revisions_loaded = self.revisions_loaded, pass_prev_loaded_rev = True)
531 self.processEvents()
532
533 if just_loaded_log:
534 # Check for any other revisions we don't know about
535
536 filter = self.log_list.log_model.file_id_filter
537 revids = [rev.revid for rev in gv.revisions if rev.revid not in self.rev_indexes]
538 filter.load(revids)
539
540 def translate_positions(self, old_lines, new_lines, old_positions):
541 sm = SequenceMatcher(None, old_lines, new_lines)
542 opcodes = sm.get_opcodes()
543 new_positions = [None for x in range(len(old_positions))]
544 opcode_len = lambda start, end, lines: sum(
545 [len(l) for l in lines[start:end]])
546 for i, old_pos in enumerate(old_positions):
547 old_char_start = 0
548 new_char_start = 0
549 for code, old_start, old_end, new_start, new_end in opcodes:
550 old_len = opcode_len(old_start, old_end, old_lines)
551 new_len = opcode_len(new_start, new_end, new_lines)
552 if (old_pos >= old_char_start and
553 old_pos < old_char_start + old_len):
554 if code == 'delete':
555 new_pos = new_char_start
556 elif (code == 'replace' and len(opcodes)>1):
557 # XXX This should cache the opcodes if we do the same
558 # block more than once.
559 new_inner_pos = self.translate_positions(
560 ''.join(old_lines[old_start:old_end]),
561 ''.join(new_lines[new_start:new_end]),
562 [old_pos - old_char_start])[0]
563 new_pos = new_char_start + new_inner_pos
564 else:
565 new_pos = new_char_start + (old_pos - old_char_start)
566 new_positions[i] = new_pos
567 break
568 old_char_start += old_len
569 new_char_start += new_len
570 return new_positions
571
572 def revisions_loaded(self, revisions, last_call):
573 for rev in revisions.values():
574 authors = rev.get_apparent_authors()
575 emails = list(map(self._maybe_extract_email, authors))
576 author_id = ';'.join(emails)
577
578 if rev.timestamp is None:
579 days = sys.maxsize
580 elif self.now < rev.timestamp:
581 days = 0
582 else:
583 days = (self.now - rev.timestamp) / (24 * 60 * 60)
584
585 alpha = 0.5/((days/50) + 1)
586 h_sh = self._get_hash(author_id)
587 hue = 1-float(h_sh) / sys.maxsize
588 color = QtGui.QColor.fromHsvF(hue, 1, 1, alpha)
589 brush = QtGui.QBrush(color)
590
591 self.annotate_bar.rev_colors[rev.revision_id] = brush
592 self.text_edit.rev_colors[rev.revision_id] = brush
593
594 self.annotate_bar.update()
595 self.text_edit.update()
596
597 def _maybe_extract_email(self, author):
598 name, email = parse_username(author)
599 if email:
600 return email
601 return author
602
603 def _get_hash(self, author_id):
604 h = self.__hashes.get(author_id)
605 if h is None:
606 h = abs(hash(author_id))
607 #h = abs(hash(hashlib.md5(author_id).hexdigest())) # maybe increase enthropy via md5?
608 # XXX [bialix 2012/03/30]
609 # I don't really like how we create colors for annotation.
610 # Also, abs(hash) loses 1 bit of the hash result.
611 # I think we can improve our algorithm to use more distinctive colors
612 # maybe we should use md5 as more enthropy source for hash,
613 # or maybe we can use some sort of predefined set of colors
614 # and each next author will use color from that set,
615 # but in this case we lose consistency of colors for the same author
616 # between different annotations
617 # I have no clever idea yet.
618 self.__hashes[author_id] = h
619 return h
620
621 def edit_cursorPositionChanged(self):
622 current_line = self.text_edit.document().findBlock(
623 self.text_edit.textCursor().position()).blockNumber()
624 if self.text_edit.annotate:
625 rev_id, is_top = self.text_edit.annotate[current_line]
626 self.log_list.select_revid(rev_id)
627
628 def edit_documentChangeFinished(self):
629 self.annotate_bar.update_highlight_lines()
630 self.guidebar_panel.update_data(annotate=self.annotate_bar.highlight_lines)
631
632 @runs_in_loading_queue
633 def set_annotate_revision(self):
634 self.throbber.show()
635 try:
636 with self.branch.lock_read():
637 revid = self.log_list.currentIndex().data(logmodel.RevIdRole)
638 if revid.startswith(CURRENT_REVISION):
639 rev = cached_revisions[revid]
640 self.annotate_tree = self.working_tree
641 else:
642 self.annotate_tree = self.branch.repository.revision_tree(revid)
643 self.path = self.annotate_tree.id2path(self.fileId)
644 self.set_annotate_title()
645 self.processEvents()
646 self.annotate(self.annotate_tree, self.fileId, self.path)
647 finally:
648 self.throbber.hide()
649
650 @runs_in_loading_queue
651 def _on_encoding_changed(self, encoding):
652 self.encoding = encoding
653 get_set_encoding(encoding, self.branch)
654 self.throbber.show()
655 try:
656 with self.branch.lock_read():
657 self.annotate(self.annotate_tree, self.fileId, self.path)
658 finally:
659 self.throbber.hide()
660
661 def log_list_selectionChanged(self, selected, deselected):
662 revids = self.log_list.get_selection_and_merged_revids()
663 self.annotate_bar.highlight_revids = revids
664 self.guidebar_panel.update_data(annotate=self.annotate_bar.highlight_lines)
665 self.annotate_bar.update()
666
667 def show_find_toggle(self, state):
668 if state:
669 self.show_goto_line.setChecked(False)
670
671 def show_goto_line_toggle(self, state):
672 self.goto_line_toolbar.setVisible(state)
673 if state:
674 self.goto_line_toolbar.line_edit.setFocus()
675 self.show_find.setChecked(False)
676 else:
677 self.goto_line_toolbar.line_edit.setText('')
678
679 def word_wrap_toggle(self, state):
680 if state:
681 self.text_edit.setLineWrapMode(QtWidgets.QPlainTextEdit.WidgetWidth)
682 else:
683 self.text_edit.setLineWrapMode(QtWidgets.QPlainTextEdit.NoWrap)
684
685 def go_to_line(self, line):
686 doc = self.text_edit.document()
687 cursor = QtGui.QTextCursor(doc)
688 cursor.setPosition(doc.findBlockByNumber(line-1).position())
689 self.text_edit.setTextCursor(cursor)
690 self.text_edit.centerCursor()
691
692
693 # QIntValidator did not work on vila's setup, so this is a workaround.
694 # RJLRJL QIntValidator seems to be working in 2020, whereas this isn't
695 # so ignored for now.
696 class IntValidator(QtGui.QValidator):
697 def validate(self, input, pos):
698 if input == '':
699 return (QtGui.QValidator.Intermediate, pos)
700 try:
701 i = int(input)
702 except ValueError:
703 return (QtGui.QValidator.Invalid, pos)
704
705 if i > 0:
706 return (QtGui.QValidator.Acceptable, pos)
707 else:
708 return (QtGui.QValidator.Invalid, pos)
709
710
711 class GotoLineToolbar(QtWidgets.QToolBar):
712
713 def __init__(self, anotate_window, show_action):
714 QtWidgets.QToolBar.__init__(self, gettext("Goto Line"), anotate_window)
715 self.anotate_window = anotate_window
716 if 0:
717 self.anotate_window = AnnotateWindow()
718 self.show_action = show_action
719
720 self.setToolButtonStyle(QtCore.Qt.ToolButtonTextBesideIcon)
721 self.setMovable(False)
722
723 label = QtWidgets.QLabel(gettext("Goto Line: "), self)
724 self.addWidget(label)
725
726 self.line_edit = QtWidgets.QLineEdit(self)
727 # QIntValidator is working in python3, so we'll use that
728 # self.line_edit.setValidator(IntValidator(self.line_edit))
729 self.line_edit.setValidator(QtGui.QIntValidator())
730 self.addWidget(self.line_edit)
731 label.setBuddy(self.line_edit)
732
733 go = self.addAction(get_icon("go-next"), gettext("Go"))
734
735 spacer = QtWidgets.QWidget()
736 spacer.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
737 self.addWidget(spacer)
738
739 close = QtWidgets.QAction(self)
740 close.setIcon(self.style().standardIcon(QtWidgets.QStyle.SP_DialogCloseButton))
741 self.addAction(close)
742 close.setShortcut((QtCore.Qt.Key_Escape))
743 close.setShortcutContext(QtCore.Qt.WidgetWithChildrenShortcut)
744 close.setStatusTip(gettext("Close Goto Line"))
745 close.triggered[bool].connect(self.close_triggered)
746 go.triggered[bool].connect(self.go_triggered)
747 self.line_edit.returnPressed.connect(self.go_triggered)
748
749 def close_triggered(self, state):
750 self.show_action.setChecked(False)
751
752 def go_triggered(self, state=True):
753 try:
754 line = int(str(self.line_edit.text()))
755 except ValueError:
756 pass
757 else:
758 self.anotate_window.go_to_line(line)
759 self.show_action.setChecked(False)
760
761
762 class AnnotateLogList(LogList):
763
764 parent_annotate_window = None
765
766 def create_context_menu(self):
767 LogList.create_context_menu(self, diff_is_default_action=False)
768 set_rev_action = QtWidgets.QAction(gettext("&Annotate this revision"), self.context_menu)
769 set_rev_action.triggered.connect(self.parent_annotate_window.set_annotate_revision)
770 self.context_menu.insertAction(self.context_menu.actions()[0], set_rev_action)
771 self.context_menu.setDefaultAction(set_rev_action)
772
773 def default_action(self, index=None):
774 self.parent_annotate_window.set_annotate_revision()