View Javadoc
1   /*
2    * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org>,
3    * Copyright (C) 2010, Christian Halstrick <christian.halstrick@sap.com>
4    * Copyright (C) 2014, Konrad Kügler
5    * and other copyright owners as documented in the project's IP log.
6    *
7    * This program and the accompanying materials are made available
8    * under the terms of the Eclipse Distribution License v1.0 which
9    * accompanies this distribution, is reproduced below, and is
10   * available at http://www.eclipse.org/org/documents/edl-v10.php
11   *
12   * All rights reserved.
13   *
14   * Redistribution and use in source and binary forms, with or
15   * without modification, are permitted provided that the following
16   * conditions are met:
17   *
18   * - Redistributions of source code must retain the above copyright
19   *   notice, this list of conditions and the following disclaimer.
20   *
21   * - Redistributions in binary form must reproduce the above
22   *   copyright notice, this list of conditions and the following
23   *   disclaimer in the documentation and/or other materials provided
24   *   with the distribution.
25   *
26   * - Neither the name of the Eclipse Foundation, Inc. nor the
27   *   names of its contributors may be used to endorse or promote
28   *   products derived from this software without specific prior
29   *   written permission.
30   *
31   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
32   * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
33   * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
34   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
35   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
36   * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
37   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
38   * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
39   * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
40   * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
41   * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
42   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
43   * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
44   */
45  
46  package org.eclipse.jgit.revplot;
47  
48  import java.text.MessageFormat;
49  import java.util.BitSet;
50  import java.util.Collection;
51  import java.util.HashMap;
52  import java.util.HashSet;
53  import java.util.TreeSet;
54  
55  import org.eclipse.jgit.internal.JGitText;
56  import org.eclipse.jgit.revwalk.RevCommitList;
57  import org.eclipse.jgit.revwalk.RevWalk;
58  
59  /**
60   * An ordered list of {@link org.eclipse.jgit.revplot.PlotCommit} subclasses.
61   * <p>
62   * Commits are allocated into lanes as they enter the list, based upon their
63   * connections between descendant (child) commits and ancestor (parent) commits.
64   * <p>
65   * The source of the list must be a {@link org.eclipse.jgit.revplot.PlotWalk}
66   * and {@link #fillTo(int)} must be used to populate the list.
67   *
68   * @param <L>
69   *            type of lane used by the application.
70   */
71  public class PlotCommitList<L extends PlotLane> extends
72  		RevCommitList<PlotCommit<L>> {
73  	static final int MAX_LENGTH = 25;
74  
75  	private int positionsAllocated;
76  
77  	private final TreeSet<Integer> freePositions = new TreeSet<>();
78  
79  	private final HashSet<PlotLane> activeLanes = new HashSet<>(32);
80  
81  	/** number of (child) commits on a lane */
82  	private final HashMap<PlotLane, Integer> laneLength = new HashMap<>(
83  			32);
84  
85  	/** {@inheritDoc} */
86  	@Override
87  	public void clear() {
88  		super.clear();
89  		positionsAllocated = 0;
90  		freePositions.clear();
91  		activeLanes.clear();
92  		laneLength.clear();
93  	}
94  
95  	/** {@inheritDoc} */
96  	@Override
97  	public void source(RevWalk w) {
98  		if (!(w instanceof PlotWalk))
99  			throw new ClassCastException(MessageFormat.format(JGitText.get().classCastNotA, PlotWalk.class.getName()));
100 		super.source(w);
101 	}
102 
103 	/**
104 	 * Find the set of lanes passing through a commit's row.
105 	 * <p>
106 	 * Lanes passing through a commit are lanes that the commit is not directly
107 	 * on, but that need to travel through this commit to connect a descendant
108 	 * (child) commit to an ancestor (parent) commit. Typically these lanes will
109 	 * be drawn as lines in the passed commit's box, and the passed commit won't
110 	 * appear to be connected to those lines.
111 	 * <p>
112 	 * This method modifies the passed collection by adding the lanes in any
113 	 * order.
114 	 *
115 	 * @param currCommit
116 	 *            the commit the caller needs to get the lanes from.
117 	 * @param result
118 	 *            collection to add the passing lanes into.
119 	 */
120 	@SuppressWarnings("unchecked")
121 	public void findPassingThrough(final PlotCommit<L> currCommit,
122 			final Collection<L> result) {
123 		for (PlotLane p : currCommit.passingLanes)
124 			result.add((L) p);
125 	}
126 
127 	/** {@inheritDoc} */
128 	@Override
129 	protected void enter(int index, PlotCommit<L> currCommit) {
130 		setupChildren(currCommit);
131 
132 		final int nChildren = currCommit.getChildCount();
133 		if (nChildren == 0) {
134 			currCommit.lane = nextFreeLane();
135 		} else if (nChildren == 1
136 				&& currCommit.children[0].getParentCount() < 2) {
137 			// Only one child, child has only us as their parent.
138 			// Stay in the same lane as the child.
139 
140 			@SuppressWarnings("unchecked")
141 			final PlotCommit<L> c = currCommit.children[0];
142 			currCommit.lane = c.lane;
143 			Integer len = laneLength.get(currCommit.lane);
144 			len = Integer.valueOf(len.intValue() + 1);
145 			laneLength.put(currCommit.lane, len);
146 		} else {
147 			// More than one child, or our child is a merge.
148 
149 			// We look for the child lane the current commit should continue.
150 			// Candidate lanes for this are those with children, that have the
151 			// current commit as their first parent.
152 			// There can be multiple candidate lanes. In that case the longest
153 			// lane is chosen, as this is usually the lane representing the
154 			// branch the commit actually was made on.
155 
156 			// When there are no candidate lanes (i.e. the current commit has
157 			// only children whose non-first parent it is) we place the current
158 			// commit on a new lane.
159 
160 			// The lane the current commit will be placed on:
161 			PlotLane reservedLane = null;
162 			PlotCommit childOnReservedLane = null;
163 			int lengthOfReservedLane = -1;
164 
165 			for (int i = 0; i < nChildren; i++) {
166 				@SuppressWarnings("unchecked")
167 				final PlotCommit<L> c = currCommit.children[i];
168 				if (c.getParent(0) == currCommit) {
169 					Integer len = laneLength.get(c.lane);
170 					// we may be the first parent for multiple lines of
171 					// development, try to continue the longest one
172 					if (len.intValue() > lengthOfReservedLane) {
173 						reservedLane = c.lane;
174 						childOnReservedLane = c;
175 						lengthOfReservedLane = len.intValue();
176 					}
177 				}
178 			}
179 
180 			if (reservedLane != null) {
181 				currCommit.lane = reservedLane;
182 				laneLength.put(reservedLane,
183 						Integer.valueOf(lengthOfReservedLane + 1));
184 				handleBlockedLanes(index, currCommit, childOnReservedLane);
185 			} else {
186 				currCommit.lane = nextFreeLane();
187 				handleBlockedLanes(index, currCommit, null);
188 			}
189 
190 			// close lanes of children, if there are no first parents that might
191 			// want to continue the child lanes
192 			for (int i = 0; i < nChildren; i++) {
193 				final PlotCommit c = currCommit.children[i];
194 				PlotCommit firstParent = (PlotCommit) c.getParent(0);
195 				if (firstParent.lane != null && firstParent.lane != c.lane)
196 					closeLane(c.lane);
197 			}
198 		}
199 
200 		continueActiveLanes(currCommit);
201 		if (currCommit.getParentCount() == 0)
202 			closeLane(currCommit.lane);
203 	}
204 
205 	private void continueActiveLanes(PlotCommit currCommit) {
206 		for (PlotLane lane : activeLanes)
207 			if (lane != currCommit.lane)
208 				currCommit.addPassingLane(lane);
209 	}
210 
211 	/**
212 	 * Sets up fork and merge information in the involved PlotCommits.
213 	 * Recognizes and handles blockades that involve forking or merging arcs.
214 	 *
215 	 * @param index
216 	 *            the index of <code>currCommit</code> in the list
217 	 * @param currCommit
218 	 * @param childOnLane
219 	 *            the direct child on the same lane as <code>currCommit</code>,
220 	 *            may be null if <code>currCommit</code> is the first commit on
221 	 *            the lane
222 	 */
223 	private void handleBlockedLanes(final int index, final PlotCommit currCommit,
224 			final PlotCommit childOnLane) {
225 		for (PlotCommit child : currCommit.children) {
226 			if (child == childOnLane)
227 				continue; // simple continuations of lanes are handled by
228 							// continueActiveLanes() calls in enter()
229 
230 			// Is the child a merge or is it forking off?
231 			boolean childIsMerge = child.getParent(0) != currCommit;
232 			if (childIsMerge) {
233 				PlotLane laneToUse = currCommit.lane;
234 				laneToUse = handleMerge(index, currCommit, childOnLane, child,
235 						laneToUse);
236 				child.addMergingLane(laneToUse);
237 			} else {
238 				// We want to draw a forking arc in the child's lane.
239 				// As an active lane, the child lane already continues
240 				// (unblocked) up to this commit, we only need to mark it as
241 				// forking off from the current commit.
242 				PlotLane laneToUse = child.lane;
243 				currCommit.addForkingOffLane(laneToUse);
244 			}
245 		}
246 	}
247 
248 	// Handles the case where currCommit is a non-first parent of the child
249 	private PlotLane handleMerge(final int index, final PlotCommit currCommit,
250 			final PlotCommit childOnLane, PlotCommit child, PlotLane laneToUse) {
251 
252 		// find all blocked positions between currCommit and this child
253 
254 		int childIndex = index; // useless initialization, should
255 								// always be set in the loop below
256 		BitSet blockedPositions = new BitSet();
257 		for (int r = index - 1; r >= 0; r--) {
258 			final PlotCommit rObj = get(r);
259 			if (rObj == child) {
260 				childIndex = r;
261 				break;
262 			}
263 			addBlockedPosition(blockedPositions, rObj);
264 		}
265 
266 		// handle blockades
267 
268 		if (blockedPositions.get(laneToUse.getPosition())) {
269 			// We want to draw a merging arc in our lane to the child,
270 			// which is on another lane, but our lane is blocked.
271 
272 			// Check if childOnLane is beetween commit and the child we
273 			// are currently processing
274 			boolean needDetour = false;
275 			if (childOnLane != null) {
276 				for (int r = index - 1; r > childIndex; r--) {
277 					final PlotCommit rObj = get(r);
278 					if (rObj == childOnLane) {
279 						needDetour = true;
280 						break;
281 					}
282 				}
283 			}
284 
285 			if (needDetour) {
286 				// It is childOnLane which is blocking us. Repositioning
287 				// our lane would not help, because this repositions the
288 				// child too, keeping the blockade.
289 				// Instead, we create a "detour lane" which gets us
290 				// around the blockade. That lane has no commits on it.
291 				laneToUse = nextFreeLane(blockedPositions);
292 				currCommit.addForkingOffLane(laneToUse);
293 				closeLane(laneToUse);
294 			} else {
295 				// The blockade is (only) due to other (already closed)
296 				// lanes at the current lane's position. In this case we
297 				// reposition the current lane.
298 				// We are the first commit on this lane, because
299 				// otherwise the child commit on this lane would have
300 				// kept other lanes from blocking us. Since we are the
301 				// first commit, we can freely reposition.
302 				int newPos = getFreePosition(blockedPositions);
303 				freePositions.add(Integer.valueOf(laneToUse
304 						.getPosition()));
305 				laneToUse.position = newPos;
306 			}
307 		}
308 
309 		// Actually connect currCommit to the merge child
310 		drawLaneToChild(index, child, laneToUse);
311 		return laneToUse;
312 	}
313 
314 	/**
315 	 * Connects the commit at commitIndex to the child, using the given lane.
316 	 * All blockades on the lane must be resolved before calling this method.
317 	 *
318 	 * @param commitIndex
319 	 * @param child
320 	 * @param laneToContinue
321 	 */
322 	private void drawLaneToChild(final int commitIndex, PlotCommit child,
323 			PlotLane laneToContinue) {
324 		for (int r = commitIndex - 1; r >= 0; r--) {
325 			final PlotCommit rObj = get(r);
326 			if (rObj == child)
327 				break;
328 			if (rObj != null)
329 				rObj.addPassingLane(laneToContinue);
330 		}
331 	}
332 
333 	private static void addBlockedPosition(BitSet blockedPositions,
334 			final PlotCommit rObj) {
335 		if (rObj != null) {
336 			PlotLane lane = rObj.getLane();
337 			// Positions may be blocked by a commit on a lane.
338 			if (lane != null)
339 				blockedPositions.set(lane.getPosition());
340 			// Positions may also be blocked by forking off and merging lanes.
341 			// We don't consider passing lanes, because every passing lane forks
342 			// off and merges at it ends.
343 			for (PlotLane l : rObj.forkingOffLanes)
344 				blockedPositions.set(l.getPosition());
345 			for (PlotLane l : rObj.mergingLanes)
346 				blockedPositions.set(l.getPosition());
347 		}
348 	}
349 
350 	@SuppressWarnings("unchecked")
351 	private void closeLane(PlotLane lane) {
352 		if (activeLanes.remove(lane)) {
353 			recycleLane((L) lane);
354 			laneLength.remove(lane);
355 			freePositions.add(Integer.valueOf(lane.getPosition()));
356 		}
357 	}
358 
359 	private void setupChildren(PlotCommit<L> currCommit) {
360 		final int nParents = currCommit.getParentCount();
361 		for (int i = 0; i < nParents; i++)
362 			((PlotCommit) currCommit.getParent(i)).addChild(currCommit);
363 	}
364 
365 	private PlotLane nextFreeLane() {
366 		return nextFreeLane(null);
367 	}
368 
369 	private PlotLane nextFreeLane(BitSet blockedPositions) {
370 		final PlotLane p = createLane();
371 		p.position = getFreePosition(blockedPositions);
372 		activeLanes.add(p);
373 		laneLength.put(p, Integer.valueOf(1));
374 		return p;
375 	}
376 
377 	/**
378 	 * @param blockedPositions
379 	 *            may be null
380 	 * @return a free lane position
381 	 */
382 	private int getFreePosition(BitSet blockedPositions) {
383 		if (freePositions.isEmpty())
384 			return positionsAllocated++;
385 
386 		if (blockedPositions != null) {
387 			for (Integer pos : freePositions)
388 				if (!blockedPositions.get(pos.intValue())) {
389 					freePositions.remove(pos);
390 					return pos.intValue();
391 				}
392 			return positionsAllocated++;
393 		} else {
394 			final Integer min = freePositions.first();
395 			freePositions.remove(min);
396 			return min.intValue();
397 		}
398 	}
399 
400 	/**
401 	 * Create a new {@link PlotLane} appropriate for this particular
402 	 * {@link PlotCommitList}.
403 	 *
404 	 * @return a new {@link PlotLane} appropriate for this particular
405 	 *         {@link PlotCommitList}.
406 	 */
407 	@SuppressWarnings("unchecked")
408 	protected L createLane() {
409 		return (L) new PlotLane();
410 	}
411 
412 	/**
413 	 * Return colors and other reusable information to the plotter when a lane
414 	 * is no longer needed.
415 	 *
416 	 * @param lane
417 	 *            a lane
418 	 */
419 	protected void recycleLane(L lane) {
420 		// Nothing.
421 	}
422 }