Skip to main content
summaryrefslogtreecommitdiffstats
blob: 0b876cc92de8587ae9790a2eb57e613e36416f0a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
/*******************************************************************************
 * Copyright (c) 2009 Atlassian and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Atlassian - initial API and implementation
 *     Tasktop Technologies - cleanup and support for gotoAnnotation
 *     Guy Perron 423242: Add ability to edit comment from compare navigator popup
 ******************************************************************************/

package org.eclipse.mylyn.internal.reviews.ui.compare;

import static org.eclipse.mylyn.internal.reviews.ui.compare.ReviewCompareAnnotationSupport.Side.LEFT_SIDE;
import static org.eclipse.mylyn.internal.reviews.ui.compare.ReviewCompareAnnotationSupport.Side.RIGHT_SIDE;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import org.eclipse.compare.contentmergeviewer.TextMergeViewer;
import org.eclipse.compare.internal.MergeSourceViewer;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.text.ITextViewerExtension5;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.Region;
import org.eclipse.jface.text.source.Annotation;
import org.eclipse.jface.text.source.IAnnotationModel;
import org.eclipse.jface.text.source.LineRange;
import org.eclipse.jface.text.source.SourceViewer;
import org.eclipse.jface.text.source.projection.AnnotationBag;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.mylyn.commons.core.StatusHandler;
import org.eclipse.mylyn.internal.reviews.ui.ReviewsUiPlugin;
import org.eclipse.mylyn.internal.reviews.ui.annotations.CommentAnnotation;
import org.eclipse.mylyn.internal.reviews.ui.annotations.CommentAnnotationHoverInput;
import org.eclipse.mylyn.internal.reviews.ui.annotations.CommentPopupDialog;
import org.eclipse.mylyn.internal.reviews.ui.annotations.ReviewAnnotationModel;
import org.eclipse.mylyn.reviews.core.model.IFileItem;
import org.eclipse.mylyn.reviews.core.model.IReviewItem;
import org.eclipse.mylyn.reviews.ui.ReviewBehavior;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.texteditor.AbstractTextEditor;

/**
 * Manages annotation models for compare viewers.
 * 
 * @author Thomas Ehrnhoefer
 * @author Steffen Pingel
 * @author Guy Perron
 */
@SuppressWarnings("restriction")
public class ReviewCompareAnnotationSupport {
	public static enum Side {
		LEFT_SIDE, RIGHT_SIDE
	}

	private static final int INTERRUPT_INTERVAL = 16;

	private static final int PAUSE_DELAY = 250;

	private static String KEY_ANNOTAION_SUPPORT = ReviewItemSetCompareEditorInput.class.getName();

	private CommentPopupDialog commentPopupDialog = null;

	public static ReviewCompareAnnotationSupport getAnnotationSupport(Viewer contentViewer) {
		ReviewCompareAnnotationSupport support = (ReviewCompareAnnotationSupport) contentViewer.getData(KEY_ANNOTAION_SUPPORT);
		if (support == null) {
			support = new ReviewCompareAnnotationSupport(contentViewer);
			contentViewer.setData(KEY_ANNOTAION_SUPPORT, support);
		}
		return support;
	}

	private Thread watchDog = null;

	private boolean sentinel = false;

	public class MonitorObject {
	};

	MonitorObject myMonitorObject = new MonitorObject();

	private ReviewBehavior behavior;

	private final ReviewAnnotationModel leftAnnotationModel;

	private ReviewCompareInputListener leftViewerListener;

	private final ReviewAnnotationModel rightAnnotationModel;

	private ReviewCompareInputListener rightViewerListener;

	private MergeSourceViewer leftSourceViewer;

	private MergeSourceViewer rightSourceViewer;

