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 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 PlotWalk} and {@link #fillTo(int)}
66   * 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  	@Override
86  	public void clear() {
87  		super.clear();
88  		positionsAllocated = 0;
89  		freePositions.clear();
90  		activeLanes.clear();
91  		laneLength.clear();
92  	}
93  
94  	@Override
95  	public void source(final RevWalk w) {
96  		if (!(w instanceof PlotWalk))
97  			throw new ClassCastException(MessageFormat.format(JGitText.get().classCastNotA, PlotWalk.class.getName()));
98  		super.source(w);
99  	}
100 
101 	/**
102 	 * Find the set of lanes passing through a commit's row.
103 	 * <p>
104 	 * Lanes passing through a commit are lanes that the commit is not directly
105 	 * on, but that need to travel through this commit to connect a descendant
106 	 * (child) commit to an ancestor (parent) commit. Typically these lanes will
107 	 * be drawn as lines in the passed commit's box, and the passed commit won't
108 	 * appear to be connected to those lines.
109 	 * <p>
110 	 * This method modifies the passed collection by adding the lanes in any
111 	 * order.
112 	 *
113 	 * @param currCommit
114 	 *            the commit the caller needs to get the lanes from.
115 	 * @param result
116 	 *            collection to add the passing lanes into.
117 	 */
118 	@SuppressWarnings("unchecked")
119 	public void findPassingThrough(final PlotCommit<L> currCommit,
120 			final Collection<L> result) {
121 		for (final PlotLane p : currCommit.passingLanes)
122 			result.add((L) p);
123 	}
124 
125 	@Override
126 	protected void enter(final int index, final PlotCommit<L> currCommit) {
127 		setupChildren(currCommit);
128 
129 		final int nChildren = currCommit.getChildCount();
130 		if (nChildren == 0) {
131 			currCommit.lane = nextFreeLane();
132 		} else if (nChildren == 1
133 				&& currCommit.children[0].getParentCount() < 2) {
134 			// Only one child, child has only us as their parent.
135 			// Stay in the same lane as the child.
136 
137 			@SuppressWarnings("unchecked")
138 			final PlotCommit<L> c = currCommit.children[0];
139 			currCommit.lane = c.lane;
140 			Integer len = laneLength.get(currCommit.lane);
141 			len = Integer.valueOf(len.intValue() + 1);
142 			laneLength.put(currCommit.lane, len);
143 		} else {
144 			// More than one child, or our child is a merge.
145 
146 			// We look for the child lane the current commit should continue.
147 			// Candidate lanes for this are those with children, that have the
148 			// current commit as their first parent.
149 			// There can be multiple candidate lanes. In that case the longest
150 			// lane is chosen, as this is usually the lane representing the
151 			// branch the commit actually was made on.
152 
153 			// When there are no candidate lanes (i.e. the current commit has
154 			// only children whose non-first parent it is) we place the current
155 			// commit on a new lane.
156 
157 			// The lane the current commit will be placed on:
158 			PlotLane reservedLane = null;
159 			PlotCommit childOnReservedLane = null;
160 			int lengthOfReservedLane = -1;
161 
162 			for (int i = 0; i < nChildren; i++) {
163 				@SuppressWarnings("unchecked")
164 				final PlotCommit<L> c = currCommit.children[i];
165 				if (c.getParent(0) == currCommit) {
166 					Integer len = laneLength.get(c.lane);
167 					// we may be the first parent for multiple lines of
168 					// development, try to continue the longest one
169 					if (len.intValue() > lengthOfReservedLane) {
170 						reservedLane = c.lane;
171 						childOnReservedLane = c;
172 						lengthOfReservedLane = len.intValue();
173 					}
174 				}
175 			}
176 
177 			if (reservedLane != null) {
178 				currCommit.lane = reservedLane;
179 				laneLength.put(reservedLane,
180 						Integer.valueOf(lengthOfReservedLane + 1));
181 				handleBlockedLanes(index, currCommit, childOnReservedLane);
182 			} else {
183 				currCommit.lane = nextFreeLane();
184 				handleBlockedLanes(index, currCommit, null);
185 			}
186 
187 			// close lanes of children, if there are no first parents that might
188 			// want to continue the child lanes
189 			for (int i = 0; i < nChildren; i++) {
190 				final PlotCommit c = currCommit.children[i];
191 				PlotCommit firstParent = (PlotCommit) c.getParent(0);
192 				if (firstParent.lane != null && firstParent.lane != c.lane)
193 					closeLane(c.lane);
194 			}
195 		}
196 
197 		continueActiveLanes(currCommit);
198 		if (currCommit.getParentCount() == 0)
199 			closeLane(currCommit.lane);
200 	}
201 
202 	private void continueActiveLanes(final PlotCommit currCommit) {
203 		for (PlotLane lane : activeLanes)
204 			if (lane != currCommit.lane)
205 				currCommit.addPassingLane(lane);
206 	}
207 
208 	/**
209 	 * Sets up fork and merge information in the involved PlotCommits.
210 	 * Recognizes and handles blockades that involve forking or merging arcs.
211 	 *
212 	 * @param index
213 	 *            the index of <code>currCommit</code> in the list
214 	 * @param currCommit
215 	 * @param childOnLane
216 	 *            the direct child on the same lane as <code>currCommit</code>,
217 	 *            may be null if <code>currCommit</code> is the first commit on
218 	 *            the lane
219 	 */
220 	private void handleBlockedLanes(final int index, final PlotCommit currCommit,
221 			final PlotCommit childOnLane) {
222 		for (PlotCommit child : currCommit.children) {
223 			if (child == childOnLane)
224 				continue; // simple continuations of lanes are handled by
225 							// continueActiveLanes() calls in enter()
226 
227 			// Is the child a merge or is it forking off?
228 			boolean childIsMerge = child.getParent(0) != currCommit;
229 			if (childIsMerge) {
230 				PlotLane laneToUse = currCommit.lane;
231 				laneToUse = handleMerge(index, currCommit, childOnLane, child,
232 						laneToUse);
233 				child.addMergingLane(laneToUse);
234 			} else {
235 				// We want to draw a forking arc in the child's lane.
236 				// As an active lane, the child lane already continues
237 				// (unblocked) up to this commit, we only need to mark it as
238 				// forking off from the current commit.
239 				PlotLane laneToUse = child.lane;
240 				currCommit.addForkingOffLane(laneToUse);
241 			}
242 		}
243 	}
244 
245 	// Handles the case where currCommit is a non-first parent of the child
246 	private PlotLane handleMerge(final int index, final PlotCommit currCommit,
247 			final PlotCommit childOnLane, PlotCommit child, PlotLane laneToUse) {
248 
249 		// find all blocked positions between currCommit and this child
250 
251 		int childIndex = index; // useless initialization, should
252 								// always be set in the loop below
253 		BitSet blockedPositions = new BitSet();
254 		for (int r = index - 1; r >= 0; r--) {
255 			final PlotCommit rObj = get(r);
256 			if (rObj == child) {
257 				childIndex = r;
258 				break;
259 			}
260 			addBlockedPosition(blockedPositions, rObj);
261 		}
262 
263 		// handle blockades
264 
265 		if (blockedPositions.get(laneToUse.getPosition())) {
266 			// We want to draw a merging arc in our lane to the child,
267 			// which is on another lane, but our lane is blocked.
268 
269 			// Check if childOnLane is beetween commit and the child we
270 			// are currently processing
271 			boolean needDetour = false;
272 			if (childOnLane != null) {
273 				for (int r = index - 1; r > childIndex; r--) {
274 					final PlotCommit rObj = get(r);
275 					if (rObj == childOnLane) {
276 						needDetour = true;
277 						break;
278 					}
279 				}
280 			}
281 
282 			if (needDetour) {
283 				// It is childOnLane which is blocking us. Repositioning
284 				// our lane would not help, because this repositions the
285 				// child too, keeping the blockade.
286 				// Instead, we create a "detour lane" which gets us
287 				// around the blockade. That lane has no commits on it.
288 				laneToUse = nextFreeLane(blockedPositions);
289 				currCommit.addForkingOffLane(laneToUse);
290 				closeLane(laneToUse);
291 			} else {
292 				// The blockade is (only) due to other (already closed)
293 				// lanes at the current lane's position. In this case we
294 				// reposition the current lane.
295 				// We are the first commit on this lane, because
296 				// otherwise the child commit on this lane would have
297 				// kept other lanes from blocking us. Since we are the
298 				// first commit, we can freely reposition.
299 				int newPos = getFreePosition(blockedPositions);
300 				freePositions.add(Integer.valueOf(laneToUse
301 						.getPosition()));
302 				laneToUse.position = newPos;
303 			}
304 		}
305 
306 		// Actually connect currCommit to the merge child
307 		drawLaneToChild(index, child, laneToUse);
308 		return laneToUse;
309 	}
310 
311 	/**
312 	 * Connects the commit at commitIndex to the child, using the given lane.
313 	 * All blockades on the lane must be resolved before calling this method.
314 	 *
315 	 * @param commitIndex
316 	 * @param child
317 	 * @param laneToContinue
318 	 */
319 	private void drawLaneToChild(final int commitIndex, PlotCommit child,
320 			PlotLane laneToContinue) {
321 		for (int r = commitIndex - 1; r >= 0; r--) {
322 			final PlotCommit rObj = get(r);
323 			if (rObj == child)
324 				break;
325 			if (rObj != null)
326 				rObj.addPassingLane(laneToContinue);
327 		}
328 	}
329 
330 	private static void addBlockedPosition(BitSet blockedPositions,
331 			final PlotCommit rObj) {
332 		if (rObj != null) {
333 			PlotLane lane = rObj.getLane();
334 			// Positions may be blocked by a commit on a lane.
335 			if (lane != null)
336 				blockedPositions.set(lane.getPosition());
337 			// Positions may also be blocked by forking off and merging lanes.
338 			// We don't consider passing lanes, because every passing lane forks
339 			// off and merges at it ends.
340 			for (PlotLane l : rObj.forkingOffLanes)
341 				blockedPositions.set(l.getPosition());
342 			for (PlotLane l : rObj.mergingLanes)
343 				blockedPositions.set(l.getPosition());
344 		}
345 	}
346 
347 	@SuppressWarnings("unchecked")
348 	private void closeLane(PlotLane lane) {
349 		if (activeLanes.remove(lane)) {
350 			recycleLane((L) lane);
351 			laneLength.remove(lane);
352 			freePositions.add(Integer.valueOf(lane.getPosition()));
353 		}
354 	}
355 
356 	private void setupChildren(final PlotCommit<L> currCommit) {
357 		final int nParents = currCommit.getParentCount();
358 		for (int i = 0; i < nParents; i++)
359 			((PlotCommit) currCommit.getParent(i)).addChild(currCommit);
360 	}
361 
362 	private PlotLane nextFreeLane() {
363 		return nextFreeLane(null);
364 	}
365 
366 	private PlotLane nextFreeLane(BitSet blockedPositions) {
367 		final PlotLane p = createLane();
368 		p.position = getFreePosition(blockedPositions);
369 		activeLanes.add(p);
370 		laneLength.put(p, Integer.valueOf(1));
371 		return p;
372 	}
373 
374 	/**
375 	 * @param blockedPositions
376 	 *            may be null
377 	 * @return a free lane position
378 	 */
379 	private int getFreePosition(BitSet blockedPositions) {
380 		if (freePositions.isEmpty())
381 			return positionsAllocated++;
382 
383 		if (blockedPositions != null) {
384 			for (Integer pos : freePositions)
385 				if (!blockedPositions.get(pos.intValue())) {
386 					freePositions.remove(pos);
387 					return pos.intValue();
388 				}
389 			return positionsAllocated++;
390 		} else {
391 			final Integer min = freePositions.first();
392 			freePositions.remove(min);
393 			return min.intValue();
394 		}
395 	}
396 
397 	/**
398 	 * @return a new Lane appropriate for this particular PlotList.
399 	 */
400 	@SuppressWarnings("unchecked")
401 	protected L createLane() {
402 		return (L) new PlotLane();
403 	}
404 
405 	/**
406 	 * Return colors and other reusable information to the plotter when a lane
407 	 * is no longer needed.
408 	 *
409 	 * @param lane
410 	 */
411 	protected void recycleLane(final L lane) {
412 		// Nothing.
413 	}
414 }