Debian Codegraph @

lib/log.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 #
3 # QBrz - Qt frontend to Breezy commands
4 # Copyright (C) 2006-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 from breezy.revision import CURRENT_REVISION
23
24 from breezy.plugins.qbrz.lib.util import (
25 BTN_CLOSE,
26 BTN_REFRESH,
27 QBzrWindow,
28 ThrobberWidget,
29 StandardButton,
30 url_for_display,
31 runs_in_loading_queue,
32 get_set_encoding,
33 )
34 from breezy.plugins.qbrz.lib.trace import reports_exception
35 from breezy.plugins.qbrz.lib.uifactory import ui_current_widget
36 from breezy.plugins.qbrz.lib.loggraphviz import GhostRevisionError
37
38 import re
39
40 from breezy import errors
41 from breezy import osutils
42 from breezy.controldir import ControlDir
43 from breezy.urlutils import determine_relative_path, join, split
44
45 from breezy.plugins.qbrz.lib.logwidget import LogList
46 from breezy.plugins.qbrz.lib import logmodel
47 from breezy.plugins.qbrz.lib.loggraphviz import BranchInfo
48
49 from breezy.plugins.qbrz.lib.diff import has_ext_diff, ExtDiffMenu, DiffButtons
50 from breezy.plugins.qbrz.lib.i18n import gettext
51 from breezy.plugins.qbrz.lib.revisionmessagebrowser import LogListRevisionMessageBrowser
52 from breezy.plugins.qbrz.lib.cat import QBzrCatWindow
53 from breezy.plugins.qbrz.lib.annotate import AnnotateWindow
54
55
56 QStringList = list
57
58 PathRole = QtCore.Qt.UserRole + 1
59 file_idRole = QtCore.Qt.UserRole + 2
60 AliveRole = QtCore.Qt.UserRole + 3
61
62 have_search = None
63
64
65 class Compleater(QtWidgets.QCompleter):
66 def splitPath(self, path):
67 return QStringList([path.split(" ")[-1]])
68
69
70 class LogWindow(QBzrWindow):
71
72 FilterIdRole = QtCore.Qt.UserRole + 100
73 FilterMessageRole = QtCore.Qt.UserRole + 101
74 FilterAuthorRole = QtCore.Qt.UserRole + 102
75 FilterRevnoRole = QtCore.Qt.UserRole + 103
76 FilterSearchRole = QtCore.Qt.UserRole + 104
77 FilterTagRole = QtCore.Qt.UserRole + 105
78 FilterBugRole = QtCore.Qt.UserRole + 106
79
80 def __init__(self, locations=None,
81 branch=None, tree=None, specific_file_ids=None,
82 parent=None, ui_mode=True, no_graph=False,
83 show_trees=False):
84 """Create qlog window.
85
86 Note: you must use either locations or branch+tree+specific_file_id
87 arguments, but not both.
88
89 @param locations: list of locations to show log
90 (either list of URL/paths for several branches,
91 or list of filenames from one branch).
92 This list used when branch argument is None.
93
94 @param branch: branch object to show the log.
95 Could be None, in this case locations list will be used
96 to open branch(es).
97
98 @param specific_file_ids: file ids from the branch to filter
99 the log.
100
101 @param parent: parent widget.
102
103 @param ui_mode: for compatibility with TortoiseBzr.
104
105 @param no_graph: don't show the graph of revisions (make sense
106 for `bzr qlog FILE` to force plain log a-la `bzr log`).
107 """
108 self.title = gettext("Log")
109 QBzrWindow.__init__(self, [self.title], parent, ui_mode=ui_mode)
110 self.restoreSize("log", (710, 580))
111
112 self.no_graph = no_graph
113 self.show_trees = show_trees
114 if branch:
115 self.branch = branch
116 self.tree = tree
117 self.locations = (branch,)
118 self.specific_file_ids = specific_file_ids
119 assert locations is None, "can't specify both branch and locations"
120 else:
121 self.branch = None
122 self.locations = locations
123 # if self.locations is None:
124 # self.locations = [u"."]
125 assert specific_file_ids is None, "specific_file_ids is ignored if branch is None"
126
127 self.branches = None
128 self.replace = {}
129
130 self.throbber = ThrobberWidget(self)
131
132 logwidget = QtWidgets.QWidget()
133 logbox = QtWidgets.QVBoxLayout(logwidget)
134 logbox.setContentsMargins(0, 0, 0, 0)
135
136 searchbox = QtWidgets.QHBoxLayout()
137
138 self.search_label = QtWidgets.QLabel(gettext("&Search:"))
139 self.search_edit = QtWidgets.QLineEdit()
140 self.search_label.setBuddy(self.search_edit)
141 self.search_edit.textEdited['QString'].connect(self.set_search_timer)
142
143 self.search_timer = QtCore.QTimer(self)
144 self.search_timer.setSingleShot(True)
145 self.search_timer.timeout.connect(self.update_search)
146
147 searchbox.addWidget(self.search_label)
148 searchbox.addWidget(self.search_edit)
149
150 self.searchType = QtWidgets.QComboBox()
151
152 self.searchType.addItem(gettext("Messages"), self.FilterMessageRole)
153 self.searchType.addItem(gettext("Authors"), self.FilterAuthorRole)
154 self.searchType.addItem(gettext("Revision IDs"), self.FilterIdRole)
155 self.searchType.addItem(gettext("Revision Numbers"), self.FilterRevnoRole)
156 self.searchType.addItem(gettext("Tags"), self.FilterTagRole)
157 self.searchType.addItem(gettext("Bugs"), self.FilterBugRole)
158 searchbox.addWidget(self.searchType)
159 self.searchType.currentIndexChanged[int].connect(self.updateSearchType)
160
161 logbox.addLayout(searchbox)
162
163 self.log_list = LogList(self.processEvents, self.throbber, self, action_commands=True)
164
165 logbox.addWidget(self.throbber)
166 logbox.addWidget(self.log_list)
167
168 self.current_rev = None
169
170 self.message = QtGui.QTextDocument()
171 self.message_browser = LogListRevisionMessageBrowser(self.log_list, self)
172 self.message_browser.setDocument(self.message)
173
174 self.file_list_container = FileListContainer(self.log_list, self)
175 self.log_list.selectionModel().selectionChanged[QtCore.QItemSelection,
176 QtCore.QItemSelection].connect(self.file_list_container.revision_selection_changed)
177
178 hsplitter = QtWidgets.QSplitter(QtCore.Qt.Horizontal)
179 hsplitter.addWidget(self.message_browser)
180 hsplitter.addWidget(self.file_list_container)
181 hsplitter.setStretchFactor(0, 3)
182 hsplitter.setStretchFactor(1, 1)
183
184 splitter = QtWidgets.QSplitter(QtCore.Qt.Vertical)
185 splitter.addWidget(logwidget)
186 splitter.addWidget(hsplitter)
187 splitter.setStretchFactor(0, 5)
188 splitter.setStretchFactor(1, 3)
189
190 buttonbox = self.create_button_box(BTN_CLOSE)
191 self.refresh_button = StandardButton(BTN_REFRESH)
192 buttonbox.addButton(self.refresh_button, QtWidgets.QDialogButtonBox.ActionRole)
193 self.refresh_button.clicked.connect(self.refresh)
194
195 self.diffbuttons = DiffButtons(self.centralwidget)
196 self.diffbuttons.setEnabled(False)
197 self.diffbuttons._triggered['QString'].connect(self.log_list.show_diff_specified_files_ext)
198
199 vbox = QtWidgets.QVBoxLayout(self.centralwidget)
200 vbox.addWidget(splitter)
201 hbox = QtWidgets.QHBoxLayout()
202 hbox.addWidget(self.diffbuttons)
203 hbox.addWidget(buttonbox)
204 vbox.addLayout(hbox)
205 self.windows = []
206 # set focus on search edit widget
207 self.log_list.setFocus()
208
209 @ui_current_widget
210 @reports_exception()
211 def load(self):
212 self.refresh_button.setDisabled(True)
213 self.throbber.show()
214 self.processEvents()
215 try:
216 # Set window title.
217 lt = self._locations_for_title(self.locations)
218 if lt:
219 self.set_title((self.title, lt))
220
221 branches, primary_bi, file_ids = self.get_branches_and_file_ids()
222 if self.show_trees:
223 gz_cls = logmodel.WithWorkingTreeGraphVizLoader
224 else:
225 gz_cls = logmodel.GraphVizLoader
226
227 self.log_list.load(branches, primary_bi, file_ids, self.no_graph, gz_cls)
228 self.log_list.selectionModel().selectionChanged[QtCore.QItemSelection, QtCore.QItemSelection].connect(self.update_selection)
229 self.load_search_indexes(branches)
230 finally:
231 self.refresh_button.setDisabled(False)
232 self.throbber.hide()
233 self.processEvents()
234
235 def get_branches_and_file_ids(self):
236 if self.branch:
237 if self.tree is None:
238 try:
239 self.tree = self.branch.controldir.open_workingtree()
240 except (errors.NoWorkingTree, errors.NotLocalUrl):
241 pass
242 label = self.branch_label(None, self.branch)
243 bi = BranchInfo(label, self.tree, self.branch)
244 return [bi], bi, self.specific_file_ids
245 else:
246 primary_bi = None
247 branches = set()
248 file_ids = []
249 if self.locations is not None:
250 locations = self.locations
251 else:
252 locations = ['.']
253
254 # Branch names that indicated primary branch.
255 # TODO: Make config option.
256 primary_branch_names = ('trunk', 'bzr.dev')
257
258 for location in locations:
259 tree, br, repo, fp = ControlDir.open_containing_tree_branch_or_repository(location)
260 self.processEvents()
261
262 if br is None:
263 if fp:
264 raise errors.NotBranchError(fp)
265
266 # RJLRJL: bzr-3.1
267 # * ``Repository.find_branches`` now returns an iterator rather than a
268 # list. (Jelmer Vernooij, #413970)
269 repo_branches = list(repo.find_branches(using=True))
270 if not repo_branches:
271 raise errors.NotBranchError(fp)
272
273 for br in repo_branches:
274 self.processEvents()
275 try:
276 tree = br.controldir.open_workingtree()
277 self.processEvents()
278 except errors.NoWorkingTree:
279 tree = None
280 label = self.branch_label(None, br, location, repo)
281 bi = BranchInfo(label, tree, br)
282 branches.add(bi)
283 if not primary_bi and br.nick in primary_branch_names:
284 primary_bi = bi
285 else:
286 if len(locations) > 1:
287 label = self.branch_label(location, br)
288 else:
289 label = None
290 bi = BranchInfo(label, tree, br)
291 if len(branches) == 0:
292 # The first sepecified branch becomes the primary
293 # branch.
294 primary_bi = bi
295 branches.add(bi)
296
297 # If no locations were sepecified, don't do fileids
298 # Otherwise it gives you the history for the dir if you are
299 # in a sub dir.
300 if fp != '' and self.locations is None:
301 fp = ''
302
303 if fp != '':
304 # TODO: Have a way to specify a revision to find to file
305 # path in, so that one can show deleted files.
306 if tree is None:
307 tree = br.basis_tree()
308
309 file_id = tree.path2id(fp)
310 if file_id is None:
311 raise errors.BzrCommandError("Path does not have any revision history: %s" % location)
312 file_ids.append(file_id)
313 if file_ids and len(branches) > 1:
314 raise errors.BzrCommandError(gettext(
315 'It is not possible to specify different file paths and different branches at the same time.'))
316 return tuple(branches), primary_bi, file_ids
317
318 def load_search_indexes(self, branches):
319 global have_search, search_errors, search_index
320 if have_search is None:
321 have_search = True
322 try:
323 from breezy.plugins.search import errors as search_errors
324 from breezy.plugins.search import index as search_index
325 except ImportError:
326 have_search = False
327
328 if have_search:
329 indexes_availble = False
330 for bi in branches:
331 try:
332 bi.index = search_index.open_index_branch(bi.branch)
333 indexes_availble = True
334 except (search_errors.NoSearchIndex, errors.IncompatibleAPI):
335 pass
336 if indexes_availble:
337 self.searchType.insertItem(0, gettext("Messages and File text (indexed)"), self.FilterSearchRole)
338 self.searchType.setCurrentIndex(0)
339 self.completer = Compleater(self)
340 self.completer_model = QStringListModel(self)
341 self.completer.setModel(self.completer_model)
342 self.search_edit.setCompleter(self.completer)
343 self.search_edit.textChanged['QString'].connect(self.update_search_completer)
344 self.suggestion_letters_loaded = {"":QStringList()}
345 self.suggestion_last_first_letter = ""
346 self.completer.activated['QString'].connect(self.set_search_timer)
347
348 no_usefull_info_in_location_re = re.compile(r'^[.:/\\]*$')
349
350 def branch_label(self, location, branch, shared_repo_location=None, shared_repo=None):
351 # We should rather use QFontMetrics.elidedText. How do we decide on the width.
352 def elided_text(text, length=20):
353 if len(text) > length + 3:
354 return text[:length] + '...'
355 return text
356
357 def elided_path(path):
358 if len(path) > 23:
359 directory, name = split(path)
360 directory = elided_text(directory, 10)
361 name = elided_text(name)
362 return join(directory, name)
363 return path
364
365 if shared_repo_location and shared_repo and not location:
366 # Once we depend on breezy 2.2, this can become .user_url
367 branch_rel = determine_relative_path(shared_repo.controldir.root_transport.base, branch.controldir.root_transport.base)
368 if shared_repo_location == 'colo:':
369 location = shared_repo_location + branch_rel
370 else:
371 location = join(shared_repo_location, branch_rel)
372 if location is None:
373 return elided_text(branch.nick)
374 has_explicit_nickname = getattr(branch.get_config(), 'has_explicit_nickname', lambda: False)()
375 append_nick = (location.startswith(':') or bool(self.no_usefull_info_in_location_re.match(location)) or has_explicit_nickname)
376 if append_nick:
377 return '%s (%s)' % (elided_path(location), branch.nick)
378
379 return elided_text(location)
380
381 def refresh(self):
382 self.file_list_container.drop_delta_cache_with_wt()
383 self.replace = {}
384 self.load()
385
386 def replace_config(self, branch):
387 if branch.base not in self.replace:
388 config = branch.get_config()
389 replace = config.get_user_option("qlog_replace")
390 if replace:
391 replace = replace.split("\n")
392 replace = [tuple(replace[2 * i:2 * i + 2]) for i in range(len(replace) // 2)]
393 self.replace[branch.base] = replace
394 return self.replace[branch.base]
395
396 def show(self):
397 # we show the bare form as soon as possible.
398 super().show()
399 # QBzrWindow.show(self)
400 QtCore.QTimer.singleShot(0, self.load)
401
402 def update_selection(self, selected, deselected):
403 indexes = self.log_list.get_selection_indexes()
404 if not indexes:
405 self.diffbuttons.setEnabled(False)
406 else:
407 self.diffbuttons.setEnabled(True)
408
409 @ui_current_widget
410 def update_search(self):
411 # TODO in_paths = self.search_in_paths.isChecked()
412 gv = self.log_list.log_model.graph_viz
413 role = self.searchType.itemData(self.searchType.currentIndex())
414 search_text = str(self.search_edit.text())
415 if search_text == "":
416 self.log_list.set_search(None, None)
417 elif role == self.FilterIdRole:
418 self.log_list.set_search(None, None)
419 self.log_list.select_revid(search_text)
420 elif role == self.FilterRevnoRole:
421 self.log_list.set_search(None, None)
422 try:
423 revno = tuple((int(number) for number in search_text.split('.')))
424 except ValueError:
425 revno = ()
426 # Not sure what to do if there is an error. Nothing for now
427 if revno in gv.revno_rev:
428 rev = gv.revno_rev[revno]
429 index = self.log_list.log_model.index_from_rev(rev)
430 self.log_list.setCurrentIndex(index)
431 else:
432 if role == self.FilterMessageRole:
433 field = "message"
434 elif role == self.FilterAuthorRole:
435 field = "author"
436 elif role == self.FilterSearchRole:
437 field = "index"
438 elif role == self.FilterTagRole:
439 field = 'tag'
440 elif role == self.FilterBugRole:
441 field = 'bug'
442 else:
443 raise Exception("Not done")
444
445 self.log_list.set_search(search_text, field)
446
447 self.log_list.scrollTo(self.log_list.currentIndex())
448 # Scroll to ensure the selection is on screen.
449
450 @ui_current_widget
451 def update_search_completer(self, text):
452 gv = self.log_list.log_model.graph_viz
453 # We only load the suggestions a letter at a time when needed.
454 term = str(text).split(" ")[-1]
455 if term:
456 first_letter = term[0]
457 else:
458 first_letter = ""
459
460 if first_letter != self.suggestion_last_first_letter:
461 self.suggestion_last_first_letter = first_letter
462 if first_letter not in self.suggestion_letters_loaded:
463 suggestions = set()
464 indexes = [bi.index for bi in gv.branches if bi.index is not None]
465 for index in indexes:
466 for s in index.suggest(((first_letter,),)):
467 # if suggestions.count() % 100 == 0:
468 # QtCore.QCoreApplication.processEvents()
469 suggestions.add(s[0])
470 suggestions = QStringList(list(suggestions))
471 suggestions.sort()
472 self.suggestion_letters_loaded[first_letter] = suggestions
473 else:
474 suggestions = self.suggestion_letters_loaded[first_letter]
475 self.completer_model.setStringList(suggestions)
476
477 def updateSearchType(self, index=None):
478 self.update_search()
479
480 def set_search_timer(self):
481 self.search_timer.start(200)
482
483 def _locations_for_title(self, locations):
484 if locations is None:
485 return osutils.getcwd()
486 else:
487 from breezy.branch import Branch
488
489 def title_for_location(location):
490 if isinstance(location, str):
491 return url_for_display(location)
492 if isinstance(location, Branch):
493 return url_for_display(location.base)
494 return str(location)
495
496 return ", ".join(title_for_location(location) for location in locations)
497
498
499 class FileListContainer(QtWidgets.QWidget):
500
501 def __init__(self, log_list, parent=None):
502 QtWidgets.QWidget.__init__(self, parent)
503
504 self.log_list = log_list
505
506 self.throbber = ThrobberWidget(self)
507 self.throbber.hide()
508
509 self.file_list = QtWidgets.QListWidget()
510 self.file_list.doubleClicked[QtCore.QModelIndex].connect(self.show_diff_files)
511 self.file_list.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
512 self.file_list_context_menu = QtWidgets.QMenu(self)
513 if has_ext_diff():
514 diff_menu = ExtDiffMenu(self)
515 self.file_list_context_menu.addMenu(diff_menu)
516 diff_menu._triggered.connect(self.show_diff_files_ext)
517 else:
518 show_diff_action = self.file_list_context_menu.addAction(gettext("Show &differences..."), self.show_diff_files)
519 self.file_list_context_menu.setDefaultAction(show_diff_action)
520
521 self.file_list_context_menu_annotate = self.file_list_context_menu.addAction(gettext("Annotate"), self.show_file_annotate)
522 self.file_list_context_menu_cat = self.file_list_context_menu.addAction(gettext("View file"), self.show_file_content)
523 self.file_list_context_menu_save_old_file = self.file_list_context_menu.addAction(
524 gettext("Save file on this revision as..."), self.save_old_revision_of_file)
525 self.file_list_context_menu_revert_file = self.file_list_context_menu.addAction(gettext("Revert to this revision"), self.revert_file)
526
527 self.file_list.customContextMenuRequested[QtCore.QPoint].connect(self.show_file_list_context_menu)
528
529 vbox = QtWidgets.QVBoxLayout(self)
530 vbox.setContentsMargins(0, 0, 0, 0)
531 vbox.addWidget(self.throbber)
532 vbox.addWidget(self.file_list)
533
534 self.delta_load_timer = QtCore.QTimer(self)
535 self.delta_load_timer.setSingleShot(True)
536 self.delta_load_timer.timeout.connect(self.load_delta)
537 self.current_revids = None
538
539 self.tree_cache = {}
540 self.delta_cache = {}
541
542 def processEvents(self):
543 self.window().processEvents()
544
545 def revision_selection_changed(self, selected, deselected):
546 revids, count = self.log_list.get_selection_top_and_parent_revids_and_count()
547 if revids != self.current_revids:
548 self.file_list.clear()
549 self.current_revids = None
550 self.delta_load_timer.start(200)
551
552 @runs_in_loading_queue
553 @ui_current_widget
554 def load_delta(self):
555 revids, count = self.log_list.get_selection_top_and_parent_revids_and_count()
556 if revids == self.current_revids:
557 return
558
559 graph_viz = self.log_list.log_model.graph_viz
560 is_working_tree_graph_viz = isinstance(graph_viz, logmodel.WithWorkingTreeGraphVizLoader)
561 if self.log_list.log_model.file_id_filter:
562 specific_file_ids = self.log_list.log_model.file_id_filter.file_ids
563 else:
564 specific_file_ids = []
565
566 if not revids or revids == (None, None):
567 return
568
569 if revids not in self.delta_cache:
570 self.throbber.show()
571 try:
572 repos = [graph_viz.get_revid_branch(revid).repository for revid in revids]
573 except GhostRevisionError:
574 delta = None
575 else:
576 if repos[0].__class__.__name__ == 'SvnRepository' or repos[1].__class__.__name__ == 'SvnRepository':
577 # Loading trees from a remote svn repo is unusably slow.
578 # See https://bugs.launchpad.net/qbrz/+bug/450225
579 # If only 1 revision is selected, use a optimized svn method
580 # which actualy gets the server to do the delta,
581 # else, don't do any delta.
582 if count == 1:
583 delta = repos[0].get_revision_delta(revids[0])
584 else:
585 delta = None
586 else:
587 if len(repos) == 2 and repos[0].base == repos[1].base:
588 # Both revids are from the same repository. Load together.
589 repos_revids = [(repos[0], revids)]
590 else:
591 repos_revids = [(repo, [revid]) for revid, repo in zip(revids, repos)]
592
593 for repo, repo_revids in repos_revids:
594 repo_revids = [revid for revid in repo_revids if revid not in self.tree_cache]
595 if repo_revids:
596 with repo.lock_read():
597 self.processEvents()
598 for revid in repo_revids:
599 if revid.startswith(CURRENT_REVISION) and is_working_tree_graph_viz:
600 tree = graph_viz.working_trees[revid]
601 else:
602 tree = repo.revision_tree(revid)
603 self.tree_cache[revid] = tree
604 self.processEvents()
605 self.processEvents()
606
607 delta = self.tree_cache[revids[0]].changes_from(self.tree_cache[revids[1]])
608 self.delta_cache[revids] = delta
609 finally:
610 self.throbber.hide()
611 self.processEvents()
612 else:
613 delta = self.delta_cache[revids]
614
615 new_revids, count = self.log_list.get_selection_top_and_parent_revids_and_count()
616
617 if new_revids != revids:
618 return
619
620 # Jelmer's commit 7389 states: TreeDelta holds TreeChange objects rather than tuples of various sizes
621 #
622 # It used to be seven lists:--
623 #
624 # added
625 # (path, id, kind)
626 # removed
627 # (path, id, kind)
628 # renamed
629 # (oldpath, newpath, id, kind, text_modified, meta_modified)
630 # kind_changed
631 # (path, id, old_kind, new_kind)
632 # modified
633 # (path, id, kind, text_modified, meta_modified)
634 # unchanged
635 # (path, id, kind)
636 # unversioned
637 # (path, None, kind)
638 #
639 # Now they are TreeChange objects in the lists added[], removed[] renamed[], copied[] and modified[]
640 #
641 # self.file_id = file_id
642 # self.path = path
643 # self.changed_content = changed_content
644 # self.versioned = versioned
645 # self.parent_id = parent_id
646 # self.name = name
647 # self.kind = kind
648 # self.executable = executable
649 #
650 if delta:
651 items = [] # each item is 6-tuple: (id, path, is_not_specific_file_id, display, color, is_alive)
652 if delta.added:
653 for tree_change in delta.added:
654 items.append(
655 (tree_change.file_id, tree_change.path[1],
656 tree_change.file_id not in specific_file_ids,
657 tree_change.path[1], 'blue', True))
658
659 if delta.modified:
660 for tree_change in delta.modified:
661 items.append(
662 (tree_change.file_id, tree_change.path[0],
663 tree_change.file_id not in specific_file_ids,
664 tree_change.path[0], None, True))
665
666 if delta.removed:
667 for tree_change in delta.removed:
668 items.append(
669 (tree_change.file_id, tree_change.path[0],
670 tree_change.file_id not in specific_file_ids,
671 tree_change.path[0], 'red', False))
672
673 if delta.renamed:
674 for tree_change in delta.renamed:
675 items.append(
676 (tree_change.file_id, tree_change.path[0],
677 tree_change.file_id not in specific_file_ids,
678 tree_change.path[1], None, True))
679
680 # for (oldpath, newpath, id, kind, text_modified, meta_modified) in delta.renamed:
681 # for tree_change in delta.renamed:
682 # items.append(
683 # (tree_change.file_id, tree_change.path,
684 # tree_change.file_id not in specific_file_ids,
685 # tree_change.path, 'purple', True))
686
687 # items.append((id,
688 # newpath,
689 # id not in specific_file_ids,
690 # "%s => %s" % (oldpath, newpath),
691 # "purple",
692 # True))
693
694 for (id, path, is_not_specific_file_id, display, color, is_alive) in sorted(items, key=lambda x: (x[2],x[1])):
695 item = QtWidgets.QListWidgetItem(display, self.file_list)
696 item.setData(PathRole, path)
697 item.setData(file_idRole, id)
698 item.setData(AliveRole, is_alive)
699 if color:
700 item.setForeground(QtGui.QColor(color))
701 if not is_not_specific_file_id:
702 f = item.font()
703 f.setBold(True)
704 item.setFont(f)
705 self.current_revids = revids
706
707 def drop_delta_cache_with_wt(self):
708 gv = self.log_list.log_model.graph_viz
709 if not isinstance(gv, logmodel.WithWorkingTreeGraphVizLoader):
710 return
711 cache = self.delta_cache
712 keys = [k for k in cache.keys() if k[0].startswith(CURRENT_REVISION)]
713 for key in keys:
714 del(cache[key])
715
716 def show_file_list_context_menu(self, pos):
717 (top_revid, old_revid), count = self.log_list.get_selection_top_and_parent_revids_and_count()
718 if count == 0:
719 return
720 # XXX - We should also check that the selected file is a file, and
721 # not a dir
722 paths, file_ids, alives = self._get_file_selection_paths_ids_and_alives()
723 is_single_file = len(paths) == 1
724 wt_selected = top_revid.startswith(CURRENT_REVISION)
725 menu_enabled = is_single_file and alives[0]
726 self.file_list_context_menu_annotate.setEnabled(menu_enabled)
727 self.file_list_context_menu_cat.setEnabled(menu_enabled)
728 menu_enabled = is_single_file and alives[0] and not wt_selected
729 self.file_list_context_menu_save_old_file.setEnabled(menu_enabled)
730 self.file_list_context_menu_save_old_file.setVisible(menu_enabled)
731
732 gv = self.log_list.log_model.graph_viz
733 # It would be nice if there were more than one branch, that we
734 # show a menu so the user can chose which branch actions should take
735 # place in.
736 menu_enabled = (len(gv.branches) == 1 and gv.branches[0].tree is not None and not wt_selected)
737
738 self.file_list_context_menu_revert_file.setEnabled(menu_enabled)
739 self.file_list_context_menu_revert_file.setVisible(menu_enabled)
740 self.file_list_context_menu.popup(self.file_list.viewport().mapToGlobal(pos))
741
742 def get_file_selection_indexes(self, index=None):
743 if index is None:
744 return self.file_list.selectionModel().selectedRows(0)
745 else:
746 return [index]
747
748 def get_file_selection_paths_and_ids(self, index=None):
749 paths, ids, alives = self._get_file_selection_paths_ids_and_alives(index)
750 return paths, ids
751
752 def _get_file_selection_paths_ids_and_alives(self, index=None):
753 indexes = self.get_file_selection_indexes(index)
754 #
755 paths = []
756 ids = []
757 alives = []
758 #
759 for index in indexes:
760 item = self.file_list.itemFromIndex(index)
761 paths.append(str(item.data(PathRole)))
762 ids.append(item.data(file_idRole))
763 alives.append(bool(item.data(AliveRole)))
764 return paths, ids, alives
765
766 @ui_current_widget
767 def show_diff_files(self, index=None, ext_diff=None):
768 """Show differences of a specific file in a single revision"""
769 paths, ids = self.get_file_selection_paths_and_ids(index)
770 self.log_list.show_diff(specific_files=paths, specific_file_ids=ids, ext_diff=ext_diff)
771
772 @ui_current_widget
773 def show_diff_files_ext(self, ext_diff=None):
774 """Show differences of a specific file in a single revision"""
775 self.show_diff_files(ext_diff=ext_diff)
776
777 @runs_in_loading_queue
778 @ui_current_widget
779 def show_file_content(self):
780 """Launch qcat for one selected file."""
781 paths, file_ids = self.get_file_selection_paths_and_ids()
782 (top_revid, old_revid), count = self.log_list.get_selection_top_and_parent_revids_and_count()
783
784 gv = self.log_list.log_model.graph_viz
785 branch = gv.get_revid_branch(top_revid)
786 if top_revid.startswith(CURRENT_REVISION):
787 tree = gv.working_trees[top_revid]
788 else:
789 tree = branch.repository.revision_tree(top_revid)
790 encoding = get_set_encoding(None, branch)
791 window = QBzrCatWindow(filename = paths[0], tree = tree, parent=self, encoding=encoding)
792 window.show()
793 self.window().windows.append(window)
794
795 @ui_current_widget
796 def save_old_revision_of_file(self):
797 """Saves the selected file in its revision to a directory."""
798 paths, file_ids = self.get_file_selection_paths_and_ids()
799 (top_revid, old_revid), count = self.log_list.get_selection_top_and_parent_revids_and_count()
800 branch = self.log_list.log_model.graph_viz.get_revid_branch(top_revid)
801 tree = branch.repository.revision_tree(top_revid)
802 path = paths[0]
803 with tree.lock_read():
804 kind = tree.kind(path)
805 if kind == 'file':
806 file_content_bytes = tree.get_file_text(path)
807 if kind != 'file':
808 QtWidgets.QMessageBox.information(self, gettext("Not a file"),
809 gettext("Operation is supported for a single file only,\nnot for a %s." % kind))
810 return
811 filename = QtWidgets.QFileDialog.getSaveFileName(self, gettext("Save file in this revision as..."))[0]
812 if filename:
813 with open(str(filename), 'wb') as f:
814 f.write(file_content_bytes)
815
816 @ui_current_widget
817 def revert_file(self):
818 """Reverts the file to what it was at the selected revision."""
819 res = QtWidgets.QMessageBox.question(self, gettext("Revert File"),
820 gettext("Are you sure you want to revert this file to the state it was at the selected revision?"),
821 QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No)
822 if res == QtWidgets.QMessageBox.Yes:
823 paths, file_ids = self.get_file_selection_paths_and_ids()
824
825 (top_revid, old_revid), count = self.log_list.get_selection_top_and_parent_revids_and_count()
826 gv = self.log_list.log_model.graph_viz
827 assert(len(gv.branches) == 1)
828 branch_info = gv.branches[0]
829 rev_tree = gv.get_revid_repo(top_revid).revision_tree(top_revid)
830 branch_info.tree.revert(paths, old_tree=rev_tree, report_changes=True)
831
832 @ui_current_widget
833 def show_file_annotate(self):
834 """Show qannotate for selected file."""
835 paths, file_ids = self.get_file_selection_paths_and_ids()
836 (top_revid, old_revid), count = self.log_list.get_selection_top_and_parent_revids_and_count()
837
838 branch_info = self.log_list.log_model.graph_viz.get_revid_branch_info(top_revid)
839 if top_revid.startswith(CURRENT_REVISION):
840 tree = branch_info.tree
841 else:
842 tree = branch_info.branch.repository.revision_tree(top_revid)
843 window = AnnotateWindow(branch_info.branch, branch_info.tree, tree, paths[0], file_ids[0])
844 window.show()
845 self.window().windows.append(window)