Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: d1535e37d43e467f59ec302bf6f1e341a7c7889d (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
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
/*******************************************************************************
 * Copyright (c) 2000, 2003 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Common Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/cpl-v10.html
 *
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/
package org.eclipse.jface.text.link;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.custom.VerifyKeyListener;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.events.ShellListener;
import org.eclipse.swt.events.VerifyEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

import org.eclipse.jface.internal.text.link.contentassist.ContentAssistant2;
import org.eclipse.jface.internal.text.link.contentassist.IProposalListener;
import org.eclipse.jface.viewers.IPostSelectionProvider;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.SelectionChangedEvent;

import org.eclipse.jface.text.Assert;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.BadPartitioningException;
import org.eclipse.jface.text.BadPositionCategoryException;
import org.eclipse.jface.text.DefaultPositionUpdater;
import org.eclipse.jface.text.DocumentCommand;
import org.eclipse.jface.text.IAutoEditStrategy;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IDocumentExtension3;
import org.eclipse.jface.text.IPositionUpdater;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.IRewriteTarget;
import org.eclipse.jface.text.ITextInputListener;
import org.eclipse.jface.text.ITextOperationTarget;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.ITextViewerExtension;
import org.eclipse.jface.text.ITextViewerExtension2;
import org.eclipse.jface.text.ITextViewerExtension5;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.Region;
import org.eclipse.jface.text.contentassist.ICompletionProposal;
import org.eclipse.jface.text.source.IAnnotationModel;
import org.eclipse.jface.text.source.IAnnotationModelExtension;
import org.eclipse.jface.text.source.ISourceViewer;

/**
 * The UI for linked mode. Detects events that influence behavior of the linked mode
 * UI and acts upon them.
 * <p>
 * <code>LinkedModeUI</code> relies on all added
 * <code>LinkedModeUITarget</code>s to provide implementations of
 * <code>ITextViewer</code> that implement <code>ITextViewerExtension</code>,
 * and the documents being edited to implement <code>IDocumentExtension3</code>.
 * </p>
 * <p>
 * Clients may instantiate and extend this class.
 * </p>
 * 
 * @since 3.0
 */
public class LinkedModeUI {
	
	/* cycle constants */
	/**
	 * Constant indicating that this UI should never cycle from the last
	 * position to the first and vice versa.
	 */
	public static final Object CYCLE_NEVER= new Object();
	/**
	 * Constant indicating that this UI should always cycle from the last
	 * position to the first and vice versa.
	 */
	public static final Object CYCLE_ALWAYS= new Object();
	/**
	 * Constant indicating that this UI should cycle from the last position to
	 * the first and vice versa if its model is not nested.
	 */
	public static final Object CYCLE_WHEN_NO_PARENT= new Object();

	/**
	 * Listener that gets notified when the linked mode UI switches its focus position.
	 * <p>
	 * Clients may implement this interface.
	 * </p>
	 */
	public static interface ILinkedModeUIFocusListener {
		/**
		 * Called when the UI for the linked mode leaves a linked position.
		 * 
		 * @param position the position being left
		 * @param target the target where <code>position</code> resides in
		 */
		void linkingFocusLost(LinkedPosition position, LinkedModeUITarget target);
		/**
		 * Called when the UI for the linked mode gives focus to a linked position.
		 * 
		 * @param position the position being entered
		 * @param target the target where <code>position</code> resides in
		 */
		void linkingFocusGained(LinkedPosition position, LinkedModeUITarget target);
	}
	
	/**
	 * Null object implementation of focus listener.
	 */
	private static final class EmtpyFocusListener implements ILinkedModeUIFocusListener {
		
		public void linkingFocusGained(LinkedPosition position, LinkedModeUITarget target) {
			// ignore
		}
		
		public void linkingFocusLost(LinkedPosition position, LinkedModeUITarget target) {
			// ignore
		}
	}
	
	/**
	 * A link target consists of a viewer and gets notified if the linked mode UI on
	 * it is being shown.
	 * <p>
	 * Clients may extend this class.
	 * </p>
	 * @since 3.0
	 */
	public static abstract class LinkedModeUITarget implements ILinkedModeUIFocusListener {
		/**
		 * Returns the viewer represented by this target, never <code>null</code>.
		 * 
		 * @return the viewer associated with this target.
		 */
		public abstract ITextViewer getViewer();
		
		/**
		 * The viewer's text widget is initialized when the UI first connects
		 * to the viewer and never changed thereafter. This is to keep the
		 * reference of the widget that we have registered our listeners with,
		 * as the viewer, when it gets disposed, does not remember it, resulting
		 * in a situation where we cannot uninstall the listeners and a memory leak.
		 */
		StyledText fWidget;
		
		/** The cached shell - same reason as fWidget. */
		Shell fShell;
		
		/** The registered listener, or <code>null</code>. */
		KeyListener fKeyListener;
		
		/** The cached custom annotation model. */
		LinkedPositionAnnotations fAnnotationModel;
	}

	private static final class EmptyTarget extends LinkedModeUITarget {

		private ITextViewer fTextViewer;

		/**
		 * @param viewer the viewer
		 */
		public EmptyTarget(ITextViewer viewer) {
			Assert.isNotNull(viewer);
			fTextViewer= viewer;
		}
		
		/*
		 * @see org.eclipse.jdt.internal.ui.text.link2.LinkedModeUI.ILinkedUITarget#getViewer()
		 */
		public ITextViewer getViewer() {
			return fTextViewer;
		}
		
		/**
		 * {@inheritDoc}
		 */
		public void linkingFocusLost(LinkedPosition position, LinkedModeUITarget target) {
		}
		
		/**
		 * {@inheritDoc}
		 */
		public void linkingFocusGained(LinkedPosition position, LinkedModeUITarget target) {
		}

	}

	/**
	 * Listens for state changes in the model.
	 */
	private final class ExitListener implements ILinkedModeListener {
		public void left(LinkedModeModel model, int flags) {
			leave(ILinkedModeListener.EXIT_ALL | flags);
		}

		public void suspend(LinkedModeModel model) {
			disconnect();
			redraw();
		}

		public void resume(LinkedModeModel model, int flags) {
			if ((flags & ILinkedModeListener.EXIT_ALL) != 0) {
				leave(flags);
			} else {
				connect();
				if ((flags & ILinkedModeListener.SELECT) != 0)
					select();
				ensureAnnotationModelInstalled();
				redraw();
			}
		}
	}

	/**
	 * Exit flags returned if a custom exit policy wants to exit linked mode.
	 * <p>
	 * Clients may instantiate this class.
	 * </p>
	 */
	public static class ExitFlags {
		/** The flags to return in the <code>leave</code> method. */
		public int flags;
		/** The doit flag of the checked <code>VerifyKeyEvent</code>. */
		public boolean doit;
		/**
		 * Creates a new instance.
		 * 
		 * @param flags the exit flags
		 * @param doit the doit flag for the verify event
		 */
		public ExitFlags(int flags, boolean doit) {
			this.flags= flags;
			this.doit= doit;
		}
	}

	/**
	 * An exit policy can be registered by a caller to get custom exit
	 * behavior.
	 * <p>
	 * Clients may implement this interface.
	 * </p>
	 */
	public interface IExitPolicy {
		/**
		 * Checks whether the linked mode should be left after receiving the
		 * given <code>VerifyEvent</code> and selection. Note that the event
		 * carries widget coordinates as opposed to <code>offset</code> and 
		 * <code>length</code> which are document coordinates.
		 * 
		 * @param model the linked mode model
		 * @param event the verify event
		 * @param offset the offset of the current selection
		 * @param length the length of the current selection
		 * @return valid exit flags or <code>null</code> if no special action
		 *         should be taken
		 */
		ExitFlags doExit(LinkedModeModel model, VerifyEvent event, int offset, int length);
	}

	/**
	 * A NullObject implementation of <code>IExitPolicy</code>.
	 */
	private static class NullExitPolicy implements IExitPolicy {
		/*
		 * @see org.eclipse.jdt.internal.ui.text.link2.LinkedModeUI.IExitPolicy#doExit(org.eclipse.swt.events.VerifyEvent, int, int)
		 */
		public ExitFlags doExit(LinkedModeModel model, VerifyEvent event, int offset, int length) {
			return null;
		}
	}

	/**
	 * Listens for shell events and acts upon them.
	 */
	private class Closer implements ShellListener, ITextInputListener {

		public void shellActivated(ShellEvent e) {
		}

		public void shellClosed(ShellEvent e) {
			leave(ILinkedModeListener.EXIT_ALL);
		}

		public void shellDeactivated(ShellEvent e) {
// 			T ODO reenable after debugging 
//			if (true) return;
			
			// from LinkedPositionUI:
			
			// don't deactivate on focus lost, since the proposal popups may take focus
			// plus: it doesn't hurt if you can check with another window without losing linked mode
			// since there is no intrusive popup sticking out.
			
			// need to check first what happens on reentering based on an open action
			// Seems to be no problem
			
			// Better:
			// Check with content assistant and only leave if its not the proposal shell that took the 
			// focus away.
			
			StyledText text;
			Display display;

			if (fAssistant == null || fCurrentTarget == null || (text= fCurrentTarget.fWidget) == null 
					|| text.isDisposed() || (display= text.getDisplay()) == null || display.isDisposed()) {
				leave(ILinkedModeListener.EXIT_ALL);
			} else {
				// Post in UI thread since the assistant popup will only get the focus after we lose it.
				display.asyncExec(new Runnable() {
					public void run() {
						if (fIsActive && (fAssistant == null || !fAssistant.hasFocus()))  {
							leave(ILinkedModeListener.EXIT_ALL);
						}
					}
				});
			}
		}

		public void shellDeiconified(ShellEvent e) {
		}

		public void shellIconified(ShellEvent e) {
			leave(ILinkedModeListener.EXIT_ALL);
		}

		/*
		 * @see org.eclipse.jface.text.ITextInputListener#inputDocumentAboutToBeChanged(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.IDocument)
		 */
		public void inputDocumentAboutToBeChanged(IDocument oldInput, IDocument newInput) {
			leave(ILinkedModeListener.EXIT_ALL);
		}

		/*
		 * @see org.eclipse.jface.text.ITextInputListener#inputDocumentChanged(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.IDocument)
		 */
		public void inputDocumentChanged(IDocument oldInput, IDocument newInput) {
		}

	}

	/**
	 * Listens for key events, checks the exit policy for custom exit
	 * strategies but defaults to handling Tab, Enter, and Escape.
	 */
	private class KeyListener implements VerifyKeyListener {

		private boolean fIsEnabled= true;

		public void verifyKey(VerifyEvent event) {

			if (!event.doit || !fIsEnabled)
				return;

			Point selection= fCurrentTarget.getViewer().getSelectedRange();
			int offset= selection.x;
			int length= selection.y;

			// if the custom exit policy returns anything, use that
			ExitFlags exitFlags= fExitPolicy.doExit(fEnvironment, event, offset, length);
			if (exitFlags != null) {
				leave(exitFlags.flags);
				event.doit= exitFlags.doit;
				return;
			}

			// standard behaviour:
			// (Shift+)Tab:	jumps from position to position, depending on cycle mode
			// Enter:		accepts all entries and leaves all (possibly stacked) environments, the last sets the caret
			// Esc:			accepts all entries and leaves all (possibly stacked) environments, the caret stays
			// ? what do we do to leave one level of a cycling model that is stacked?
			// -> This is only the case if the level was set up with forced cycling (CYCLE_ALWAYS), in which case
			// the caller is sure that one does not need by-level exiting.
			switch (event.character) {
				// [SHIFT-]TAB = hop between edit boxes
				case 0x09:
					if (!(fExitPosition != null && fExitPosition.includes(offset)) && !fEnvironment.anyPositionContains(offset)) {
						// outside any edit box -> leave (all? TODO should only leave the affected, level and forward to the next upper)
						leave(ILinkedModeListener.EXIT_ALL);
						break;
					} else {
						if (event.stateMask == SWT.SHIFT)
							previous();
						else
							next();
					}

					event.doit= false;
					break;

				// ENTER
				case 0x0A:
				// Ctrl+Enter on WinXP
				case 0x0D:
//					if ((fExitPosition != null && fExitPosition.includes(offset)) || !fEnvironment.anyPositionContains(offset)) {
					if (!fEnvironment.anyPositionContains(offset)) {
//					if ((fExitPosition == null || !fExitPosition.includes(offset)) && !fEnvironment.anyPositionContains(offset)) {
						// outside any edit box or on exit position -> leave (all? TODO should only leave the affected, level and forward to the next upper)
						leave(ILinkedModeListener.EXIT_ALL);
						break;
					} else {
						// normal case: exit entire stack and put caret to final position
						leave(ILinkedModeListener.EXIT_ALL | ILinkedModeListener.UPDATE_CARET);
						event.doit= false;
						break;
					}

				// ESC
				case 0x1B:
					// exit entire stack and leave caret
					leave(ILinkedModeListener.EXIT_ALL);
					event.doit= false;
					break;

				default:
					if (event.character != 0) {
						if (!controlUndoBehavior(offset, length)) {
							leave(ILinkedModeListener.EXIT_ALL);
							break;
						}
					}
			}
		}

		private boolean controlUndoBehavior(int offset, int length) {
			LinkedPosition position= fEnvironment.findPosition(new LinkedPosition(fCurrentTarget.getViewer().getDocument(), offset, length, LinkedPositionGroup.NO_STOP));
			if (position != null) {

				// if the last position is not the same and there is an open change: close it.
				if (!position.equals(fPreviousPosition))
					endCompoundChange();

				beginCompoundChange();
			}

			fPreviousPosition= position;
			return fPreviousPosition != null;
		}

		/**
		 * @param enabled the new enabled state
		 */
		public void setEnabled(boolean enabled) {
			fIsEnabled= enabled;
		}

	}

	/**
	 * Installed as post selection listener on the watched viewer. Updates the
	 * linked position after cursor movement, even to positions not in the
	 * iteration list.
	 */
	private class MySelectionListener implements ISelectionChangedListener {

		/*
		 * @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent)
		 */
		public void selectionChanged(SelectionChangedEvent event) {
			ISelection selection= event.getSelection();
			if (selection instanceof ITextSelection) {
				ITextSelection textsel= (ITextSelection) selection;
				if (event.getSelectionProvider() instanceof ITextViewer) {
					IDocument doc= ((ITextViewer) event.getSelectionProvider()).getDocument();
					if (doc != null) {
						int offset= textsel.getOffset();
						int length= textsel.getLength();
						if (offset >= 0 && length >= 0) {
							LinkedPosition find= new LinkedPosition(doc, offset, length, LinkedPositionGroup.NO_STOP);
							LinkedPosition pos= fEnvironment.findPosition(find);
							if (pos == null && fExitPosition != null && fExitPosition.includes(find))
								pos= fExitPosition;
								
							if (pos != null)
								switchPosition(pos, false, false);
						}
					}
				}
			}
		}

	}
	
	private class ProposalListener implements IProposalListener {
		
		/*
		 * @see org.eclipse.jface.internal.text.link.contentassist.IProposalListener#proposalChosen(org.eclipse.jface.text.contentassist.ICompletionProposal)
		 */
		public void proposalChosen(ICompletionProposal proposal) {
			next();
		}
	}

	/** The current viewer. */
	private LinkedModeUITarget fCurrentTarget;
	/** The manager of the linked positions we provide a UI for. */
	private LinkedModeModel fEnvironment;
	/** The set of viewers we manage. */
	private LinkedModeUITarget[] fTargets;
	/** The iterator over the tab stop positions. */
	private TabStopIterator fIterator;

	/* Our team of event listeners */
	/** The shell listener. */
	private Closer fCloser= new Closer();
	/** The linked mode listener. */
	private ILinkedModeListener fLinkedListener= new ExitListener();
	/** The selection listener. */
	private MySelectionListener fSelectionListener= new MySelectionListener();
	/** The content assist listener. */
	private ProposalListener fProposalListener= new ProposalListener();
	
	/** The last caret position, used by fCaretListener. */
	private final Position fCaretPosition= new Position(0, 0);
	/** The exit policy to control custom exit behaviour */
	private IExitPolicy fExitPolicy= new NullExitPolicy();
	/** The current frame position shown in the UI, or <code>null</code>. */
	private LinkedPosition fFramePosition;
	/** The last visisted position, used for undo / redo. */
	private LinkedPosition fPreviousPosition;
	/** The content assistant used to show proposals. */
	private ContentAssistant2 fAssistant;
	/** The exit position. */
	private LinkedPosition fExitPosition;
	/** State indicator to prevent multiple invocation of leave. */
	private boolean fIsActive= false;
	/** The position updater for the exit position. */
	private IPositionUpdater fPositionUpdater= new DefaultPositionUpdater(getCategory());
	/** Whether to show context info. */
	private boolean fDoContextInfo= false;
	/** Whether we have begun a compound change, but not yet closed. */
	private boolean fHasOpenCompoundChange= false;
	/** The position listener. */
	private ILinkedModeUIFocusListener fPositionListener= new EmtpyFocusListener();
	private IAutoEditStrategy fAutoEditVetoer= new IAutoEditStrategy() {
		
		/*
		 * @see org.eclipse.jface.text.IAutoEditStrategy#customizeDocumentCommand(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.DocumentCommand)
		 */
		public void customizeDocumentCommand(IDocument document, DocumentCommand command) {
			// invalidate the change to ensure that the change is performed on the document only.
			if (fEnvironment.anyPositionContains(command.offset)) {
				command.doit= false;
				command.caretOffset= command.offset + command.length;
			}
			
		}
	};
	/** Whether this UI is in simple highlighting mode or not. */
	private boolean fSimple;

	/**
	 * Creates a new UI on the given model and the set of viewers. The model
	 * must provide a tab stop sequence with a non-empty list of tab stops.
	 * 
	 * @param model the linked mode model
	 * @param targets the non-empty list of targets upon which the linked mode
	 *        UI should act
	 */
	public LinkedModeUI(LinkedModeModel model, LinkedModeUITarget[] targets) {
		constructor(model, targets);
	}

	/**
	 * Convenience constructor for just one viewer.
	 * 
	 * @param model the linked mode model
	 * @param viewer the viewer upon which the linked mode UI should act
	 */
	public LinkedModeUI(LinkedModeModel model, ITextViewer viewer) {
		constructor(model, new LinkedModeUITarget[]{new EmptyTarget(viewer)});
	}

	/**
	 * Convenience constructor for multiple viewers.
	 * 
	 * @param model the linked mode model
	 * @param viewers the non-empty list of viewers upon which the linked mode
	 *        UI should act
	 */
	public LinkedModeUI(LinkedModeModel model, ITextViewer[] viewers) {
		LinkedModeUITarget[] array= new LinkedModeUITarget[viewers.length];
		for (int i= 0; i < array.length; i++) {
			array[i]= new EmptyTarget(viewers[i]);
		}
		constructor(model, array);
	}

	/**
	 * Convenience constructor for one target.
	 * 
	 * @param model the linked mode model
	 * @param target the target upon which the linked mode UI should act
	 */
	public LinkedModeUI(LinkedModeModel model, LinkedModeUITarget target) {
		constructor(model, new LinkedModeUITarget[]{target});
	}

	/**
	 * This does the actual constructor work.
	 * 
	 * @param model the linked mode model
	 * @param targets the non-empty array of targets upon which the linked mode ui
	 *        should act
	 */
	private void constructor(LinkedModeModel model, LinkedModeUITarget[] targets) {
		Assert.isNotNull(model);
		Assert.isNotNull(targets);
		Assert.isTrue(targets.length > 0);
		Assert.isTrue(model.getTabStopSequence().size() > 0);

		fEnvironment= model;
		fTargets= targets;
		fCurrentTarget= targets[0];
		fIterator= new TabStopIterator(fEnvironment.getTabStopSequence());
		fIterator.setCycling(!fEnvironment.isNested());
		fEnvironment.addLinkingListener(fLinkedListener);

		fAssistant= new ContentAssistant2();
		fAssistant.addProposalListener(fProposalListener);
		// TODO find a way to set up content assistant.
//		fAssistant.setDocumentPartitioning(IJavaPartitions.JAVA_PARTITIONING);

		fCaretPosition.delete();
	}

	/**
	 * Starts this UI on the first position.
	 */
	public void enter() {
		fIsActive= true;
		connect();
		next();
	}

	/**
	 * Sets an <code>IExitPolicy</code> to customize the exit behavior of
	 * this linked mode UI.
	 * 
	 * @param policy the exit policy to use.
	 */
	public void setExitPolicy(IExitPolicy policy) {
		fExitPolicy= policy;
	}

	/**
	 * Sets the exit position to move the caret to when linked mode mode is
	 * exited.
	 * 
	 * @param target the target where the exit position is located
	 * @param offset the offset of the exit position
	 * @param length the length of the exit position (in case there should be a
	 *        selection)
	 * @param sequence set to the tab stop position of the exit position, or
	 *        <code>LinkedPositionGroup.NO_STOP</code> if there should be no
	 *        tab stop.
	 * @throws BadLocationException if the position is not valid in the viewer's
	 *         document
	 */
	public void setExitPosition(LinkedModeUITarget target, int offset, int length, int sequence) throws BadLocationException {
		// remove any existing exit position
		if (fExitPosition != null) {
			fExitPosition.getDocument().removePosition(fExitPosition);
			fIterator.removePosition(fExitPosition);
			fExitPosition= null;
		}

		IDocument doc= target.getViewer().getDocument();
		if (doc == null)
			return;

		fExitPosition= new LinkedPosition(doc, offset, length, sequence);
		doc.addPosition(fExitPosition); // gets removed in leave()
		if (sequence != LinkedPositionGroup.NO_STOP)
			fIterator.addPosition(fExitPosition);

	}

	/**
	 * Sets the exit position to move the caret to when linked mode is exited.
	 * 
	 * @param viewer the viewer where the exit position is located
	 * @param offset the offset of the exit position
	 * @param length the length of the exit position (in case there should be a
	 *        selection)
	 * @param sequence set to the tab stop position of the exit position, or 
	 * 		  <code>LinkedPositionGroup.NO_STOP</code> if there should be no tab stop.
	 * @throws BadLocationException if the position is not valid in the
	 *         viewer's document
	 */
	public void setExitPosition(ITextViewer viewer, int offset, int length, int sequence) throws BadLocationException {
		setExitPosition(new EmptyTarget(viewer), offset, length, sequence);
	}

	/**
	 * Sets the cycling mode to either of <code>CYCLING_ALWAYS</code>,
	 * <code>CYCLING_NEVER</code>, or <code>CYCLING_WHEN_NO_PARENT</code>,
	 * which is the default.
	 * 
	 * @param mode the new cycling mode.
	 */
	public void setCyclingMode(Object mode) {
		if (mode != CYCLE_ALWAYS && mode != CYCLE_NEVER && mode != CYCLE_WHEN_NO_PARENT)
			throw new IllegalArgumentException();
		
		if (mode == CYCLE_ALWAYS || mode == CYCLE_WHEN_NO_PARENT && !fEnvironment.isNested())
			fIterator.setCycling(true);
		else
			fIterator.setCycling(false);
	}

	void next() {
		if (fIterator.hasNext(fFramePosition)) {
			switchPosition(fIterator.next(fFramePosition), true, true);
			return;
		} else
			leave(ILinkedModeListener.UPDATE_CARET);
	}

	void previous() {
		if (fIterator.hasPrevious(fFramePosition)) {
			switchPosition(fIterator.previous(fFramePosition), true, true);
		} else
			// dont't update caret, but rather select the current frame
			leave(ILinkedModeListener.SELECT);
	}
	
	private void triggerContextInfo() {
		ITextOperationTarget target= fCurrentTarget.getViewer().getTextOperationTarget();
		if (target != null) {
			if (target.canDoOperation(ISourceViewer.CONTENTASSIST_CONTEXT_INFORMATION))
				target.doOperation(ISourceViewer.CONTENTASSIST_CONTEXT_INFORMATION);
		}
	}

	/** Trigger content assist on choice positions */
	private void triggerContentAssist() {
		if (fFramePosition instanceof ProposalPosition) {
			ProposalPosition pp= (ProposalPosition) fFramePosition;
			ICompletionProposal[] choices= pp.getChoices();
			if (choices != null && choices.length > 0) {
				fAssistant.setCompletions(choices);
				fAssistant.showPossibleCompletions();
				return;
			}
		}
		
		fAssistant.setCompletions(new ICompletionProposal[0]);
		fAssistant.hidePossibleCompletions();
	}

	private void switchPosition(LinkedPosition pos, boolean select, boolean showProposals) {
		Assert.isNotNull(pos);
		if (pos.equals(fFramePosition))
			return;
		
		if (fFramePosition != null && fCurrentTarget != null)
			fPositionListener.linkingFocusLost(fFramePosition, fCurrentTarget);
	
		// undo
		endCompoundChange();
	
		redraw(); // redraw current position being left - usually not needed
		IDocument oldDoc= fFramePosition == null ? null : fFramePosition.getDocument();
		IDocument newDoc= pos.getDocument();
		
		switchViewer(oldDoc, newDoc, pos);
		fFramePosition= pos;

		if (select)
			select();
		if (fFramePosition == fExitPosition && !fIterator.isCycling())
			leave(ILinkedModeListener.NONE);
		else {
			redraw(); // redraw new position
			ensureAnnotationModelInstalled();
		}
		if (showProposals)
			triggerContentAssist();
		if (fFramePosition != fExitPosition && fDoContextInfo)
			triggerContextInfo();
		
		if (fFramePosition != null && fCurrentTarget != null)
			fPositionListener.linkingFocusGained(fFramePosition, fCurrentTarget);
		
	}

	private void ensureAnnotationModelInstalled() {
		LinkedPositionAnnotations lpa= fCurrentTarget.fAnnotationModel;
		if (lpa != null) {
			ITextViewer viewer= fCurrentTarget.getViewer();
			if (viewer instanceof ISourceViewer) {
				ISourceViewer sv= (ISourceViewer) viewer;
				IAnnotationModel model= sv.getAnnotationModel();
				if (model instanceof IAnnotationModelExtension) {
					IAnnotationModelExtension ext= (IAnnotationModelExtension) model;
					IAnnotationModel ourModel= ext.getAnnotationModel(getUniqueKey());
					if (ourModel == null) {
						ext.addAnnotationModel(getUniqueKey(), lpa);
					}
				}
			}
		}
	}
	
	private void uninstallAnnotationModel(LinkedModeUITarget target) {
		ITextViewer viewer= target.getViewer();
		if (viewer instanceof ISourceViewer) {
			ISourceViewer sv= (ISourceViewer) viewer;
			IAnnotationModel model= sv.getAnnotationModel();
			if (model instanceof IAnnotationModelExtension) {
				IAnnotationModelExtension ext= (IAnnotationModelExtension) model;
				ext.removeAnnotationModel(getUniqueKey());
			}
		}
	}

	private void switchViewer(IDocument oldDoc, IDocument newDoc, LinkedPosition pos) {
		if (oldDoc != newDoc) {
			
			// redraw current document with new position before switching viewer
			if (fCurrentTarget.fAnnotationModel != null)
				fCurrentTarget.fAnnotationModel.switchToPosition(fEnvironment, pos);
			
			LinkedModeUITarget target= null;
			for (int i= 0; i < fTargets.length; i++) {
				if (fTargets[i].getViewer().getDocument() == newDoc) {
					target= fTargets[i];
					break;
				}
			}
			if (target != fCurrentTarget) {
				disconnect();
				fCurrentTarget= target;
				target.linkingFocusLost(fFramePosition, target);
				connect();
				ensureAnnotationModelInstalled();
				if (fCurrentTarget != null)
					fCurrentTarget.linkingFocusGained(pos, fCurrentTarget);
			}
		}
	}

	private void select() {
		ITextViewer viewer= fCurrentTarget.getViewer();
		if (viewer instanceof ITextViewerExtension5) {
			ITextViewerExtension5 extension5= (ITextViewerExtension5) viewer;
			extension5.exposeModelRange(new Region(fFramePosition.offset, fFramePosition.length));
		} else if (!viewer.overlapsWithVisibleRegion(fFramePosition.offset, fFramePosition.length)) {
			viewer.resetVisibleRegion();
		}
		viewer.revealRange(fFramePosition.offset, fFramePosition.length);
		viewer.setSelectedRange(fFramePosition.offset, fFramePosition.length);
	}

	private void redraw() {
		if (fCurrentTarget.fAnnotationModel != null)
			fCurrentTarget.fAnnotationModel.switchToPosition(fEnvironment, fFramePosition);
	}

	private void connect() {
		Assert.isNotNull(fCurrentTarget);
		ITextViewer viewer= fCurrentTarget.getViewer();
		Assert.isNotNull(viewer);
		fCurrentTarget.fWidget= viewer.getTextWidget();
		if (fCurrentTarget.fWidget == null)
			leave(ILinkedModeListener.EXIT_ALL);

		if (fCurrentTarget.fKeyListener == null) {
			fCurrentTarget.fKeyListener= new KeyListener();
			((ITextViewerExtension) viewer).prependVerifyKeyListener(fCurrentTarget.fKeyListener);
		} else
			fCurrentTarget.fKeyListener.setEnabled(true);
		
		registerAutoEditVetoer(viewer);
		
		((IPostSelectionProvider) viewer).addPostSelectionChangedListener(fSelectionListener);

		createAnnotationModel();
		
		showSelection();

		fCurrentTarget.fShell= fCurrentTarget.fWidget.getShell();
		if (fCurrentTarget.fShell == null)
			leave(ILinkedModeListener.EXIT_ALL);
		fCurrentTarget.fShell.addShellListener(fCloser);

		fAssistant.install(viewer);
		
		viewer.addTextInputListener(fCloser);
	}

	/**
	 * Reveals the selection on the current target's widget, if it is valid.
	 */
	private void showSelection() {
		try {
			fCurrentTarget.fWidget.showSelection();
		} catch (IllegalArgumentException e) {
			// https://bugs.eclipse.org/bugs/show_bug.cgi?id=66914
			// if the StyledText is in setRedraw(false) mode, its
			// selection may not be up2date and calling showSelection
			// will throw an IAE.
			// we don't have means to find out whether the selection is valid
			// or whether the widget is redrawing or not therefore we try
			// and ignore an IAE.
		}
	}

	/**
	 * Registers our auto edit vetoer with the viewer.
	 * 
	 * @param viewer the viewer we want to veto ui-triggered changes within
	 *        linked positions
	 */
	private void registerAutoEditVetoer(ITextViewer viewer) {
		try {
			if (viewer.getDocument() instanceof IDocumentExtension3) {
				IDocumentExtension3 ext= (IDocumentExtension3) viewer.getDocument();
				String[] contentTypes= ext.getLegalContentTypes(IDocumentExtension3.DEFAULT_PARTITIONING);
				if (viewer instanceof ITextViewerExtension2) {
					ITextViewerExtension2 vExtension= ((ITextViewerExtension2) viewer);
					for (int i= 0; i < contentTypes.length; i++) {
						vExtension.prependAutoEditStrategy(fAutoEditVetoer, contentTypes[i]);
					}
				} else {
					Assert.isTrue(false);
				}
			}

		} catch (BadPartitioningException e) {
			leave(ILinkedModeListener.EXIT_ALL);
		}
	}

	private void unregisterAutoEditVetoer(ITextViewer viewer) {
		try {
			if (viewer.getDocument() instanceof IDocumentExtension3) {
				IDocumentExtension3 ext= (IDocumentExtension3) viewer.getDocument();
				String[] contentTypes= ext.getLegalContentTypes(IDocumentExtension3.DEFAULT_PARTITIONING);
				if (viewer instanceof ITextViewerExtension2) {
					ITextViewerExtension2 vExtension= ((ITextViewerExtension2) viewer);
					for (int i= 0; i < contentTypes.length; i++) {
						vExtension.removeAutoEditStrategy(fAutoEditVetoer, contentTypes[i]);
					}
				}
			}

		} catch (BadPartitioningException e) {
			leave(ILinkedModeListener.EXIT_ALL);
		}
	}

	private void createAnnotationModel() {
		if (fCurrentTarget.fAnnotationModel == null) {
			LinkedPositionAnnotations lpa= new LinkedPositionAnnotations();
			if (fSimple) {
				lpa.markExitTarget(true);
				lpa.markFocus(false);
				lpa.markSlaves(false);
				lpa.markTargets(false);
			}
			lpa.setTargets(fIterator.getPositions());
			lpa.setExitTarget(fExitPosition);
			lpa.connect(fCurrentTarget.getViewer().getDocument());
			fCurrentTarget.fAnnotationModel= lpa;
		}
	}

	private String getUniqueKey() {
		return "linked.annotationmodelkey."+toString(); //$NON-NLS-1$
	}

	private void disconnect() {
		Assert.isNotNull(fCurrentTarget);
		ITextViewer viewer= fCurrentTarget.getViewer();
		Assert.isNotNull(viewer);

		fAssistant.uninstall();
		fAssistant.removeProposalListener(fProposalListener);

		fCurrentTarget.fWidget= null;
		
		Shell shell= fCurrentTarget.fShell;
		fCurrentTarget.fShell= null;
		
		if (shell != null && !shell.isDisposed())
			shell.removeShellListener(fCloser);
		
		// this one is asymmetric: we don't install the model in
		// connect, but leave it to its callers to ensure they
		// have the model installed if they need it
		uninstallAnnotationModel(fCurrentTarget);

		unregisterAutoEditVetoer(viewer);
		
		// don't remove the verify key listener to let it keep its position
		// in the listener queue
		fCurrentTarget.fKeyListener.setEnabled(false);
		
		((IPostSelectionProvider) viewer).removePostSelectionChangedListener(fSelectionListener);

		redraw();
	}

	void leave(final int flags) {
		if (!fIsActive)
			return;
		fIsActive= false;

		endCompoundChange();
		
		Display display= null;
		if (fCurrentTarget.fWidget != null && !fCurrentTarget.fWidget.isDisposed())
			display= fCurrentTarget.fWidget.getDisplay();
		
//		// debug trace
//		JavaPlugin.log(new Status(IStatus.INFO, JavaPlugin.getPluginId(), IStatus.OK, "leaving linked mode", null));
		if (fCurrentTarget.fAnnotationModel != null)
			fCurrentTarget.fAnnotationModel.removeAllAnnotations();
		disconnect();
		
		for (int i= 0; i < fTargets.length; i++) {
			LinkedModeUITarget target= fTargets[i];
			ITextViewer viewer= target.getViewer();
			if (target.fKeyListener != null) {
				((ITextViewerExtension) viewer).removeVerifyKeyListener(target.fKeyListener);
				target.fKeyListener= null;
			}
			
			viewer.removeTextInputListener(fCloser);
		}
		
		for (int i= 0; i < fTargets.length; i++) {
			
			if (fTargets[i].fAnnotationModel != null) {
				fTargets[i].fAnnotationModel.removeAllAnnotations();
				fTargets[i].fAnnotationModel.disconnect(fTargets[i].getViewer().getDocument());
				fTargets[i].fAnnotationModel= null;
			}
			
			uninstallAnnotationModel(fTargets[i]);
		}

		
		if (fExitPosition != null)
			fExitPosition.getDocument().removePosition(fExitPosition);

		if ((flags & ILinkedModeListener.UPDATE_CARET) != 0 && fExitPosition != null && fFramePosition != fExitPosition && !fExitPosition.isDeleted())
			switchPosition(fExitPosition, true, false);

		final List docs= new ArrayList();
		for (int i= 0; i < fTargets.length; i++) {
			IDocument doc= fTargets[i].getViewer().getDocument();
			if (doc != null)
				docs.add(doc);
		}

		Runnable runnable= new Runnable() {
			public void run() {
				for (Iterator iter = docs.iterator(); iter.hasNext(); ) {
					IDocument doc= (IDocument) iter.next();
					doc.removePositionUpdater(fPositionUpdater);
					boolean uninstallCat= false;
					String[] cats= doc.getPositionCategories();
					for (int j= 0; j < cats.length; j++) {
						if (getCategory().equals(cats[j])) {
							uninstallCat= true;
							break;
						}
					}
					if (uninstallCat)
						try {
							doc.removePositionCategory(getCategory());
						} catch (BadPositionCategoryException e) {
							// ignore
						}
				}
				fEnvironment.exit(flags);
			}
		};

		// remove positions (both exit positions AND linked positions in the
		// model) async to make sure that the annotation painter
		// gets correct document offsets.
		if (display != null)
			display.asyncExec(runnable);
		else
			runnable.run();
	}

	private void endCompoundChange() {
		if (fHasOpenCompoundChange) {
			ITextViewerExtension extension= (ITextViewerExtension) fCurrentTarget.getViewer();
			IRewriteTarget target= extension.getRewriteTarget();
			target.endCompoundChange();
			fHasOpenCompoundChange= false;
		}
	}
	
	private void beginCompoundChange() {
		if (!fHasOpenCompoundChange) {
			ITextViewerExtension extension= (ITextViewerExtension) fCurrentTarget.getViewer();
			IRewriteTarget target= extension.getRewriteTarget();
			target.beginCompoundChange();
			fHasOpenCompoundChange= true;
		}
	}

	/**
	 * Returns the currently selected region or <code>null</code>.
	 * 
	 * @return the currently selected region or <code>null</code>
	 */
	public IRegion getSelectedRegion() {
		if (fFramePosition == null)
			if (fExitPosition != null)
				return new Region(fExitPosition.getOffset(), fExitPosition.getLength());
			else
				return null;
		else
			return new Region(fFramePosition.getOffset(), fFramePosition.getLength());
	}

	private String getCategory() {
		return toString();
	}

	/**
	 * Sets the context info property. If set to <code>true</code>, context
	 * info will be invoked on the current target's viewer whenever a position
	 * is switched.
	 * 
	 * @param doContextInfo <code>true</code> if context information should be
	 *        displayed
	 */
	public void setDoContextInfo(boolean doContextInfo) {
		fDoContextInfo= doContextInfo;
	}
	
	/**
	 * Sets the focus callback which will get informed when the focus of the 
	 * linked mode UI changes.
	 * <p>
	 * If there is a listener installed already, it will be replaced.
	 * </p>
	 *  
	 * @param listener the new listener, never <code>null</code>.
	 */
	protected void setPositionListener(ILinkedModeUIFocusListener listener) {
		Assert.isNotNull(listener);
		fPositionListener= listener;
	}
	
	/**
	 * Sets the "simple" mode of the receiver. A linked mode UI in simple mode 
	 * merely draws the exit position, but not the target, focus, and slave
	 * positions. Default is <code>false</code>. This method must be called
	 * before it is entered.
	 * 
	 * @param simple <code>true</code> if the UI should be in simple mode.
	 */
	public void setSimpleMode(boolean simple) {
		fSimple= simple;
	}

}

Back to the top