	public ReviewCompareAnnotationSupport(Viewer contentViewer) {
		this.leftAnnotationModel = new ReviewAnnotationModel();
		this.rightAnnotationModel = new ReviewAnnotationModel();
		install(contentViewer);
		contentViewer.setData(KEY_ANNOTAION_SUPPORT, this);
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}
		if (obj == null) {
			return false;
		}
		if (getClass() != obj.getClass()) {
			return false;
		}
		ReviewCompareAnnotationSupport other = (ReviewCompareAnnotationSupport) obj;
		if (leftAnnotationModel == null) {
			if (other.leftAnnotationModel != null) {
				return false;
			}
		} else if (!leftAnnotationModel.equals(other.leftAnnotationModel)) {
			return false;
		}
		if (rightAnnotationModel == null) {
			if (other.rightAnnotationModel != null) {
				return false;
			}
		} else if (!rightAnnotationModel.equals(other.rightAnnotationModel)) {
			return false;
		}
		return true;
	}

	public ReviewBehavior getBehavior() {
		return behavior;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((leftAnnotationModel == null) ? 0 : leftAnnotationModel.hashCode());
		result = prime * result + ((rightAnnotationModel == null) ? 0 : rightAnnotationModel.hashCode());
		return result;
	}

	public void install(Viewer contentViewer) {
		// FIXME: hack
		if (contentViewer instanceof TextMergeViewer) {
			TextMergeViewer textMergeViewer = (TextMergeViewer) contentViewer;
			try {
				Class<TextMergeViewer> clazz = TextMergeViewer.class;
				Field declaredField = clazz.getDeclaredField("fLeft"); //$NON-NLS-1$
				declaredField.setAccessible(true);
				leftSourceViewer = (MergeSourceViewer) declaredField.get(textMergeViewer);

				declaredField = clazz.getDeclaredField("fRight"); //$NON-NLS-1$
				declaredField.setAccessible(true);
				rightSourceViewer = (MergeSourceViewer) declaredField.get(textMergeViewer);

				leftViewerListener = registerInputListener(leftSourceViewer, leftAnnotationModel);
				rightViewerListener = registerInputListener(rightSourceViewer, rightAnnotationModel);
			} catch (Throwable t) {
				StatusHandler.log(new Status(IStatus.WARNING, ReviewsUiPlugin.PLUGIN_ID,
						"Could not initialize annotation model for " + Viewer.class.getName(), t)); //$NON-NLS-1$
			}
		}
	}

	public boolean hasAnnotation(Direction direction) {
		Position rightPosition = new Position(0, 0);
		return findAnnotation(rightSourceViewer, direction, rightPosition, rightAnnotationModel) != null;
	}

	/**
	 * Jumps to the next annotation according to the given direction.
	 * 
	 * @param direction
	 *            the search direction
	 * @return the selected annotation or <code>null</code> if none
	 */
	public Annotation gotoAnnotation(Direction direction) {
		if (leftSourceViewer == null) {
			return null;
		}
		int currentLeftOffset = getSelection(leftSourceViewer).getOffset();

		Position nextLeftPosition = new Position(0, 0);
		Annotation leftAnnotation = findAnnotation(leftSourceViewer, direction, nextLeftPosition, leftAnnotationModel);
		Position nextRightPosition = new Position(0, 0);
		Annotation rightAnnotation = findAnnotation(rightSourceViewer, direction, nextRightPosition,
				rightAnnotationModel);
		if (leftAnnotation == null && rightAnnotation != null) {
			selectAndReveal(rightSourceViewer, nextRightPosition);
			return rightAnnotation;
		} else if (leftAnnotation != null && rightAnnotation == null) {
			selectAndReveal(leftSourceViewer, nextLeftPosition);
			return leftAnnotation;
		} else if (leftAnnotation != null && rightAnnotation != null) {
			nextLeftPosition.offset = getLineOffset(leftAnnotationModel, nextLeftPosition.offset);
			nextLeftPosition.length = 1;
			nextRightPosition.offset = getLineOffset(rightAnnotationModel, nextRightPosition.offset);
			nextRightPosition.length = 1;
			currentLeftOffset = getLineOffset(leftAnnotationModel, currentLeftOffset);

			if (calculateNextAnnotation(direction, nextLeftPosition, nextRightPosition, currentLeftOffset) == LEFT_SIDE) {
				return leftAnnotation;
			} else {
				return rightAnnotation;
			}
		}
		return null;
	}

	private int getLineOffset(ReviewAnnotationModel annotationModel, int offset) {
		try {
			int line = annotationModel.getDocument().getLineOfOffset(offset);
			return annotationModel.getDocument().getLineOffset(line);
		} catch (BadLocationException e) {
			StatusHandler.log(new Status(IStatus.ERROR, ReviewsUiPlugin.PLUGIN_ID, "Error displaying comment", e)); //$NON-NLS-1$
		}
		return 0;
	}

	public Side calculateNextAnnotation(Direction direction, Position nextLeftPosition, Position nextRightPosition,
			Integer currentLeftOffset) {
		if (direction == Direction.FORWARDS) {
			if (nextLeftPosition.offset == nextRightPosition.offset) {
				moveToAnnotation(rightSourceViewer, leftSourceViewer, nextLeftPosition);
				rightSourceViewer.getSourceViewer().revealRange(nextLeftPosition.offset - 1,
						nextLeftPosition.length - 1);
				rightSourceViewer.getSourceViewer().setSelectedRange(nextLeftPosition.offset - 1,
						nextLeftPosition.length - 1);
				return LEFT_SIDE;
			} else if ((nextLeftPosition.offset < currentLeftOffset && nextRightPosition.offset < currentLeftOffset)
					|| (nextLeftPosition.offset > currentLeftOffset && nextRightPosition.offset > currentLeftOffset)) {
				if ((nextLeftPosition.offset < nextRightPosition.offset)) {
					return moveToLeftAnnotation(nextLeftPosition);
				} else {
					return moveToRightAnnotation(nextRightPosition);
				}
			} else if ((nextLeftPosition.offset < currentLeftOffset && nextRightPosition.offset > currentLeftOffset)) {
				return moveToRightAnnotation(nextRightPosition);
			} else if ((nextLeftPosition.offset > currentLeftOffset && nextRightPosition.offset < currentLeftOffset)) {
				return moveToLeftAnnotation(nextLeftPosition);
			} else if (nextRightPosition.offset == currentLeftOffset) {
				return moveToLeftAnnotation(nextLeftPosition);
			} else {
				return moveToRightAnnotation(nextRightPosition);
			}

		} else { // backwards
			if (nextLeftPosition.offset == nextRightPosition.offset) {
				moveToAnnotation(leftSourceViewer, rightSourceViewer, nextRightPosition);
				Position position = getNextLine(nextRightPosition.offset);
				leftSourceViewer.getSourceViewer().revealRange(position.offset, position.length);
				leftSourceViewer.getSourceViewer().setSelectedRange(position.offset, position.length);
				return RIGHT_SIDE;
			} else if ((nextLeftPosition.offset > currentLeftOffset && nextRightPosition.offset > currentLeftOffset)
					|| (nextLeftPosition.offset < currentLeftOffset && nextRightPosition.offset < currentLeftOffset)) {
				if ((nextLeftPosition.offset > nextRightPosition.offset)) {
					return moveToLeftAnnotation(nextLeftPosition);
				} else {
					return moveToRightAnnotation(nextRightPosition);
				}
			} else if ((nextLeftPosition.offset > currentLeftOffset && nextRightPosition.offset < currentLeftOffset)) {
				return moveToRightAnnotation(nextRightPosition);
			} else if ((nextLeftPosition.offset < currentLeftOffset && nextRightPosition.offset > currentLeftOffset)) {
				return moveToLeftAnnotation(nextLeftPosition);
			} else if (nextRightPosition.offset == currentLeftOffset) {
				return moveToLeftAnnotation(nextLeftPosition);
			} else {
				return moveToRightAnnotation(nextRightPosition);
			}

		}
	}

	private Position getNextLine(int offset) {
		Position position = new Position(0, 0);
		try {
			int line = rightAnnotationModel.getDocument().getLineOfOffset(offset);
			IRegion region = rightAnnotationModel.getDocument().getLineInformation(line + 1);
			position.offset = region.getOffset();
			position.length = region.getLength();
		} catch (BadLocationException e) {
			StatusHandler.log(new Status(IStatus.ERROR, ReviewsUiPlugin.PLUGIN_ID, "Error displaying comment", e)); //$NON-NLS-1$
		}
		return position;
	}

	private Side moveToLeftAnnotation(Position nextLeftPosition) {
		moveToAnnotation(rightSourceViewer, leftSourceViewer, nextLeftPosition);
		return LEFT_SIDE;
	}

	private Side moveToRightAnnotation(Position nextRightPosition) {
		moveToAnnotation(leftSourceViewer, rightSourceViewer, nextRightPosition);
		return RIGHT_SIDE;
	}

	public void moveToAnnotation(MergeSourceViewer adjacentViewer, MergeSourceViewer annotationViewer, Position position) {
		adjacentViewer.getSourceViewer().revealRange(position.offset, position.length);
		adjacentViewer.getSourceViewer().setSelectedRange(position.offset, position.length);
		selectAndReveal(annotationViewer, position);
	}

	// adapted from {@link AbstractTextEditor#selectAndReveal(int, int)}
	private void selectAndReveal(MergeSourceViewer sourceViewer, Position position) {
		StyledText widget = sourceViewer.getSourceViewer().getTextWidget();
		widget.setRedraw(false);
		adjustHighlightRange(sourceViewer.getSourceViewer(), position.offset, position.length);
		sourceViewer.getSourceViewer().revealRange(position.offset, position.length);
		sourceViewer.getSourceViewer().setSelectedRange(position.offset, position.length);
		SourceViewer srcViewer = sourceViewer.getSourceViewer();

		IReviewItem reviewitem = ((ReviewAnnotationModel) srcViewer.getAnnotationModel()).getItem();

		List<CommentAnnotation> comments = getAnnotationsForLine(srcViewer, position.offset);

		Point p = sourceViewer.getLineRange(position, sourceViewer.getSourceViewer().getSelectedRange());
		LineRange range = new LineRange(p.x + 1, p.y);

		if (commentPopupDialog != null) {
			if (watchDog != null) {
				try {
					synchronized (myMonitorObject) {
						sentinel = true;
						commentPopupDialog.dispose();
						myMonitorObject.wait();
					}
				} catch (InterruptedException e) {
					StatusHandler.log(new Status(IStatus.ERROR, ReviewsUiPlugin.PLUGIN_ID, "Error destroying dialog", e)); //$NON-NLS-1$
				}
			}
		}

		commentPopupDialog = new CommentPopupDialog(ReviewsUiPlugin.getDefault()
				.getWorkbench()
				.getActiveWorkbenchWindow()
				.getShell(), SWT.NO_FOCUS | SWT.ON_TOP, true, reviewitem, range);
		CommentAnnotationHoverInput input = new CommentAnnotationHoverInput(comments,
				((ReviewAnnotationModel) srcViewer.getAnnotationModel()).getBehavior());
		commentPopupDialog.create();
		commentPopupDialog.setInput(input);
		commentPopupDialog.setSize(50, 150);

		Point location = sourceViewer.getSourceViewer().getControl().getLocation();
		location = Display.getCurrent().getCursorLocation();
		location.y = location.y + (sourceViewer.getViewportHeight() / 2);
		commentPopupDialog.setLocation(location);
		commentPopupDialog.open();

		watchDog = new Thread(new Runnable() {
			public void run() {
				try {
					for (int x = 0; x < INTERRUPT_INTERVAL; x++) {
						if (sentinel) {
							Thread.currentThread().interrupt();
							break;
						}
						Thread.sleep(PAUSE_DELAY);
					}
				} catch (Exception e) {
					StatusHandler.log(new Status(IStatus.ERROR, ReviewsUiPlugin.PLUGIN_ID,
							"Error interrupting thread", e)); //$NON-NLS-1$
				}
				if (!sentinel) {
					Display.getDefault().asyncExec(new Runnable() {
						public void run() {
							if (commentPopupDialog != null) {
								commentPopupDialog.dispose();
								commentPopupDialog = null;
							}
						}
					});
				}
				synchronized (myMonitorObject) {
					myMonitorObject.notify();
				}
			}
		});
		sentinel = false;

		watchDog.start();
		widget.setRedraw(true);
	}

	@SuppressWarnings("unchecked")
	private List<CommentAnnotation> getAnnotationsForLine(SourceViewer viewer, int offset) {
		IAnnotationModel model = viewer.getAnnotationModel();
		if (model == null) {
			return Collections.emptyList();
		}

		IDocument document = viewer.getDocument();
		int line = 0;
		try {
			line = document.getLineOfOffset(offset);
		} catch (BadLocationException e1) {
			StatusHandler.log(new Status(IStatus.ERROR, ReviewsUiPlugin.PLUGIN_ID, "Error fetching line", e1)); //$NON-NLS-1$
		}

		List<CommentAnnotation> commentAnnotations = new ArrayList<CommentAnnotation>();

		for (Iterator<Annotation> it = model.getAnnotationIterator(); it.hasNext();) {
			Annotation annotation = it.next();
			Position position = model.getPosition(annotation);
			if (position == null || !isPositionOnLine(position, line, document)) {
				continue;
			}
			if (annotation instanceof AnnotationBag) {
				AnnotationBag bag = (AnnotationBag) annotation;
				Iterator<Annotation> e = bag.iterator();
				while (e.hasNext()) {
					annotation = e.next();
					position = model.getPosition(annotation);
					if (position != null && includeAnnotation(annotation, position, commentAnnotations)) {
						commentAnnotations.add((CommentAnnotation) annotation);
					}
				}
			} else if (includeAnnotation(annotation, position, commentAnnotations)) {
				commentAnnotations.add((CommentAnnotation) annotation);
			}
		}

		return commentAnnotations;
	}

	private boolean includeAnnotation(Annotation annotation, Position position, List<CommentAnnotation> annotations) {
		return annotation instanceof CommentAnnotation && !annotations.contains(annotation);
	}

	private boolean isPositionOnLine(Position position, int line, IDocument document) {
		if (position.getOffset() > -1 && position.getLength() > -1) {
			try {
				return line == document.getLineOfOffset(position.getOffset());
			} catch (BadLocationException x) {
				// ignore
			}
		}
		return false;
	}

	// adapted from {@link AbstractTextEditor#selectAndReveal(int, int)}
	protected void adjustHighlightRange(SourceViewer sourceViewer, int offset, int length) {
		if (sourceViewer instanceof ITextViewerExtension5) {
			ITextViewerExtension5 extension = (ITextViewerExtension5) sourceViewer;
			extension.exposeModelRange(new Region(offset, length));
		} else if (!isVisible(sourceViewer, offset, length)) {
			sourceViewer.resetVisibleRegion();
		}
	}

	// adapted from {@link AbstractTextEditor#selectAndReveal(int, int)}
	private boolean isVisible(SourceViewer viewer, int offset, int length) {
		if (viewer instanceof ITextViewerExtension5) {
			ITextViewerExtension5 extension = (ITextViewerExtension5) viewer;
			IRegion overlap = extension.modelRange2WidgetRange(new Region(offset, length));
			return overlap != null;
		}
		return viewer.overlapsWithVisibleRegion(offset, length);
	}

	public void setReviewItem(IFileItem item, ReviewBehavior behavior) {
		leftAnnotationModel.setItem(item.getBase(), behavior);
		rightAnnotationModel.setItem(item.getTarget(), behavior);
		Display.getDefault().asyncExec(new Runnable() {
			public void run() {
				try {
					// if listeners exist, just make sure the hover hack is in there
					if (leftViewerListener != null) {
						leftViewerListener.forceCustomAnnotationHover();
					}
					if (rightViewerListener != null) {
						rightViewerListener.forceCustomAnnotationHover();
					}
				} catch (Exception e) {
					StatusHandler.log(new Status(IStatus.ERROR, ReviewsUiPlugin.PLUGIN_ID,
							"Error attaching annotation hover", e)); //$NON-NLS-1$
				}
			}
		});
	}

	private ReviewCompareInputListener registerInputListener(final MergeSourceViewer sourceViewer,
			final ReviewAnnotationModel annotationModel) {
		ReviewCompareInputListener listener = new ReviewCompareInputListener(sourceViewer, annotationModel);
		SourceViewer viewer = CompareUtil.getSourceViewer(sourceViewer);
		if (viewer != null) {
			viewer.addTextInputListener(listener);
		}
		listener.registerContextMenu();
		return listener;
	}

	/**
	 * Returns the annotation closest to the given range respecting the given direction. If an annotation is found, the
	 * annotations current position is copied into the provided annotation position.
	 * 
	 * @param viewer
	 *            the viewer
	 * @param direction
	 *            the search direction
	 * @param annotationPosition
	 *            the position of the found annotation
	 * @param annotationModel
	 *            the annotation model to process
	 * @return the found annotation
	 * @see borrowed and adapted from {@link AbstractTextEditor}
	 */
	@SuppressWarnings("null")
	protected Annotation findAnnotation(MergeSourceViewer viewer, Direction direction, Position annotationPosition,
			ReviewAnnotationModel annotationModel) {
		if (viewer == null) {
			return null;
		}
		ITextSelection selection = getSelection(viewer);
		final int offset = selection.getOffset();
		final int length = selection.getLength();

		Annotation nextAnnotation = null;
		Position nextAnnotationPosition = null;
		Annotation containingAnnotation = null;
		Position containingAnnotationPosition = null;
		boolean currentAnnotation = false;

		IDocument document = annotationModel.getDocument();
		if (document == null) {
			return null;
		}

		int endOfDocument = document.getLength();
		int distance = Integer.MAX_VALUE;

		Iterator<CommentAnnotation> e = annotationModel.getAnnotationIterator();
		while (e.hasNext()) {
			CommentAnnotation a = e.next();

			Position p = a.getPosition();
			if (p == null) {
				continue;
			}

			if (direction == Direction.FORWARDS && p.offset == offset || direction == Direction.BACKWARDS
					&& p.offset + p.getLength() == offset + length) {// || p.includes(offset)) {
				if (containingAnnotation == null
						|| (direction == Direction.FORWARDS && p.length >= containingAnnotationPosition.length || direction == Direction.BACKWARDS
								&& p.length >= containingAnnotationPosition.length)) {
					containingAnnotation = a;
					containingAnnotationPosition = p;
					currentAnnotation = p.length == length;
				}
			} else {
				int currentDistance = 0;

				if (direction == Direction.FORWARDS) {
					currentDistance = p.getOffset() - offset;
					if (currentDistance < 0) {
						currentDistance = endOfDocument + currentDistance;
					}

					if (currentDistance < distance || currentDistance == distance
							&& p.length < nextAnnotationPosition.length) {
						distance = currentDistance;
						nextAnnotation = a;
						nextAnnotationPosition = p;
					}
				} else {
					currentDistance = offset + length - (p.getOffset() + p.length);
					if (currentDistance < 0) {
						currentDistance = endOfDocument + currentDistance;
					}

					if (currentDistance < distance || currentDistance == distance
							&& p.length < nextAnnotationPosition.length) {
						distance = currentDistance;
						nextAnnotation = a;
						nextAnnotationPosition = p;
					}
				}
			}
		}
		if (containingAnnotationPosition != null && (!currentAnnotation || nextAnnotation == null)) {
			annotationPosition.setOffset(containingAnnotationPosition.getOffset());
			annotationPosition.setLength(containingAnnotationPosition.getLength());
			return containingAnnotation;
		}
		if (nextAnnotationPosition != null) {
			annotationPosition.setOffset(nextAnnotationPosition.getOffset());
			annotationPosition.setLength(nextAnnotationPosition.getLength());
		}

		return nextAnnotation;
	}

	private ITextSelection getSelection(MergeSourceViewer viewer) {
		return (ITextSelection) viewer.getSourceViewer().getSelectionProvider().getSelection();
	}

}

Back to the top