Debian Codegraph @

lib/loggraphviz.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 #
3 # QBrz - Qt frontend to Breezy commands
4 # Copyright (C) 2006-2010 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 """
21 Layout a revision graph for visual representation, allowing for filtering and
22 collapsible branches.
23
24 Usage example
25 =============
26
27 .. python::
28 bi = loggraphviz.BranchInfo('branch-label', tree, branch)
29 graph_viz = loggraphviz.GraphVizLoader([bi], bi, False)
30 graph_viz.load()
31 state = loggraphviz.GraphVizFilterState(graph_viz)
32 computed = graph_viz.compute_viz(state)
33
34 """
35
36 import gc
37 from functools import reduce
38
39
40 from breezy import errors
41 from breezy.controldir import ControlDir
42 from breezy.transport.local import LocalTransport
43 from breezy.revision import NULL_REVISION, CURRENT_REVISION
44 from breezy.graph import (
45 Graph,
46 StackedParentsProvider,
47 KnownGraph,
48 DictParentsProvider,
49 )
50
51
52 class BranchInfo(object):
53 """Wrapper for a branch, it's working tree, if available, and a label."""
54
55 def __init__(self, label, tree, branch, index=None):
56 self.label = label
57 self.tree = tree
58 self.branch = branch
59 self.index = index
60
61 def __hash__(self):
62 return self.branch.base.__hash__()
63
64 def __eq__(self, other):
65 if isinstance(other, BranchInfo):
66 return self.branch.base.__eq__(other.branch.base)
67 return False
68
69
70 class RevisionData(object):
71 """
72 Container for data for a revision in the graph that gets calculated
73 when the graph is loaded.
74 """
75
76 # Instance of this object are typically named "rev".
77
78 __slots__ = ["index", "_merge_sort_node", "branch", "_revno_str",
79 "merges", "merged_by", 'branch_id', 'color']
80
81 def __init__(self, index, merge_sort_node):
82 """Create a new RevisionData instance."""
83 self.index = index
84 self._merge_sort_node = merge_sort_node
85 self.branch = None
86 self._revno_str = None
87 self.merges = []
88 """Revision indexes that this revision merges"""
89 self.merged_by = None
90 """Revision index that merges this revision."""
91 self.branch_id = self._merge_sort_node.revno[0:-1]
92 self.color = reduce(lambda x, y: x + y, self.branch_id, 0)
93
94 revid = property(lambda self: self._merge_sort_node.key)
95 merge_depth = property(lambda self: self._merge_sort_node.merge_depth)
96 revno_sequence = property(lambda self: self._merge_sort_node.revno)
97 end_of_merge = property(lambda self: self._merge_sort_node.end_of_merge)
98
99 def get_revno_str(self):
100 if self._revno_str is None:
101 self._revno_str = ".".join(["%d" % revno for revno in self.revno_sequence])
102 if self.revid.startswith(CURRENT_REVISION):
103 self._revno_str += " ?"
104 return self._revno_str
105 revno_str = property(get_revno_str)
106
107 def __repr__(self):
108 return "%s <%s %s>" % (self.__class__.__name__, self.revno_str, self.revid)
109
110
111 class BranchLine(object):
112 """Container for data for a branch line, aka merge line."""
113
114 __slots__ = ["branch_id", "revs", "merges", "merged_by", "color", "merge_depth"]
115
116 def __init__(self, branch_id):
117 self.branch_id = branch_id
118 self.revs = []
119 self.merges = []
120 self.merged_by = []
121 self.merge_depth = 0
122
123 def __repr__(self):
124 return "%s <%s>" % (self.__class__.__name__, self.branch_id)
125
126
127 class GhostRevisionError(errors.InternalBzrError):
128
129 _fmt = "{%(revision_id)s} is a ghost."
130
131 def __init__(self, revision_id):
132 errors.BzrError.__init__(self)
133 self.revision_id = revision_id
134
135
136 class GraphVizLoader(object):
137 """
138 Loads graph for branches and provides computed layout for visual
139 representation.
140 """
141
142 # Most list/dicts related to revisions are unfiltered. When we do a graph
143 # layout, we filter these revisions. A revision may be filter out because:
144 # * It's branch is hidden (or collapsed).
145 # * We have a specified file_id(s), and the revision does not touch the
146 # file_id(s).
147 # * We have a search, and the revision does not match the search.
148 #
149 # The main list of unfiltered revisions is self.revisions. A revisions
150 # index in revisions are normally called index. The main list of filtered
151 # revisions is filtered_revs. Revision indexes in this list are called
152 # f_index.
153
154 def __init__(self, branches, primary_bi, no_graph):
155 self.branches = branches
156 """List of BranchInfo for each branch."""
157 self.primary_bi = primary_bi
158 self.no_graph = no_graph
159
160 self.repos = []
161 self.local_repo_copies = []
162 """A list of repositories that revisions will be attempted to be loaded from first."""
163
164 self.revid_head_info = {}
165 """Dict with a keys of head revid and value of
166 (list of (branch, label),
167 list of revids that are unique to this head)
168
169 We can't just store the BranchInfo, because the label may have
170 have addition text in it, e.g. "Working Tree", "Pending Merges"
171 """
172
173 self.revid_branch_info = {}
174
175 self.ghosts = set()
176
177 self.revisions = []
178 """List of RevisionInfo from merge_sort."""
179
180 self.revid_rev = {}
181 self.graph_children = {}
182
183 self.tags = {} # map revid -> tags set
184
185 def load(self):
186 # Get a unique list of repositories. If the url is the same,
187 # we consider it the same repositories
188 repo_urls = set()
189 for bi in self.branches:
190 repo = bi.branch.repository
191 if repo.base not in repo_urls:
192 repo_urls.add(repo.base)
193 self.repos.append(repo)
194
195 no_local_repos = True
196 for repo in self.repos:
197 if repo_is_local(repo):
198 no_local_repos = False
199 if no_local_repos:
200 self.load_current_dir_repo()
201 self.repos.sort(key=lambda repo: not repo_is_local(repo))
202
203 self.lock_read_branches()
204 try:
205 head_revids, graph_parents = self.load_graph_parents()
206 self.process_graph_parents(head_revids, graph_parents)
207
208 self.compute_head_info()
209 del self.graph
210
211 if not self.no_graph:
212 self.compute_branch_lines()
213 self.compute_merge_info()
214
215 self.load_tags()
216 finally:
217 self.unlock_branches()
218
219 def load_current_dir_repo(self):
220 # There are no local repositories. Try open the repository
221 # of the current directory, and try load revisions data from
222 # this before trying from remote repositories. This makes
223 # the common use case of viewing a remote branch that is
224 # related to the current branch much faster, because most
225 # of the revision can be loaded from the local repository.
226 try:
227 controldir, relpath = ControlDir.open_containing(".")
228 repo = controldir.find_repository()
229 self.repos.add(repo)
230 self.local_repo_copies.append(repo)
231 except Exception:
232 pass
233
234 def update_ui(self):
235 pass
236
237 def throbber_show(self):
238 pass
239
240 def throbber_hide(self):
241 pass
242
243 def lock_read_branches(self):
244 for bi in self.branches:
245 bi.branch.lock_read()
246 for repo in self.repos:
247 repo.lock_read()
248
249 def unlock_branches(self):
250 for bi in self.branches:
251 bi.branch.unlock()
252 for repo in self.repos:
253 repo.unlock()
254
255 def load_tags(self):
256 self.tags = {}
257 for bi in self.branches:
258 # revid to tags map
259 branch_tags = bi.branch.tags.get_reverse_tag_dict()
260 for revid, tags in branch_tags.items():
261 if revid in self.tags:
262 self.tags[revid].update(set(tags))
263 else:
264 self.tags[revid] = set(tags)
265
266 def append_head_info(self, revid, branch_info, tag):
267 if not revid == NULL_REVISION:
268 if revid not in self.revid_head_info:
269 self.revid_head_info[revid] = ([], [])
270 self.revid_head_info[revid][0].append((branch_info, tag))
271
272 # So that early calls to get_revid_branch work
273 self.revid_branch_info[revid] = branch_info
274
275 def load_branch_heads(self, bi):
276 branch_heads = []
277
278 def append_head_info(revid, branch_info, label):
279 self.append_head_info(revid, branch_info, label)
280 branch_heads.append(revid)
281
282 if len(self.branches) > 0:
283 label = bi.label
284 else:
285 label = None
286
287 branch_last_revision = bi.branch.last_revision()
288 append_head_info(branch_last_revision, bi, bi.label)
289 self.update_ui()
290
291 if bi.tree:
292 parent_ids = bi.tree.get_parent_ids()
293 if parent_ids:
294 # first parent is last revision of the tree
295 revid = parent_ids[0]
296 if revid != branch_last_revision:
297 # working tree is out of date
298 if label:
299 wt_label = "%s - Working Tree" % label
300 else:
301 wt_label = "Working Tree"
302 append_head_info(revid, bi, wt_label)
303 # other parents are pending merges
304 for revid in parent_ids[1:]:
305 if label:
306 pm_label = "%s - Pending Merge" % label
307 else:
308 pm_label = "Pending Merge"
309 append_head_info(revid, bi, pm_label)
310 self.update_ui()
311 return branch_heads, branch_heads, ()
312
313 def load_graph_parents(self):
314 """Load the heads of the graph, and the graph parents"""
315
316 extra_parents = {}
317 branches_heads = []
318
319 def load_branch_heads(bi, insert_at_begin=False):
320 load_heads, sort_heads, extra_parents_ = self.load_branch_heads(bi)
321 for key, parents in extra_parents_:
322 extra_parents[key] = parents
323 if insert_at_begin:
324 branches_heads.insert(0, (load_heads, sort_heads))
325 else:
326 branches_heads.append((load_heads, sort_heads))
327
328 for bi in self.branches:
329 # Don't do the primary branch, as that will be inserted later at
330 # the first position.
331 if bi != self.primary_bi:
332 load_branch_heads(bi)
333
334 if len(branches_heads) >= 2:
335 head_revids = [revid for load_heads, sort_heads in branches_heads for revid in load_heads]
336 head_revs = self.load_revisions(head_revids)
337
338 get_max_timestamp = lambda branch_heads: max([head_revs[revid].timestamp for revid in branch_heads[0]])
339 branches_heads.sort(key=get_max_timestamp, reverse=True)
340
341 if self.primary_bi:
342 load_branch_heads(self.primary_bi, True)
343
344 load_heads = [revid for load_heads_, sort_heads_ in branches_heads for revid in load_heads_]
345 sort_heads = [revid for load_heads_, sort_heads_ in branches_heads for revid in sort_heads_]
346
347 parents_providers = [repo._make_parents_provider() for repo in self.repos]
348 parents_providers.append(DictParentsProvider(extra_parents))
349 self.graph = Graph(StackedParentsProvider(parents_providers))
350 return sort_heads, self.graph.iter_ancestry(sort_heads)
351
352 def process_graph_parents(self, head_revids, graph_parents_iter):
353 graph_parents = {}
354 self.ghosts = set()
355
356 for (revid, parent_revids) in graph_parents_iter:
357 if revid == NULL_REVISION:
358 continue
359 if parent_revids is None:
360 # Ghost
361 graph_parents[revid] = ()
362 self.ghosts.add(revid)
363 elif parent_revids == (NULL_REVISION,):
364 graph_parents[revid] = ()
365 else:
366 graph_parents[revid] = parent_revids
367 if len(graph_parents) % 100 == 0:
368 self.update_ui()
369
370 graph_parents["top:"] = head_revids
371
372 if len(graph_parents) > 0:
373 enabled = gc.isenabled()
374 if enabled:
375 gc.disable()
376
377 def make_kg():
378 return KnownGraph(graph_parents)
379 self.known_graph = make_kg()
380
381 merge_sorted_revisions = self.known_graph.merge_sort('top:')
382 # So far, we are a bit faster than the pure-python code. But the
383 # last step hurts. Specifically, we take
384 # 377ms KnownGraph(self.graph_parents)
385 # 263ms kg.merge_sort() [640ms combined]
386 # 1322ms self.revisions = [...]
387 # vs
388 # 1152ms tsort.merge_sort(self.graph_parents)
389 # 691ms self.revisions = [...]
390 #
391 # It is a gc thing... :(
392 # Adding gc.disable() / gc.enable() around this whole loop changes
393 # things to be:
394 # 100ms KnownGraph(self.graph_parents)
395 # 77ms kg.merge_sort() [177ms combined]
396 # 174ms self.revisions = [...]
397 # vs
398 # 639ms tsort.merge_sort(self.graph_parents)
399 # 150ms self.revisions = [...]
400 # Also known as "wow that's a lot faster". This is because KG()
401 # creates a bunch of Python objects, then merge_sort() creates a
402 # bunch more. And then self.revisions() creates another whole set.
403 # And all of these are moderately long lived, so you have a *lot*
404 # of allocations without removals (which triggers the gc checker
405 # over and over again.) And they probably don't live in cycles
406 # anyway, so you can skip it for now, and just run at the end.
407
408 # self.revisions *is* a little bit slower. Probably because pyrex
409 # MergeSortNodes use long integers rather than PyIntObject and thus
410 # create them on-the-fly.
411
412 # Get rid of the 'top:' revision
413 merge_sorted_revisions.pop(0)
414 self.revisions = [RevisionData(index, node)
415 for index, node in enumerate(merge_sorted_revisions)]
416 if enabled:
417 gc.enable()
418 else:
419 self.revisions = ()
420
421 self.revid_rev = {}
422 self.revno_rev = {}
423
424 self.max_mainline_revno = 0
425
426 for rev in self.revisions:
427 self.max_mainline_revno = max(self.max_mainline_revno, rev.revno_sequence[0])
428 self.revid_rev[rev.revid] = rev
429 self.revno_rev[rev.revno_sequence] = rev
430
431 def branch_id_sort_key(self, x):
432 merge_depth = self.branch_lines[x].merge_depth
433
434 # Note: This greatly affects the layout of the graph.
435 #
436 # Branch line that have a smaller merge depth should be to the left
437 # of those with bigger merge depths.
438 #
439 # For branch lines that have the same parent in the mainline -
440 # those with bigger branch numbers to be to the rights. E.g. for
441 # the following dag, you want the graph to appear as on the left,
442 # not as on the right:
443 #
444 # 3 F_ F
445 # | \ |\
446 # 1.2.1 | E | E
447 # | | | \
448 # 2 D | D_|
449 # |\ | | +_
450 # 1.1.2 | C| | | C
451 # | |/ | \|
452 # 1.1.1 | B | B
453 # |/ | /
454 # 1 A A
455 #
456 # Otherwise, those with a greater mainline parent revno should
457 # appear to the left.
458
459 if len(x) == 0:
460 return merge_depth, 0, 0
461 else:
462 return merge_depth, -x[0], x[1]
463
464 def compute_branch_lines(self):
465 self.branch_lines = {}
466
467 """A list of branch lines (aka merge lines).
468
469 For a revisions, the revision number less the least significant
470 digit is the branch_id, and used as the key for the dict. Hence
471 revision with the same revision number less the least significant
472 digit are considered to be in the same branch line. e.g.: for
473 revisions 290.12.1 and 290.12.2, the branch_id would be 290.12,
474 and these two revisions will be in the same branch line.
475
476 """
477
478 self.branch_ids = []
479 """List of branch ids, sorted in the order that the branches will
480 be shown, from left to right on the graph."""
481
482 for rev in self.revisions:
483
484 branch_line = None
485 if rev.branch_id not in self.branch_lines:
486 branch_line = BranchLine(rev.branch_id)
487 self.branch_lines[rev.branch_id] = branch_line
488 else:
489 branch_line = self.branch_lines[rev.branch_id]
490
491 branch_line.revs.append(rev)
492 branch_line.merge_depth = max(rev.merge_depth, branch_line.merge_depth)
493 rev.branch = branch_line
494
495 self.branch_ids = list(self.branch_lines.keys())
496 self.branch_ids.sort(key=self.branch_id_sort_key)
497
498 def compute_merge_info(self):
499
500 def set_merged_by(rev, merged_by, merged_by_rev, do_branches=False):
501 if merged_by is None:
502 return
503
504 if merged_by_rev is None:
505 merged_by_rev = self.revisions[merged_by]
506 rev.merged_by = merged_by
507 merged_by_rev.merges.append(rev.index)
508
509 if do_branches:
510 branch_id = rev.branch_id
511 branch_merged_by = self.branch_lines[branch_id].merged_by
512 merged_by_branch_id = self.revisions[merged_by].branch_id
513 merged_by_branch_merges = self.branch_lines[merged_by_branch_id].merges
514
515 if branch_id not in merged_by_branch_merges:
516 merged_by_branch_merges.append(branch_id)
517 if merged_by_branch_id not in branch_merged_by:
518 branch_merged_by.append(merged_by_branch_id)
519
520 for rev in self.revisions:
521
522 parents = [self.revid_rev[parent] for parent in self.known_graph.get_parent_keys(rev.revid)]
523 if len(parents) > 0:
524 if rev.branch_id == parents[0].branch_id:
525 set_merged_by(parents[0], rev.merged_by, None)
526
527 for parent in parents[1:]:
528 if rev.merge_depth <= parent.merge_depth:
529 set_merged_by(parent, rev.index, rev, do_branches=True)
530
531 def compute_head_info(self):
532 def get_revid_head(heads):
533 revision_map = {}
534 for i in range(len(heads)):
535 prev_revids = [revid for revid, head in heads[:i]]
536 unique_ancestors = self.graph.find_unique_ancestors(
537 heads[i][0], prev_revids)
538 for ancestor_revid in unique_ancestors:
539 revision_map[ancestor_revid] = heads[i][1]
540 return revision_map
541
542 if len(self.branches) > 1:
543 head_revid_branch_info = sorted(
544 [(revid, branch_info)
545 for revid, (head_info, ur) in self.revid_head_info.items()
546 for (branch_info, tag) in head_info],
547 key=lambda x: not repo_is_local(x[1].branch.repository))
548 self.revid_branch_info = get_revid_head(head_revid_branch_info)
549 else:
550 self.revid_branch_info = {}
551
552 head_count = 0
553 for head_info, ur in self.revid_head_info.values():
554 head_count += len(head_info)
555
556 if head_count > 1:
557 # Populate unique revisions for heads
558 for revid, (head_info, ur) in self.revid_head_info.items():
559 rev = None
560 if revid in self.revid_rev:
561 rev = self.revid_rev[revid]
562 if rev and rev.merged_by:
563 # This head has been merged.
564 # d
565 # |\
566 # b c
567 # |/
568 # a
569 # if revid == c,then we want other_revids = [b]
570
571 merged_by_revid = self.revisions[rev.merged_by].revid
572 other_revids = [self.known_graph.get_parent_keys(merged_by_revid)[0]]
573 else:
574 other_revids = [other_revid for other_revid in self.revid_head_info.keys()
575 if not other_revid == revid]
576 ur.append(revid)
577 ur.extend([revid for revid
578 in self.graph.find_unique_ancestors(revid, other_revids)
579 if not revid == NULL_REVISION and revid in self.revid_rev])
580 ur.sort(key=lambda x: self.revid_rev[x].index)
581
582 def compute_viz(self, state):
583
584 # Overview:
585 # Work out which revision need to be displayed.
586 # Create ComputedGraphViz and ComputedRevisionData objects
587 # Assign columns for branches, and lines that go between branches.
588 # These are intermingled, because some of the lines need to come
589 # before it's branch, and others need to come after. Other lines
590 # (such a the line from the last rev in a branch) are treated a
591 # special cases.
592 # Return ComputedGraphViz object
593 gc_enabled = gc.isenabled()
594 gc.disable()
595 try:
596 computed = ComputedGraphViz(self)
597 computed.filtered_revs = [ComputedRevisionData(rev) for rev in state.get_filtered_revisions()]
598
599 c_revisions = computed.revisions
600 for f_index, c_rev in enumerate(computed.filtered_revs):
601 c_revisions[c_rev.rev.index] = c_rev
602 c_rev.f_index = f_index
603
604 for (revid, (head_info, unique_revids)) in self.revid_head_info.items():
605 for unique_revid in unique_revids:
606 rev = self.revid_rev[unique_revid]
607 c_rev = c_revisions[rev.index]
608 if c_rev is not None:
609 c_rev.branch_labels.extend(head_info)
610 break
611 finally:
612 if gc_enabled:
613 gc.enable()
614
615 if self.no_graph:
616 for c_rev in computed.filtered_revs:
617 c_rev.col_index = c_rev.rev.merge_depth * 0.5
618 return computed
619
620 # This will hold a tuple of (child, parent, col_index, direct) for each
621 # line that needs to be drawn. If col_index is not none, then the line
622 # is drawn along that column, else the the line can be drawn directly
623 # between the child and parent because either the child and parent are
624 # in the same branch line, or the child and parent are 1 row apart.
625 lines = []
626 lines_by_column = []
627
628 def branch_line_col_search_order(start_col_index):
629 for col_index in range(start_col_index, len(lines_by_column)):
630 yield col_index
631 #for col_index in range(parent_col_index-1, -1, -1):
632 # yield col_index
633
634 def line_col_search_order(parent_col_index, child_col_index):
635 if parent_col_index is not None and child_col_index is not None:
636 max_index = max(parent_col_index, child_col_index)
637 min_index = min(parent_col_index, child_col_index)
638 # First yield the columns between the child and parent.
639 for col_index in range(max_index, min_index - 1, -1):
640 yield col_index
641 elif child_col_index is not None:
642 max_index = child_col_index
643 min_index = child_col_index
644 yield child_col_index
645 elif parent_col_index is not None:
646 max_index = parent_col_index
647 min_index = parent_col_index
648 yield parent_col_index
649 else:
650 max_index = 0
651 min_index = 0
652 yield 0
653 i = 1
654 # then yield the columns on either side.
655 while max_index + i < len(lines_by_column) or min_index - i > -1:
656 if max_index + i < len(lines_by_column):
657 yield max_index + i
658 #if min_index - i > -1:
659 # yield min_index - i
660 i += 1
661
662 def is_col_free_for_range(col_index, child_f_index, parent_f_index):
663 return not any(
664 range_overlaps(child_f_index, parent_f_index, line_child_f_index, line_parent_f_index)
665 for line_child_f_index, line_parent_f_index
666 in lines_by_column[col_index])
667
668 def find_free_column(col_search_order, child_f_index, parent_f_index):
669 for col_index in col_search_order:
670 if is_col_free_for_range(col_index, child_f_index, parent_f_index):
671 break
672 else:
673 # No free columns found. Add an empty one on the end.
674 col_index = len(lines_by_column)
675 lines_by_column.append([])
676 return col_index
677
678 def append_line(child, parent, direct, col_index=None):
679 lines.append((child, parent, col_index, direct))
680
681 if col_index is not None:
682 lines_by_column[int(round(col_index))].append(
683 (child.f_index, parent.f_index))
684
685 def find_visible_parent(c_rev, parent, twisty_hidden_parents):
686 if c_revisions[parent.index] is not None:
687 return (c_rev, c_revisions[parent.index], True)
688 else:
689 if parent.index in twisty_hidden_parents:
690 # no need to draw a line if there is a twisty,
691 # except if this is the last in the branch.
692 return None
693 # The parent was not visible. Search for a ancestor
694 # that is. Stop searching if we make a hop, i.e. we
695 # go away from our branch, and we come back to it.
696 has_seen_different_branch = False
697 while c_revisions[parent.index] is None:
698 if not parent.branch_id == c_rev.rev.branch_id:
699 has_seen_different_branch = True
700 # find grand parent.
701 g_parent_ids = (self.known_graph.get_parent_keys(parent.revid))
702
703 if len(g_parent_ids) == 0:
704 return None
705 else:
706 parent = self.revid_rev[g_parent_ids[0]]
707
708 if has_seen_different_branch and parent.branch_id == branch_id:
709 # We have gone away and come back to our
710 # branch. Stop.
711 return None
712 if parent:
713 # Not Direct
714 return c_rev, c_revisions[parent.index], False
715
716 def append_branch_parent_lines(branch_rev_visible_parents):
717 groups = group_overlapping(branch_rev_visible_parents)
718 for parents, start, end, group_key in groups:
719 # Since all parents go from the same branch line to the
720 # same branch line, we can use the col indexes of the
721 # parent.
722 if end - start == 1:
723 col_index = None
724 else:
725 col_search_order = line_col_search_order(parents[0][1].col_index, parents[0][0].col_index)
726 col_index = find_free_column(col_search_order, start, end)
727
728 col_offset_increment = 1.0 / len(parents)
729 for i, (c_rev, parent_c_rev, direct) in enumerate(parents):
730 if col_index is None:
731 col_index_offset = None
732 else:
733 col_index_offset = (col_index - 0.5 + (i * col_offset_increment) + (col_offset_increment / 2))
734 append_line(c_rev, parent_c_rev, direct, col_index_offset)
735
736 for branch_id in self.branch_ids:
737 if branch_id not in state.branch_line_state:
738 continue
739
740 branch_line = self.branch_lines[branch_id]
741 branch_revs = [c_revisions[rev.index] for rev in branch_line.revs if c_revisions[rev.index] is not None]
742
743 if not branch_revs:
744 continue
745
746 branch_rev_visible_parents_post = []
747 branch_rev_visible_parents_pre = []
748 # Lists of ([(c_rev, parent_c_rev, is_direct)],
749 # start, end, group_key]
750
751 last_c_rev = branch_revs[-1]
752 last_rev_left_parents = (self.known_graph.get_parent_keys(last_c_rev.rev.revid))
753 if last_rev_left_parents:
754 last_parent = find_visible_parent(last_c_rev, self.revid_rev[last_rev_left_parents[0]], [])
755 else:
756 last_parent = None
757
758 sprout_with_lines = {}
759
760 merged_by_max_col_index = 0
761
762 # In this loop:
763 # * Populate twisty_branch_ids and twisty_state
764 # * Find visible parents.
765 # * Append lines that go before the branch line.
766 # * Append lines to children for sprouts.
767 for c_rev in branch_revs:
768 rev = c_rev.rev
769
770 if rev.merged_by is not None:
771 merged_by_c_rev = c_revisions[rev.merged_by]
772 if merged_by_c_rev:
773 merged_by_max_col_index = max(merged_by_max_col_index, merged_by_c_rev.col_index)
774
775 parents = [self.revid_rev[parent_revid] for parent_revid in self.known_graph.get_parent_keys(rev.revid)]
776
777 twisty_hidden_parents = []
778 # Find and add necessary twisties
779 for parent in parents:
780 if parent.branch_id == branch_id:
781 continue
782 if parent.branch_id == ():
783 continue
784 if parent.branch_id in branch_line.merged_by:
785 continue
786 parent_branch = self.branch_lines[parent.branch_id]
787 # Does this branch have any visible revisions
788 pb_visible = (parent_branch.branch_id in state.branch_line_state)
789 for pb_rev in parent_branch.revs:
790 if pb_visible:
791 visible = c_revisions[pb_rev.index] is not None
792 else:
793 visible = state.get_revision_visible_if_branch_visible(pb_rev)
794 if visible:
795 (c_rev.twisty_expands_branch_ids.append(parent_branch.branch_id))
796 if not pb_visible:
797 twisty_hidden_parents.append(parent.index)
798 break
799
800 # Work out if the twisty needs to show a + or -. If all
801 # twisty_branch_ids are visible, show - else +.
802 if len(c_rev.twisty_expands_branch_ids) > 0:
803 c_rev.twisty_state = True
804 for twisty_branch_id in c_rev.twisty_expands_branch_ids:
805 if twisty_branch_id not in state.branch_line_state:
806 c_rev.twisty_state = False
807 break
808
809 # Don't include left hand parents All of these parents in the
810 # branch can be drawn with one line.
811 parents = parents[1:]
812
813 branch_id_sort_key = self.branch_id_sort_key(branch_id)
814 for i, parent in enumerate(parents):
815 parent_info = find_visible_parent(c_rev, parent, twisty_hidden_parents)
816 if parent_info:
817 c_rev, parent_c_rev, direct = parent_info
818 if (last_parent and parent_c_rev.f_index <= last_parent[1].f_index and
819 self.branch_id_sort_key(parent_c_rev.rev.branch_id) < branch_id_sort_key):
820 # This line goes before the branch line
821 dest = branch_rev_visible_parents_pre
822 else:
823 # This line goes after
824 dest = branch_rev_visible_parents_post
825
826 line_len = parent_c_rev.f_index - c_rev.f_index
827 if line_len == 1:
828 group_key = None
829 else:
830 group_key = parent_c_rev.rev.branch_id
831
832 dest.append(([parent_info], c_rev.f_index, parent_c_rev.f_index, group_key))
833
834 # This may be a sprout. Add line to first visible child
835 if c_rev.rev.merged_by is not None:
836 merged_by = self.revisions[c_rev.rev.merged_by]
837 if c_revisions[merged_by.index] is None and branch_revs[0].f_index == c_rev.f_index:
838 # The revision that merges this revision is not
839 # visible, and it is the first visible revision in
840 # the branch line. This is a sprout.
841 #
842 # XXX What if multiple merges with --force,
843 # aka octopus merge?
844 #
845 # Search until we find a descendant that is visible.
846
847 while merged_by is not None and c_revisions[merged_by.index] is None:
848 if merged_by.merged_by is not None:
849 merged_by = self.revisions[merged_by.merged_by]
850 else:
851 merged_by = None
852
853 if merged_by is not None:
854 # Ensure only one line to a descendant.
855 if merged_by.index not in sprout_with_lines:
856 sprout_with_lines[merged_by.index] = True
857 parent = c_revisions[merged_by.index]
858 if parent is not None:
859 if c_rev.f_index - parent.f_index == 1:
860 col_index = None
861 else:
862 col_search_order = line_col_search_order(parent.col_index, c_rev.col_index)
863 col_index = find_free_column(col_search_order, parent.f_index, c_rev.f_index)
864 append_line(parent, c_rev, False, col_index)
865
866 # Find a column for this branch.
867 #
868 # Find the col_index for the direct parent branch. This will
869 # be the starting point when looking for a free column.
870
871 append_branch_parent_lines(branch_rev_visible_parents_pre)
872
873 if branch_id == ():
874 start_col_index = 0
875 else:
876 start_col_index = 1
877
878 if last_parent and last_parent[0].col_index is not None:
879 parent_col_index = last_parent[1].col_index
880 start_col_index = max(start_col_index, parent_col_index)
881
882 start_col_index = max(start_col_index, merged_by_max_col_index)
883
884 col_search_order = branch_line_col_search_order(start_col_index)
885
886 if last_parent:
887 col_index = find_free_column(col_search_order, branch_revs[0].f_index, last_parent[1].f_index)
888 else:
889 col_index = find_free_column(col_search_order, branch_revs[0].f_index, branch_revs[-1].f_index)
890
891 # Free column for this branch found. Set node for all
892 # revision in this branch.
893 for rev in branch_revs:
894 rev.col_index = col_index
895
896 append_line(branch_revs[0], branch_revs[-1], True, col_index)
897 if last_parent:
898 append_line(last_parent[0], last_parent[1], last_parent[2], col_index)
899
900 branch_rev_visible_parents_post.reverse()
901 append_branch_parent_lines(branch_rev_visible_parents_post)
902
903 # It has now been calculated which column a line must go into. Now
904 # copy the lines in to computed_revisions.
905 for (child, parent, line_col_index, direct) in lines:
906 parent_color = parent.rev.color
907 line_length = parent.f_index - child.f_index
908 if line_length == 0:
909 # Nothing to do
910 pass
911 elif line_length == 1:
912 child.lines.append((child.col_index, parent.col_index, parent_color, direct))
913 else:
914 # line from the child's column to the lines column
915 child.lines.append((child.col_index, line_col_index, parent_color, direct))
916 # lines down the line's column
917 for line_part_f_index in range(child.f_index + 1, parent.f_index - 1):
918 computed.filtered_revs[line_part_f_index].lines.append((line_col_index, line_col_index, parent_color, direct))
919 # line from the line's column to the parent's column
920 computed.filtered_revs[parent.f_index - 1].lines.append((line_col_index, parent.col_index, parent_color, direct))
921
922 return computed
923
924 def get_revid_branch_info(self, revid):
925 """This returns a branch info whos branch contains the revision.
926
927 If the revision exists more than one branch, it will only return the
928 first branch info. """
929
930 if revid in self.ghosts:
931 raise GhostRevisionError(revid)
932 if len(self.branches) == 1 or revid not in self.revid_branch_info:
933 return self.branches[0]
934 return self.revid_branch_info[revid]
935
936 def get_revid_branch(self, revid):
937 return self.get_revid_branch_info(revid).branch
938
939 def get_revid_repo(self, revid):
940 return self.get_revid_branch_info(revid).branch.repository
941
942 def get_repo_revids(self, revids):
943 """Returns list of tuple of (repo, revids)"""
944 repo_revids = {}
945 for repo in self.repos:
946 repo_revids[repo.base] = []
947
948 for local_repo_copy in self.local_repo_copies:
949 for revid in self.repos[local_repo_copy].has_revisions(revids):
950 revids.remove(revid)
951 repo_revids[local_repo_copy].append(revid)
952
953 for revid in revids:
954 try:
955 repo = self.get_revid_repo(revid)
956 except GhostRevisionError:
957 pass
958 else:
959 repo_revids[repo.base].append(revid)
960
961 return [(repo, repo_revids[repo.base]) for repo in self.repos]
962
963 def load_revisions(self, revids):
964 return_revisions = {}
965 for repo, revids in self.get_repo_revids(revids):
966 if revids:
967 with repo.lock_read():
968 self.update_ui()
969 for rev in repo.get_revisions(revids):
970 return_revisions[rev.revision_id] = rev
971 return return_revisions
972
973
974 def repo_is_local(repo):
975 return isinstance(repo.controldir.transport, LocalTransport)
976
977
978 def group_overlapping(groups):
979 """ Groups items with overlapping ranges together.
980
981 :param groups: List of uncollapsed groups.
982 :param group: (start of range, end of range, items in group)
983 :return: List of collapsed groups.
984
985 """
986
987 has_change = True
988 while has_change:
989 has_change = False
990 a = 0
991 while a < len(groups):
992 inner_has_change = False
993 items_a, start_a, end_a, group_key_a = groups[a]
994 if group_key_a is not None:
995 b = a + 1
996 while b < len(groups):
997 items_b, start_b, end_b, group_key_b = groups[b]
998 if group_key_a == group_key_b and range_overlaps(start_a, end_a, start_b, end_b):
999 # overlaps. Merge b into a
1000 items_a.extend(items_b)
1001 start_a = min(start_a, start_b)
1002 end_a = max(end_a, end_b)
1003 del groups[b]
1004 has_change = True
1005 inner_has_change = True
1006 else:
1007 b += 1
1008 if inner_has_change:
1009 groups[a] = (items_a, start_a, end_a, group_key_a)
1010 a += 1
1011
1012 return groups
1013
1014
1015 def range_overlaps(start_a, end_a, start_b, end_b):
1016 """Tests if two ranges overlap."""
1017 return start_b < start_a < end_b or start_b < end_a < end_b or (start_a <= start_b and end_a >= end_b)
1018
1019
1020 class PendingMergesGraphVizLoader(GraphVizLoader):
1021 """GraphVizLoader that only loads pending merges.
1022
1023 As only the pending merges are passed to merge_sort, the revno
1024 are incorrect, and should be ignored.
1025
1026 Only works on a single branch.
1027
1028 """
1029
1030 def load_graph_parents(self):
1031 if not len(self.branches) == 1 or not len(self.repos) == 1:
1032 AssertionError("load_graph_pending_merges should only be called when 1 branch and repo has been opened.")
1033
1034 bi = self.branches[0]
1035 if bi.tree is None:
1036 AssertionError("PendingMergesGraphVizLoader must have a working tree.")
1037
1038 self.graph = bi.branch.repository.get_graph()
1039 tree_heads = bi.tree.get_parent_ids()
1040 other_revisions = [tree_heads[0], ]
1041 self.update_ui()
1042
1043 self.append_head_info('root:', bi, None)
1044 pending_merges = []
1045 for head in tree_heads[1:]:
1046 self.append_head_info(head, bi, None)
1047 pending_merges.extend(self.graph.find_unique_ancestors(head, other_revisions))
1048 other_revisions.append(head)
1049 self.update_ui()
1050
1051 graph_parents = self.graph.get_parent_map(pending_merges)
1052 graph_parents["root:"] = ()
1053 self.update_ui()
1054
1055 for (revid, parents) in list(graph_parents.items()):
1056 new_parents = []
1057 for index, parent in enumerate(parents):
1058 if parent in graph_parents:
1059 new_parents.append(parent)
1060 elif index == 0:
1061 new_parents.append("root:")
1062 graph_parents[revid] = tuple(new_parents)
1063 return ["root:", ] + tree_heads[1:], list(graph_parents.items())
1064
1065
1066 class WithWorkingTreeGraphVizLoader(GraphVizLoader):
1067 """
1068 GraphVizLoader that shows uncommitted working tree changes as a node
1069 in the graph, as if it was already committed.
1070 """
1071
1072 def tree_revid(self, tree):
1073 return CURRENT_REVISION + tree.basedir.encode('utf-8')
1074
1075 def load(self):
1076 self.working_trees = {}
1077 for bi in self.branches:
1078 if bi.tree is not None:
1079 self.working_trees[self.tree_revid(bi.tree)] = bi.tree
1080
1081 super(WithWorkingTreeGraphVizLoader, self).load()
1082
1083 def load_branch_heads(self, bi):
1084 # returns load_heads, sort_heads and also calls append_head_info.
1085 #
1086 # == For branch with tree ==
1087 # Graph | load_heads | sort_heads | append_head_info
1088 # wt | No | Yes | Yes
1089 # | \ | | |
1090 # | 1.1.2 pending merge | Yes | No | Yes
1091 # 2 | basis rev | Yes | No | Yes
1092 #
1093 # == For branch with tree not up to date ==
1094 # Graph | load_heads | sort_heads | append_head_info
1095 # wt | No | Yes | Yes
1096 # | \ | | |
1097 # | 1.1.2 pending merge | Yes | No | Yes
1098 # 3/ | branch tip | Yes | Yes | Yes
1099 # 2 | basis rev | Yes | No | No
1100 #
1101 # == For branch without tree ==
1102 # branch tip | Yes | head | yes
1103
1104 load_heads = []
1105 sort_heads = []
1106 extra_parents = []
1107
1108 if len(self.branches) > 0:
1109 label = bi.label
1110 else:
1111 label = None
1112
1113 branch_last_revision = bi.branch.last_revision()
1114 self.append_head_info(branch_last_revision, bi, bi.label)
1115 load_heads.append(branch_last_revision)
1116 self.update_ui()
1117
1118 if bi.tree:
1119 wt_revid = self.tree_revid(bi.tree)
1120 if label:
1121 wt_label = "%s - Working Tree" % label
1122 else:
1123 wt_label = "Working Tree"
1124 self.append_head_info(wt_revid, bi, wt_label)
1125 parent_ids = bi.tree.get_parent_ids()
1126
1127 extra_parents.append((wt_revid, parent_ids))
1128 load_heads.extend(parent_ids)
1129
1130 if parent_ids:
1131 # first parent is last revision of the tree
1132 if parent_ids[0] != branch_last_revision:
1133 # tree is not up to date.
1134 sort_heads.append(branch_last_revision)
1135
1136 # other parents are pending merges
1137 for revid in parent_ids[1:]:
1138 if label:
1139 pm_label = "%s - Pending Merge" % label
1140 else:
1141 pm_label = "Pending Merge"
1142 self.append_head_info(revid, bi, pm_label)
1143
1144 sort_heads.append(wt_revid)
1145 self.update_ui()
1146 else:
1147 sort_heads.append(branch_last_revision)
1148
1149 return load_heads, sort_heads, extra_parents
1150
1151
1152 class GraphVizFilterState(object):
1153 """
1154 Records the state of which branch lines are expanded, and what filters
1155 are applied.
1156 """
1157
1158 def __init__(self, graph_viz, filter_changed_callback=None):
1159 self.graph_viz = graph_viz
1160 self.filter_changed_callback = filter_changed_callback
1161
1162 self.branch_line_state = {}
1163 "If a branch_id is in this dict, it is visible. The value of the dict "
1164 "indicates which branches expanded this branch."
1165
1166 for revid in self.graph_viz.revid_head_info:
1167 rev = self.graph_viz.revid_rev[revid]
1168 self.branch_line_state[rev.branch_id] = None
1169
1170 self.filters = []
1171
1172 # This keeps a cache of the filter state so that when one of the
1173 # filters notifies us of a change, we can check if anything did change.
1174
1175 self.filter_cache = [None for rev in self.graph_viz.revisions]
1176
1177 def get_filtered_revisions(self):
1178 if self.graph_viz.no_graph:
1179 rev_whos_branch_is_visible = self.graph_viz.revisions
1180 else:
1181 rev_whos_branch_is_visible = []
1182 for branch_id in self.branch_line_state.keys():
1183 try:
1184 branch_line = self.graph_viz.branch_lines[branch_id]
1185 except KeyError:
1186 continue
1187 rev_whos_branch_is_visible.extend(branch_line.revs)
1188 rev_whos_branch_is_visible.sort(key=lambda rev: rev.index)
1189
1190 visible = self.get_revision_visible_if_branch_visible
1191 return (rev for rev in rev_whos_branch_is_visible if visible(rev))
1192
1193 def get_revision_visible_if_branch_visible(self, rev):
1194 rev_filter_cache = self.filter_cache[rev.index]
1195 if rev_filter_cache is None:
1196 rev_filter_cache = self._get_revision_visible_if_branch_visible(rev)
1197 self.filter_cache[rev.index] = rev_filter_cache
1198 return rev_filter_cache
1199
1200 def _get_revision_visible_if_branch_visible(self, rev):
1201 filters_value = True
1202 for filter in self.filters:
1203 if not filter.get_revision_visible(rev):
1204 filters_value = False
1205 break
1206 if filters_value:
1207 return True
1208
1209 if not self.graph_viz.no_graph:
1210 for merged_index in rev.merges:
1211 merged_rev = self.graph_viz.revisions[merged_index]
1212 if self.get_revision_visible_if_branch_visible(merged_rev):
1213 return True
1214
1215 return False
1216
1217 def filter_changed(self, revs=None, last_call=True):
1218 if revs is None:
1219 self.filter_cache = [None for rev in self.graph_viz.revisions]
1220 if self.filter_changed_callback:
1221 self.filter_changed_callback()
1222 else:
1223 pending_revs = revs
1224 processed_revs = set()
1225 prev_cached_revs = []
1226 while pending_revs:
1227 rev = pending_revs.pop(0)
1228 if rev in processed_revs:
1229 continue
1230 processed_revs.add(rev)
1231
1232 rev_filter_cache = self.filter_cache[rev.index]
1233
1234 if rev_filter_cache is not None:
1235 prev_cached_revs.append((rev, rev_filter_cache))
1236 self.filter_cache[rev.index] = None
1237
1238 if not self.graph_viz.no_graph:
1239 if rev.merged_by is not None:
1240 pending_revs.append(self.graph_viz.revisions[rev.merged_by])
1241
1242 # Check if any visibilities have changes. If they have, call
1243 # filter_changed_callback
1244 for rev, prev_visible in prev_cached_revs:
1245 visible = self.get_revision_visible_if_branch_visible(rev)
1246 if visible != prev_visible:
1247 if self.filter_changed_callback:
1248 self.filter_changed_callback()
1249 break
1250
1251 def ensure_rev_visible(self, rev):
1252 if self.graph_viz.no_graph:
1253 return False
1254 branch_id = rev.branch_id
1255 if branch_id not in self.branch_line_state:
1256 self.branch_line_state[branch_id] = None
1257 if self.filter_changed_callback:
1258 self.filter_changed_callback()
1259 return True
1260 return False
1261
1262 def collapse_expand_rev(self, c_rev):
1263 if c_rev is None:
1264 return False
1265 visible = not c_rev.twisty_state
1266 branch_ids = list(zip(
1267 c_rev.twisty_expands_branch_ids,
1268 [c_rev.rev.branch_id] * len(c_rev.twisty_expands_branch_ids)))
1269
1270 seen_branch_ids = set(branch_id for branch_id, expanded_by in branch_ids)
1271 has_change = False
1272 while branch_ids:
1273 branch_id, expanded_by = branch_ids.pop()
1274 if (branch_id in self.branch_line_state) != visible:
1275 has_change = True
1276 if not visible:
1277 del self.branch_line_state[branch_id]
1278 parents = self.graph_viz.branch_lines[branch_id].merges
1279 for parent_branch_id in parents:
1280 parent_visible = parent_branch_id in self.branch_line_state
1281 if not parent_visible or parent_branch_id in seen_branch_ids:
1282 continue
1283
1284 if self.branch_line_state[parent_branch_id] == branch_id:
1285 # This branch expanded the parent branch, so we must
1286 # collapse it.
1287 branch_ids.append((parent_branch_id, branch_id))
1288 seen_branch_ids.add(parent_branch_id)
1289 else:
1290 # Check if this parent has any other visible branches
1291 # that merge it.
1292 has_visible = False
1293 parent = self.graph_viz.branch_lines[parent_branch_id]
1294 for merged_by_branch_id in parent.merged_by:
1295 if merged_by_branch_id in self.branch_line_state:
1296 has_visible = True
1297 break
1298 if not has_visible:
1299 branch_ids.append((parent_branch_id, branch_id))
1300 seen_branch_ids.add(parent_branch_id)
1301 else:
1302 self.branch_line_state[branch_id] = expanded_by
1303 if has_change and self.filter_changed_callback:
1304 self.filter_changed_callback()
1305
1306 def expand_all_branch_lines(self):
1307 for branch_id in list(self.graph_viz.branch_lines.keys()):
1308 if branch_id not in self.branch_line_state:
1309 self.branch_line_state[branch_id] = None
1310
1311
1312 class FileIdFilter (object):
1313 """
1314 Filter that only shows revisions that modify one of the specified files.
1315 """
1316
1317 def __init__(self, graph_viz, filter_changed_callback, file_ids):
1318 self.graph_viz = graph_viz
1319 self.filter_changed_callback = filter_changed_callback
1320 self.file_ids = file_ids
1321 self.has_dir = False
1322 self.filter_file_id = [False for rev in self.graph_viz.revisions]
1323
1324 # don't filter working tree nodes
1325 if isinstance(self.graph_viz, WithWorkingTreeGraphVizLoader):
1326 for wt_revid in self.graph_viz.working_trees.keys():
1327 try:
1328 rev_index = self.graph_viz.revid_rev[wt_revid].index
1329 self.filter_file_id[rev_index] = True
1330 except KeyError:
1331 pass
1332
1333 def uses_inventory(self):
1334 return self.has_dir
1335
1336 def load(self, revids=None):
1337 """Load which revisions affect the file_ids"""
1338 if self.file_ids:
1339 self.graph_viz.throbber_show()
1340
1341 for bi in self.graph_viz.branches:
1342 tree = bi.tree
1343 if tree is None:
1344 tree = bi.branch.basis_tree()
1345
1346 with tree.lock_read():
1347 for file_id in self.file_ids:
1348 if tree.kind(tree.id2path(file_id)) in ('directory', 'tree-reference'):
1349 self.has_dir = True
1350 break
1351 if self.has_dir:
1352 break
1353
1354 if revids is None:
1355 revids = [rev.revid for rev in self.graph_viz.revisions]
1356 revids = [revid for revid in revids if not revid.startswith(CURRENT_REVISION)]
1357
1358 for repo, revids in self.graph_viz.get_repo_revids(revids):
1359 if self.uses_inventory():
1360 chunk_size = 200
1361 else:
1362 chunk_size = 500
1363 for start in range(0, len(revids), chunk_size):
1364 self.load_filter_file_id_chunk(repo, revids[start:start + chunk_size])
1365
1366 self.load_filter_file_id_chunk_finished()
1367
1368 def load_filter_file_id_chunk(self, repo, revids):
1369 graph = repo.get_file_graph()
1370
1371 def check_text_keys(text_keys):
1372 changed_revs = []
1373 for file_id, revid in graph.get_parent_map(text_keys):
1374 rev = self.graph_viz.revid_rev[revid]
1375 self.filter_file_id[rev.index] = True
1376 changed_revs.append(rev)
1377
1378 self.graph_viz.update_ui()
1379 self.filter_changed_callback(changed_revs, False)
1380 self.graph_viz.update_ui()
1381
1382 with repo.lock_read():
1383 if not self.uses_inventory():
1384 text_keys = [(file_id, revid) for revid in revids for file_id in self.file_ids]
1385 check_text_keys(text_keys)
1386 else:
1387 text_keys = []
1388 # We have to load the inventory for each revisions, to find
1389 # the children of any directories.
1390 for inv, revid in zip(repo.iter_inventories(revids), revids):
1391 entries = inv.iter_entries_by_dir(specific_file_ids=self.file_ids)
1392 for path, entry in entries:
1393 text_keys.append((entry.file_id, revid))
1394 if entry.kind == "directory":
1395 sub_entries = inv.iter_entries(from_dir=entry)
1396 for rc_path, rc_entry in sub_entries:
1397 text_keys.append((rc_entry.file_id, revid))
1398
1399 self.graph_viz.update_ui()
1400
1401 check_text_keys(text_keys)
1402
1403 def load_filter_file_id_chunk_finished(self):
1404 self.filter_changed_callback([], True)
1405 self.graph_viz.throbber_hide()
1406
1407 def get_revision_visible(self, rev):
1408 return self.filter_file_id[rev.index]
1409
1410
1411 class WorkingTreeHasChangeFilter(object):
1412 """
1413 Filter out working trees that don't have any changes.
1414 """
1415
1416 def __init__(self, graph_viz, filter_changed_callback, file_ids):
1417 self.graph_viz = graph_viz
1418 self.file_ids = file_ids
1419 if not isinstance(graph_viz, WithWorkingTreeGraphVizLoader):
1420 raise TypeError('graph_viz expected to be a WithWorkingTreeGraphVizLoader')
1421 self.filter_changed_callback = filter_changed_callback
1422 self.tree_revids_with_changes = set()
1423
1424 def load(self):
1425 """Load if the working trees have changes."""
1426 self.tree_revids_with_changes = set()
1427 self.graph_viz.throbber_show()
1428 try:
1429 for wt_revid, tree in self.graph_viz.working_trees.items():
1430 if self.has_changes(tree):
1431 self.tree_revids_with_changes.add(wt_revid)
1432 rev = self.graph_viz.revid_rev[wt_revid]
1433 self.filter_changed_callback([rev], False)
1434 self.filter_changed_callback([], True)
1435 finally:
1436 self.graph_viz.throbber_hide()
1437
1438 def has_changes(self, tree):
1439 """Quickly check that the tree contains at least one commitable change.
1440
1441 :param _from_tree: tree to compare against to find changes (default to
1442 the basis tree and is intended to be used by tests).
1443
1444 :return: True if a change is found. False otherwise
1445 """
1446 with tree.lock_read():
1447 # Copied from mutabletree, cause we need file_ids too.
1448 # Check pending merges
1449 if len(tree.get_parent_ids()) > 1:
1450 return True
1451 from_tree = tree.basis_tree()
1452
1453 specific_files = None
1454 if self.file_ids:
1455 specific_files = [tree.id2path(file_id) for file_id in self.file_ids]
1456
1457 changes = tree.iter_changes(from_tree, specific_files=specific_files)
1458 try:
1459 change = next(changes)
1460 # Exclude root (talk about black magic... --vila 20090629)
1461 if change.name == (None, None):
1462 change = next(changes)
1463 return True
1464 except StopIteration:
1465 # No changes
1466 return False
1467
1468 def get_revision_visible(self, rev):
1469 if rev.revid.startswith(CURRENT_REVISION):
1470 return rev.revid in self.tree_revids_with_changes
1471 else:
1472 return True
1473
1474
1475 class ComputedRevisionData(object):
1476 """Container for computed layout data for a revision.
1477
1478 :ivar rev: Reference to RevisionData. Use to get revno, revid, color and
1479 others.
1480 :ivar f_index: Index in `ComputedGraphViz.filtered_revs`.
1481 :ivar col_index: Column index to place node for revision in.
1482 :ivar lines: Lines that need to be drawn from from this revision's line to
1483 the next revision's line. Note that not all these lines relate to this
1484 revision, but be a part of a longer line that is passing this revision.
1485
1486 Each line is a tuple of `(end col_index, start col_index, color,
1487 direct)`.
1488
1489 If direct is False, it indicates that this line represents an
1490 ancestry, with revisions that are filtered. This should be shown as
1491 a dotted line.
1492
1493 :ivar branch_labels: Labels for branch tips.
1494 :ivar twisty_state: State of the revision:
1495
1496 * None: No twisty.
1497 * True: There are branch lines that this revision merges that can
1498 expanded. Show a '+'.
1499 * False: All branches that this revision merges are already expanded.
1500 Show a '-'.
1501 :ivar twisty_expands_branch_ids: Branch lines that will be expanded if the
1502 twisty is clicked.
1503 """
1504
1505 # Instance of this object are typically named "c_rev".
1506 __slots__ = ['rev', 'f_index', 'lines', 'col_index', 'branch_labels', 'twisty_state', 'twisty_expands_branch_ids']
1507
1508 def __init__(self, rev):
1509 self.rev = rev
1510 self.lines = []
1511 self.col_index = None
1512 self.twisty_state = None
1513 self.twisty_expands_branch_ids = []
1514 self.branch_labels = []
1515
1516
1517 class ComputedGraphViz(object):
1518 """Computed layout data for a graph.
1519
1520 :ivar graph_viz: Reference to parent `GraphVizLoader`.
1521 :ivar filtered_revs: List `ComputedRevisionData`. Only visible revisions
1522 are included.
1523 :ivar revisions: List `ComputedRevisionData`. Revision that are not
1524 visible are None.
1525 """
1526 def __init__(self, graph_viz):
1527 self.graph_viz = graph_viz
1528 self.filtered_revs = []
1529 self.revisions = [None] * len(graph_viz.revisions)