Debian Codegraph @

lib/treewidget.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 #
3 # QBrz - Qt frontend to Breezy commands
4 # Copyright (C) 2009 Gary van der Merwe <[email protected]>
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 import os, sys
21 from typing import Union, Any, Callable
22
23 from PyQt5 import QtCore, QtGui, QtWidgets
24 from PyQt5.QtCore import QModelIndex
25
26 from breezy import errors
27 from breezy.bzr.inventorytree import InventoryTreeChange
28 from breezy.osutils import minimum_path_selection
29
30 try:
31 from breezy.transport.local import file_kind
32 except ImportError: # breezy < 3.5
33 from breezy.osutils import file_kind
34
35 try:
36 from breezy.transport import NoSuchFile
37 except ImportError:
38 from breezy.errors import NoSuchFile
39
40 from breezy.plugins.qbrz.lib.i18n import gettext
41
42 from breezy.plugins.qbrz.lib.revtreeview import (RevisionTreeView, RevNoItemDelegate)
43 from breezy.plugins.qbrz.lib.uifactory import ui_current_widget
44 from breezy.plugins.qbrz.lib.lazycachedrevloader import cached_revisions
45 from breezy.plugins.qbrz.lib.trace import report_exception, SUB_LOAD_METHOD
46
47 from breezy.bzr.conflicts import TextConflict
48 from breezy.transport import NoSuchFile
49
50 import posixpath # to use '/' path sep in path.join().
51 from time import (strftime, localtime)
52
53 from breezy.workingtree import WorkingTree
54 from breezy.revisiontree import RevisionTree
55 from breezy.conflicts import resolve
56 from breezy.tree import TreeChange
57
58 from breezy.plugins.qbrz.lib.cat import QBzrCatWindow, QBzrViewWindow, cat_to_native_app
59 from breezy.plugins.qbrz.lib.annotate import AnnotateWindow
60 from breezy.plugins.qbrz.lib.log import LogWindow
61 from breezy.plugins.qbrz.lib.util import (
62 get_set_encoding,
63 get_summary,
64 get_apparent_author_name,
65 )
66 from breezy.plugins.qbrz.lib.subprocess import SimpleSubProcessDialog
67 from breezy.plugins.qbrz.lib.diff import (
68 show_diff,
69 has_ext_diff,
70 ExtDiffMenu,
71 InternalWTDiffArgProvider,
72 )
73
74 from enum import IntEnum
75
76
77 class FilterModelKeys(IntEnum):
78 UNCHANGED = 0
79 CHANGED = 1
80 UNVERSIONED = 2
81 IGNORED = 3
82
83
84 def dict_set_add(d:dict, key, value):
85 if key in d:
86 d[key].add(value)
87 else:
88 d[key] = {value}
89
90
91 def group_large_dirs(paths):
92 # XXX - check the performance of this method with lots of paths, and deep paths.
93
94 all_paths_expanded = {'':('', 0, set([]))}
95 """Dict of all paths expanded, and their depth, and a set of decendents
96 they contain.
97
98 The key is the path
99 The value is a tuple of (path, depths, decendents)
100 """
101 if not paths:
102 paths = frozenset(('',))
103
104 for path in paths:
105 if path == '':
106 continue
107
108 parent_paths = []
109 dir_path = path
110 while True:
111 dir_path, name = os.path.split(dir_path)
112 parent_paths.append(dir_path)
113 if not dir_path:
114 break
115
116 for i, dir_path in enumerate(parent_paths):
117 depth = len(parent_paths) - i - 1
118 if dir_path in all_paths_expanded:
119 all_paths_expanded[dir_path][2].add(path)
120 else:
121 all_paths_expanded[dir_path] = [dir_path, depth, set((path,))]
122
123 container_dirs = {}
124 """Dict of a container dir path, with a set of its decendents"""
125 paths_deep_first = sorted(iter(all_paths_expanded.values()), key=lambda x: -x[1])
126
127 def set_dir_as_container(path_to_set):
128 path_to_set_decendents = all_paths_expanded[path_to_set][2]
129 container_dirs[path_to_set] = path_to_set_decendents
130 dir_path_to_set = path_to_set
131 while dir_path_to_set:
132 dir_path_to_set, _ = os.path.split(dir_path_to_set)
133 ancestors_descendents = all_paths_expanded[dir_path_to_set][2]
134 old_len = len(ancestors_descendents)
135 ancestors_descendents.difference_update(path_to_set_decendents)
136 if len(ancestors_descendents) < old_len:
137 ancestors_descendents.add(path_to_set)
138
139 # directories included in the original paths container.
140 for path, depth, decendents in paths_deep_first:
141 if decendents and (path in paths):
142 set_dir_as_container(path_to_set=path)
143
144 for path, depth, decendents in paths_deep_first:
145 len_decendents = len(decendents)
146 # Config?
147 if len_decendents >= 4 and path not in container_dirs:
148 has_ancestor_with_others = False
149 dir_path = path
150 while dir_path:
151 dir_path, name = os.path.split(dir_path)
152 if len_decendents < len(all_paths_expanded[dir_path][2]):
153 has_ancestor_with_others = True
154 break
155 if has_ancestor_with_others:
156 set_dir_as_container(path_to_set=path)
157
158 set_dir_as_container('')
159 return container_dirs
160
161
162 def missing_unversioned(missing, unversioned):
163 return (missing.change is not None and missing.change.is_missing() and
164 unversioned.change is not None and unversioned.change[3][1] is False)
165
166
167 def move_or_rename(old_path, new_path):
168 old_split = os.path.split(old_path)
169 new_split = os.path.split(new_path)
170 return (old_split[0] != new_split[0],
171 old_split[1] != new_split[1])
172
173
174 class InternalItem:
175 __slots__ = ["name", "kind", "file_id"]
176
177 def __init__(self, name, kind, file_id):
178 self.name = name
179 self.kind = kind
180 self.file_id = file_id
181
182 def __repr__(self):
183 return "<%s %r %s>" % (self.__class__.__name__, self.name, self.kind)
184
185 # RJLRJL: revision doesn't appear to be used anywhere anyway!
186 revision = property(lambda self:None)
187
188
189 class ModelItemData:
190 __slots__ = ["id", "item", "change", "checked", "children_ids",
191 "parent_id", "row", "path", "icon", "conflicts"]
192
193 def __init__(self, path, item=None, change=None, conflicts=None):
194 self.path = path
195 self.item = item
196 self.change = change
197 if conflicts is None:
198 self.conflicts = []
199 else:
200 self.conflicts = conflicts
201 self.checked = QtCore.Qt.Unchecked
202
203 self.children_ids = None
204 self.parent_id = None
205 self.id = None
206 self.row = None
207 self.icon = None
208
209 def dirs_first_sort_key(self):
210 """
211 Gives a string key that will sort directories before files
212
213 This works by annotating each path segment with either 'D' or 'F', so
214 that directories compare smaller than files on the same level.
215 """
216 item = self.item
217 if item.kind == "directory":
218 return "D" + item.name.replace("/", "/D")
219 if "/" not in item.name:
220 return "F" + item.name
221 path, f = item.name.rsplit("/", 1)
222 return "D" + path.replace("/", "/D") + "/F" + f
223
224 def __repr__(self):
225 return "<ModelItemData %s, %r>" % (self.path, self.item,)
226
227
228 class PersistantItemReference(object):
229 """This is use to stores a reference to a item that is persisted when we refresh the model."""
230 __slots__ = ["file_id", "path"]
231
232 def __init__(self, file_id, path):
233 self.file_id = file_id
234 self.path = path
235
236 def __repr__(self):
237 return "<%s %s %s>" % (self.__class__.__name__, self.path, self.file_id)
238
239
240 class ChangeDescription:
241 """
242 delta.py's comments and code help here:-
243
244 `kind` is None if no file is present
245
246 files are "renamed" if they are moved or if name changes, as long as it had a value
247 versioned_change_map = {
248 (True, True): 'unchanged',
249 (True, False): 'removed',
250 (False, True): 'added',
251 (False, False): 'unversioned',
252 }
253
254 if change.copied:
255 copied = True
256 renamed = False
257 elif change.renamed:
258 renamed = True
259 copied = False
260 else:
261 copied = False
262 renamed = False
263
264
265 if change.kind[0] != change.kind[1]:
266 if change.kind[0] is None:
267 modified = "created"
268 elif change.kind[1] is None:
269 modified = "deleted"
270 else:
271 modified = "kind changed"
272 else:
273 if change.changed_content:
274 modified = "modified"
275 elif change.kind[0] is None:
276 modified = "missing"
277 else:
278 modified = "unchanged"
279 if change.kind[1] == "file":
280 exe_change = (change.executable[0] != change.executable[1])
281 """
282 VERSIONED_BUT_REMOVED = (True, False)
283 NEVER_VERSIONED = (False, False)
284 NEWLY_ADDED_THUS_VERSIONED = (False, True)
285 UNCHANGED_VERSIONING_THUS_VERSIONED = (True, True)
286 NO_PARENT = (None, None)
287
288 def __init__(self, tree_change_object: Union[TreeChange, InventoryTreeChange], ignored_pattern=None):
289 self.tree_change = tree_change_object
290 self._ignored_pattern = ignored_pattern
291
292 def old_or_new_path(self): # was path()
293 """Return a suitable entry for a 'specific_files' param to bzr functions."""
294 oldpath, newpath = self.tree_change.path
295 return newpath or oldpath
296
297 def old_path(self):
298 """Return oldpath for renames."""
299 return self.tree_change.path[0]
300
301 def old_or_new_kind(self): # was kind
302 oldkind, newkind = self.tree_change.kind
303 return newkind or oldkind
304
305 def is_versioned(self) -> bool:
306 return self.tree_change.versioned != self.NEVER_VERSIONED
307
308 def is_renamed(self) -> bool:
309 return self.tree_change.renamed
310
311 def been_removed(self) -> bool:
312 return self.tree_change.versioned == self.VERSIONED_BUT_REMOVED
313
314 def kind_changed(self) -> bool:
315 # Some difference between the old and new values of kind
316 return self.tree_change.kind[0] != self.tree_change.kind[1]
317
318 def was_created(self) -> bool:
319 return self.kind_changed() and self.tree_change.kind[0] is None
320
321 def was_deleted(self) -> bool:
322 return self.kind_changed() and self.tree_change.kind[1] is None
323
324 def was_modified_delta(self) -> bool:
325 return not self.kind_changed() and self.tree_change.changed_content
326
327 def was_modified(self) -> bool:
328 return self.is_versioned() and self.tree_change.changed_content
329
330 def is_missing_delta(self) -> bool:
331 # This is a DIFFERENT missing detection to the original one
332 return not self.kind_changed() and self.tree_change.kind[0] is None
333
334 def is_missing(self) -> bool:
335 return self.tree_change.versioned == self.NEWLY_ADDED_THUS_VERSIONED and self.tree_change.kind[1] is None
336
337 def is_misadded(self) -> bool:
338 return self.is_missing()
339
340 def is_tree_root(self) -> bool:
341 return self.is_versioned() and self.tree_change.parent_id == self.NO_PARENT
342
343 def is_on_disk(self) -> bool:
344 return self.tree_change.kind[1] is not None
345
346 def ignored_pattern(self):
347 """
348 The old routine stated:
349
350 Returns ignore pattern if file is ignored;
351 None if none pattern match;
352 False is there is pattern but file actually versioned.
353
354 Which was actually untrue, as it returned either True or None. The problem is that in various
355 places `lambda c:not c.ignored_pattern` gets used and as `not True` -> False and `1not None` -> False
356 it basically ended up as False. THIS version now does what the above comment states (whether that
357 is correct or not).
358 """
359 # if len(self.change._as_tuple()) > 8:
360 # # ignored is when file match ignore pattern and not versioned
361 # # HOWEVER, the old [8] position is now occupied by 'copied'
362 # #return self.change.copied and self.change.versioned == (False, False)
363 # return self.ignored_pattern and self.change.versioned == (False, False)
364 # # return desc[8] and desc[3] == (False, False)
365 # else:
366 # return None
367 # ignored is when file match ignore pattern and not versioned
368 if self.is_versioned() and self._ignored_pattern is not None:
369 return False
370 elif not self.is_versioned() and self._ignored_pattern is not None:
371 return self._ignored_pattern
372 else:
373 return None
374
375 def status(self) -> str:
376 # is_ignored = self.associated_tree.is_ignored(self.old_or_new_path())
377 versioned = self.tree_change.versioned
378 is_ignored = self._ignored_pattern is not None
379 if versioned == (False, False):
380 if is_ignored:
381 return gettext("ignored")
382 else:
383 return gettext("non-versioned")
384 elif versioned == (False, True):
385 # if kind[1] is None:
386 if self.tree_change.kind[1] is None:
387 return gettext("added, missing")
388 else:
389 return gettext("added")
390 elif versioned == (True, False):
391 return gettext("removed")
392 elif self.tree_change.kind[0] is not None and self.tree_change.kind[1] is None:
393 return gettext("missing")
394 else:
395 # versioned = True, True - so either renamed or modified
396 # or properties changed (x-bit).
397 mod_strs = []
398
399 if self.tree_change.parent_id[0] != self.tree_change.parent_id[1]:
400 mod_strs.append(gettext("moved"))
401 if self.tree_change.name[0] != self.tree_change.name[1]:
402 mod_strs.append(gettext("renamed"))
403 if self.tree_change.changed_content:
404 mod_strs.append(gettext("modified"))
405 if self.tree_change.executable[0] != self.tree_change.executable[1]:
406 mod_strs.append(gettext("x-bit"))
407 return ", ".join(mod_strs)
408
409 @staticmethod
410 def dump_header_line():
411 s = f'{"file_id":<22} {"Path_old":<25} {"Path_new":<25} {"Changed?":<9}'
412 s += f' {"V(old)":7} {"V(new)":7} {"Name(old)":25} {"Name(new)":25}'
413 s += f' {"Kind_old":10} {"Kind_new":10} {"Exec_old":10} {"Exec_new":10}'
414 s += f' {"Copied?":10} {"Ignored?":20}'
415 return s
416
417 def dump_row(self) -> str:
418 c = self.tree_change
419 s = "{0:<22} {1:25} {2:25}".format(str(self.tree_change.file_id)[:21], str(c.path[0]), str(c.path[1]))
420 s += " {:^9} {:^7} {:^7}".format(str(c.changed_content), str(c.versioned[0]), str(c.versioned[1]))
421 s += " {0:25} {1:25}".format(str(c.name[0]), str(c.name[1]))
422 s += " {0:10} {1:10}".format(str(c.kind[0]), str(c.kind[1]))
423 s += " {0:10} {1:10}".format(str(c.executable[0]), str(c.executable[1]))
424 s += " {0:10} {1:20}".format(str(c.copied), str(self._ignored_pattern))
425 return s
426
427
428 class TreeModel(QtCore.QAbstractItemModel):
429 layoutAboutToBeChanged = QtCore.pyqtSignal()
430 layoutChanged = QtCore.pyqtSignal()
431 dataChanged = QtCore.pyqtSignal(QtCore.QModelIndex, QtCore.QModelIndex)
432
433 HEADER_LABELS = [gettext("File Name"),
434 gettext("Date"),
435 gettext("Rev"),
436 gettext("Message"),
437 gettext("Author"),
438 gettext("Status")]
439
440 # These are the columns
441 NAME = 0
442 DATE = 1
443 REVNO = 2
444 MESSAGE = 3
445 AUTHOR = 4
446 STATUS = 5
447
448 REVID = QtCore.Qt.UserRole + 1
449 FILEID = QtCore.Qt.UserRole + 2
450 PATH = QtCore.Qt.UserRole + 3
451
452 _many_loaddirs_started = False
453 _many_loaddirs_should_start = False
454
455 def __init__(self, parent=None):
456 # XXX parent object: instance of what class it supposed to be?
457 # QtCore.QAbstractTableModel.__init__(self, parent)
458 super().__init__(parent=parent)
459
460 self.unver_by_parent = None
461 self.change_load_filter = None
462 self.changes_mode = None
463 self.branch = None
464 self.get_children = None
465 self.is_item_in_select_all: Callable
466 self.revno_map = None
467 self.missing_icon = QtGui.QIcon()
468 if parent is not None:
469 # TreeModel is subclass of QtCore.QAbstractItemModel,
470 # the latter can have parent in constructor
471 # as instance of QtCore.QModelIndex and the latter does not have style()
472 style = parent.style()
473 self.file_icon = style.standardIcon(QtWidgets.QStyle.SP_FileIcon)
474 self.dir_icon = style.standardIcon(QtWidgets.QStyle.SP_DirIcon)
475 self.symlink_icon = style.standardIcon(QtWidgets.QStyle.SP_FileLinkIcon)
476 self.missing_icon.addFile(':/16x16/missing.png')
477 else:
478 self.file_icon = QtGui.QIcon()
479 self.dir_icon = QtGui.QIcon()
480 self.symlink_icon = QtGui.QIcon()
481
482 self.tree = None
483 self.inventory_data = []
484 self.inventory_data_by_path = {}
485 self.inventory_data_by_id = {} # Will not contain unversioned items.
486 self.checkable = False
487 self.icon_provider = QtWidgets.QFileIconProvider()
488 self.parent_view = parent
489 self._index_cache = {}
490 self.set_select_all_kind()
491 self.last_item_data = []
492
493 def get_name(self, dir_fileid, dir_path, path, basis_tree, change: ChangeDescription):
494 # If we've a name like 'somedir/thisname' then dirpath will be non-empty ('somedir') remove it from the name
495 if dir_path:
496 name = path[len(dir_path) + 1:]
497 else:
498 name = path
499 if change and change.is_renamed():
500 old_inventory_item = self._get_entry(basis_tree, change.tree_change.file_id)
501 old_names = [old_inventory_item.name]
502 while old_inventory_item.parent_id:
503 if old_inventory_item.parent_id == dir_fileid:
504 break
505 old_inventory_item = self._get_entry(basis_tree, old_inventory_item.parent_id)
506 old_names.append(old_inventory_item.name)
507 old_names.reverse()
508 old_path = "/".join(old_names)
509 name = "%s => %s" % (old_path, name)
510 return name
511
512 def set_tree(self, tree, branch=None, changes_mode=False, want_unversioned=True,
513 initial_checked_paths=None, change_load_filter=None, load_dirs=None):
514 """
515 Work out the various filters for display (ignored, select all and so on).
516 Eventually we'll fill self.inventory_data via self.append_item()
517 """
518 self.tree = tree
519 self.branch = branch
520 self.revno_map = None
521 self.changes_mode = changes_mode
522 self.change_load_filter = change_load_filter
523
524 # ? sourceModel ?
525 self.layoutAboutToBeChanged.emit()
526
527 is_refresh = len(self.inventory_data) > 0
528 if is_refresh:
529 self.beginRemoveRows(QtCore.QModelIndex(), 0, len(self.inventory_data[0].children_ids) - 1)
530 self.inventory_data = []
531 self._index_cache = {}
532 self.unver_by_parent = {}
533 self.inventory_data_by_path = {}
534 self.inventory_data_by_id = {}
535 if is_refresh:
536 self.endRemoveRows()
537
538 if isinstance(self.tree, WorkingTree):
539 with tree.lock_read():
540 root_id = self.tree.path2id('')
541 basis_tree = self.tree.basis_tree()
542 with basis_tree.lock_read():
543 # Compare the widget's tree with the basis (original tree)
544 # for other_lines, the_change in enumerate(self.tree.iter_changes(basis_tree, want_unversioned=want_unversioned)):
545 the_changes = list(self.tree.iter_changes(basis_tree, want_unversioned=want_unversioned))
546 for other_lines, the_change in enumerate(the_changes):
547 # iter_changes now seems to appear to return a TreeChange type See Jelmer's 7390.
548 # Handily, it has an as_tuple() function, so we'll cheat for now
549 # change = ChangeDesc(tree_change_object=the_change, associated_tree=self.tree)
550 change = ChangeDescription(the_change)
551 fileid = change.tree_change.file_id
552 if fileid == root_id:
553 continue
554 path = change.old_or_new_path()
555 # tree.is_ignored() doesn't actually return a boolean, instead it
556 # returns either None or the pattern to be ignored.
557 is_ignored = self.tree.is_ignored(path)
558 change._ignored_pattern = is_ignored
559 if self.change_load_filter is not None and not self.change_load_filter(change):
560 continue
561
562 item = InternalItem("", change.old_or_new_kind(), fileid)
563 item_data = ModelItemData(path, change=change, item=item)
564 self.inventory_data_by_path[path] = item_data
565 if fileid:
566 self.inventory_data_by_id[fileid] = item_data
567
568 for conflict in self.tree.conflicts():
569 path = conflict.path
570 if path in self.inventory_data_by_path:
571 self.inventory_data_by_path[path].conflicts.append(conflict)
572 else:
573 item_data = ModelItemData(path, conflicts=[conflict])
574 fileid = conflict.file_id
575 try:
576 kind = file_kind(self.tree.abspath(path))
577 except NoSuchFile:
578 kind = ''
579
580 item_data.item = InternalItem("", kind, fileid)
581 self.inventory_data_by_path[path] = item_data
582 if fileid:
583 self.inventory_data_by_id[fileid] = item_data
584
585 if initial_checked_paths:
586 # Add versioned directories so that we can easily check them.
587 for path in initial_checked_paths:
588 fileid = self.tree.path2id(path)
589 if fileid:
590 kind = self.tree.kind(path)
591 if kind == "directory":
592 item_data = self.inventory_data_by_path.get(path)
593 if item_data is None:
594 item = InternalItem("", kind, fileid)
595 item_data = ModelItemData(path, item=item)
596 self.inventory_data_by_path[path] = item_data
597 self.inventory_data_by_id[fileid] = item_data
598
599 if changes_mode:
600 self.unver_by_parent = group_large_dirs(frozenset(iter(self.inventory_data_by_path.keys())))
601
602 # Add items for directories added
603 for path in self.unver_by_parent.keys():
604 if path not in self.inventory_data_by_path:
605 kind = "directory"
606 file_id = self.tree.path2id(path)
607 item = InternalItem("", kind, file_id)
608 item_data = ModelItemData(path, item=item)
609 self.inventory_data_by_path[path] = item_data
610 if file_id:
611 self.inventory_data_by_id[file_id] = item_data
612
613 # Name setting
614 for dir_path, decendents in self.unver_by_parent.items():
615 dir_fileid = self.tree.path2id(dir_path)
616 for path in decendents:
617 item_data = self.inventory_data_by_path[path]
618 item_data.item.name = self.get_name(dir_fileid, dir_path, path,
619 basis_tree=basis_tree, change=item_data.change)
620 # RJLRJL: added - original code manipulated item_data but seemed to do nothing with it
621 self.inventory_data_by_path[path] = item_data
622 if dir_fileid:
623 self.inventory_data_by_id[dir_fileid] = item_data
624 # end of RJLRJL added
625 else:
626 # record the unversioned items
627 for item_data in self.inventory_data_by_path.values():
628 if item_data.change and not item_data.change.is_versioned() or not item_data.change:
629 parent_path, name = os.path.split(item_data.path)
630 dict_set_add(self.unver_by_parent, parent_path, item_data.path)
631
632 # Name setting
633 for item_data in self.inventory_data_by_path.values():
634 dir_path, name = os.path.split(item_data.path)
635 dir_fileid = self.tree.path2id(dir_path)
636 item_data.item.name = self.get_name(dir_fileid, dir_path, item_data.path,
637 basis_tree=basis_tree, change=item_data.change)
638
639 self.process_tree(self.working_tree_get_children, initial_checked_paths, load_dirs)
640 else:
641 self.process_tree(self.revision_tree_get_children, initial_checked_paths, load_dirs)
642
643 self.layoutChanged.emit()
644
645 def revision_tree_get_children(self, item_data):
646 path = self.tree.id2path(item_data.item.file_id)
647 for child in self.tree.iter_child_entries(path):
648 path = self.tree.id2path(child.file_id)
649 yield ModelItemData(path, item=child)
650
651 def working_tree_get_children(self, item_data):
652 item = item_data.item
653 # RJLRJL temp bypass
654 if item.file_id is None:
655 abspath = self.tree.abspath(item_data.path)
656
657 for name in os.listdir(abspath):
658 path = item_data.path + "/" + name
659 (kind, executable, stat_value) = self.tree._comparison_data(None, path)
660 child = InternalItem(name, kind, None)
661 is_ignored = self.tree.is_ignored(path)
662 # RJL BUGBUG: TreeChange initialisation looks incorrect
663 # tree.iter_changes states:
664 # Changed_content is True if the file's content has changed. This
665 # includes changes to its kind, and to a symlink's target.
666 #
667 # versioned, parent, name, kind, executable are tuples of (from, to).
668 # If a file is missing in a tree, its kind is None.
669 # t = TreeChange((None, path), False, (False, False), (None, None), (None, name), (None, kind), (None, executable))
670 t = TreeChange(path=(None, path), changed_content=False, versioned=(False, False),
671 name=(None, name), kind=(None, kind), executable=(None, executable))
672 # change = ChangeDesc(tree_change_object=t, ignored_pattern=is_ignored, associated_tree=self.tree)
673 change = ChangeDescription(tree_change_object=t, ignored_pattern=is_ignored)
674
675 # change = ChangeDesc((None,(None, path), False, (False, False),
676 # (None, None),
677 # (None, name), (None, kind),
678 # (None, executable),
679 # is_ignored))
680
681 if self.change_load_filter is not None and not self.change_load_filter(change):
682 continue
683
684 yield ModelItemData(path, item=child, change=change)
685
686 if not isinstance(item, InternalItem) and item.kind == 'directory' and not self.changes_mode:
687 # Because we create copies, we have to get the real item.
688 item = self._get_entry(self.tree, item.file_id)
689 path = self.tree.id2path(item.file_id)
690 for child in self.tree.iter_child_entries(path):
691
692 if child.file_id in self.inventory_data_by_id:
693 child_item_data = self.inventory_data_by_id[child.file_id]
694 else:
695 path = self.tree.id2path(child.file_id)
696 child_item_data = ModelItemData(path)
697
698 # Create a copy so that we don't have to hold a lock of the wt.
699 child = self._get_entry(self.tree, child.file_id).copy()
700 child_item_data.item = child
701 yield child_item_data
702
703 if item_data.path in self.unver_by_parent:
704 for path in self.unver_by_parent[item_data.path]:
705 yield self.inventory_data_by_path[path]
706
707 def start_maybe_many_loaddirs(self):
708 self._many_loaddirs_should_start = True
709
710 def end_maybe_many_loaddirs(self):
711 self._many_loaddirs_should_start = False
712 if self._many_loaddirs_started:
713 self._many_loaddirs_started = False
714 self.tree.unlock()
715
716 def load_dir(self, dir_id):
717 if dir_id >= len(self.inventory_data):
718 return
719 dir_item = self.inventory_data[dir_id]
720 if dir_item.children_ids is not None:
721 return # This dir has already been loaded.
722 if not dir_item.item.kind == 'directory':
723 return
724
725 if not self._many_loaddirs_started:
726 self.tree.lock_read()
727 if self._many_loaddirs_should_start:
728 self._many_loaddirs_started = True
729
730 # RJL: the strange construction with self.get_children pointing to
731 # revision_tree_get_children seems to be a hangover from
732 # python 2.4 days when one could not have yield in a try / finally block
733 # nor had context managers.
734 try:
735 dir_item.children_ids = []
736 child_list = list(self.get_children(dir_item))
737 children = sorted(child_list, key=ModelItemData.dirs_first_sort_key)
738 parent_model_index = self._index_from_id(dir_id, 0)
739 self.beginInsertRows(parent_model_index, 0, len(children) - 1)
740 try:
741 for child in children:
742 child_id = self.append_item(child, dir_id)
743 dir_item.children_ids.append(child_id)
744 finally:
745 self.endInsertRows()
746 finally:
747 if not self._many_loaddirs_started:
748 self.tree.unlock()
749
750 def _get_entry(self, tree, file_id):
751 # RJLRJL BUGBUG it looks like requesting specific_files must NOT pass any
752 # We only ever get one entry, so we don't need a loop
753 # entries consist of (path, entry) tuples: entry appears to be an Inventory Directory or Path
754 # actual paths (e.g. dir/movedandrenamed should be stripped to movedandrenamed)
755 # RJLRJL: id2path() seems to be the problem - we are looking at self.tree but then call
756 # iter_entries on the PASSED tree
757 the_path = self.tree.id2path(file_id)
758 entries = list(tree.iter_entries_by_dir(specific_files=[the_path], recurse_nested=True))
759 if entries:
760 return entries[0][1]
761 else:
762 the_other_path = tree.id2path(file_id)
763 entries = list(tree.iter_entries_by_dir(specific_files=[the_other_path], recurse_nested=True))
764 if entries:
765 return entries[0][1]
766 raise errors.NoSuchId(tree, (file_id, the_path))
767
768 def process_tree(self, get_children, initial_checked_paths, load_dirs):
769 # RJL get_children seems to be a passed function and looks like it is used by load_dir
770 self.get_children = get_children
771 root_item = ModelItemData('', item=self._get_entry(self.tree, self.tree.path2id('')))
772 root_id = self.append_item(root_item, None)
773 self.load_dir(root_id)
774
775 if load_dirs:
776 # refs2indexes will load the parents if nesseary.
777 for index in self.refs2indexes(load_dirs, ignore_no_file_error=True):
778 self.load_dir(index.internalId())
779
780 if self.checkable:
781 if initial_checked_paths is not None:
782 self.set_checked_paths(initial_checked_paths)
783 else:
784 # RJL initial_checked_paths will be None (I think) if EVERYTHING is to be checked that is, 'select all'
785 self.setData(self._index_from_id(root_id, self.NAME), QtCore.Qt.Checked, QtCore.Qt.CheckStateRole)
786
787 def append_item(self, item_data, parent_id):
788 item_data.id = len(self.inventory_data)
789 if parent_id is not None:
790 parent_data = self.inventory_data[parent_id]
791 item_data.row = len(parent_data.children_ids)
792 else:
793 # Root Item
794 item_data.row = 0
795 item_data.parent_id = parent_id
796 self.inventory_data.append(item_data)
797 self.inventory_data_by_path[item_data.path] = item_data
798 if item_data.item.file_id is not None:
799 self.inventory_data_by_id[item_data.item.file_id] = item_data
800 return item_data.id
801
802 def set_revno_map(self, revno_map):
803 self.revno_map = revno_map
804 for item_data in self.inventory_data[1:0]:
805 index = self.createIndex(item_data.row, self.REVNO, item_data.id)
806 self.dataChanged.emit(index, index)
807
808 # The ellipsis is to match the QtCore stub
809 def columnCount(self, parent=...) -> int:
810 return len(self.HEADER_LABELS)
811
812 def rowCount(self, parent=...) -> int:
813 # if 0: parent = QtCore.QModelIndex()
814 # Note, internalID() is part of pyQt4
815 if parent.column() > 0 or parent.internalId() >= len(self.inventory_data):
816 return 0
817 parent_data = self.inventory_data[parent.internalId()]
818 if parent_data.children_ids is None:
819 return 0
820 return len(parent_data.children_ids)
821
822 def canFetchMore(self, parent):
823 if parent.internalId() >= len(self.inventory_data):
824 return False
825 parent_data = self.inventory_data[parent.internalId()]
826 return parent_data.children_ids is None and parent_data.item.kind == "directory"
827
828 def fetchMore(self, parent):
829 self.load_dir(parent.internalId())
830
831 def _index(self, row, column, parent_id):
832 if parent_id >= len(self.inventory_data):
833 return QtCore.QModelIndex()
834
835 cache_key = (parent_id, row, column)
836 if cache_key in self._index_cache:
837 return self._index_cache[cache_key]
838 else:
839 parent_data = self.inventory_data[parent_id]
840 if parent_data.children_ids is None:
841 return QtCore.QModelIndex()
842
843 if row < 0 or row >= len(parent_data.children_ids) or column < 0 or column >= len(self.HEADER_LABELS):
844 return QtCore.QModelIndex()
845 item_id = parent_data.children_ids[row]
846 index = self.createIndex(row, column, item_id)
847 self._index_cache[cache_key] = index
848 return index
849
850 def _index_from_id(self, item_id, column):
851 if item_id >= len(self.inventory_data):
852 return QtCore.QModelIndex()
853 item_data = self.inventory_data[item_id]
854 return self.createIndex(item_data.row, column, item_id)
855
856 def index(self, row, column, parent=QtCore.QModelIndex()):
857 if parent.column() > 0:
858 return QtCore.QModelIndex()
859 return self._index(row, column, parent.internalId())
860
861 def sibling(self, row, column, index):
862 sibling_id = index.internalId()
863 if sibling_id == 0:
864 return QtCore.QModelIndex()
865 item_data = self.inventory_data[sibling_id]
866 return self._index(row, column, item_data.parent_id)
867
868 def parent(self, child):
869 child_id = child.internalId()
870 if child_id == 0:
871 return QtCore.QModelIndex()
872 item_data = self.inventory_data[child_id]
873 if item_data.parent_id == 0:
874 return QtCore.QModelIndex()
875
876 return self._index_from_id(item_data.parent_id, 0)
877
878 def hasChildren(self, parent=...):
879 if self.tree is None:
880 return False
881 if parent.internalId() == 0:
882 return True
883 item_data = self.inventory_data[parent.internalId()]
884 return item_data.item.kind == "directory"
885
886 def set_select_all_kind(self, kind='all'):
887 """Set checker function for 'select all' checkbox. Possible kind values: all, versioned."""
888
889 def _is_item_in_select_all_all(item):
890 """Returns whether an item is changed when select all is clicked,
891 and whether it's children are looked at."""
892 return True, True
893
894 def _is_item_in_select_all_versioned(item):
895 return item.change is None or item.change.is_versioned(), True
896
897 if kind == 'all':
898 self.is_item_in_select_all = _is_item_in_select_all_all
899 elif kind == 'versioned':
900 self.is_item_in_select_all = _is_item_in_select_all_versioned
901
902 def set_checked(self, item_data, checked, emit=True) -> bool:
903 old_checked = item_data.checked
904 item_data.checked = checked
905 return not old_checked == checked
906
907 def set_child_checked_recurse(self, item_data, value):
908 # Recursively set all children to checked.
909 if item_data.children_ids is None and item_data.item.kind == "directory":
910 self.load_dir(item_data.id)
911 if not item_data.children_ids:
912 return False
913 have_changed_item = False
914
915 for child_id in item_data.children_ids:
916 child = self.inventory_data[child_id]
917
918 # If unchecking, uncheck everything, but if checking, only check those in "select_all" get checked.
919 if value == QtCore.Qt.Unchecked:
920 change = True
921 lookat_children = True
922 else:
923 (change, lookat_children) = self.is_item_in_select_all(child)
924
925 self.last_item_data[0] = child
926
927 if lookat_children:
928 has_children_changed = self.set_child_checked_recurse(child, value)
929 else:
930 has_children_changed = False
931
932 if change or has_children_changed:
933 have_changed_item = True
934 self.set_checked(child, value, False)
935 return have_changed_item
936
937 def setData(self, index: QModelIndex, value: Any, role:int = ...) -> bool:
938 # This appears to be used when clicking select / deselect all (at least in qAdd)
939 if index.column() == self.NAME and role == QtCore.Qt.CheckStateRole:
940
941 # RJLRJL: patch undo
942 # value = int(value)
943 if index.internalId() >= len(self.inventory_data):
944 return False
945
946 item_data = self.inventory_data[index.internalId()]
947 first_index = self._index_from_id(item_data.id, self.NAME)
948 self.set_checked(item_data, value)
949 self.last_item_data = [None]
950 # RJLRJL: this many_loadirs stuff possibly needs a context manager
951 self.start_maybe_many_loaddirs()
952 try:
953 self.set_child_checked_recurse(item_data, value=value)
954 finally:
955 self.end_maybe_many_loaddirs()
956
957 if self.last_item_data[0]:
958 last_index = self._index_from_id(self.last_item_data[0].id, self.NAME)
959 else:
960 last_index = first_index
961 self.dataChanged.emit(first_index, last_index)
962
963 # Walk up the tree, and update every dir
964 parent_data = item_data
965 while parent_data.parent_id is not None:
966 (in_select_all, look_at_children) = self.is_item_in_select_all(parent_data)
967 if not in_select_all and value == QtCore.Qt.Unchecked:
968 # Don't uncheck parents if not in "select_all".
969 break
970 parent_data = self.inventory_data[parent_data.parent_id]
971 has_checked = False
972 has_unchecked = False
973 for child_id in parent_data.children_ids:
974 child = self.inventory_data[child_id]
975 (child_in_select_all, child_look_at_children) = self.is_item_in_select_all(parent_data)
976
977 if child.checked == QtCore.Qt.Checked:
978 has_checked = True
979 elif child.checked == QtCore.Qt.Unchecked and child_in_select_all:
980 has_unchecked = True
981 elif child.checked == QtCore.Qt.PartiallyChecked:
982 has_checked = True
983 if child_in_select_all:
984 has_unchecked = True
985
986 if has_checked and has_unchecked:
987 break
988
989 if has_checked and has_unchecked:
990 checked = QtCore.Qt.PartiallyChecked
991 elif has_checked:
992 checked = QtCore.Qt.Checked
993 else:
994 checked = QtCore.Qt.Unchecked
995
996 if self.set_checked(parent_data, checked):
997 index = self._index_from_id(parent_data.id, self.NAME)
998 self.dataChanged.emit(index, index)
999
1000 return True
1001
1002 if index.column() == self.NAME and role == QtCore.Qt.EditRole:
1003
1004 if not isinstance(self.tree, WorkingTree):
1005 return False
1006 # Rename
1007 value = str(value)
1008 item_data = self.inventory_data[index.internalId()]
1009 parent = self.inventory_data[item_data.parent_id]
1010 new_path = posixpath.join(parent.path, value)
1011 if item_data.path == new_path:
1012 return False
1013 try:
1014 if item_data.item.file_id:
1015 # Versioned file
1016 self.tree.rename_one(item_data.path, new_path)
1017 else:
1018 old_path_abs=self.tree.abspath(item_data.path)
1019 new_path_abs=self.tree.abspath(new_path)
1020 os.rename(old_path_abs, new_path_abs)
1021 except Exception:
1022 report_exception(type=SUB_LOAD_METHOD, window=self.parent_view.window())
1023 # We do this so that the ref has the new_path, and hence refresh
1024 # restores it's state correctly.
1025 item_data.path = new_path
1026 ref = self.index2ref(index)
1027 self.parent_view.refresh()
1028 try:
1029 new_index = self.ref2index(ref)
1030 new_index = self.parent_view.tree_filter_model.mapFromSource(new_index)
1031 self.parent_view.scrollTo(new_index)
1032 except (errors.NoSuchId, NoSuchFile):
1033 pass
1034 return True
1035 return False
1036
1037 def data(self, index, role):
1038 # QT function, mostly display stuff as self.inventory_data should have been filled by now
1039 if not index.isValid():
1040 return None
1041 if role in (QtCore.Qt.FontRole, QtCore.Qt.TextAlignmentRole, QtCore.Qt.BackgroundRole,
1042 QtCore.Qt.BackgroundColorRole, QtCore.Qt.ForegroundRole, QtCore.Qt.TextColorRole):
1043 return None
1044
1045 item_data = self.inventory_data[index.internalId()]
1046 item = item_data.item
1047
1048 if role == self.FILEID:
1049 return QtCore.QByteArray(item.file_id)
1050
1051 column = index.column()
1052 if column == self.NAME:
1053 if role == QtCore.Qt.DisplayRole:
1054 return item.name
1055 if role == QtCore.Qt.EditRole:
1056 path = item_data.path
1057 if item_data.parent_id:
1058 parent = self.inventory_data[item_data.parent_id]
1059 path = path[len(parent.path) + 1:]
1060 return path
1061 if role == QtCore.Qt.DecorationRole:
1062 if item_data.icon is None:
1063 if item_data.change and not item_data.change.is_on_disk() or item.kind == '':
1064 item_data.icon = self.missing_icon
1065 elif isinstance(self.tree, WorkingTree):
1066 abspath = self.tree.abspath(item_data.path)
1067 info = QtCore.QFileInfo(abspath)
1068 item_data.icon = self.icon_provider.icon(info)
1069 else:
1070 if item.kind == "file":
1071 item_data.icon = self.file_icon
1072 if item.kind == "directory":
1073 item_data.icon = self.dir_icon
1074 if item.kind == "symlink":
1075 item_data.icon = self.symlink_icon
1076 if item_data.icon is None:
1077 item_data.icon = None
1078 return item_data.icon
1079
1080 if role == QtCore.Qt.CheckStateRole:
1081 if not self.checkable:
1082 return None
1083 else:
1084 return item_data.checked
1085
1086 if column == self.STATUS:
1087 if role == QtCore.Qt.DisplayRole:
1088 status = []
1089 if item_data.change is not None:
1090 status.append(item_data.change.status())
1091 for conflict in item_data.conflicts:
1092 status.append(conflict.typestring)
1093 return ", ".join(status)
1094
1095 # RJLRJL check this before patch changes (patch line ~= 1897)
1096 try:
1097 revid = item_data.item.revision
1098 except AttributeError:
1099 # GitTreeDirectory object has no attribute 'repository'
1100 return None
1101
1102 if role == self.REVID:
1103 return revid
1104
1105 if column == self.REVNO:
1106 if role == QtCore.Qt.DisplayRole:
1107 if self.revno_map is not None and revid in self.revno_map:
1108 revno_sequence = self.revno_map[revid]
1109 return ".".join(["%d" % revno for revno in revno_sequence])
1110 else:
1111 return ""
1112
1113 if role == QtCore.Qt.DisplayRole:
1114 if revid in cached_revisions:
1115 rev = cached_revisions[revid]
1116
1117 if column == self.AUTHOR:
1118 return get_apparent_author_name(rev)
1119
1120 if column == self.MESSAGE:
1121 return get_summary(rev)
1122
1123 if column == self.DATE:
1124 return strftime("%Y-%m-%d %H:%M", localtime(rev.timestamp))
1125
1126 if role == self.PATH:
1127 return item_data.path
1128
1129 if role == QtCore.Qt.DisplayRole:
1130 return ""
1131 return None
1132
1133 def flags(self, index):
1134 if not index.isValid():
1135 return QtCore.Qt.NoItemFlags
1136
1137 flags = (QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable)
1138
1139 if isinstance(self.tree, WorkingTree):
1140 flags = flags | QtCore.Qt.ItemIsDragEnabled
1141
1142 if index.column() == self.NAME:
1143 flags = flags | QtCore.Qt.ItemIsEditable
1144 if self.checkable:
1145 flags = flags | QtCore.Qt.ItemIsUserCheckable
1146
1147 internal_id = index.internalId()
1148 if internal_id < len(self.inventory_data):
1149 item_data = self.inventory_data[index.internalId()]
1150 if item_data.item.kind == "directory":
1151 flags = flags | QtCore.Qt.ItemIsDropEnabled
1152
1153 return flags
1154
1155 def headerData(self, section, orientation, role):
1156 if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole:
1157 return self.HEADER_LABELS[section]
1158 return None
1159
1160 def on_revisions_loaded(self, revisions, last_call):
1161 for item_data in self.inventory_data:
1162 if item_data.id == 0:
1163 continue
1164
1165 if item_data.item.revision in revisions:
1166 self.dataChanged.emit(self.createIndex(item_data.row, self.DATE, item_data.id),
1167 self.createIndex(item_data.row, self.AUTHOR, item_data.id))
1168
1169 def get_repo(self):
1170 # RJLRJL Check this patch line ~= 1966
1171 if self.branch is not None:
1172 return self.branch.repository
1173 else:
1174 return None
1175
1176 @staticmethod
1177 def item2ref(item_data):
1178 return PersistantItemReference(item_data.item.file_id, item_data.path)
1179
1180 def index2ref(self, index):
1181 item_data = self.inventory_data[index.internalId()]
1182 return self.item2ref(item_data)
1183
1184 def indexes2refs(self, indexes):
1185 refs = []
1186 for index in indexes:
1187 refs.append(self.index2ref(index))
1188 return refs
1189
1190 def ref2index(self, ref):
1191 if ref.file_id is not None:
1192 key = ref.file_id
1193 inventory_data_dict = self.inventory_data_by_id
1194
1195 def iter_parents():
1196 parent_id = self._get_entry(self.tree, ref.file_id).parent_id
1197 parent_ids = []
1198 while parent_id is not None:
1199 parent_ids.append(parent_id)
1200 parent_id = self._get_entry(self.tree, parent_id).parent_id
1201 return reversed(parent_ids)
1202 else:
1203 key = ref.path
1204 inventory_data_dict = self.inventory_data_by_path
1205
1206 def iter_parents():
1207 path_split = ref.path.split("/")
1208 parent_dir_path = None
1209 for parent_name in path_split[:-1]:
1210 if parent_dir_path is None:
1211 parent_dir_path = parent_name
1212 else:
1213 parent_dir_path += "/" + parent_name
1214 yield parent_dir_path
1215
1216 if key not in inventory_data_dict or inventory_data_dict[key].id is None:
1217 # Try loading the parents
1218 for parent_key in iter_parents():
1219 if parent_key in inventory_data_dict:
1220 self.load_dir(inventory_data_dict[parent_key].id)
1221
1222 if key not in inventory_data_dict:
1223 raise NoSuchFile(ref.path)
1224
1225 return self._index_from_id(inventory_data_dict[key].id, self.NAME)
1226
1227 def refs2indexes(self, refs, ignore_no_file_error=False):
1228 indexes = []
1229 for ref in refs:
1230 try:
1231 indexes.append(self.ref2index(ref))
1232 except (errors.NoSuchId, NoSuchFile):
1233 if not ignore_no_file_error:
1234 raise
1235 return indexes
1236
1237 def iter_checked(self, include_unchanged_dirs=True):
1238 """
1239 Iterate over the list of checked items and emit the entires.
1240
1241 @param include_unchanged_dirs: should we include unchanged directories
1242 or skip them.
1243 """
1244 # We have to recurse and load all dirs, because we use --no-recurse
1245 # for add, and commit and revert don't recurse.
1246 # i = 0
1247 # while i < len(self.inventory_data):
1248 # item_data = self.inventory_data[i]
1249 # if item_data.children_ids is None and item_data.item.kind == "directory" and item_data.checked:
1250 # self.load_dir(item_data.id)
1251 # i += 1
1252
1253 for item_data in self.inventory_data:
1254 if item_data.children_ids is None and item_data.item.kind == "directory" and item_data.checked:
1255 self.load_dir(item_data.id)
1256
1257 for item_data in self.inventory_data[1:]:
1258 if item_data.checked == QtCore.Qt.Checked:
1259 if item_data.change is None and item_data.item.kind == 'directory' and not include_unchanged_dirs:
1260 continue
1261 yield self.item2ref(item_data)
1262
1263 def set_checked_items(self, refs, ignore_no_file_error=True):
1264 # set every thing off
1265 root_index = self._index_from_id(0, self.NAME)
1266 self.setData(root_index, QtCore.Qt.Unchecked, QtCore.Qt.CheckStateRole)
1267
1268 for index in self.refs2indexes(refs, ignore_no_file_error):
1269 self.setData(index, QtCore.Qt.Checked, QtCore.Qt.CheckStateRole)
1270
1271 def set_checked_paths(self, paths):
1272 return self.set_checked_items([PersistantItemReference(None, path) for path in paths])
1273
1274 def supportedDropActions(self):
1275 return QtCore.Qt.MoveAction
1276
1277
1278 class TreeFilterProxyModel(QtCore.QSortFilterProxyModel):
1279 source_model = None
1280
1281 filters = [True, True, True, False] # Unchanged, Changed, Unversioned, Ignored
1282 filter_cache = {}
1283
1284 def setSourceModel(self, source_model):
1285 self.source_model = source_model
1286 QtCore.QSortFilterProxyModel.setSourceModel(self, source_model)
1287
1288 def invalidateFilter(self):
1289 # self.layoutAboutToBeChanged.emit()
1290 self.filter_cache = {}
1291 self.source_model.start_maybe_many_loaddirs()
1292 try:
1293 QtCore.QSortFilterProxyModel.invalidateFilter(self)
1294 finally:
1295 self.source_model.end_maybe_many_loaddirs()
1296
1297 def setFilter(self, the_filter, value):
1298 self.filters[the_filter] = value
1299 # This is slow. It causes TreeModel.index, and TreeModel.data thousands of times.
1300 self.invalidateFilter()
1301
1302 def setFilters(self, filters):
1303 def iff(b, x, y):
1304 if b:
1305 return x
1306 else:
1307 return y
1308
1309 self.filters = [iff(f is not None, f, old_f) for f, old_f in zip(filters, self.filters)]
1310 self.invalidateFilter()
1311
1312 def filterAcceptsRow(self, source_row, source_parent) -> bool:
1313 # if all(self.filters):
1314 # return True
1315 model = self.source_model
1316 parent_id = source_parent.internalId()
1317 children_ids = model.inventory_data[parent_id].children_ids
1318 if len(children_ids) <= source_row:
1319 return False
1320 child_id = children_ids[source_row]
1321 if model.checkable and not model.inventory_data[child_id].checked == QtCore.Qt.Unchecked:
1322 return True
1323 return bool(self.filter_id_cached(child_id))
1324
1325 def filter_id_cached(self, child_id):
1326 if child_id in self.filter_cache:
1327 return self.filter_cache[child_id]
1328 else:
1329 result = self.filter_id_recurse(child_id)
1330 self.filter_cache[child_id] = result
1331 return result
1332
1333 def filter_id_recurse(self, child_id):
1334 item_data = self.source_model.inventory_data[child_id]
1335
1336 the_filter = self.filter_id(child_id, item_data)
1337 if the_filter is not None:
1338 return the_filter
1339
1340 if item_data.item.kind == "directory":
1341 if item_data.children_ids is None:
1342 self.source_model.load_dir(child_id)
1343
1344 for child_id in item_data.children_ids:
1345 if self.filter_id_cached(child_id):
1346 return True
1347 return False
1348
1349 def filter_id(self, child_id, item_data):
1350 """Determines whether a item should be displayed.
1351 Returns :
1352 * True: Show the item
1353 * False: Do not show the item
1354 * None: Show the item if there are any children that are visible.
1355 """
1356 (unchanged, changed, unversioned, ignored) = self.filters
1357 is_changed = item_data.change is not None
1358 is_versioned = item_data.item.file_id is not None
1359
1360 if is_versioned and not is_changed and unchanged:
1361 return True
1362
1363 if is_versioned and is_changed and changed:
1364 return True
1365
1366 if not is_versioned:
1367 if is_changed and (unversioned or ignored):
1368 is_ignored = item_data.change.ignored_pattern()
1369 if not is_ignored and unversioned:
1370 return True
1371 if is_ignored:
1372 return ignored
1373 else:
1374 return False
1375
1376 return None
1377
1378 def on_revisions_loaded(self, revisions, last_call):
1379 self.source_model.on_revisions_loaded(revisions, last_call)
1380
1381 def get_repo(self):
1382 return self.source_model.get_repo()
1383
1384 def hasChildren(self, parent):
1385 return self.source_model.hasChildren(self.mapToSource(parent))
1386
1387
1388 class TreeFilterMenu(QtWidgets.QMenu):
1389 triggered = QtCore.pyqtSignal(int, bool)
1390
1391 def __init__(self, parent=None):
1392 QtWidgets.QMenu.__init__(self, gettext("&Filter"), parent)
1393
1394 filters = (gettext("Unchanged"),
1395 gettext("Changed"),
1396 gettext("Unversioned"),
1397 gettext("Ignored"))
1398
1399 self.actions = []
1400 for i, text in enumerate(filters):
1401 action = QtWidgets.QAction(text, self)
1402 action.setData(i)
1403 action.setCheckable(True)
1404 self.addAction(action)
1405 self.actions.append(action)
1406
1407 # self.triggered[QtWidgets.QAction].connect(self._triggered)
1408 self.triggered.connect(self._triggered)
1409
1410 def _triggered(self, action):
1411 # filter = action.data().toInt()[0]
1412 the_filter = int(action.data())
1413 checked = action.isChecked()
1414 self.triggered.emit(the_filter, checked)
1415
1416 def set_filters(self, filters):
1417 for checked, action in zip(filters, self.actions):
1418 action.setChecked(checked)
1419
1420
1421 class TreeWidget(RevisionTreeView):
1422 dataChanged = QtCore.pyqtSignal(QtCore.QModelIndex, QtCore.QModelIndex)
1423
1424 def __init__(self, *args):
1425 RevisionTreeView.__init__(self, *args)
1426
1427 self.setAlternatingRowColors(True)
1428
1429 self.change_load_filter = None
1430 self.want_unversioned = None
1431 self.changes_mode = None
1432 self.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
1433 self.setUniformRowHeights(True)
1434 self.setEditTriggers(QtWidgets.QAbstractItemView.SelectedClicked | QtWidgets.QAbstractItemView.EditKeyPressed)
1435 self.viewport().setAcceptDrops(True)
1436 self.setDropIndicatorShown(True)
1437 self.setDragDropMode(QtWidgets.QAbstractItemView.InternalMove)
1438
1439 self.tree = None
1440 self.branch = None
1441
1442 self.tree_model = TreeModel(self)
1443 self.tree_filter_model = TreeFilterProxyModel()
1444 self.tree_filter_model.setSourceModel(self.tree_model)
1445 self.setModel(self.tree_filter_model)
1446 # self.setModel(self.tree_model)
1447
1448 self.revno_item_delegate = RevNoItemDelegate(parent=self)
1449 self.set_header_width_settings()
1450 self.setItemDelegateForColumn(self.tree_model.REVNO, self.revno_item_delegate)
1451 self.doubleClicked[QtCore.QModelIndex].connect(self.do_default_action)
1452 self.context_menu = QtWidgets.QMenu(self)
1453 self.action_open_file = self.context_menu.addAction(gettext("&Open"), self.open_file)
1454 self.action_show_file = self.context_menu.addAction(gettext("&View file"), self.show_file_content)
1455 self.action_show_annotate = self.context_menu.addAction(gettext("Show &annotate"), self.show_file_annotate)
1456 self.action_show_log = self.context_menu.addAction(gettext("Show &log"), self.show_file_log)
1457 if has_ext_diff():
1458 diff_menu = ExtDiffMenu(self)
1459 self.action_show_diff = self.context_menu.addMenu(diff_menu)
1460 diff_menu._triggered.connect(self.show_differences)
1461 else:
1462 self.action_show_diff = self.context_menu.addAction(gettext("Show &differences"), self.show_differences)
1463
1464 self.context_menu.addSeparator()
1465 self.action_merge = self.context_menu.addAction(gettext("&Merge conflict"), self.merge)
1466 self.action_resolve = self.context_menu.addAction(gettext("Mark conflict &resolved"), self.resolve)
1467
1468 self.context_menu.addSeparator()
1469 self.action_add = self.context_menu.addAction(gettext("&Add"), self.add)
1470 self.action_revert = self.context_menu.addAction(gettext("&Revert"), self.revert)
1471 self.action_rename = self.context_menu.addAction(gettext("Re&name"), self.rename)
1472 self.action_remove = self.context_menu.addAction(gettext("Remove"), self.remove)
1473 # The text for this is set per selection, depending on move or rename.
1474 self.action_mark_move = self.context_menu.addAction("mv --after", self.mark_move)
1475
1476 def set_header_width_settings(self):
1477 header = self.header()
1478 header.setStretchLastSection(False)
1479 header.setSectionResizeMode(self.tree_model.NAME, QtWidgets.QHeaderView.ResizeToContents)
1480 header.setSectionResizeMode(self.tree_model.DATE, QtWidgets.QHeaderView.Interactive)
1481 header.setSectionResizeMode(self.tree_model.REVNO, QtWidgets.QHeaderView.Interactive)
1482 header.setSectionResizeMode(self.tree_model.MESSAGE, QtWidgets.QHeaderView.Stretch)
1483 header.setSectionResizeMode(self.tree_model.AUTHOR, QtWidgets.QHeaderView.Interactive)
1484 header.setSectionResizeMode(self.tree_model.STATUS, QtWidgets.QHeaderView.Stretch)
1485 fm = self.fontMetrics()
1486 # XXX Make this dynamic.
1487 col_margin = (self.style().pixelMetric(QtWidgets.QStyle.PM_FocusFrameHMargin, None, self) + 1) * 2
1488
1489 header.resizeSection(self.tree_model.REVNO, fm.width("8" * self.revno_item_delegate.max_mainline_digits + ".8.888") + col_margin)
1490 header.resizeSection(self.tree_model.DATE, fm.width("88-88-8888 88:88") + col_margin)
1491 header.resizeSection(self.tree_model.AUTHOR, fm.width("Joe I have a Long Name") + col_margin)
1492 if self.tree and isinstance(self.tree, WorkingTree):
1493 header.setSectionResizeMode(self.tree_model.NAME, QtWidgets.QHeaderView.Stretch)
1494 header.setSectionResizeMode(self.tree_model.STATUS, QtWidgets.QHeaderView.ResizeToContents)
1495
1496 def set_visible_headers(self):
1497 header = self.header()
1498 if isinstance(self.tree, WorkingTree):
1499 # We currently have to hide the revision columns, because the
1500 # revision property is not availible from the WorkingTree.inventory.
1501 # We may be able to get this by looking at the revision tree for
1502 # the revision of the basis tree.
1503 header.hideSection(self.tree_model.DATE)
1504 header.hideSection(self.tree_model.REVNO)
1505 header.hideSection(self.tree_model.MESSAGE)
1506 header.hideSection(self.tree_model.AUTHOR)
1507 header.showSection(self.tree_model.STATUS)
1508 header.setSectionResizeMode(self.tree_model.NAME, QtWidgets.QHeaderView.Stretch)
1509 header.setSectionResizeMode(self.tree_model.STATUS, QtWidgets.QHeaderView.ResizeToContents)
1510
1511 self.context_menu.setDefaultAction(self.action_open_file)
1512 else:
1513 header.showSection(self.tree_model.DATE)
1514 header.showSection(self.tree_model.REVNO)
1515 header.showSection(self.tree_model.MESSAGE)
1516 header.showSection(self.tree_model.AUTHOR)
1517 header.hideSection(self.tree_model.STATUS)
1518 header.setSectionResizeMode(self.tree_model.NAME, QtWidgets.QHeaderView.ResizeToContents)
1519 header.setSectionResizeMode(self.tree_model.STATUS, QtWidgets.QHeaderView.Stretch)
1520
1521 self.context_menu.setDefaultAction(self.action_show_file)
1522
1523 def set_tree(self, tree, branch=None, changes_mode=False, want_unversioned=True,
1524 initial_checked_paths=None, change_load_filter=None):
1525 """Causes a tree to be loaded, and displayed in the widget.
1526
1527 @param changes_mode: If in changes mode, a list of changes, and
1528 unversioned items, rather than a tree, is diplayed.
1529 e.g., when not in changes mode, one will get:
1530
1531 dir1
1532 file1 changed
1533 file2 changed
1534
1535 but when in changes mode, one will get:
1536
1537 dir1/file1 changed
1538 file2 changed
1539
1540 When in changes mode, no unchanged items are shown.
1541
1542 @param initial_checked_paths: list of specific filenames
1543 which should be selected in the widget. By default all items
1544 selected. Value None or empty list means: all selected.
1545 """
1546 self.tree = tree
1547 if isinstance(tree, RevisionTree) and branch is None:
1548 raise AttributeError("A branch must be provided if the tree is a RevisionTree")
1549
1550 self.revision_loading_disabled = isinstance(tree, WorkingTree)
1551 self.branch = branch
1552 self.changes_mode = changes_mode
1553 self.want_unversioned = want_unversioned
1554 self.change_load_filter = change_load_filter
1555
1556 if branch:
1557 with branch.lock_read():
1558 last_revno = branch.last_revision_info()[0]
1559 self.revno_item_delegate.set_max_revno(last_revno)
1560 # update width uncoditionally because we may change the revno column
1561 self.set_header_width_settings()
1562 self.set_visible_headers()
1563 QtCore.QCoreApplication.processEvents()
1564
1565 if initial_checked_paths and not self.tree_model.checkable:
1566 raise AttributeError("You can't have a initial_selection if tree_model.checkable is not True.")
1567
1568 self.tree_model.set_tree(self.tree, self.branch, changes_mode, want_unversioned=want_unversioned,
1569 change_load_filter=self.change_load_filter, initial_checked_paths=initial_checked_paths)
1570
1571 if self.tree_model.checkable:
1572 refs = self.tree_model.iter_checked()
1573 indexes = self.tree_model.refs2indexes(refs)
1574 self.expanded_to_indexes(indexes)
1575
1576 if sys.platform.startswith("win"):
1577 # This is to fix Bug 402276, where the treewidget does not get
1578 # repainted when you scroll.
1579 # (https://bugs.launchpad.net/qbrz/+bug/402276)
1580 # I think that this is a bug with qt, and so this is just a work-
1581 # arround. We should check when we bump the min qt version to 4.5 if
1582 # we can take this out. I think it only happens on windows. This may
1583 # need to be checked.
1584 # RJLRJL: review this for the ignored / select all checkboxes which
1585 # suffer the same non-repainting problem
1586 for row in range(len(self.tree_model.inventory_data[0].children_ids)):
1587 index = self.tree_model.createIndex(row, self.tree_model.NAME, 0)
1588 self.tree_model.dataChanged.emit(index, index)
1589
1590 def iter_expanded_indexes(self):
1591 parents_to_check = [QtCore.QModelIndex()]
1592 while parents_to_check:
1593 parent = parents_to_check.pop(0)
1594 for row in range(self.tree_filter_model.rowCount(parent)):
1595 child = self.tree_filter_model.index(row, 0, parent)
1596 if self.isExpanded(child):
1597 parents_to_check.append(child)
1598 yield self.tree_filter_model.mapToSource(child)
1599
1600 def set_expanded_indexes(self, indexes):
1601 for index in indexes:
1602 self.expand(self.tree_filter_model.mapFromSource(index))
1603
1604 def expanded_to_indexes(self, indexes):
1605 for index in indexes:
1606 while index.internalId():
1607 self.expand(self.tree_filter_model.mapFromSource(index))
1608 index = self.tree_model.parent(index)
1609
1610 def get_state(self):
1611 if self.tree_model.checkable:
1612 checked = [(self.tree_model.item2ref(item_data), item_data.checked) for item_data in self.tree_model.inventory_data[1:]]
1613 else:
1614 checked = None
1615 expanded = self.tree_model.indexes2refs(self.iter_expanded_indexes())
1616 selected = self.tree_model.indexes2refs(self.get_selection_indexes())
1617 v_scroll = self.verticalScrollBar().value()
1618 return checked, expanded, selected, v_scroll
1619
1620 def restore_state(self, state):
1621 (checked, expanded, selected, v_scroll) = state
1622 with self.tree.lock_read():
1623 if self.tree_model.checkable and checked is not None:
1624 for (ref, state) in checked:
1625 if not state == QtCore.Qt.PartiallyChecked:
1626 try:
1627 index = self.tree_model.ref2index(ref)
1628 self.tree_model.setData(index, state, QtCore.Qt.CheckStateRole)
1629 except (errors.NoSuchId, NoSuchFile):
1630 pass
1631
1632 self.set_expanded_indexes(self.tree_model.refs2indexes(expanded, ignore_no_file_error=True))
1633
1634 for index in self.tree_model.refs2indexes(selected, ignore_no_file_error=True):
1635 # XXX This does not work for sub items. I can't figure out why.
1636 # GaryvdM - 14/07/2009
1637 # RJLRJL I can't either (2021 / 2023)
1638 self.selectionModel().select(
1639 self.tree_filter_model.mapFromSource(index),
1640 QtCore.QItemSelectionModel.SelectCurrent | QtCore.QItemSelectionModel.Rows)
1641 self.verticalScrollBar().setValue(v_scroll)
1642
1643 def refresh(self):
1644 with self.tree.lock_read():
1645 state = self.get_state()
1646 self.tree_model.set_tree(self.tree, self.branch, self.changes_mode, self.want_unversioned,
1647 change_load_filter=self.change_load_filter, load_dirs=state[1])
1648 self.restore_state(state)
1649 self.tree_filter_model.invalidateFilter()
1650
1651 def mousePressEvent(self, event):
1652 index = self.indexAt(event.pos())
1653 if not isinstance(self.tree, WorkingTree):
1654 self.setDragEnabled(False)
1655 if not self.selectionModel().isSelected(index):
1656 # Don't drag if we are not over the selection.
1657 self.setDragEnabled(False)
1658 else:
1659 # Don't allow draging a selection that goes across dirs.
1660 ok_selection = True
1661 item_by_path = {}
1662 item_ids = set()
1663 for item in self.get_selection_items():
1664 item_by_path[item.path] = item
1665 item_ids.add(item.id)
1666 root_dir = None
1667 for path in minimum_path_selection(list(item_by_path.keys())):
1668 dir_path, name = os.path.split(path)
1669 if root_dir is None:
1670 root_dir = dir_path
1671 if dir_path != root_dir:
1672 ok_selection = False
1673 break
1674 item = item_by_path[path]
1675 if item.item.kind == "directory" and item.children_ids:
1676 # Either all, or none of the children must be selected.
1677 first = None
1678 for child_id in item.children_ids:
1679 this = child_id in item_ids
1680 if first is None:
1681 first = this
1682 if first != this:
1683 ok_selection = False
1684 break
1685 if not ok_selection:
1686 break
1687 self.setDragEnabled(ok_selection)
1688
1689 QtWidgets.QTreeView.mousePressEvent(self, event)
1690
1691 def dropEvent(self, event):
1692 if not isinstance(self.tree, WorkingTree):
1693 return
1694
1695 # we should encode the paths list, give it an appropriate mime type, etc.
1696 # Easier to just get the selection.
1697 drop_index = self.tree_filter_model.mapToSource(self.indexAt(event.pos()))
1698 drop_item = self.tree_model.inventory_data[drop_index.internalId()]
1699 if drop_item.item.kind == "directory":
1700 drop_path = drop_item.path
1701 else:
1702 drop_path, name = os.path.split(drop_item.path)
1703 paths = [item.path for item in self.get_selection_items()]
1704 try:
1705 self.tree.move(paths, drop_path)
1706 except Exception:
1707 report_exception(type=SUB_LOAD_METHOD, window=self.window())
1708 self.refresh()
1709
1710 def contextMenuEvent(self, event):
1711 self.filter_context_menu()
1712 self.context_menu.popup(event.globalPos())
1713 event.accept()
1714
1715 def keyPressEvent(self, event):
1716 """Processing Enter key to launch default action for files and
1717 expand/collapse directories.
1718 """
1719 e_key = event.key()
1720 if e_key in (QtCore.Qt.Key_Enter, QtCore.Qt.Key_Return):
1721 if not self.state() & QtWidgets.QAbstractItemView.EditingState:
1722 event.accept()
1723 indexes = self.selectionModel().selectedRows(0)
1724 if len(indexes) == 1 and self.get_selection_items(indexes)[0].item.kind == 'directory':
1725 self.setExpanded(indexes[0], not self.isExpanded(indexes[0]))
1726 else:
1727 self.do_default_action(None)
1728 return
1729 QtWidgets.QTreeView.keyPressEvent(self, event)
1730
1731 def get_selection_indexes(self, indexes=None):
1732 if indexes is None or (len(indexes) == 1 and indexes[0] is None):
1733 indexes = self.selectionModel().selectedRows(0)
1734 return [self.tree_filter_model.mapToSource(index) for index in indexes]
1735
1736 def get_selection_items(self, indexes=None):
1737 items = []
1738 indexes = self.get_selection_indexes(indexes)
1739 for index in indexes:
1740 items.append(self.tree_model.inventory_data[index.internalId()])
1741 return items
1742
1743 def filter_context_menu(self):
1744 is_working_tree = isinstance(self.tree, WorkingTree)
1745 items = self.get_selection_items()
1746 versioned = [item.item.file_id is not None for item in items]
1747 changed = [item.change is not None for item in items]
1748 versioned_changed = [ver and ch for ver,ch in zip(versioned, changed)]
1749 conflicts = [len(item.conflicts) > 0 for item in items]
1750 text_conflicts = [len([conflicts for conflict in item.conflicts if isinstance(conflict, TextConflict)]) > 0 for item in items]
1751 on_disk = [item.change is None or item.change.is_on_disk() for item in items]
1752 selection_len = len(items)
1753
1754 single_item_in_tree = (selection_len == 1 and (items[0].change is None or items[0].change[6][1] is not None))
1755 single_file = (single_item_in_tree and items[0].item.kind == "file")
1756 single_versioned_file = (single_file and versioned[0])
1757
1758 self.action_open_file.setEnabled(single_item_in_tree)
1759 self.action_show_file.setEnabled(single_file)
1760 self.action_show_annotate.setEnabled(single_versioned_file)
1761 self.action_show_log.setEnabled(any(versioned))
1762 self.action_show_diff.setVisible(is_working_tree)
1763 self.action_show_diff.setEnabled(any(versioned_changed))
1764
1765 self.action_merge.setVisible(is_working_tree)
1766 self.action_merge.setEnabled(any(text_conflicts))
1767 self.action_resolve.setVisible(is_working_tree)
1768 self.action_resolve.setEnabled(any(conflicts))
1769
1770 self.action_add.setVisible(is_working_tree)
1771 self.action_add.setDisabled(all(versioned))
1772 self.action_revert.setVisible(is_working_tree)
1773 self.action_revert.setEnabled(any(versioned_changed))
1774 self.action_rename.setVisible(is_working_tree)
1775 self.action_rename.setEnabled(single_item_in_tree)
1776 self.action_remove.setVisible(is_working_tree)
1777 self.action_remove.setEnabled(any(on_disk))
1778
1779 can_mark_move = (selection_len == 2 and
1780 (missing_unversioned(items[0], items[1]) or missing_unversioned(items[1], items[0])))
1781 self.action_mark_move.setVisible(can_mark_move)
1782 if can_mark_move:
1783 move, rename = move_or_rename(items[0].path, items[1].path)
1784 if move and rename:
1785 self.action_mark_move.setText(gettext("&Mark as moved and renamed"))
1786 elif move:
1787 self.action_mark_move.setText(gettext("&Mark as moved"))
1788 elif rename:
1789 self.action_mark_move.setText(gettext("&Mark as renamed"))
1790
1791 if is_working_tree:
1792 if any(versioned_changed):
1793 self.context_menu.setDefaultAction(self.action_show_diff)
1794 else:
1795 self.context_menu.setDefaultAction(self.action_open_file)
1796
1797 def do_default_action(self, index):
1798 # XXX This should be made to handle selections of multiple items.
1799 item_data = self.get_selection_items([index])[0]
1800 if item_data.item.kind == "directory":
1801 # Don't do anything, so that the directory can be expanded.
1802 return
1803
1804 if isinstance(self.tree, WorkingTree):
1805 if item_data.change is not None and item_data.change.is_versioned():
1806 self.show_differences(index=index)
1807 else:
1808 self.open_file(index)
1809 else:
1810 self.show_file_content(index)
1811
1812 @ui_current_widget
1813 def show_file_content(self, index=None):
1814 """Launch qcat for one selected file."""
1815 items = self.get_selection_items([index])
1816 if not len(items) == 1:
1817 return
1818 item = items[0]
1819
1820 encoding = get_set_encoding(None, self.branch)
1821 if item.item.file_id is not None:
1822 window = QBzrCatWindow(filename=item.path, tree=self.tree, parent=self, encoding=encoding)
1823 else:
1824 abspath = os.path.join(self.tree.basedir, item.path)
1825 window = QBzrViewWindow(filename=abspath, encoding=encoding, parent=self)
1826 window.show()
1827 self.window().windows.append(window)
1828
1829 @ui_current_widget
1830 def open_file(self, index=None):
1831 """Open the file in the os specified editor."""
1832
1833 items = self.get_selection_items([index])
1834 if not len(items) == 1:
1835 return
1836 item = items[0]
1837
1838 if isinstance(self.tree, WorkingTree):
1839 with self.tree.lock_read():
1840 abspath = self.tree.abspath(item.path)
1841 url = QtCore.QUrl.fromLocalFile(abspath)
1842 QtGui.QDesktopServices.openUrl(url)
1843 else:
1844 cat_to_native_app(self.tree, item.path)
1845
1846 @ui_current_widget
1847 def show_file_log(self):
1848 """Show qlog for one selected file(s)."""
1849
1850 items = self.get_selection_items()
1851 fileids = [item.item.file_id for item in items if item.item.file_id is not None]
1852 window = LogWindow(branch=self.branch,specific_file_ids=fileids)
1853 window.show()
1854 self.window().windows.append(window)
1855
1856 @ui_current_widget
1857 def show_file_annotate(self):
1858 """Show qannotate for selected file."""
1859 index = self.currentIndex()
1860 file_id = bytes(index.data(self.tree_model.FILEID))
1861 path = str(index.data(self.tree_model.PATH))
1862
1863 if isinstance(file_id, str):
1864 raise errors.InternalBzrError('file_id should be plain string, not unicode')
1865
1866 window = AnnotateWindow(self.branch, None, self.tree, path, file_id)
1867 window.show()
1868 self.window().windows.append(window)
1869
1870 @ui_current_widget
1871 def show_differences(self, ext_diff=None, index=None):
1872 """Show differences for selected file(s)."""
1873
1874 items = self.get_selection_items([index])
1875 if len(items) > 0:
1876 # Only paths that have changes.
1877 paths = [item.path for item in items if item.change is not None]
1878 else:
1879 # Show all.
1880 paths = None
1881
1882 arg_provider = InternalWTDiffArgProvider(None, self.tree, self.tree.branch, self.tree.branch, specific_files=paths)
1883 show_diff(arg_provider, ext_diff=ext_diff, parent_window=self.window(), context=self.diff_context)
1884
1885 def unversioned_parents_paths(self, item, include_item=True):
1886 paths = []
1887 first = True
1888 while item.item.file_id is None:
1889 if first:
1890 if include_item:
1891 paths.append(item.path)
1892 first = False
1893 else:
1894 paths.append(item.path)
1895
1896 if item.parent_id:
1897 item = self.tree_model.inventory_data[item.parent_id]
1898 else:
1899 break
1900 paths.reverse()
1901 return paths
1902
1903 @ui_current_widget
1904 def add(self):
1905 """Add selected file(s)."""
1906
1907 items = self.get_selection_items()
1908
1909 # Only paths that are not versioned.
1910 paths = []
1911 for item in items:
1912 paths.extend(self.unversioned_parents_paths(item))
1913 if len(paths) == 0:
1914 return
1915 try:
1916 self.tree.add(paths)
1917 except Exception:
1918 report_exception(type=SUB_LOAD_METHOD, window=self.window())
1919
1920 # XXX - it would be good it we could just refresh the selected items
1921 self.refresh()
1922
1923 @ui_current_widget
1924 def revert(self):
1925 """Revert selected file(s)."""
1926
1927 items = self.get_selection_items()
1928 # Only paths that have changes.
1929 paths = [item.path for item in items if item.change is not None and item.item.file_id is not None]
1930 if len(paths) == 0:
1931 return
1932
1933 res = QtWidgets.QMessageBox.question(self,
1934 gettext("Revert"),
1935 gettext("Do you really want to revert the selected file(s)?"),
1936 QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No)
1937 if res == QtWidgets.QMessageBox.Yes:
1938 try:
1939 with self.tree.lock_write():
1940 self.tree.revert(paths, self.tree.basis_tree())
1941 except Exception:
1942 report_exception(type=SUB_LOAD_METHOD, window=self.window())
1943 # XXX - it would be good it we could just refresh the selected items
1944 self.refresh()
1945
1946 @ui_current_widget
1947 def merge(self):
1948 """Merge conflicting file in external merge app"""
1949
1950 items = self.get_selection_items()
1951 # Only paths that have text conflicts.
1952 paths = [item.path
1953 for item in items
1954 if len([conflict for conflict in item.conflicts if isinstance(conflict, TextConflict)]) > 0]
1955 if len(paths) == 0:
1956 return
1957
1958 args = ["extmerge"]
1959 args.extend(paths)
1960 desc = " ".join(args)
1961 SimpleSubProcessDialog(gettext("External Merge"),
1962 desc=desc,
1963 args=args,
1964 dir=self.tree.basedir,
1965 parent=self,
1966 auto_start_show_on_failed=True,
1967 hide_progress=True,)
1968 # RJLRJL: Check that the comment below is warranted
1969 # We don't refesh the tree, because it is very unlikley to have changed.
1970
1971 def resolve(self):
1972 """Mark selected file(s) as resolved."""
1973
1974 items = self.get_selection_items()
1975 # Only paths that have changes.
1976 paths = [item.path for item in items if len(item.conflicts) > 0]
1977 if len(paths) == 0:
1978 return
1979 try:
1980 resolve(self.tree, paths)
1981 except Exception:
1982 report_exception(type=SUB_LOAD_METHOD, window=self.window())
1983 self.refresh()
1984
1985 def mark_move(self):
1986 items = self.get_selection_items()
1987 if len(items) != 2:
1988 return
1989 if missing_unversioned(items[0], items[1]):
1990 old = items[0]
1991 new = items[1]
1992 elif missing_unversioned(items[1], items[0]):
1993 old = items[1]
1994 new = items[0]
1995 else:
1996 return
1997 try:
1998 # add the new parent
1999 self.tree.add(self.unversioned_parents_paths(new, False))
2000 self.tree.rename_one(old.path, new.path, after=True)
2001 except Exception:
2002 report_exception(type=SUB_LOAD_METHOD, window=self.window())
2003 self.refresh()
2004
2005 @ui_current_widget
2006 def rename(self):
2007 """Rename the selected file."""
2008
2009 indexes = self.get_selection_indexes()
2010 if len(indexes) != 1:
2011 return
2012 index = indexes[0]
2013 index = self.tree_filter_model.mapFromSource(index)
2014 self.edit(index)
2015
2016 @ui_current_widget
2017 def remove(self):
2018 """Remove selected file(s)."""
2019
2020 items = self.get_selection_items()
2021 # Only paths that are not missing
2022 paths = [item.path for item in items if item.change is None or item.change.is_on_disk()]
2023 if len(paths) == 0:
2024 return
2025 try:
2026 try:
2027 self.tree.remove(paths, keep_files=False)
2028 except errors.BzrRemoveChangedFilesError:
2029 # RJL: BUGBUG seems to no longer be a BzrRemoveChangedFilesError
2030 res = QtWidgets.QMessageBox.question(
2031 self, gettext("Remove"),
2032 gettext("Some of the files selected cannot be recovered if "
2033 "removed. Are you sure you want to remove these "
2034 "files?"),
2035 QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No)
2036 if res == QtWidgets.QMessageBox.Yes:
2037 self.tree.remove(paths, keep_files=False, force=True)
2038 except Exception:
2039 report_exception(type=SUB_LOAD_METHOD, window=self.window())
2040
2041 self.refresh()
2042
2043
2044 class SelectAllCheckBox(QtWidgets.QCheckBox):
2045
2046 clicked = QtCore.pyqtSignal(bool)
2047
2048 def __init__(self, tree_widget, parent=None):
2049 super().__init__(text=gettext("Select / deselect all"), parent=parent)
2050 self.tree_widget = tree_widget
2051 # self.setTristate(True)
2052 tree_widget.tree_model.dataChanged[QtCore.QModelIndex, QtCore.QModelIndex].connect(self.on_data_changed)
2053 # RJLRJL: changed from clicked[bool] to toggled for pyqt5
2054 self.toggled[bool].connect(self._clicked)
2055
2056 def on_data_changed(self, start_index, end_index):
2057 self.update_state()
2058
2059 def update_state(self):
2060 model = self.tree_widget.tree_model
2061 root_index = model._index_from_id(0, model.NAME)
2062 state = model.data(root_index, QtCore.Qt.CheckStateRole)
2063 self.setCheckState(QtCore.Qt.CheckState(state))
2064
2065 def _clicked(self, state):
2066 model = self.tree_widget.tree_model
2067 root_index = model._index_from_id(0, model.NAME)
2068 if state:
2069 state = QtCore.Qt.Checked
2070 else:
2071 state = QtCore.Qt.Unchecked
2072 model.setData(root_index, state, QtCore.Qt.CheckStateRole)