View | Details | Raw Unified | Return to bug 69581 | Differences between
and this patch

Collapse All | Expand All

(-)ui/org/eclipse/jdt/internal/ui/javaeditor/ClipboardOperationAction.java (-13 / +23 lines)
Lines 41-52 Link Here
41
import org.eclipse.jface.text.ITextOperationTarget;
41
import org.eclipse.jface.text.ITextOperationTarget;
42
import org.eclipse.jface.text.ITextSelection;
42
import org.eclipse.jface.text.ITextSelection;
43
import org.eclipse.jface.text.Region;
43
import org.eclipse.jface.text.Region;
44
import org.eclipse.jface.text.templates.Template;
44
45
45
import org.eclipse.ui.IWorkbenchPartSite;
46
import org.eclipse.ui.IWorkbenchPartSite;
46
import org.eclipse.ui.texteditor.IAbstractTextEditorHelpContextIds;
47
import org.eclipse.ui.texteditor.IAbstractTextEditorHelpContextIds;
47
import org.eclipse.ui.texteditor.ITextEditor;
48
import org.eclipse.ui.texteditor.ITextEditor;
48
import org.eclipse.ui.texteditor.IWorkbenchActionDefinitionIds;
49
import org.eclipse.ui.texteditor.IWorkbenchActionDefinitionIds;
49
import org.eclipse.ui.texteditor.TextEditorAction;
50
import org.eclipse.ui.texteditor.TextEditorAction;
51
import org.eclipse.ui.texteditor.templates.TemplateTransfer;
52
53
import org.eclipse.ui.views.templates.ITemplatesPage;
50
54
51
import org.eclipse.jdt.core.ICompilationUnit;
55
import org.eclipse.jdt.core.ICompilationUnit;
52
import org.eclipse.jdt.core.IJavaElement;
56
import org.eclipse.jdt.core.IJavaElement;
Lines 66-71 Link Here
66
import org.eclipse.jdt.ui.PreferenceConstants;
70
import org.eclipse.jdt.ui.PreferenceConstants;
67
71
68
import org.eclipse.jdt.internal.ui.JavaPlugin;
72
import org.eclipse.jdt.internal.ui.JavaPlugin;
73
import org.eclipse.jdt.internal.ui.preferences.JavaTemplatesPage;
69
74
70
75
71
/**
76
/**
Lines 89-95 Link Here
89
		}
94
		}
90
95
91
		public ClipboardData(byte[] bytes) throws IOException {
96
		public ClipboardData(byte[] bytes) throws IOException {
92
			DataInputStream dataIn = new DataInputStream(new ByteArrayInputStream(bytes));
97
			DataInputStream dataIn= new DataInputStream(new ByteArrayInputStream(bytes));
93
			try {
98
			try {
94
				fOriginHandle= dataIn.readUTF();
99
				fOriginHandle= dataIn.readUTF();
95
				fTypeImports= readArray(dataIn);
100
				fTypeImports= readArray(dataIn);
Lines 103-109 Link Here
103
			int count= dataIn.readInt();
108
			int count= dataIn.readInt();
104
109
105
			String[] array= new String[count];
110
			String[] array= new String[count];
106
			for (int i = 0; i < count; i++) {
111
			for (int i= 0; i < count; i++) {
107
				array[i]= dataIn.readUTF();
112
				array[i]= dataIn.readUTF();
108
			}
113
			}
109
			return array;
114
			return array;
Lines 111-117 Link Here
111
116
112
		private static void writeArray(DataOutputStream dataOut, String[] array) throws IOException {
117
		private static void writeArray(DataOutputStream dataOut, String[] array) throws IOException {
113
			dataOut.writeInt(array.length);
118
			dataOut.writeInt(array.length);
114
			for (int i = 0; i < array.length; i++) {
119
			for (int i= 0; i < array.length; i++) {
115
				dataOut.writeUTF(array[i]);
120
				dataOut.writeUTF(array[i]);
116
			}
121
			}
117
		}
122
		}
Lines 129-136 Link Here
129
		}
134
		}
130
135
131
		public byte[] serialize() throws IOException {
136
		public byte[] serialize() throws IOException {
132
			ByteArrayOutputStream out = new ByteArrayOutputStream();
137
			ByteArrayOutputStream out= new ByteArrayOutputStream();
133
			DataOutputStream dataOut = new DataOutputStream(out);
138
			DataOutputStream dataOut= new DataOutputStream(out);
134
			try {
139
			try {
135
				dataOut.writeUTF(fOriginHandle);
140
				dataOut.writeUTF(fOriginHandle);
136
				writeArray(dataOut, fTypeImports);
141
				writeArray(dataOut, fTypeImports);
Lines 147-155 Link Here
147
152
148
	private static class ClipboardTransfer extends ByteArrayTransfer {
153
	private static class ClipboardTransfer extends ByteArrayTransfer {
149
154
150
		private static final String TYPE_NAME = "source-with-imports-transfer-format" + System.currentTimeMillis(); //$NON-NLS-1$
155
		private static final String TYPE_NAME= "source-with-imports-transfer-format" + System.currentTimeMillis(); //$NON-NLS-1$
151
156
152
		private static final int TYPEID = registerType(TYPE_NAME);
157
		private static final int TYPEID= registerType(TYPE_NAME);
153
158
154
		/* (non-Javadoc)
159
		/* (non-Javadoc)
155
		 * @see org.eclipse.swt.dnd.Transfer#getTypeIds()
160
		 * @see org.eclipse.swt.dnd.Transfer#getTypeIds()
Lines 182-188 Link Here
182
		 * Method declared on Transfer.
187
		 * Method declared on Transfer.
183
		 */
188
		 */
184
		protected Object nativeToJava(TransferData transferData) {
189
		protected Object nativeToJava(TransferData transferData) {
185
			byte[] bytes = (byte[]) super.nativeToJava(transferData);
190
			byte[] bytes= (byte[]) super.nativeToJava(transferData);
186
			if (bytes != null) {
191
			if (bytes != null) {
187
				try {
192
				try {
188
					return new ClipboardData(bytes);
193
					return new ClipboardData(bytes);
Lines 194-200 Link Here
194
199
195
	}
200
	}
196
201
197
	private static final ClipboardTransfer fgTransferInstance = new ClipboardTransfer();
202
	private static final ClipboardTransfer fgTransferInstance= new ClipboardTransfer();
198
203
199
	/** The text operation code */
204
	/** The text operation code */
200
	private int fOperationCode= -1;
205
	private int fOperationCode= -1;
Lines 295-301 Link Here
295
		}
300
		}
296
301
297
		ITextEditor editor= getTextEditor();
302
		ITextEditor editor= getTextEditor();
298
		if (fOperationTarget == null && editor!= null && fOperationCode != -1)
303
		if (fOperationTarget == null && editor != null && fOperationCode != -1)
299
			fOperationTarget= (ITextOperationTarget) editor.getAdapter(ITextOperationTarget.class);
304
			fOperationTarget= (ITextOperationTarget) editor.getAdapter(ITextOperationTarget.class);
300
305
301
		boolean isEnabled= (fOperationTarget != null && fOperationTarget.canDoOperation(fOperationCode));
306
		boolean isEnabled= (fOperationTarget != null && fOperationTarget.canDoOperation(fOperationCode));
Lines 430-438 Link Here
430
					typeBinding= typeBinding.getElementType();
435
					typeBinding= typeBinding.getElementType();
431
				}
436
				}
432
				if (typeBinding.isTypeVariable() || typeBinding.isCapture() || typeBinding.isWildcardType()) { // can be removed when bug 98473 is fixed
437
				if (typeBinding.isTypeVariable() || typeBinding.isCapture() || typeBinding.isWildcardType()) { // can be removed when bug 98473 is fixed
433
					continue; 
438
					continue;
434
				}
439
				}
435
				
440
436
				if (typeBinding.isMember() || typeBinding.isTopLevel()) {
441
				if (typeBinding.isMember() || typeBinding.isTopLevel()) {
437
					String name= Bindings.getRawQualifiedName(typeBinding);
442
					String name= Bindings.getRawQualifiedName(typeBinding);
438
					if (name.length() > 0) {
443
					if (name.length() > 0) {
Lines 489-495 Link Here
489
				}
494
				}
490
			}
495
			}
491
		} else {
496
		} else {
492
			fOperationTarget.doOperation(fOperationCode);
497
			Template[] templates= (Template[]) clipboard.getContents(TemplateTransfer.getInstance());
498
			if (templates != null) {
499
				JavaTemplatesPage page= (JavaTemplatesPage) editor.getAdapter(ITemplatesPage.class);
500
				page.insertTemplate(templates[0]);
501
			} else
502
				fOperationTarget.doOperation(fOperationCode);
493
		}
503
		}
494
	}
504
	}
495
505
(-)ui/org/eclipse/jdt/internal/ui/javaeditor/JavaEditor.java (-133 / +151 lines)
Lines 141-146 Link Here
141
141
142
import org.eclipse.ui.views.contentoutline.ContentOutline;
142
import org.eclipse.ui.views.contentoutline.ContentOutline;
143
import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
143
import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
144
import org.eclipse.ui.views.templates.ITemplatesPage;
144
145
145
import org.eclipse.jdt.core.IClassFile;
146
import org.eclipse.jdt.core.IClassFile;
146
import org.eclipse.jdt.core.ICompilationUnit;
147
import org.eclipse.jdt.core.ICompilationUnit;
Lines 194-199 Link Here
194
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectNextAction;
195
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectNextAction;
195
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectPreviousAction;
196
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectPreviousAction;
196
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectionAction;
197
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectionAction;
198
import org.eclipse.jdt.internal.ui.preferences.JavaTemplatesPage;
197
import org.eclipse.jdt.internal.ui.search.BreakContinueTargetFinder;
199
import org.eclipse.jdt.internal.ui.search.BreakContinueTargetFinder;
198
import org.eclipse.jdt.internal.ui.search.ExceptionOccurrencesFinder;
200
import org.eclipse.jdt.internal.ui.search.ExceptionOccurrencesFinder;
199
import org.eclipse.jdt.internal.ui.search.ImplementOccurrencesFinder;
201
import org.eclipse.jdt.internal.ui.search.ImplementOccurrencesFinder;
Lines 223-229 Link Here
223
	 * Internal implementation class for a change listener.
225
	 * Internal implementation class for a change listener.
224
	 * @since 3.0
226
	 * @since 3.0
225
	 */
227
	 */
226
	protected abstract class AbstractSelectionChangedListener implements ISelectionChangedListener  {
228
	protected abstract class AbstractSelectionChangedListener implements ISelectionChangedListener {
227
229
228
		/**
230
		/**
229
		 * Installs this selection changed listener with the given selection provider. If
231
		 * Installs this selection changed listener with the given selection provider. If
Lines 237-246 Link Here
237
			if (selectionProvider == null)
239
			if (selectionProvider == null)
238
				return;
240
				return;
239
241
240
			if (selectionProvider instanceof IPostSelectionProvider)  {
242
			if (selectionProvider instanceof IPostSelectionProvider) {
241
				IPostSelectionProvider provider= (IPostSelectionProvider) selectionProvider;
243
				IPostSelectionProvider provider= (IPostSelectionProvider) selectionProvider;
242
				provider.addPostSelectionChangedListener(this);
244
				provider.addPostSelectionChangedListener(this);
243
			} else  {
245
			} else {
244
				selectionProvider.addSelectionChangedListener(this);
246
				selectionProvider.addSelectionChangedListener(this);
245
			}
247
			}
246
		}
248
		}
Lines 254-263 Link Here
254
			if (selectionProvider == null)
256
			if (selectionProvider == null)
255
				return;
257
				return;
256
258
257
			if (selectionProvider instanceof IPostSelectionProvider)  {
259
			if (selectionProvider instanceof IPostSelectionProvider) {
258
				IPostSelectionProvider provider= (IPostSelectionProvider) selectionProvider;
260
				IPostSelectionProvider provider= (IPostSelectionProvider) selectionProvider;
259
				provider.removePostSelectionChangedListener(this);
261
				provider.removePostSelectionChangedListener(this);
260
			} else  {
262
			} else {
261
				selectionProvider.removeSelectionChangedListener(this);
263
				selectionProvider.removeSelectionChangedListener(this);
262
			}
264
			}
263
		}
265
		}
Lines 282-288 Link Here
282
	/**
284
	/**
283
	 * Updates the selection in the editor's widget with the selection of the outline page.
285
	 * Updates the selection in the editor's widget with the selection of the outline page.
284
	 */
286
	 */
285
	class OutlineSelectionChangedListener  extends AbstractSelectionChangedListener {
287
	class OutlineSelectionChangedListener extends AbstractSelectionChangedListener {
286
		public void selectionChanged(SelectionChangedEvent event) {
288
		public void selectionChanged(SelectionChangedEvent event) {
287
			doSelectionChanged(event);
289
			doSelectionChanged(event);
288
		}
290
		}
Lines 773-779 Link Here
773
				if (next != BreakIterator.DONE)
775
				if (next != BreakIterator.DONE)
774
					widget= modelOffset2WidgetOffset(viewer, next);
776
					widget= modelOffset2WidgetOffset(viewer, next);
775
			}
777
			}
776
			
778
777
			IDocument document= viewer.getDocument();
779
			IDocument document= viewer.getDocument();
778
			LinkedModeModel model= LinkedModeModel.getModel(document, position);
780
			LinkedModeModel model= LinkedModeModel.getModel(document, position);
779
			if (model != null) {
781
			if (model != null) {
Lines 791-797 Link Here
791
					}
793
					}
792
				}
794
				}
793
			}
795
			}
794
			
796
795
			return next;
797
			return next;
796
		}
798
		}
797
799
Lines 967-973 Link Here
967
				if (previous != BreakIterator.DONE)
969
				if (previous != BreakIterator.DONE)
968
					widget= modelOffset2WidgetOffset(viewer, previous);
970
					widget= modelOffset2WidgetOffset(viewer, previous);
969
			}
971
			}
970
			
972
971
			IDocument document= viewer.getDocument();
973
			IDocument document= viewer.getDocument();
972
			LinkedModeModel model= LinkedModeModel.getModel(document, position);
974
			LinkedModeModel model= LinkedModeModel.getModel(document, position);
973
			if (model != null) {
975
			if (model != null) {
Lines 985-991 Link Here
985
					}
987
					}
986
				}
988
				}
987
			}
989
			}
988
			
990
989
			return previous;
991
			return previous;
990
		}
992
		}
991
993
Lines 1116-1122 Link Here
1116
	 * @since 3.0
1118
	 * @since 3.0
1117
	 */
1119
	 */
1118
	protected class FormatElementAction extends Action implements IUpdate {
1120
	protected class FormatElementAction extends Action implements IUpdate {
1119
		
1121
1120
		/*
1122
		/*
1121
		 * @since 3.2
1123
		 * @since 3.2
1122
		 */
1124
		 */
Lines 1146-1152 Link Here
1146
								final int kind= element.getElementType();
1148
								final int kind= element.getElementType();
1147
								if (kind == IJavaElement.TYPE || kind == IJavaElement.METHOD || kind == IJavaElement.INITIALIZER) {
1149
								if (kind == IJavaElement.TYPE || kind == IJavaElement.METHOD || kind == IJavaElement.INITIALIZER) {
1148
1150
1149
									final ISourceReference reference= (ISourceReference)element;
1151
									final ISourceReference reference= (ISourceReference) element;
1150
									final ISourceRange range= reference.getSourceRange();
1152
									final ISourceRange range= reference.getSourceRange();
1151
1153
1152
									if (range != null) {
1154
									if (range != null) {
Lines 1194-1200 Link Here
1194
		public void windowActivated(IWorkbenchWindow window) {
1196
		public void windowActivated(IWorkbenchWindow window) {
1195
			if (window == getEditorSite().getWorkbenchWindow() && fMarkOccurrenceAnnotations && isActivePart()) {
1197
			if (window == getEditorSite().getWorkbenchWindow() && fMarkOccurrenceAnnotations && isActivePart()) {
1196
				fForcedMarkOccurrencesSelection= getSelectionProvider().getSelection();
1198
				fForcedMarkOccurrencesSelection= getSelectionProvider().getSelection();
1197
				updateOccurrenceAnnotations((ITextSelection)fForcedMarkOccurrencesSelection, JavaPlugin.getDefault().getASTProvider().getAST(getInputJavaElement(), ASTProvider.WAIT_NO, getProgressMonitor()));
1199
				updateOccurrenceAnnotations((ITextSelection) fForcedMarkOccurrencesSelection, JavaPlugin.getDefault().getASTProvider().getAST(getInputJavaElement(), ASTProvider.WAIT_NO,
1200
						getProgressMonitor()));
1198
			}
1201
			}
1199
		}
1202
		}
1200
1203
Lines 1314-1336 Link Here
1314
			}
1317
			}
1315
		}
1318
		}
1316
1319
1317
		public void partActivated(IWorkbenchPartReference partRef) {}
1320
		public void partActivated(IWorkbenchPartReference partRef) {
1318
		public void partBroughtToTop(IWorkbenchPartReference partRef) {}
1321
		}
1319
		public void partDeactivated(IWorkbenchPartReference partRef) {}
1322
1320
		public void partOpened(IWorkbenchPartReference partRef) {}
1323
		public void partBroughtToTop(IWorkbenchPartReference partRef) {
1321
		public void partHidden(IWorkbenchPartReference partRef) {}
1324
		}
1322
		public void partInputChanged(IWorkbenchPartReference partRef) {}
1325
1326
		public void partDeactivated(IWorkbenchPartReference partRef) {
1327
		}
1328
1329
		public void partOpened(IWorkbenchPartReference partRef) {
1330
		}
1331
1332
		public void partHidden(IWorkbenchPartReference partRef) {
1333
		}
1334
1335
		public void partInputChanged(IWorkbenchPartReference partRef) {
1336
		}
1323
	}
1337
	}
1324
1338
1325
	/** Preference key for matching brackets */
1339
	/** Preference key for matching brackets */
1326
	protected final static String MATCHING_BRACKETS=  PreferenceConstants.EDITOR_MATCHING_BRACKETS;
1340
	protected final static String MATCHING_BRACKETS= PreferenceConstants.EDITOR_MATCHING_BRACKETS;
1327
	/** Preference key for matching brackets color */
1341
	/** Preference key for matching brackets color */
1328
	protected final static String MATCHING_BRACKETS_COLOR=  PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR;
1342
	protected final static String MATCHING_BRACKETS_COLOR= PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR;
1329
1343
1330
	protected final static char[] BRACKETS= { '{', '}', '(', ')', '[', ']', '<', '>' };
1344
	protected final static char[] BRACKETS= { '{', '}', '(', ')', '[', ']', '<', '>' };
1331
1345
1332
	/** The outline page */
1346
	/** The outline page */
1333
	protected JavaOutlinePage fOutlinePage;
1347
	protected JavaOutlinePage fOutlinePage;
1348
	/** The templates page */
1349
	private JavaTemplatesPage fTemplatesPage;
1334
	/** Outliner context menu Id */
1350
	/** Outliner context menu Id */
1335
	protected String fOutlinerContextMenuId;
1351
	protected String fOutlinerContextMenuId;
1336
	/**
1352
	/**
Lines 1419-1432 Link Here
1419
	 * @since 3.0
1435
	 * @since 3.0
1420
	 */
1436
	 */
1421
	private boolean fMarkMethodExitPoints;
1437
	private boolean fMarkMethodExitPoints;
1422
	
1438
1423
	/**
1439
	/**
1424
	 * Tells whether to mark targets of <code>break</code> and <code>continue</code> statements in this editor.
1440
	 * Tells whether to mark targets of <code>break</code> and <code>continue</code> statements in this editor.
1425
	 * Only valid if {@link #fMarkOccurrenceAnnotations} is <code>true</code>.
1441
	 * Only valid if {@link #fMarkOccurrenceAnnotations} is <code>true</code>.
1426
	 * @since 3.2
1442
	 * @since 3.2
1427
	 */
1443
	 */
1428
	private boolean fMarkBreakContinueTargets;
1444
	private boolean fMarkBreakContinueTargets;
1429
	
1445
1430
	/**
1446
	/**
1431
	 * Tells whether to mark implementors in this editor.
1447
	 * Tells whether to mark implementors in this editor.
1432
	 * Only valid if {@link #fMarkOccurrenceAnnotations} is <code>true</code>.
1448
	 * Only valid if {@link #fMarkOccurrenceAnnotations} is <code>true</code>.
Lines 1486-1492 Link Here
1486
	 * @since 3.1
1502
	 * @since 3.1
1487
	 */
1503
	 */
1488
	private ToggleFoldingRunner fFoldingRunner;
1504
	private ToggleFoldingRunner fFoldingRunner;
1489
	
1505
1490
	/**
1506
	/**
1491
	 * Tells whether the selection changed event is caused
1507
	 * Tells whether the selection changed event is caused
1492
	 * by a call to {@link #gotoAnnotation(boolean)}.
1508
	 * by a call to {@link #gotoAnnotation(boolean)}.
Lines 1525-1531 Link Here
1525
	public JavaEditor() {
1541
	public JavaEditor() {
1526
		super();
1542
		super();
1527
	}
1543
	}
1528
	
1544
1529
	/**
1545
	/**
1530
	 * Sets the input of the editor's outline page.
1546
	 * Sets the input of the editor's outline page.
1531
	 *
1547
	 *
Lines 1535-1554 Link Here
1535
	protected void setOutlinePageInput(JavaOutlinePage page, IEditorInput input) {
1551
	protected void setOutlinePageInput(JavaOutlinePage page, IEditorInput input) {
1536
		if (page == null)
1552
		if (page == null)
1537
			return;
1553
			return;
1538
		
1554
1539
		IJavaElement je= getInputJavaElement();
1555
		IJavaElement je= getInputJavaElement();
1540
		if (je != null && je.exists())
1556
		if (je != null && je.exists())
1541
			page.setInput(je);
1557
			page.setInput(je);
1542
		else
1558
		else
1543
			page.setInput(null);
1559
			page.setInput(null);
1544
		
1560
1545
	}
1561
	}
1546
1562
1547
	/*
1563
	/*
1548
	 * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#initializeKeyBindingScopes()
1564
	 * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#initializeKeyBindingScopes()
1549
	 */
1565
	 */
1550
	protected void initializeKeyBindingScopes() {
1566
	protected void initializeKeyBindingScopes() {
1551
		setKeyBindingScopes(new String[] { "org.eclipse.jdt.ui.javaEditorScope" });  //$NON-NLS-1$
1567
		setKeyBindingScopes(new String[] { "org.eclipse.jdt.ui.javaEditorScope" }); //$NON-NLS-1$
1552
	}
1568
	}
1553
1569
1554
	/*
1570
	/*
Lines 1591-1600 Link Here
1591
		ISourceViewer viewer= createJavaSourceViewer(parent, verticalRuler, getOverviewRuler(), isOverviewRulerVisible(), styles, store);
1607
		ISourceViewer viewer= createJavaSourceViewer(parent, verticalRuler, getOverviewRuler(), isOverviewRulerVisible(), styles, store);
1592
1608
1593
		JavaUIHelp.setHelp(this, viewer.getTextWidget(), IJavaHelpContextIds.JAVA_EDITOR);
1609
		JavaUIHelp.setHelp(this, viewer.getTextWidget(), IJavaHelpContextIds.JAVA_EDITOR);
1594
		
1610
1595
		JavaSourceViewer javaSourceViewer= null;
1611
		JavaSourceViewer javaSourceViewer= null;
1596
		if (viewer instanceof JavaSourceViewer)
1612
		if (viewer instanceof JavaSourceViewer)
1597
			javaSourceViewer= (JavaSourceViewer)viewer;
1613
			javaSourceViewer= (JavaSourceViewer) viewer;
1598
1614
1599
		/*
1615
		/*
1600
		 * This is a performance optimization to reduce the computation of
1616
		 * This is a performance optimization to reduce the computation of
Lines 1602-1609 Link Here
1602
		 */
1618
		 */
1603
		if (javaSourceViewer != null && isFoldingEnabled() && (store == null || !store.getBoolean(PreferenceConstants.EDITOR_SHOW_SEGMENTS)))
1619
		if (javaSourceViewer != null && isFoldingEnabled() && (store == null || !store.getBoolean(PreferenceConstants.EDITOR_SHOW_SEGMENTS)))
1604
			javaSourceViewer.prepareDelayedProjection();
1620
			javaSourceViewer.prepareDelayedProjection();
1605
		
1621
1606
		ProjectionViewer projectionViewer= (ProjectionViewer)viewer;
1622
		ProjectionViewer projectionViewer= (ProjectionViewer) viewer;
1607
		fProjectionSupport= new ProjectionSupport(projectionViewer, getAnnotationAccess(), getSharedColors());
1623
		fProjectionSupport= new ProjectionSupport(projectionViewer, getAnnotationAccess(), getSharedColors());
1608
		fProjectionSupport.addSummarizableAnnotationType("org.eclipse.ui.workbench.texteditor.error"); //$NON-NLS-1$
1624
		fProjectionSupport.addSummarizableAnnotationType("org.eclipse.ui.workbench.texteditor.error"); //$NON-NLS-1$
1609
		fProjectionSupport.addSummarizableAnnotationType("org.eclipse.ui.workbench.texteditor.warning"); //$NON-NLS-1$
1625
		fProjectionSupport.addSummarizableAnnotationType("org.eclipse.ui.workbench.texteditor.warning"); //$NON-NLS-1$
Lines 1646-1652 Link Here
1646
	 * @see AbstractTextEditor#affectsTextPresentation(PropertyChangeEvent)
1662
	 * @see AbstractTextEditor#affectsTextPresentation(PropertyChangeEvent)
1647
	 */
1663
	 */
1648
	protected boolean affectsTextPresentation(PropertyChangeEvent event) {
1664
	protected boolean affectsTextPresentation(PropertyChangeEvent event) {
1649
		return ((JavaSourceViewerConfiguration)getSourceViewerConfiguration()).affectsTextPresentation(event) || super.affectsTextPresentation(event);
1665
		return ((JavaSourceViewerConfiguration) getSourceViewerConfiguration()).affectsTextPresentation(event) || super.affectsTextPresentation(event);
1650
	}
1666
	}
1651
1667
1652
	/**
1668
	/**
Lines 1708-1714 Link Here
1708
		menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, action);
1724
		menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, action);
1709
		action= getAction(IJavaEditorActionDefinitionIds.OPEN_HIERARCHY);
1725
		action= getAction(IJavaEditorActionDefinitionIds.OPEN_HIERARCHY);
1710
		menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, action);
1726
		menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, action);
1711
		
1727
1712
	}
1728
	}
1713
1729
1714
	/**
1730
	/**
Lines 1778-1783 Link Here
1778
			return fOutlinePage;
1794
			return fOutlinePage;
1779
		}
1795
		}
1780
1796
1797
		if (required.equals(ITemplatesPage.class)) {
1798
			return getTemplatesPage();
1799
		}
1800
1781
		if (IEncodingSupport.class.equals(required))
1801
		if (IEncodingSupport.class.equals(required))
1782
			return fEncodingSupport;
1802
			return fEncodingSupport;
1783
1803
Lines 1794-1800 Link Here
1794
			IJavaElement inputJE= getInputJavaElement();
1814
			IJavaElement inputJE= getInputJavaElement();
1795
			if (inputJE instanceof ICompilationUnit && !JavaModelUtil.isPrimary((ICompilationUnit) inputJE))
1815
			if (inputJE instanceof ICompilationUnit && !JavaModelUtil.isPrimary((ICompilationUnit) inputJE))
1796
				return null;
1816
				return null;
1797
			
1817
1798
			return new IShowInSource() {
1818
			return new IShowInSource() {
1799
				public ShowInContext getShowInContext() {
1819
				public ShowInContext getShowInContext() {
1800
					return new ShowInContext(getEditorInput(), null) {
1820
					return new ShowInContext(getEditorInput(), null) {
Lines 1832-1837 Link Here
1832
		return super.getAdapter(required);
1852
		return super.getAdapter(required);
1833
	}
1853
	}
1834
1854
1855
	private JavaTemplatesPage getTemplatesPage() {
1856
		if (fTemplatesPage == null) {
1857
			fTemplatesPage= new JavaTemplatesPage(this);
1858
1859
		}
1860
		return fTemplatesPage;
1861
	}
1862
1835
	/**
1863
	/**
1836
	 * React to changed selection.
1864
	 * React to changed selection.
1837
	 *
1865
	 *
Lines 1865-1871 Link Here
1865
1893
1866
		if (reference != null) {
1894
		if (reference != null) {
1867
1895
1868
			StyledText  textWidget= null;
1896
			StyledText textWidget= null;
1869
1897
1870
			ISourceViewer sourceViewer= getSourceViewer();
1898
			ISourceViewer sourceViewer= getSourceViewer();
1871
			if (sourceViewer != null)
1899
			if (sourceViewer != null)
Lines 1877-1885 Link Here
1877
			try {
1905
			try {
1878
				ISourceRange range= null;
1906
				ISourceRange range= null;
1879
				if (reference instanceof ILocalVariable) {
1907
				if (reference instanceof ILocalVariable) {
1880
					IJavaElement je= ((ILocalVariable)reference).getParent();
1908
					IJavaElement je= ((ILocalVariable) reference).getParent();
1881
					if (je instanceof ISourceReference)
1909
					if (je instanceof ISourceReference)
1882
						range= ((ISourceReference)je).getSourceRange();
1910
						range= ((ISourceReference) je).getSourceRange();
1883
				} else
1911
				} else
1884
					range= reference.getSourceRange();
1912
					range= reference.getSourceRange();
1885
1913
Lines 1913-1919 Link Here
1913
						length= range.getLength();
1941
						length= range.getLength();
1914
					}
1942
					}
1915
				} else if (reference instanceof ILocalVariable) {
1943
				} else if (reference instanceof ILocalVariable) {
1916
					range= ((ILocalVariable)reference).getNameRange();
1944
					range= ((ILocalVariable) reference).getNameRange();
1917
					if (range != null) {
1945
					if (range != null) {
1918
						offset= range.getOffset();
1946
						offset= range.getOffset();
1919
						length= range.getLength();
1947
						length= range.getLength();
Lines 1924-1935 Link Here
1924
						int start= content.indexOf("import") + 6; //$NON-NLS-1$
1952
						int start= content.indexOf("import") + 6; //$NON-NLS-1$
1925
						while (start < content.length() && content.charAt(start) == ' ')
1953
						while (start < content.length() && content.charAt(start) == ' ')
1926
							start++;
1954
							start++;
1927
						
1955
1928
						int end= content.indexOf(';');
1956
						int end= content.indexOf(';');
1929
						do {
1957
						do {
1930
							end--;
1958
							end--;
1931
						} while (end >= 0 && content.charAt(end) == ' ');
1959
						} while (end >= 0 && content.charAt(end) == ' ');
1932
						
1960
1933
						offset= range.getOffset() + start;
1961
						offset= range.getOffset() + start;
1934
						length= end - start + 1;
1962
						length= end - start + 1;
1935
					} else {
1963
					} else {
Lines 1942-1948 Link Here
1942
					if (name != null && name.length() > 0) {
1970
					if (name != null && name.length() > 0) {
1943
						String content= reference.getSource();
1971
						String content= reference.getSource();
1944
						if (content != null) {
1972
						if (content != null) {
1945
							int packageKeyWordIndex = content.lastIndexOf("package"); //$NON-NLS-1$
1973
							int packageKeyWordIndex= content.lastIndexOf("package"); //$NON-NLS-1$
1946
							if (packageKeyWordIndex != -1) {
1974
							if (packageKeyWordIndex != -1) {
1947
								offset= range.getOffset() + content.indexOf(name, packageKeyWordIndex + 7);
1975
								offset= range.getOffset() + content.indexOf(name, packageKeyWordIndex + 7);
1948
								length= name.length();
1976
								length= name.length();
Lines 1953-1959 Link Here
1953
1981
1954
				if (offset > -1 && length > 0) {
1982
				if (offset > -1 && length > 0) {
1955
1983
1956
					try  {
1984
					try {
1957
						textWidget.setRedraw(false);
1985
						textWidget.setRedraw(false);
1958
						sourceViewer.revealRange(offset, length);
1986
						sourceViewer.revealRange(offset, length);
1959
						sourceViewer.setSelectedRange(offset, length);
1987
						sourceViewer.setSelectedRange(offset, length);
Lines 2016-2036 Link Here
2016
			JavaPlugin.getActivePage().bringToTop(this);
2044
			JavaPlugin.getActivePage().bringToTop(this);
2017
2045
2018
		setSelection(reference, !isActivePart());
2046
		setSelection(reference, !isActivePart());
2019
		
2047
2020
		ISelectionProvider selectionProvider= getSelectionProvider();
2048
		ISelectionProvider selectionProvider= getSelectionProvider();
2021
		if (selectionProvider == null )
2049
		if (selectionProvider == null)
2022
			return;
2050
			return;
2023
		
2051
2024
		ISelection textSelection= selectionProvider.getSelection();
2052
		ISelection textSelection= selectionProvider.getSelection();
2025
		if (!(textSelection instanceof ITextSelection))
2053
		if (!(textSelection instanceof ITextSelection))
2026
			return;
2054
			return;
2027
		
2055
2028
		CompilationUnit ast= JavaPlugin.getDefault().getASTProvider().getAST(getInputJavaElement(), ASTProvider.WAIT_ACTIVE_ONLY, getProgressMonitor());
2056
		CompilationUnit ast= JavaPlugin.getDefault().getASTProvider().getAST(getInputJavaElement(), ASTProvider.WAIT_ACTIVE_ONLY, getProgressMonitor());
2029
		if (ast != null) {
2057
		if (ast != null) {
2030
			fForcedMarkOccurrencesSelection= textSelection;
2058
			fForcedMarkOccurrencesSelection= textSelection;
2031
			updateOccurrenceAnnotations((ITextSelection)textSelection, ast);
2059
			updateOccurrenceAnnotations((ITextSelection) textSelection, ast);
2032
		}
2060
		}
2033
		
2061
2034
	}
2062
	}
2035
2063
2036
	/*
2064
	/*
Lines 2084-2090 Link Here
2084
2112
2085
	private boolean isJavaOutlinePageActive() {
2113
	private boolean isJavaOutlinePageActive() {
2086
		IWorkbenchPart part= getActivePart();
2114
		IWorkbenchPart part= getActivePart();
2087
		return part instanceof ContentOutline && ((ContentOutline)part).getCurrentPage() == fOutlinePage;
2115
		return part instanceof ContentOutline && ((ContentOutline) part).getCurrentPage() == fOutlinePage;
2088
	}
2116
	}
2089
2117
2090
	private IWorkbenchPart getActivePart() {
2118
	private IWorkbenchPart getActivePart() {
Lines 2143-2149 Link Here
2143
2171
2144
		// uninstall & unregister preference store listener
2172
		// uninstall & unregister preference store listener
2145
		getSourceViewerDecorationSupport(sourceViewer).uninstall();
2173
		getSourceViewerDecorationSupport(sourceViewer).uninstall();
2146
		((ISourceViewerExtension2)sourceViewer).unconfigure();
2174
		((ISourceViewerExtension2) sourceViewer).unconfigure();
2147
2175
2148
		setPreferenceStore(createCombinedPreferenceStore(input));
2176
		setPreferenceStore(createCombinedPreferenceStore(input));
2149
2177
Lines 2158-2169 Link Here
2158
		ISourceViewer sourceViewer= getSourceViewer();
2186
		ISourceViewer sourceViewer= getSourceViewer();
2159
		JavaSourceViewer javaSourceViewer= null;
2187
		JavaSourceViewer javaSourceViewer= null;
2160
		if (sourceViewer instanceof JavaSourceViewer)
2188
		if (sourceViewer instanceof JavaSourceViewer)
2161
			javaSourceViewer= (JavaSourceViewer)sourceViewer;
2189
			javaSourceViewer= (JavaSourceViewer) sourceViewer;
2162
		
2190
2163
		IPreferenceStore store= getPreferenceStore();
2191
		IPreferenceStore store= getPreferenceStore();
2164
		if (javaSourceViewer != null && isFoldingEnabled() &&(store == null || !store.getBoolean(PreferenceConstants.EDITOR_SHOW_SEGMENTS)))
2192
		if (javaSourceViewer != null && isFoldingEnabled() && (store == null || !store.getBoolean(PreferenceConstants.EDITOR_SHOW_SEGMENTS)))
2165
			javaSourceViewer.prepareDelayedProjection();
2193
			javaSourceViewer.prepareDelayedProjection();
2166
		
2194
2167
		super.doSetInput(input);
2195
		super.doSetInput(input);
2168
2196
2169
		if (javaSourceViewer != null && javaSourceViewer.getReconciler() == null) {
2197
		if (javaSourceViewer != null && javaSourceViewer.getReconciler() == null) {
Lines 2194-2200 Link Here
2194
			setSourceViewerConfiguration(new JavaSourceViewerConfiguration(textTools.getColorManager(), store, this, IJavaPartitions.JAVA_PARTITIONING));
2222
			setSourceViewerConfiguration(new JavaSourceViewerConfiguration(textTools.getColorManager(), store, this, IJavaPartitions.JAVA_PARTITIONING));
2195
		}
2223
		}
2196
		if (getSourceViewer() instanceof JavaSourceViewer)
2224
		if (getSourceViewer() instanceof JavaSourceViewer)
2197
			((JavaSourceViewer)getSourceViewer()).setPreferenceStore(store);
2225
			((JavaSourceViewer) getSourceViewer()).setPreferenceStore(store);
2198
	}
2226
	}
2199
2227
2200
	/*
2228
	/*
Lines 2240-2246 Link Here
2240
			fSelectionHistory= null;
2268
			fSelectionHistory= null;
2241
		}
2269
		}
2242
2270
2243
		if (fEditorSelectionChangedListener != null)  {
2271
		if (fEditorSelectionChangedListener != null) {
2244
			fEditorSelectionChangedListener.uninstall(getSelectionProvider());
2272
			fEditorSelectionChangedListener.uninstall(getSelectionProvider());
2245
			fEditorSelectionChangedListener= null;
2273
			fEditorSelectionChangedListener= null;
2246
		}
2274
		}
Lines 2249-2270 Link Here
2249
			fActionGroups.dispose();
2277
			fActionGroups.dispose();
2250
			fActionGroups= null;
2278
			fActionGroups= null;
2251
		}
2279
		}
2252
		
2280
2253
		super.dispose();
2281
		super.dispose();
2254
	}
2282
	}
2255
2283
2256
	protected void createActions() {
2284
	protected void createActions() {
2257
		installEncodingSupport();
2285
		installEncodingSupport();
2258
		
2286
2259
		super.createActions();
2287
		super.createActions();
2260
2288
2261
		ActionGroup oeg, ovg, jsg;
2289
		ActionGroup oeg, ovg, jsg;
2262
		fActionGroups= new CompositeActionGroup(new ActionGroup[] {
2290
		fActionGroups= new CompositeActionGroup(new ActionGroup[] { oeg= new OpenEditorActionGroup(this), ovg= new OpenViewActionGroup(this), jsg= new JavaSearchActionGroup(this) });
2263
			oeg= new OpenEditorActionGroup(this),
2291
		fContextMenuGroup= new CompositeActionGroup(new ActionGroup[] { oeg, ovg, jsg });
2264
			ovg= new OpenViewActionGroup(this),
2265
			jsg= new JavaSearchActionGroup(this)
2266
		});
2267
		fContextMenuGroup= new CompositeActionGroup(new ActionGroup[] {oeg, ovg, jsg});
2268
2292
2269
		fFoldingGroup= new FoldingActionGroup(this, getViewer());
2293
		fFoldingGroup= new FoldingActionGroup(this, getViewer());
2270
2294
Lines 2272-2288 Link Here
2272
		action.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_MATCHING_BRACKET);
2296
		action.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_MATCHING_BRACKET);
2273
		setAction(GotoMatchingBracketAction.GOTO_MATCHING_BRACKET, action);
2297
		setAction(GotoMatchingBracketAction.GOTO_MATCHING_BRACKET, action);
2274
2298
2275
		action= new TextOperationAction(JavaEditorMessages.getBundleForConstructedKeys(),"ShowOutline.", this, JavaSourceViewer.SHOW_OUTLINE, true); //$NON-NLS-1$
2299
		action= new TextOperationAction(JavaEditorMessages.getBundleForConstructedKeys(), "ShowOutline.", this, JavaSourceViewer.SHOW_OUTLINE, true); //$NON-NLS-1$
2276
		action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SHOW_OUTLINE);
2300
		action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SHOW_OUTLINE);
2277
		setAction(IJavaEditorActionDefinitionIds.SHOW_OUTLINE, action);
2301
		setAction(IJavaEditorActionDefinitionIds.SHOW_OUTLINE, action);
2278
		PlatformUI.getWorkbench().getHelpSystem().setHelp(action, IJavaHelpContextIds.SHOW_OUTLINE_ACTION);
2302
		PlatformUI.getWorkbench().getHelpSystem().setHelp(action, IJavaHelpContextIds.SHOW_OUTLINE_ACTION);
2279
2303
2280
		action= new TextOperationAction(JavaEditorMessages.getBundleForConstructedKeys(),"OpenStructure.", this, JavaSourceViewer.OPEN_STRUCTURE, true); //$NON-NLS-1$
2304
		action= new TextOperationAction(JavaEditorMessages.getBundleForConstructedKeys(), "OpenStructure.", this, JavaSourceViewer.OPEN_STRUCTURE, true); //$NON-NLS-1$
2281
		action.setActionDefinitionId(IJavaEditorActionDefinitionIds.OPEN_STRUCTURE);
2305
		action.setActionDefinitionId(IJavaEditorActionDefinitionIds.OPEN_STRUCTURE);
2282
		setAction(IJavaEditorActionDefinitionIds.OPEN_STRUCTURE, action);
2306
		setAction(IJavaEditorActionDefinitionIds.OPEN_STRUCTURE, action);
2283
		PlatformUI.getWorkbench().getHelpSystem().setHelp(action, IJavaHelpContextIds.OPEN_STRUCTURE_ACTION);
2307
		PlatformUI.getWorkbench().getHelpSystem().setHelp(action, IJavaHelpContextIds.OPEN_STRUCTURE_ACTION);
2284
2308
2285
		action= new TextOperationAction(JavaEditorMessages.getBundleForConstructedKeys(),"OpenHierarchy.", this, JavaSourceViewer.SHOW_HIERARCHY, true); //$NON-NLS-1$
2309
		action= new TextOperationAction(JavaEditorMessages.getBundleForConstructedKeys(), "OpenHierarchy.", this, JavaSourceViewer.SHOW_HIERARCHY, true); //$NON-NLS-1$
2286
		action.setActionDefinitionId(IJavaEditorActionDefinitionIds.OPEN_HIERARCHY);
2310
		action.setActionDefinitionId(IJavaEditorActionDefinitionIds.OPEN_HIERARCHY);
2287
		setAction(IJavaEditorActionDefinitionIds.OPEN_HIERARCHY, action);
2311
		setAction(IJavaEditorActionDefinitionIds.OPEN_HIERARCHY, action);
2288
		PlatformUI.getWorkbench().getHelpSystem().setHelp(action, IJavaHelpContextIds.OPEN_HIERARCHY_ACTION);
2312
		PlatformUI.getWorkbench().getHelpSystem().setHelp(action, IJavaHelpContextIds.OPEN_HIERARCHY_ACTION);
Lines 2326-2336 Link Here
2326
		// add annotation actions for roll-over expand hover
2350
		// add annotation actions for roll-over expand hover
2327
		action= new JavaSelectMarkerRulerAction2(JavaEditorMessages.getBundleForConstructedKeys(), "Editor.RulerAnnotationSelection.", this); //$NON-NLS-1$
2351
		action= new JavaSelectMarkerRulerAction2(JavaEditorMessages.getBundleForConstructedKeys(), "Editor.RulerAnnotationSelection.", this); //$NON-NLS-1$
2328
		setAction("AnnotationAction", action); //$NON-NLS-1$
2352
		setAction("AnnotationAction", action); //$NON-NLS-1$
2329
		
2353
2330
		action= new ShowInPackageViewAction(this);
2354
		action= new ShowInPackageViewAction(this);
2331
		action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SHOW_IN_PACKAGE_VIEW);
2355
		action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SHOW_IN_PACKAGE_VIEW);
2332
		setAction("ShowInPackageView", action); //$NON-NLS-1$
2356
		setAction("ShowInPackageView", action); //$NON-NLS-1$
2333
		
2357
2334
2358
2335
		// replace cut/copy paste actions with a version that implement 'add imports on paste'
2359
		// replace cut/copy paste actions with a version that implement 'add imports on paste'
2336
2360
Lines 2342-2365 Link Here
2342
2366
2343
		action= new ClipboardOperationAction(JavaEditorMessages.getBundleForConstructedKeys(), "Editor.Paste.", this, ITextOperationTarget.PASTE); //$NON-NLS-1$
2367
		action= new ClipboardOperationAction(JavaEditorMessages.getBundleForConstructedKeys(), "Editor.Paste.", this, ITextOperationTarget.PASTE); //$NON-NLS-1$
2344
		setAction(ITextEditorActionConstants.PASTE, action);
2368
		setAction(ITextEditorActionConstants.PASTE, action);
2345
		
2369
2346
		action= new CopyQualifiedNameAction(this);
2370
		action= new CopyQualifiedNameAction(this);
2347
		setAction(IJavaEditorActionConstants.COPY_QUALIFIED_NAME, action);
2371
		setAction(IJavaEditorActionConstants.COPY_QUALIFIED_NAME, action);
2348
	}
2372
	}
2349
	
2373
2350
	/**
2374
	/**
2351
	 * Installs the encoding support on the given text editor.
2375
	 * Installs the encoding support on the given text editor.
2352
	 * <p>
2376
	 * <p>
2353
 	 * Subclasses may override to install their own encoding
2377
	 * Subclasses may override to install their own encoding
2354
 	 * support or to disable the default encoding support.
2378
	 * support or to disable the default encoding support.
2355
 	 * </p>
2379
	 * </p>
2356
	 * @since 3.2
2380
	 * @since 3.2
2357
	 */
2381
	 */
2358
	protected void installEncodingSupport() {
2382
	protected void installEncodingSupport() {
2359
		fEncodingSupport= new DefaultEncodingSupport();
2383
		fEncodingSupport= new DefaultEncodingSupport();
2360
		fEncodingSupport.initialize(this);
2384
		fEncodingSupport.initialize(this);
2361
	}
2385
	}
2362
	
2386
2363
2387
2364
	public void updatedTitleImage(Image image) {
2388
	public void updatedTitleImage(Image image) {
2365
		setTitleImage(image);
2389
		setTitleImage(image);
Lines 2465-2471 Link Here
2465
				// fall through as others are interested in source change as well.
2489
				// fall through as others are interested in source change as well.
2466
			}
2490
			}
2467
2491
2468
			((JavaSourceViewerConfiguration)getSourceViewerConfiguration()).handlePropertyChangeEvent(event);
2492
			((JavaSourceViewerConfiguration) getSourceViewerConfiguration()).handlePropertyChangeEvent(event);
2469
2493
2470
			if (affectsOverrideIndicatorAnnotations(event)) {
2494
			if (affectsOverrideIndicatorAnnotations(event)) {
2471
				if (isShowingOverrideIndicators()) {
2495
				if (isShowingOverrideIndicators()) {
Lines 2492-2499 Link Here
2492
				return;
2516
				return;
2493
			}
2517
			}
2494
2518
2495
			if (DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE.equals(property)
2519
			if (DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE.equals(property) || DefaultCodeFormatterConstants.FORMATTER_INDENTATION_SIZE.equals(property)
2496
					|| DefaultCodeFormatterConstants.FORMATTER_INDENTATION_SIZE.equals(property)
2497
					|| DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR.equals(property)) {
2520
					|| DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR.equals(property)) {
2498
				StyledText textWidget= sourceViewer.getTextWidget();
2521
				StyledText textWidget= sourceViewer.getTextWidget();
2499
				int tabWidth= getSourceViewerConfiguration().getTabWidth(sourceViewer);
2522
				int tabWidth= getSourceViewerConfiguration().getTabWidth(sourceViewer);
Lines 2512-2518 Link Here
2512
		} finally {
2535
		} finally {
2513
			super.handlePreferenceStoreChanged(event);
2536
			super.handlePreferenceStoreChanged(event);
2514
		}
2537
		}
2515
		
2538
2516
		if (AbstractDecoratedTextEditorPreferenceConstants.SHOW_RANGE_INDICATOR.equals(property)) {
2539
		if (AbstractDecoratedTextEditorPreferenceConstants.SHOW_RANGE_INDICATOR.equals(property)) {
2517
			// superclass already installed the range indicator
2540
			// superclass already installed the range indicator
2518
			Object newValue= event.getNewValue();
2541
			Object newValue= event.getNewValue();
Lines 2539-2545 Link Here
2539
	}
2562
	}
2540
2563
2541
	private boolean isJavaEditorHoverProperty(String property) {
2564
	private boolean isJavaEditorHoverProperty(String property) {
2542
		return	PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS.equals(property);
2565
		return PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS.equals(property);
2543
	}
2566
	}
2544
2567
2545
	/*
2568
	/*
Lines 2565-2583 Link Here
2565
			ISourceViewer sourceViewer= getSourceViewer();
2588
			ISourceViewer sourceViewer= getSourceViewer();
2566
			if (sourceViewer instanceof ITextViewerExtension2) {
2589
			if (sourceViewer instanceof ITextViewerExtension2) {
2567
				// Remove existing hovers
2590
				// Remove existing hovers
2568
				((ITextViewerExtension2)sourceViewer).removeTextHovers(t);
2591
				((ITextViewerExtension2) sourceViewer).removeTextHovers(t);
2569
2592
2570
				int[] stateMasks= configuration.getConfiguredTextHoverStateMasks(getSourceViewer(), t);
2593
				int[] stateMasks= configuration.getConfiguredTextHoverStateMasks(getSourceViewer(), t);
2571
2594
2572
				if (stateMasks != null) {
2595
				if (stateMasks != null) {
2573
					for (int j= 0; j < stateMasks.length; j++)	{
2596
					for (int j= 0; j < stateMasks.length; j++) {
2574
						int stateMask= stateMasks[j];
2597
						int stateMask= stateMasks[j];
2575
						ITextHover textHover= configuration.getTextHover(sourceViewer, t, stateMask);
2598
						ITextHover textHover= configuration.getTextHover(sourceViewer, t, stateMask);
2576
						((ITextViewerExtension2)sourceViewer).setTextHover(textHover, t, stateMask);
2599
						((ITextViewerExtension2) sourceViewer).setTextHover(textHover, t, stateMask);
2577
					}
2600
					}
2578
				} else {
2601
				} else {
2579
					ITextHover textHover= configuration.getTextHover(sourceViewer, t);
2602
					ITextHover textHover= configuration.getTextHover(sourceViewer, t);
2580
					((ITextViewerExtension2)sourceViewer).setTextHover(textHover, t, ITextViewerExtension2.DEFAULT_HOVER_STATE_MASK);
2603
					((ITextViewerExtension2) sourceViewer).setTextHover(textHover, t, ITextViewerExtension2.DEFAULT_HOVER_STATE_MASK);
2581
				}
2604
				}
2582
			} else
2605
			} else
2583
				sourceViewer.setTextHover(configuration.getTextHover(sourceViewer, t), t);
2606
				sourceViewer.setTextHover(configuration.getTextHover(sourceViewer, t), t);
Lines 2608-2614 Link Here
2608
	 * @since 3.1
2631
	 * @since 3.1
2609
	 */
2632
	 */
2610
	public int getOrientation() {
2633
	public int getOrientation() {
2611
		return SWT.LEFT_TO_RIGHT;	//Java editors are always left to right by default
2634
		return SWT.LEFT_TO_RIGHT; //Java editors are always left to right by default
2612
	}
2635
	}
2613
2636
2614
	/*
2637
	/*
Lines 2644-2650 Link Here
2644
	 */
2667
	 */
2645
	private Object getLockObject(IAnnotationModel annotationModel) {
2668
	private Object getLockObject(IAnnotationModel annotationModel) {
2646
		if (annotationModel instanceof ISynchronizable) {
2669
		if (annotationModel instanceof ISynchronizable) {
2647
			Object lock= ((ISynchronizable)annotationModel).getLockObject();
2670
			Object lock= ((ISynchronizable) annotationModel).getLockObject();
2648
			if (lock != null)
2671
			if (lock != null)
2649
				return lock;
2672
				return lock;
2650
		}
2673
		}
Lines 2662-2668 Link Here
2662
				while (e.hasNext()) {
2685
				while (e.hasNext()) {
2663
					Object o= e.next();
2686
					Object o= e.next();
2664
					if (o instanceof MarkerAnnotation) {
2687
					if (o instanceof MarkerAnnotation) {
2665
						super.updateMarkerViews((MarkerAnnotation)o);
2688
						super.updateMarkerViews((MarkerAnnotation) o);
2666
						return;
2689
						return;
2667
					}
2690
					}
2668
				}
2691
				}
Lines 2693-2699 Link Here
2693
			fPositions= positions;
2716
			fPositions= positions;
2694
2717
2695
			if (getSelectionProvider() instanceof ISelectionValidator)
2718
			if (getSelectionProvider() instanceof ISelectionValidator)
2696
				fPostSelectionValidator= (ISelectionValidator)getSelectionProvider();
2719
				fPostSelectionValidator= (ISelectionValidator) getSelectionProvider();
2697
		}
2720
		}
2698
2721
2699
		// cannot use cancel() because it is declared final
2722
		// cannot use cancel() because it is declared final
Lines 2703-2711 Link Here
2703
		}
2726
		}
2704
2727
2705
		private boolean isCanceled() {
2728
		private boolean isCanceled() {
2706
			return fCanceled || fProgressMonitor.isCanceled()
2729
			return fCanceled || fProgressMonitor.isCanceled() || fPostSelectionValidator != null && !(fPostSelectionValidator.isValid(fSelection) || fForcedMarkOccurrencesSelection == fSelection)
2707
				||  fPostSelectionValidator != null && !(fPostSelectionValidator.isValid(fSelection) || fForcedMarkOccurrencesSelection == fSelection)
2730
					|| LinkedModeModel.hasInstalledModel(fDocument);
2708
				|| LinkedModeModel.hasInstalledModel(fDocument);
2709
		}
2731
		}
2710
2732
2711
		/*
2733
		/*
Lines 2752-2759 Link Here
2752
					// Skip this match
2774
					// Skip this match
2753
					continue;
2775
					continue;
2754
				}
2776
				}
2755
				annotationMap.put(
2777
				annotationMap.put(new Annotation("org.eclipse.jdt.ui.occurrences", false, message), //$NON-NLS-1$
2756
						new Annotation("org.eclipse.jdt.ui.occurrences", false, message), //$NON-NLS-1$
2757
						position);
2778
						position);
2758
			}
2779
			}
2759
2780
Lines 2762-2777 Link Here
2762
2783
2763
			synchronized (getLockObject(annotationModel)) {
2784
			synchronized (getLockObject(annotationModel)) {
2764
				if (annotationModel instanceof IAnnotationModelExtension) {
2785
				if (annotationModel instanceof IAnnotationModelExtension) {
2765
					((IAnnotationModelExtension)annotationModel).replaceAnnotations(fOccurrenceAnnotations, annotationMap);
2786
					((IAnnotationModelExtension) annotationModel).replaceAnnotations(fOccurrenceAnnotations, annotationMap);
2766
				} else {
2787
				} else {
2767
					removeOccurrenceAnnotations();
2788
					removeOccurrenceAnnotations();
2768
					Iterator iter= annotationMap.entrySet().iterator();
2789
					Iterator iter= annotationMap.entrySet().iterator();
2769
					while (iter.hasNext()) {
2790
					while (iter.hasNext()) {
2770
						Map.Entry mapEntry= (Map.Entry)iter.next();
2791
						Map.Entry mapEntry= (Map.Entry) iter.next();
2771
						annotationModel.addAnnotation((Annotation)mapEntry.getKey(), (Position)mapEntry.getValue());
2792
						annotationModel.addAnnotation((Annotation) mapEntry.getKey(), (Position) mapEntry.getValue());
2772
					}
2793
					}
2773
				}
2794
				}
2774
				fOccurrenceAnnotations= (Annotation[])annotationMap.keySet().toArray(new Annotation[annotationMap.keySet().size()]);
2795
				fOccurrenceAnnotations= (Annotation[]) annotationMap.keySet().toArray(new Annotation[annotationMap.keySet().size()]);
2775
			}
2796
			}
2776
2797
2777
			return Status.OK_STATUS;
2798
			return Status.OK_STATUS;
Lines 2803-2810 Link Here
2803
2824
2804
		if (document instanceof IDocumentExtension4) {
2825
		if (document instanceof IDocumentExtension4) {
2805
			int offset= selection.getOffset();
2826
			int offset= selection.getOffset();
2806
			long currentModificationStamp= ((IDocumentExtension4)document).getModificationStamp();
2827
			long currentModificationStamp= ((IDocumentExtension4) document).getModificationStamp();
2807
			IRegion markOccurrenceTargetRegion= fMarkOccurrenceTargetRegion; 
2828
			IRegion markOccurrenceTargetRegion= fMarkOccurrenceTargetRegion;
2808
			if (markOccurrenceTargetRegion != null && currentModificationStamp == fMarkOccurrenceModificationStamp) {
2829
			if (markOccurrenceTargetRegion != null && currentModificationStamp == fMarkOccurrenceModificationStamp) {
2809
				if (markOccurrenceTargetRegion.getOffset() <= offset && offset <= markOccurrenceTargetRegion.getOffset() + markOccurrenceTargetRegion.getLength())
2830
				if (markOccurrenceTargetRegion.getOffset() <= offset && offset <= markOccurrenceTargetRegion.getOffset() + markOccurrenceTargetRegion.getLength())
2810
					return;
2831
					return;
Lines 2814-2822 Link Here
2814
		}
2835
		}
2815
2836
2816
		List matches= null;
2837
		List matches= null;
2817
		
2838
2818
		ASTNode selectedNode= NodeFinder.perform(astRoot, selection.getOffset(), selection.getLength());
2839
		ASTNode selectedNode= NodeFinder.perform(astRoot, selection.getOffset(), selection.getLength());
2819
		
2840
2820
		if (fMarkExceptions || fMarkTypeOccurrences) {
2841
		if (fMarkExceptions || fMarkTypeOccurrences) {
2821
			ExceptionOccurrencesFinder exceptionFinder= new ExceptionOccurrencesFinder();
2842
			ExceptionOccurrencesFinder exceptionFinder= new ExceptionOccurrencesFinder();
2822
			String message= exceptionFinder.initialize(astRoot, selectedNode);
2843
			String message= exceptionFinder.initialize(astRoot, selectedNode);
Lines 2860-2870 Link Here
2860
		if (matches == null) {
2881
		if (matches == null) {
2861
			IBinding binding= null;
2882
			IBinding binding= null;
2862
			if (selectedNode instanceof Name)
2883
			if (selectedNode instanceof Name)
2863
				binding= ((Name)selectedNode).resolveBinding();
2884
				binding= ((Name) selectedNode).resolveBinding();
2864
2885
2865
			if (binding != null && markOccurrencesOfType(binding)) {
2886
			if (binding != null && markOccurrencesOfType(binding)) {
2866
				// Find the matches && extract positions so we can forget the AST
2887
				// Find the matches && extract positions so we can forget the AST
2867
				OccurrencesFinder finder = new OccurrencesFinder(binding);
2888
				OccurrencesFinder finder= new OccurrencesFinder(binding);
2868
				String message= finder.initialize(astRoot, selectedNode);
2889
				String message= finder.initialize(astRoot, selectedNode);
2869
				if (message == null)
2890
				if (message == null)
2870
					matches= finder.perform();
2891
					matches= finder.perform();
Lines 2880-2886 Link Here
2880
		Position[] positions= new Position[matches.size()];
2901
		Position[] positions= new Position[matches.size()];
2881
		int i= 0;
2902
		int i= 0;
2882
		for (Iterator each= matches.iterator(); each.hasNext();) {
2903
		for (Iterator each= matches.iterator(); each.hasNext();) {
2883
			ASTNode currentNode= (ASTNode)each.next();
2904
			ASTNode currentNode= (ASTNode) each.next();
2884
			positions[i++]= new Position(currentNode.getStartPosition(), currentNode.getLength());
2905
			positions[i++]= new Position(currentNode.getStartPosition(), currentNode.getLength());
2885
		}
2906
		}
2886
2907
Lines 2902-2908 Link Here
2902
		SelectionListenerWithASTManager.getDefault().addListener(this, fPostSelectionListenerWithAST);
2923
		SelectionListenerWithASTManager.getDefault().addListener(this, fPostSelectionListenerWithAST);
2903
		if (forceUpdate && getSelectionProvider() != null) {
2924
		if (forceUpdate && getSelectionProvider() != null) {
2904
			fForcedMarkOccurrencesSelection= getSelectionProvider().getSelection();
2925
			fForcedMarkOccurrencesSelection= getSelectionProvider().getSelection();
2905
			updateOccurrenceAnnotations((ITextSelection)fForcedMarkOccurrencesSelection, JavaPlugin.getDefault().getASTProvider().getAST(getInputJavaElement(), ASTProvider.WAIT_NO, getProgressMonitor()));
2926
			updateOccurrenceAnnotations((ITextSelection) fForcedMarkOccurrencesSelection, JavaPlugin.getDefault().getASTProvider().getAST(getInputJavaElement(), ASTProvider.WAIT_NO,
2927
					getProgressMonitor()));
2906
		}
2928
		}
2907
2929
2908
		if (fOccurrencesFinderJobCanceler == null) {
2930
		if (fOccurrencesFinderJobCanceler == null) {
Lines 2951-2957 Link Here
2951
			return true;
2973
			return true;
2952
2974
2953
		if (kind == IBinding.VARIABLE) {
2975
		if (kind == IBinding.VARIABLE) {
2954
			IVariableBinding variableBinding= (IVariableBinding)binding;
2976
			IVariableBinding variableBinding= (IVariableBinding) binding;
2955
			if (variableBinding.isField()) {
2977
			if (variableBinding.isField()) {
2956
				int constantModifier= IModifierConstants.ACC_STATIC | IModifierConstants.ACC_FINAL;
2978
				int constantModifier= IModifierConstants.ACC_STATIC | IModifierConstants.ACC_FINAL;
2957
				boolean isConstant= (variableBinding.getModifiers() & constantModifier) == constantModifier;
2979
				boolean isConstant= (variableBinding.getModifiers() & constantModifier) == constantModifier;
Lines 2981-2987 Link Here
2981
3003
2982
		synchronized (getLockObject(annotationModel)) {
3004
		synchronized (getLockObject(annotationModel)) {
2983
			if (annotationModel instanceof IAnnotationModelExtension) {
3005
			if (annotationModel instanceof IAnnotationModelExtension) {
2984
				((IAnnotationModelExtension)annotationModel).replaceAnnotations(fOccurrenceAnnotations, null);
3006
				((IAnnotationModelExtension) annotationModel).replaceAnnotations(fOccurrenceAnnotations, null);
2985
			} else {
3007
			} else {
2986
				for (int i= 0, length= fOccurrenceAnnotations.length; i < length; i++)
3008
				for (int i= 0, length= fOccurrenceAnnotations.length; i < length; i++)
2987
					annotationModel.removeAnnotation(fOccurrenceAnnotations[i]);
3009
					annotationModel.removeAnnotation(fOccurrenceAnnotations[i]);
Lines 3006-3012 Link Here
3006
			return;
3028
			return;
3007
3029
3008
		fOverrideIndicatorManager= new OverrideIndicatorManager(model, inputElement, null);
3030
		fOverrideIndicatorManager= new OverrideIndicatorManager(model, inputElement, null);
3009
		
3031
3010
		if (provideAST) {
3032
		if (provideAST) {
3011
			CompilationUnit ast= JavaPlugin.getDefault().getASTProvider().getAST(inputElement, ASTProvider.WAIT_ACTIVE_ONLY, getProgressMonitor());
3033
			CompilationUnit ast= JavaPlugin.getDefault().getASTProvider().getAST(inputElement, ASTProvider.WAIT_ACTIVE_ONLY, getProgressMonitor());
3012
			fOverrideIndicatorManager.reconciled(ast, true, getProgressMonitor());
3034
			fOverrideIndicatorManager.reconciled(ast, true, getProgressMonitor());
Lines 3022-3031 Link Here
3022
	protected boolean isShowingOverrideIndicators() {
3044
	protected boolean isShowingOverrideIndicators() {
3023
		AnnotationPreference preference= getAnnotationPreferenceLookup().getAnnotationPreference(OverrideIndicatorManager.ANNOTATION_TYPE);
3045
		AnnotationPreference preference= getAnnotationPreferenceLookup().getAnnotationPreference(OverrideIndicatorManager.ANNOTATION_TYPE);
3024
		IPreferenceStore store= getPreferenceStore();
3046
		IPreferenceStore store= getPreferenceStore();
3025
		return getBoolean(store, preference.getHighlightPreferenceKey())
3047
		return getBoolean(store, preference.getHighlightPreferenceKey()) || getBoolean(store, preference.getVerticalRulerPreferenceKey())
3026
			|| getBoolean(store, preference.getVerticalRulerPreferenceKey())
3048
				|| getBoolean(store, preference.getOverviewRulerPreferenceKey()) || getBoolean(store, preference.getTextPreferenceKey());
3027
			|| getBoolean(store, preference.getOverviewRulerPreferenceKey())
3028
			|| getBoolean(store, preference.getTextPreferenceKey());
3029
	}
3049
	}
3030
3050
3031
	/**
3051
	/**
Lines 3054-3063 Link Here
3054
		if (key == null || preference == null)
3074
		if (key == null || preference == null)
3055
			return false;
3075
			return false;
3056
3076
3057
		return key.equals(preference.getHighlightPreferenceKey())
3077
		return key.equals(preference.getHighlightPreferenceKey()) || key.equals(preference.getVerticalRulerPreferenceKey()) || key.equals(preference.getOverviewRulerPreferenceKey())
3058
			|| key.equals(preference.getVerticalRulerPreferenceKey())
3078
				|| key.equals(preference.getTextPreferenceKey());
3059
			|| key.equals(preference.getOverviewRulerPreferenceKey())
3060
			|| key.equals(preference.getTextPreferenceKey());
3061
	}
3079
	}
3062
3080
3063
	/**
3081
	/**
Lines 3137-3143 Link Here
3137
		// #26314
3155
		// #26314
3138
		int sourceCaretOffset= selection.getOffset() + selection.getLength();
3156
		int sourceCaretOffset= selection.getOffset() + selection.getLength();
3139
		if (isSurroundedByBrackets(document, sourceCaretOffset))
3157
		if (isSurroundedByBrackets(document, sourceCaretOffset))
3140
			sourceCaretOffset -= selection.getLength();
3158
			sourceCaretOffset-= selection.getLength();
3141
3159
3142
		IRegion region= fBracketMatcher.match(document, sourceCaretOffset);
3160
		IRegion region= fBracketMatcher.match(document, sourceCaretOffset);
3143
		if (region == null) {
3161
		if (region == null) {
Lines 3154-3160 Link Here
3154
3172
3155
		int anchor= fBracketMatcher.getAnchor();
3173
		int anchor= fBracketMatcher.getAnchor();
3156
		// http://dev.eclipse.org/bugs/show_bug.cgi?id=34195
3174
		// http://dev.eclipse.org/bugs/show_bug.cgi?id=34195
3157
		int targetOffset= (ICharacterPairMatcher.RIGHT == anchor) ? offset + 1: offset + length;
3175
		int targetOffset= (ICharacterPairMatcher.RIGHT == anchor) ? offset + 1 : offset + length;
3158
3176
3159
		boolean visible= false;
3177
		boolean visible= false;
3160
		if (sourceViewer instanceof ITextViewerExtension5) {
3178
		if (sourceViewer instanceof ITextViewerExtension5) {
Lines 3173-3179 Link Here
3173
		}
3191
		}
3174
3192
3175
		if (selection.getLength() < 0)
3193
		if (selection.getLength() < 0)
3176
			targetOffset -= selection.getLength();
3194
			targetOffset-= selection.getLength();
3177
3195
3178
		sourceViewer.setSelectedRange(targetOffset, selection.getLength());
3196
		sourceViewer.setSelectedRange(targetOffset, selection.getLength());
3179
		sourceViewer.revealRange(targetOffset, selection.getLength());
3197
		sourceViewer.revealRange(targetOffset, selection.getLength());
Lines 3225-3230 Link Here
3225
	protected void handleCursorPositionChanged() {
3243
	protected void handleCursorPositionChanged() {
3226
		super.handleCursorPositionChanged();
3244
		super.handleCursorPositionChanged();
3227
		fCachedSelectedRange= getViewer().getSelectedRange();
3245
		fCachedSelectedRange= getViewer().getSelectedRange();
3246
		if (fTemplatesPage != null)
3247
			fTemplatesPage.cursorPositionChanged();
3228
	}
3248
	}
3229
3249
3230
	private static boolean isBracket(char character) {
3250
	private static boolean isBracket(char character) {
Lines 3239-3247 Link Here
3239
			return false;
3259
			return false;
3240
3260
3241
		try {
3261
		try {
3242
			return
3262
			return isBracket(document.getChar(offset - 1)) && isBracket(document.getChar(offset));
3243
				isBracket(document.getChar(offset - 1)) &&
3244
				isBracket(document.getChar(offset));
3245
3263
3246
		} catch (BadLocationException e) {
3264
		} catch (BadLocationException e) {
3247
			return false;
3265
			return false;
Lines 3277-3283 Link Here
3277
		Iterator e= new JavaAnnotationIterator(model, true, true);
3295
		Iterator e= new JavaAnnotationIterator(model, true, true);
3278
		while (e.hasNext()) {
3296
		while (e.hasNext()) {
3279
			Annotation a= (Annotation) e.next();
3297
			Annotation a= (Annotation) e.next();
3280
			if ((a instanceof IJavaAnnotation) && ((IJavaAnnotation)a).hasOverlay() || !isNavigationTarget(a))
3298
			if ((a instanceof IJavaAnnotation) && ((IJavaAnnotation) a).hasOverlay() || !isNavigationTarget(a))
3281
				continue;
3299
				continue;
3282
3300
3283
			Position p= model.getPosition(a);
3301
			Position p= model.getPosition(a);
Lines 3357-3363 Link Here
3357
		fSelectionChangedViaGotoAnnotation= true;
3375
		fSelectionChangedViaGotoAnnotation= true;
3358
		return super.gotoAnnotation(forward);
3376
		return super.gotoAnnotation(forward);
3359
	}
3377
	}
3360
	
3378
3361
	/**
3379
	/**
3362
	 * Computes and returns the source reference that includes the caret and
3380
	 * Computes and returns the source reference that includes the caret and
3363
	 * serves as provider for the outline page selection and the editor range
3381
	 * serves as provider for the outline page selection and the editor range
Lines 3377-3383 Link Here
3377
3395
3378
		int caret= 0;
3396
		int caret= 0;
3379
		if (sourceViewer instanceof ITextViewerExtension5) {
3397
		if (sourceViewer instanceof ITextViewerExtension5) {
3380
			ITextViewerExtension5 extension= (ITextViewerExtension5)sourceViewer;
3398
			ITextViewerExtension5 extension= (ITextViewerExtension5) sourceViewer;
3381
			caret= extension.widgetOffset2ModelOffset(styledText.getCaretOffset());
3399
			caret= extension.widgetOffset2ModelOffset(styledText.getCaretOffset());
3382
		} else {
3400
		} else {
3383
			int offset= sourceViewer.getVisibleRegion().getOffset();
3401
			int offset= sourceViewer.getVisibleRegion().getOffset();
Lines 3386-3392 Link Here
3386
3404
3387
		IJavaElement element= getElementAt(caret, false);
3405
		IJavaElement element= getElementAt(caret, false);
3388
3406
3389
		if ( !(element instanceof ISourceReference))
3407
		if (!(element instanceof ISourceReference))
3390
			return null;
3408
			return null;
3391
3409
3392
		if (element.getElementType() == IJavaElement.IMPORT_DECLARATION) {
3410
		if (element.getElementType() == IJavaElement.IMPORT_DECLARATION) {
Lines 3486-3492 Link Here
3486
						((IUpdate) action).update();
3504
						((IUpdate) action).update();
3487
					// hack to propagate line change
3505
					// hack to propagate line change
3488
					if (action instanceof ISelectionListener) {
3506
					if (action instanceof ISelectionListener) {
3489
						((ISelectionListener)action).selectionChanged(null, null);
3507
						((ISelectionListener) action).selectionChanged(null, null);
3490
					}
3508
					}
3491
					if (action.isEnabled())
3509
					if (action.isEnabled())
3492
						action.run();
3510
						action.run();
Lines 3494-3500 Link Here
3494
			}
3512
			}
3495
3513
3496
		}));
3514
		}));
3497
		
3515
3498
		return column;
3516
		return column;
3499
	}
3517
	}
3500
3518
Lines 3579-3585 Link Here
3579
		System.arraycopy(inheritedPages, 0, result, length, inheritedPages.length);
3597
		System.arraycopy(inheritedPages, 0, result, length, inheritedPages.length);
3580
		return result;
3598
		return result;
3581
	}
3599
	}
3582
	
3600
3583
	/*
3601
	/*
3584
	 * @see AbstractTextEditor#getUndoRedoOperationApprover(IUndoContext)
3602
	 * @see AbstractTextEditor#getUndoRedoOperationApprover(IUndoContext)
3585
	 * @since 3.1
3603
	 * @since 3.1
Lines 3587-3593 Link Here
3587
	protected IOperationApprover getUndoRedoOperationApprover(IUndoContext undoContext) {
3605
	protected IOperationApprover getUndoRedoOperationApprover(IUndoContext undoContext) {
3588
		// since IResource is a more general way to compare java elements, we
3606
		// since IResource is a more general way to compare java elements, we
3589
		// use this as the preferred class for comparing objects.
3607
		// use this as the preferred class for comparing objects.
3590
		return new NonLocalUndoUserApprover(undoContext, this, new Object [] { getInputJavaElement() }, IResource.class);
3608
		return new NonLocalUndoUserApprover(undoContext, this, new Object[] { getInputJavaElement() }, IResource.class);
3591
	}
3609
	}
3592
3610
3593
	/**
3611
	/**
Lines 3601-3607 Link Here
3601
			fProjectionModelUpdater.initialize();
3619
			fProjectionModelUpdater.initialize();
3602
		}
3620
		}
3603
	}
3621
	}
3604
	
3622
3605
	/**
3623
	/**
3606
	 * Collapses all foldable members if supported by the folding
3624
	 * Collapses all foldable members if supported by the folding
3607
	 * structure provider.
3625
	 * structure provider.
Lines 3614-3620 Link Here
3614
			extension.collapseMembers();
3632
			extension.collapseMembers();
3615
		}
3633
		}
3616
	}
3634
	}
3617
	
3635
3618
	/**
3636
	/**
3619
	 * Collapses all foldable comments if supported by the folding
3637
	 * Collapses all foldable comments if supported by the folding
3620
	 * structure provider.
3638
	 * structure provider.
(-)ui/org/eclipse/jdt/internal/ui/preferences/JavaTemplatesPage.java (+258 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2006 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
10
 *******************************************************************************/
11
package org.eclipse.jdt.internal.ui.preferences;
12
13
import org.eclipse.swt.SWT;
14
import org.eclipse.swt.graphics.Font;
15
import org.eclipse.swt.graphics.Point;
16
import org.eclipse.swt.layout.GridData;
17
import org.eclipse.swt.widgets.Composite;
18
import org.eclipse.swt.widgets.Control;
19
20
import org.eclipse.jface.preference.IPreferenceStore;
21
import org.eclipse.jface.resource.JFaceResources;
22
import org.eclipse.jface.window.Window;
23
24
import org.eclipse.jface.text.BadLocationException;
25
import org.eclipse.jface.text.Document;
26
import org.eclipse.jface.text.IDocument;
27
import org.eclipse.jface.text.ITextSelection;
28
import org.eclipse.jface.text.Position;
29
import org.eclipse.jface.text.Region;
30
import org.eclipse.jface.text.TextSelection;
31
import org.eclipse.jface.text.TextUtilities;
32
import org.eclipse.jface.text.source.ISourceViewer;
33
import org.eclipse.jface.text.source.SourceViewer;
34
import org.eclipse.jface.text.templates.ContextTypeRegistry;
35
import org.eclipse.jface.text.templates.Template;
36
import org.eclipse.jface.text.templates.TemplateContextType;
37
38
import org.eclipse.ui.PlatformUI;
39
import org.eclipse.ui.part.FileEditorInput;
40
import org.eclipse.ui.texteditor.templates.TemplatesPage;
41
42
import org.eclipse.jdt.core.ICompilationUnit;
43
import org.eclipse.jdt.core.JavaCore;
44
45
import org.eclipse.jdt.internal.corext.template.java.CompilationUnitContext;
46
import org.eclipse.jdt.internal.corext.template.java.CompilationUnitContextType;
47
import org.eclipse.jdt.internal.corext.template.java.JavaContextType;
48
import org.eclipse.jdt.internal.corext.template.java.JavaDocContextType;
49
50
import org.eclipse.jdt.ui.PreferenceConstants;
51
import org.eclipse.jdt.ui.text.IJavaPartitions;
52
import org.eclipse.jdt.ui.text.JavaTextTools;
53
54
import org.eclipse.jdt.internal.ui.JavaPlugin;
55
import org.eclipse.jdt.internal.ui.javaeditor.JavaEditor;
56
import org.eclipse.jdt.internal.ui.javaeditor.JavaSourceViewer;
57
import org.eclipse.jdt.internal.ui.text.SimpleJavaSourceViewerConfiguration;
58
import org.eclipse.jdt.internal.ui.text.template.contentassist.TemplateProposal;
59
import org.eclipse.jdt.internal.ui.text.template.preferences.TemplateVariableProcessor;
60
61
/**
62
 * A TemplatesPage implementation for Java CompilationUnitEditor
63
 * 
64
 * @author kd
65
 */
66
public class JavaTemplatesPage extends TemplatesPage {
67
68
	private static final ContextTypeRegistry TEMPLATE_CONTEXT_REGISTRY= JavaPlugin.getDefault().getTemplateContextRegistry();
69
	private TemplateVariableProcessor fTemplateProcessor;
70
	private ScrolledPageContent fScrolled;
71
	private final JavaEditor fEditor;
72
	private IDocument fDocument;
73
	private String fJavaDocId;
74
	private String fJavaId;
75
	private String fCurrentId;
76
77
	/**
78
	 * @param javaEditor
79
	 */
80
	public JavaTemplatesPage(JavaEditor javaEditor) {
81
		fEditor= javaEditor;
82
		setTemplateStore(JavaPlugin.getDefault().getTemplateStore(), JavaPlugin.getDefault().getPreferenceStore());
83
		setContextTypeRegistry(TEMPLATE_CONTEXT_REGISTRY);
84
		fJavaDocId= new JavaDocContextType().getId();
85
		fJavaId= new JavaContextType().getId();
86
		fTemplateProcessor= new TemplateVariableProcessor();
87
		fDocument= fEditor.getDocumentProvider().getDocument(fEditor.getEditorInput());
88
		cursorPositionChanged();
89
		setupEditorDropTarget(fEditor.getSite(), fEditor.getViewer().getTextWidget());
90
	}
91
92
	public void dispose() {
93
		super.dispose();
94
	}
95
96
	/* (non-Javadoc)
97
	 * @see org.eclipse.ui.texteditor.templates.TemplatesPage#createControl(org.eclipse.swt.widgets.Composite)
98
	 */
99
	public void createControl(Composite ancestor) {
100
		fScrolled= new ScrolledPageContent(ancestor, SWT.H_SCROLL | SWT.V_SCROLL);
101
		fScrolled.setExpandHorizontal(true);
102
		fScrolled.setExpandVertical(true);
103
104
		super.createControl(fScrolled);
105
		Control control= super.getControl();
106
107
		fScrolled.setContent(control);
108
		final Point size= control.computeSize(SWT.DEFAULT, SWT.DEFAULT);
109
		fScrolled.setMinSize(size.x, size.y);
110
	}
111
112
	/* (non-Javadoc)
113
	 * @see org.eclipse.ui.texteditor.templates.TemplatesPage#editTemplate(org.eclipse.jface.text.templates.Template, boolean, boolean)
114
	 */
115
	protected Template editTemplate(Template template, boolean edit, boolean isNameModifiable) {
116
		EditTemplateDialog dialog= new EditTemplateDialog(getShell(), template, edit, isNameModifiable, getContextTypeRegistry());
117
		if (dialog.open() == Window.OK) {
118
			return dialog.getTemplate();
119
		}
120
		return null;
121
	}
122
123
	/* (non-Javadoc)
124
	 * @see org.eclipse.ui.texteditor.templates.TemplatesPage#createViewer(org.eclipse.swt.widgets.Composite)
125
	 */
126
	protected SourceViewer createViewer(Composite parent) {
127
		IDocument document= new Document();
128
		JavaTextTools tools= JavaPlugin.getDefault().getJavaTextTools();
129
		tools.setupJavaDocumentPartitioner(document, IJavaPartitions.JAVA_PARTITIONING);
130
		IPreferenceStore store= JavaPlugin.getDefault().getCombinedPreferenceStore();
131
		SourceViewer viewer= new JavaSourceViewer(parent, null, null, false, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL, store);
132
		SimpleJavaSourceViewerConfiguration configuration= new SimpleJavaSourceViewerConfiguration(tools.getColorManager(), store, null, IJavaPartitions.JAVA_PARTITIONING, false);
133
		viewer.configure(configuration);
134
		viewer.setEditable(false);
135
		viewer.setDocument(document);
136
137
		Font font= JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT);
138
		viewer.getTextWidget().setFont(font);
139
		new JavaSourcePreviewerUpdater(viewer, configuration, store);
140
141
		Control control= viewer.getControl();
142
		GridData data= new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.FILL_VERTICAL);
143
		control.setLayoutData(data);
144
145
		return viewer;
146
	}
147
148
149
	/* (non-Javadoc)
150
	 * @see org.eclipse.ui.texteditor.templates.TemplatesPage#updateViewerInput(org.eclipse.jface.text.templates.Template)
151
	 */
152
	protected void updateViewerInput(Template template) {
153
		SourceViewer viewer= getViewer();
154
155
		String contextId= template.getContextTypeId();
156
		TemplateContextType type= TEMPLATE_CONTEXT_REGISTRY.getContextType(contextId);
157
		fTemplateProcessor.setContextType(type);
158
159
		IDocument doc= viewer.getDocument();
160
161
		String start= null;
162
		if ("javadoc".equals(contextId)) { //$NON-NLS-1$
163
			start= "/**" + doc.getLegalLineDelimiters()[0]; //$NON-NLS-1$
164
		} else
165
			start= ""; //$NON-NLS-1$
166
167
		doc.set(start + template.getPattern());
168
		int startLen= start.length();
169
		viewer.setDocument(doc, startLen, doc.getLength() - startLen);
170
	}
171
172
	/* (non-Javadoc)
173
	 * @see org.eclipse.ui.texteditor.templates.TemplatesPage#getControl()
174
	 */
175
	public Control getControl() {
176
		return fScrolled;
177
	}
178
179
	/* (non-Javadoc)
180
	 * @see org.eclipse.ui.part.Page#setFocus()
181
	 */
182
	public void setFocus() {
183
	}
184
185
	/* (non-Javadoc)
186
	 * @see org.eclipse.ui.texteditor.templates.TemplatesPage#getPreferencePageId()
187
	 */
188
	protected String getPreferencePageId() {
189
		return "org.eclipse.jdt.ui.preferences.JavaTemplatePreferencePage"; //$NON-NLS-1$
190
	}
191
192
	/* (non-Javadoc)
193
	 * @see org.eclipse.ui.texteditor.templates.TemplatesPage#insertTemplate(org.eclipse.jface.text.templates.Template)
194
	 */
195
	public void insertTemplate(Template template) {
196
		if (!fEditor.isEditorInputModifiable())
197
			return;
198
		TemplateContextType type= TEMPLATE_CONTEXT_REGISTRY.getContextType(template.getContextTypeId());
199
		if (type == null)
200
			return;
201
		ISourceViewer contextViewer= fEditor.getViewer();
202
		ITextSelection textSelection= (ITextSelection) contextViewer.getSelectionProvider().getSelection();
203
		IDocument document= contextViewer.getDocument();
204
		/*
205
		 * The Editor checks whether a completion for a word exists before it allows for the template to be
206
		 * applied. We pickup the current text at the selection position and replace it with the first char
207
		 * of the template name for this to succeed.
208
		 * We don't need to go through this, if the editors simply support applyTemplate(Template).
209
		 */
210
		String savedText;
211
		try {
212
			savedText= document.get(textSelection.getOffset(), textSelection.getLength());
213
			document.replace(textSelection.getOffset(), textSelection.getLength(), template.getName().substring(0, 1));
214
		} catch (BadLocationException e) {
215
			e.printStackTrace();
216
			return;
217
		}
218
		Position position= new Position(textSelection.getOffset() + 1, 0);
219
		Region region= new Region(textSelection.getOffset() + 1, 0);
220
		contextViewer.getSelectionProvider().setSelection(new TextSelection(textSelection.getOffset(), 1));
221
		ICompilationUnit compilationUnit= JavaCore.createCompilationUnitFrom(((FileEditorInput) fEditor.getEditorInput()).getFile());
222
223
		CompilationUnitContext context= ((CompilationUnitContextType) type).createContext(document, position, compilationUnit);
224
		context.setVariable("selection", savedText); //$NON-NLS-1$
225
		if (context.getKey().length() == 0) {
226
			try {
227
				document.replace(textSelection.getOffset(), 1, savedText);
228
			} catch (BadLocationException e) {
229
				e.printStackTrace();
230
				return;
231
			}
232
		}
233
		TemplateProposal proposal= new TemplateProposal(template, context, region, null);
234
		PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().activate(fEditor);
235
		proposal.apply(fEditor.getViewer(), ' ', 0, region.getOffset());
236
	}
237
238
	/**
239
	 * Invoked by the editor whenever the caret position is updated
240
	 */
241
	public void cursorPositionChanged() {
242
		Point selectedRange= fEditor.getViewer().getSelectedRange();
243
		int cursor= selectedRange.x + selectedRange.y;
244
		String partition;
245
		try {
246
			partition= TextUtilities.getContentType(fDocument, IJavaPartitions.JAVA_PARTITIONING, cursor, true);
247
		} catch (BadLocationException e) {
248
			return;
249
		}
250
		String id= fJavaId;
251
		if (partition.equals(IJavaPartitions.JAVA_DOC))
252
			id= fJavaDocId;
253
		if (!id.equals(fCurrentId)) {
254
			fCurrentId= id;
255
			contextTypeChanged(new String[] { id });
256
		}
257
	}
258
}
(-)META-INF/MANIFEST.MF (-1 / +2 lines)
Lines 11-17 Link Here
11
 org.eclipse.ui.internal.views.contentoutline;x-internal:=true,
11
 org.eclipse.ui.internal.views.contentoutline;x-internal:=true,
12
 org.eclipse.ui.internal.views.properties;x-internal:=true,
12
 org.eclipse.ui.internal.views.properties;x-internal:=true,
13
 org.eclipse.ui.views.contentoutline,
13
 org.eclipse.ui.views.contentoutline,
14
 org.eclipse.ui.views.properties
14
 org.eclipse.ui.views.properties,
15
 org.eclipse.ui.views.templates
15
Require-Bundle: org.eclipse.core.runtime;bundle-version="[3.2.0,4.0.0)",
16
Require-Bundle: org.eclipse.core.runtime;bundle-version="[3.2.0,4.0.0)",
16
 org.eclipse.help;bundle-version="[3.2.0,4.0.0)",
17
 org.eclipse.help;bundle-version="[3.2.0,4.0.0)",
17
 org.eclipse.ui;bundle-version="[3.2.0,4.0.0)"
18
 org.eclipse.ui;bundle-version="[3.2.0,4.0.0)"
(-)plugin.properties (-1 / +1 lines)
Lines 13-16 Link Here
13
13
14
Views.PropertySheet = Properties
14
Views.PropertySheet = Properties
15
Views.ContentOutline = Outline
15
Views.ContentOutline = Outline
16
16
Views.Templates = Templates
(-)plugin.xml (+7 lines)
Lines 18-23 Link Here
18
            class="org.eclipse.ui.views.contentoutline.ContentOutline"
18
            class="org.eclipse.ui.views.contentoutline.ContentOutline"
19
            id="org.eclipse.ui.views.ContentOutline">
19
            id="org.eclipse.ui.views.ContentOutline">
20
      </view>
20
      </view>
21
      <view
22
            name="%Views.Templates"
23
            icon="$nl$/icons/full/eview16/templates.gif"
24
            category="org.eclipse.ui"
25
            class="org.eclipse.ui.views.templates.Templates"
26
            id="org.eclipse.ui.views.Templates">
27
      </view>
21
   </extension>
28
   </extension>
22
   
29
   
23
</plugin>
30
</plugin>
(-)icons/full/eview16/templates.gif (+2 lines)
Added Link Here
1
GIF89aæûwyômqåU_ì`gàNY÷øüö÷ûøùüôöû‰•­‰•¬òõûöøüûüþúûýùúüøùûˆ•­‰–­ˆ•¬ìñú2]ˆ–­ˆ–¬‰–¬Œ˜«çîùíòúòõúo¹™§ÅÑããìùðôúöøûh‰·hŠ¶ô÷û\„´]ƒ³äíøéðùòöûñõúP}°P}¯”œ¥Bv«Cw«øúüüýþûüý+k¤+j£,j¤,k¤,j£,k£6p§7q§+k£˜Ÿ¢‹S1•^T¦o¢žz·‚Ç‘´Ò£¥›¨¨—­«”ÞÝÔ¹³‹µ°Ž¿¶ˆ¼´‰²­’ÿÿÿÿÿÿÿ!ùP,¡€P‚ƒ„…ƒKˆ‰ŠK…LL…I1—1™I…J—2"¤J…M%3
2
%%%M…G*¶¶*H…F!ÁǃE$O͑#ƒA'"N&ƒ=),ϑ-ƒ.0">DCB@?/ƒ(:ûù+;ƒ2€ÀqƒG6hðà‘£Æ 	,L˜!‚‹i4;
(-)src/org/eclipse/ui/internal/views/templates/TemplatesMessages.java (+21 lines)
Added Link Here
1
package org.eclipse.ui.internal.views.templates;
2
3
import org.eclipse.osgi.util.NLS;
4
5
/**
6
 * TemplatesMessages is the message class for the messages used in the templates view.
7
 *
8
 */
9
public class TemplatesMessages extends NLS {
10
	private static final String BUNDLE_NAME = "org.eclipse.ui.internal.views.templates.TemplatesMessages"; //$NON-NLS-1$
11
	
12
	// Default message for an empty templates view
13
	public static String Templates_defaultMessage;
14
	static {
15
		// initialize resource bundle
16
		NLS.initializeMessages(BUNDLE_NAME, TemplatesMessages.class);
17
	}
18
19
	private TemplatesMessages() {
20
	}
21
}
(-)src/org/eclipse/ui/internal/views/templates/TemplatesMessages.properties (+1 lines)
Added Link Here
1
Templates_defaultMessage=No templates available for this editor
(-)src/org/eclipse/ui/views/templates/Templates.java (+183 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2006 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
10
 *******************************************************************************/
11
12
package org.eclipse.ui.views.templates;
13
14
import org.eclipse.swt.widgets.Composite;
15
import org.eclipse.ui.IEditorPart;
16
import org.eclipse.ui.IWorkbenchPage;
17
import org.eclipse.ui.IWorkbenchPart;
18
import org.eclipse.ui.PlatformUI;
19
import org.eclipse.ui.internal.views.ViewsPlugin;
20
import org.eclipse.ui.internal.views.templates.TemplatesMessages;
21
import org.eclipse.ui.part.IContributedContentsView;
22
import org.eclipse.ui.part.IPage;
23
import org.eclipse.ui.part.MessagePage;
24
import org.eclipse.ui.part.PageBook;
25
import org.eclipse.ui.part.PageBookView;
26
27
/**
28
 * Main class for the Templates View.
29
 * <p>
30
 * This standard view has id <code>"org.eclipse.ui.views.TemplatesView"</code>.
31
 * </p>
32
 * When a <b>templates view</b> notices an editor being activated, it 
33
 * asks the editor whether it has a <b>template page</b> to include
34
 * in the templates view. This is done using <code>getAdapter</code>:
35
 * <pre>
36
 * IEditorPart editor = ...;
37
 * ITemplatePage templatePage = (ITemplatePage) editor.getAdapter(ITemplatePage.class);
38
 * if (templatePage != null) {
39
 *    // editor wishes to contribute templatePage to templates view
40
 * }
41
 * </pre>
42
 * If the editor supports a templates page, the editor instantiates
43
 * and configures the page, and returns it. This page is then added to the 
44
 * templates view (a pagebook which presents one page at a time) and 
45
 * immediately made the current page (the templates view need not be
46
 * visible). If the editor does not support a template page, the templates
47
 * view shows a special default page which makes it clear to the user
48
 * that the templates view is disengaged. When the templates view notices a
49
 * different editor being activated, it flips to the editor's corresponding
50
 * template page. When the templates view notices an editor being
51
 * closed, it may destroy the editor's corresponding content outline page.
52
 * </p>
53
 * <p>
54
 * The workbench will automatically instantiate this class when a templates
55
 * view is needed for a workbench window. This class was not intended
56
 * to be instantiated or subclassed by clients.
57
 * </p>
58
 */
59
public class Templates extends PageBookView {
60
    /**
61
     * The plugin prefix.
62
     */
63
    public static final String PREFIX = PlatformUI.PLUGIN_ID + "."; //$NON-NLS-1$
64
65
    /**
66
     * Help context id used for the content outline view
67
     * (value <code>"org.eclipse.ui.content_outline_context"</code>).
68
     */
69
    public static final String TEMPLATES_VIEW_HELP_CONTEXT_ID = PREFIX
70
            + "templates_view_context";//$NON-NLS-1$
71
72
    /**
73
     * Message to show on the default page.
74
     */
75
    private String defaultText = TemplatesMessages.Templates_defaultMessage; 
76
77
    /**
78
     * Creates a content outline view with no content outline pages.
79
     */
80
    public Templates() {
81
        super();
82
    }
83
84
    /* (non-Javadoc)
85
     * Method declared on PageBookView.
86
     */
87
    protected IPage createDefaultPage(PageBook book) {
88
        MessagePage page = new MessagePage();
89
        initPage(page);
90
        page.createControl(book);
91
        page.setMessage(defaultText);
92
        return page;
93
    }
94
95
    /**
96
     * The <code>PageBookView</code> implementation of this <code>IWorkbenchPart</code>
97
     * method creates a <code>PageBook</code> control with its default page showing.
98
     */
99
    public void createPartControl(Composite parent) {
100
        super.createPartControl(parent);
101
        PlatformUI.getWorkbench().getHelpSystem().setHelp(getPageBook(),
102
                TEMPLATES_VIEW_HELP_CONTEXT_ID);
103
    }
104
105
    /* (non-Javadoc)
106
     * Method declared on PageBookView.
107
     */
108
    protected PageRec doCreatePage(IWorkbenchPart part) {
109
        // Try to get template page.
110
        Object obj = ViewsPlugin.getAdapter(part, ITemplatesPage.class, false);
111
        if (obj instanceof ITemplatesPage) {
112
            ITemplatesPage page = (ITemplatesPage) obj;
113
			initPage(page);
114
            page.createControl(getPageBook());
115
            return new PageRec(part, page);
116
        }
117
        // There is no template page
118
        return null;
119
    }
120
121
    /* (non-Javadoc)
122
     * Method declared on PageBookView.
123
     */
124
    protected void doDestroyPage(IWorkbenchPart part, PageRec rec) {
125
        ITemplatesPage page = (ITemplatesPage) rec.page;
126
        page.dispose();
127
        rec.dispose();
128
    }
129
130
    /* (non-Javadoc)
131
     * Method declared on IAdaptable.
132
     */
133
    public Object getAdapter(Class key) {
134
        if (key == IContributedContentsView.class) {
135
			return new IContributedContentsView() {
136
                public IWorkbenchPart getContributingPart() {
137
                    return getContributingEditor();
138
                }
139
            };
140
		}
141
        return super.getAdapter(key);
142
    }
143
144
    /* (non-Javadoc)
145
     * Method declared on PageBookView.
146
     */
147
    protected IWorkbenchPart getBootstrapPart() {
148
        IWorkbenchPage page = getSite().getPage();
149
        if (page != null) {
150
			return page.getActiveEditor();
151
		}
152
153
        return null;
154
    }
155
156
    /**
157
     * Returns the editor which contributed the current 
158
     * page to this view.
159
     *
160
     * @return the editor which contributed the current page
161
     * or <code>null</code> if no editor contributed the current page
162
     */
163
    private IWorkbenchPart getContributingEditor() {
164
        return getCurrentContributingPart();
165
    }
166
167
    /* (non-Javadoc)
168
     * Method declared on PageBookView.
169
     * We only want to track editors.
170
     */
171
    protected boolean isImportant(IWorkbenchPart part) {
172
        //We only care about editors
173
        return (part instanceof IEditorPart);
174
    }
175
176
    /* (non-Javadoc)
177
     * Method declared on IViewPart.
178
     * Treat this the same as part activation.
179
     */
180
    public void partBroughtToTop(IWorkbenchPart part) {
181
        partActivated(part);
182
    }
183
}
(-)src/org/eclipse/ui/views/templates/ITemplatesPage.java (+13 lines)
Added Link Here
1
package org.eclipse.ui.views.templates;
2
3
import org.eclipse.ui.part.IPageBookViewPage;
4
5
/**
6
 * Interface for a template page. This interface defines
7
 * the minimum requirement for pages within the templates view, namely
8
 * they must be pages (implement <code>IPageBookViewPage</code>).
9
 *
10
 * @see TemplatesView
11
 */
12
public interface ITemplatesPage extends IPageBookViewPage {
13
}
(-)META-INF/MANIFEST.MF (-1 / +2 lines)
Lines 25-31 Link Here
25
 org.eclipse.core.expressions;bundle-version="[3.2.0,4.0.0)",
25
 org.eclipse.core.expressions;bundle-version="[3.2.0,4.0.0)",
26
 org.eclipse.jface.text;bundle-version="[3.4.0,4.0.0)",
26
 org.eclipse.jface.text;bundle-version="[3.4.0,4.0.0)",
27
 org.eclipse.core.filesystem;bundle-version="[1.1.0,2.0.0)",
27
 org.eclipse.core.filesystem;bundle-version="[1.1.0,2.0.0)",
28
 org.eclipse.ui;bundle-version="[3.3.0,4.0.0)"
28
 org.eclipse.ui;bundle-version="[3.3.0,4.0.0)",
29
 org.eclipse.ui.views
29
Eclipse-LazyStart: true
30
Eclipse-LazyStart: true
30
Bundle-RequiredExecutionEnvironment: J2SE-1.4
31
Bundle-RequiredExecutionEnvironment: J2SE-1.4
31
Import-Package: com.ibm.icu.text
32
Import-Package: com.ibm.icu.text
(-)src/org/eclipse/ui/texteditor/templates/TextEditorTemplateMessages.java (-1 / +24 lines)
Lines 20-30 Link Here
20
final class TextEditorTemplateMessages extends NLS {
20
final class TextEditorTemplateMessages extends NLS {
21
21
22
	private static final String BUNDLE_NAME= TextEditorTemplateMessages.class.getName();
22
	private static final String BUNDLE_NAME= TextEditorTemplateMessages.class.getName();
23
24
	private TextEditorTemplateMessages() {
23
	private TextEditorTemplateMessages() {
25
		// Do not instantiate
24
		// Do not instantiate
26
	}
25
	}
27
26
27
	// TemplatesView
28
	public static String TemplatesPage_collapse_expand;
29
	public static String TemplatesPage_column_context;
30
	public static String TemplatesPage_column_description;
31
	public static String TemplatesPage_column_name;
32
	public static String TemplatesPage_insert;
33
	public static String TemplatesPage_edit;
34
	public static String TemplatesPage_paste_description;
35
	public static String TemplatesPage_preference_page;
36
	public static String TemplatesPage_link_to_editor;
37
	public static String TemplatesPage_new;
38
	public static String TemplatesPage_preview;
39
	public static String TemplatesPage_question_create_new_message;
40
	public static String TemplatesPage_question_create_new_title;
41
	public static String TemplatesPage_remove;
42
	public static String TemplatesPage_save_error_message;
43
	public static String TemplatesPage_snippet;
44
	public static String TemplatesPage_show_disabled;
45
	public static String TemplatesPage_show_new_dialog;
46
	public static String TemplatesPage_context_description;
47
	public static String TemplatesPage_remove_message;
48
	public static String TemplatesPage_remove_title;
49
50
	// TemplatePreferencePage
28
	public static String TemplatePreferencePage_error_import;
51
	public static String TemplatePreferencePage_error_import;
29
	public static String TemplatePreferencePage_error_export;
52
	public static String TemplatePreferencePage_error_export;
30
	public static String TemplatePreferencePage_error_read_title;
53
	public static String TemplatePreferencePage_error_read_title;
(-)src/org/eclipse/ui/texteditor/templates/TextEditorTemplateMessages.properties (+23 lines)
Lines 9-14 Link Here
9
#     IBM Corporation - initial API and implementation
9
#     IBM Corporation - initial API and implementation
10
###############################################################################
10
###############################################################################
11
11
12
# templates page (view)
13
TemplatesPage_collapse_expand=Collapse or Expand
14
TemplatesPage_column_context=Context
15
TemplatesPage_column_description=Description
16
TemplatesPage_save_error_message=Error Saving the Templates
17
TemplatesPage_column_name=Name
18
TemplatesPage_edit=&Edit...
19
TemplatesPage_insert=&Insert...
20
TemplatesPage_preference_page=&Preference Page...
21
TemplatesPage_paste_description=Pasted from editor
22
TemplatesPage_link_to_editor=Link to Editor
23
TemplatesPage_new=&New...
24
TemplatesPage_preview=Previe&w:
25
TemplatesPage_snippet=snippet
26
TemplatesPage_question_create_new_message= The name of the template has been changed. Click 'Yes' to create an additional template with the new name or 'No' to rename the existing one.
27
TemplatesPage_context_description=Context
28
TemplatesPage_remove_title=Removing Templates
29
TemplatesPage_remove_message=Are you sure you want to remove the selected templates?
30
TemplatesPage_question_create_new_title= Edit Template
31
TemplatesPage_remove=&Remove
32
TemplatesPage_show_disabled=&Show Disabled
33
TemplatesPage_show_new_dialog=S&how New Dialog on Drop
34
12
# preference page
35
# preference page
13
TemplatePreferencePage_error_import=Failed to import templates.
36
TemplatePreferencePage_error_import=Failed to import templates.
14
TemplatePreferencePage_error_export=Failed to export templates.
37
TemplatePreferencePage_error_export=Failed to export templates.
(-)src/org/eclipse/ui/texteditor/templates/TemplatePreferencePage.java (-577 lines)
Lines 16-54 Link Here
16
import java.io.InputStream;
16
import java.io.InputStream;
17
import java.io.OutputStream;
17
import java.io.OutputStream;
18
import java.util.ArrayList;
18
import java.util.ArrayList;
19
import java.util.HashMap;
20
import java.util.Iterator;
19
import java.util.Iterator;
21
import java.util.List;
20
import java.util.List;
22
import java.util.Map;
23
21
24
import org.eclipse.swt.SWT;
22
import org.eclipse.swt.SWT;
25
import org.eclipse.swt.custom.StyledText;
26
import org.eclipse.swt.custom.VerifyKeyListener;
27
import org.eclipse.swt.events.FocusEvent;
28
import org.eclipse.swt.events.FocusListener;
29
import org.eclipse.swt.events.ModifyEvent;
30
import org.eclipse.swt.events.ModifyListener;
31
import org.eclipse.swt.events.SelectionEvent;
32
import org.eclipse.swt.events.SelectionListener;
33
import org.eclipse.swt.events.VerifyEvent;
34
import org.eclipse.swt.graphics.GC;
23
import org.eclipse.swt.graphics.GC;
35
import org.eclipse.swt.graphics.Image;
24
import org.eclipse.swt.graphics.Image;
36
import org.eclipse.swt.layout.GridData;
25
import org.eclipse.swt.layout.GridData;
37
import org.eclipse.swt.layout.GridLayout;
26
import org.eclipse.swt.layout.GridLayout;
38
import org.eclipse.swt.widgets.Button;
27
import org.eclipse.swt.widgets.Button;
39
import org.eclipse.swt.widgets.Combo;
40
import org.eclipse.swt.widgets.Composite;
28
import org.eclipse.swt.widgets.Composite;
41
import org.eclipse.swt.widgets.Control;
29
import org.eclipse.swt.widgets.Control;
42
import org.eclipse.swt.widgets.Event;
30
import org.eclipse.swt.widgets.Event;
43
import org.eclipse.swt.widgets.FileDialog;
31
import org.eclipse.swt.widgets.FileDialog;
44
import org.eclipse.swt.widgets.Label;
32
import org.eclipse.swt.widgets.Label;
45
import org.eclipse.swt.widgets.Listener;
33
import org.eclipse.swt.widgets.Listener;
46
import org.eclipse.swt.widgets.Menu;
47
import org.eclipse.swt.widgets.Shell;
48
import org.eclipse.swt.widgets.Table;
34
import org.eclipse.swt.widgets.Table;
49
import org.eclipse.swt.widgets.TableColumn;
35
import org.eclipse.swt.widgets.TableColumn;
50
import org.eclipse.swt.widgets.Text;
51
import org.eclipse.swt.widgets.Widget;
52
36
53
import org.eclipse.core.filesystem.EFS;
37
import org.eclipse.core.filesystem.EFS;
54
import org.eclipse.core.filesystem.IFileInfo;
38
import org.eclipse.core.filesystem.IFileInfo;
Lines 57-73 Link Here
57
import org.eclipse.core.runtime.CoreException;
41
import org.eclipse.core.runtime.CoreException;
58
import org.eclipse.core.runtime.Path;
42
import org.eclipse.core.runtime.Path;
59
43
60
import org.eclipse.jface.action.Action;
61
import org.eclipse.jface.action.GroupMarker;
62
import org.eclipse.jface.action.IAction;
63
import org.eclipse.jface.action.IMenuListener;
64
import org.eclipse.jface.action.IMenuManager;
65
import org.eclipse.jface.action.MenuManager;
66
import org.eclipse.jface.action.Separator;
67
import org.eclipse.jface.dialogs.Dialog;
44
import org.eclipse.jface.dialogs.Dialog;
68
import org.eclipse.jface.dialogs.IDialogSettings;
69
import org.eclipse.jface.dialogs.MessageDialog;
45
import org.eclipse.jface.dialogs.MessageDialog;
70
import org.eclipse.jface.dialogs.StatusDialog;
71
import org.eclipse.jface.preference.IPreferenceStore;
46
import org.eclipse.jface.preference.IPreferenceStore;
72
import org.eclipse.jface.preference.PreferencePage;
47
import org.eclipse.jface.preference.PreferencePage;
73
import org.eclipse.jface.resource.JFaceResources;
48
import org.eclipse.jface.resource.JFaceResources;
Lines 91-110 Link Here
91
66
92
import org.eclipse.jface.text.Document;
67
import org.eclipse.jface.text.Document;
93
import org.eclipse.jface.text.IDocument;
68
import org.eclipse.jface.text.IDocument;
94
import org.eclipse.jface.text.ITextListener;
95
import org.eclipse.jface.text.ITextOperationTarget;
96
import org.eclipse.jface.text.ITextViewer;
97
import org.eclipse.jface.text.TextEvent;
98
import org.eclipse.jface.text.contentassist.ContentAssistant;
99
import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
100
import org.eclipse.jface.text.contentassist.IContentAssistant;
101
import org.eclipse.jface.text.source.ISourceViewer;
102
import org.eclipse.jface.text.source.SourceViewer;
69
import org.eclipse.jface.text.source.SourceViewer;
103
import org.eclipse.jface.text.source.SourceViewerConfiguration;
70
import org.eclipse.jface.text.source.SourceViewerConfiguration;
104
import org.eclipse.jface.text.templates.ContextTypeRegistry;
71
import org.eclipse.jface.text.templates.ContextTypeRegistry;
105
import org.eclipse.jface.text.templates.Template;
72
import org.eclipse.jface.text.templates.Template;
106
import org.eclipse.jface.text.templates.TemplateContextType;
73
import org.eclipse.jface.text.templates.TemplateContextType;
107
import org.eclipse.jface.text.templates.TemplateException;
108
import org.eclipse.jface.text.templates.persistence.TemplatePersistenceData;
74
import org.eclipse.jface.text.templates.persistence.TemplatePersistenceData;
109
import org.eclipse.jface.text.templates.persistence.TemplateReaderWriter;
75
import org.eclipse.jface.text.templates.persistence.TemplateReaderWriter;
110
import org.eclipse.jface.text.templates.persistence.TemplateStore;
76
import org.eclipse.jface.text.templates.persistence.TemplateStore;
Lines 112-120 Link Here
112
import org.eclipse.ui.IWorkbench;
78
import org.eclipse.ui.IWorkbench;
113
import org.eclipse.ui.IWorkbenchPreferencePage;
79
import org.eclipse.ui.IWorkbenchPreferencePage;
114
import org.eclipse.ui.internal.texteditor.NLSUtility;
80
import org.eclipse.ui.internal.texteditor.NLSUtility;
115
import org.eclipse.ui.internal.texteditor.TextEditorPlugin;
116
import org.eclipse.ui.texteditor.ITextEditorActionConstants;
117
import org.eclipse.ui.texteditor.IUpdate;
118
81
119
/**
82
/**
120
 * A template preference page allows configuration of the templates for an
83
 * A template preference page allows configuration of the templates for an
Lines 132-677 Link Here
132
95
133
	
96
	
134
	/**
97
	/**
135
	 * Dialog to edit a template. Clients will usually instantiate, but
136
	 * may also extend.
137
	 *
138
	 * @since 3.3
139
	 */
140
	protected static class EditTemplateDialog extends StatusDialog {
141
142
		private class TextViewerAction extends Action implements IUpdate {
143
144
			private int fOperationCode= -1;
145
			private ITextOperationTarget fOperationTarget;
146
147
			/**
148
			 * Creates a new action.
149
			 *
150
			 * @param viewer the viewer
151
			 * @param operationCode the opcode
152
			 */
153
			public TextViewerAction(ITextViewer viewer, int operationCode) {
154
				fOperationCode= operationCode;
155
				fOperationTarget= viewer.getTextOperationTarget();
156
				update();
157
			}
158
159
			/**
160
			 * Updates the enabled state of the action.
161
			 * Fires a property change if the enabled state changes.
162
			 *
163
			 * @see Action#firePropertyChange(String, Object, Object)
164
			 */
165
			public void update() {
166
167
				boolean wasEnabled= isEnabled();
168
				boolean isEnabled= (fOperationTarget != null && fOperationTarget.canDoOperation(fOperationCode));
169
				setEnabled(isEnabled);
170
171
				if (wasEnabled != isEnabled) {
172
					firePropertyChange(ENABLED, wasEnabled ? Boolean.TRUE : Boolean.FALSE, isEnabled ? Boolean.TRUE : Boolean.FALSE);
173
				}
174
			}
175
176
			/**
177
			 * @see Action#run()
178
			 */
179
			public void run() {
180
				if (fOperationCode != -1 && fOperationTarget != null) {
181
					fOperationTarget.doOperation(fOperationCode);
182
				}
183
			}
184
		}
185
186
		private final Template fOriginalTemplate;
187
188
		private Text fNameText;
189
		private Text fDescriptionText;
190
		private Combo fContextCombo;
191
		private SourceViewer fPatternEditor;
192
		private Button fInsertVariableButton;
193
		private Button fAutoInsertCheckbox;
194
		private boolean fIsNameModifiable;
195
196
		private StatusInfo fValidationStatus;
197
		private boolean fSuppressError= true; // #4354
198
		private Map fGlobalActions= new HashMap(10);
199
		private List fSelectionActions = new ArrayList(3);
200
		private String[][] fContextTypes;
201
202
		private ContextTypeRegistry fContextTypeRegistry;
203
204
		private final TemplateVariableProcessor fTemplateProcessor= new TemplateVariableProcessor();
205
206
		private Template fNewTemplate;
207
208
		/**
209
		 * Creates a new dialog.
210
		 *
211
		 * @param parent the shell parent of the dialog
212
		 * @param template the template to edit
213
		 * @param edit whether this is a new template or an existing being edited
214
		 * @param isNameModifiable whether the name of the template may be modified
215
		 * @param registry the context type registry to use
216
		 */
217
		public EditTemplateDialog(Shell parent, Template template, boolean edit, boolean isNameModifiable, ContextTypeRegistry registry) {
218
			super(parent);
219
220
			setShellStyle(getShellStyle() | SWT.MAX | SWT.RESIZE);
221
222
			String title= edit
223
				? TextEditorTemplateMessages.EditTemplateDialog_title_edit
224
				: TextEditorTemplateMessages.EditTemplateDialog_title_new;
225
			setTitle(title);
226
227
			fOriginalTemplate= template;
228
			fIsNameModifiable= isNameModifiable;
229
230
			List contexts= new ArrayList();
231
			for (Iterator it= registry.contextTypes(); it.hasNext();) {
232
				TemplateContextType type= (TemplateContextType) it.next();
233
				contexts.add(new String[] { type.getId(), type.getName() });
234
			}
235
			fContextTypes= (String[][]) contexts.toArray(new String[contexts.size()][]);
236
237
			fValidationStatus= new StatusInfo();
238
239
			fContextTypeRegistry= registry;
240
241
			TemplateContextType type= fContextTypeRegistry.getContextType(template.getContextTypeId());
242
			fTemplateProcessor.setContextType(type);
243
		}
244
245
		/*
246
		 * @see org.eclipse.ui.texteditor.templates.StatusDialog#create()
247
		 */
248
		public void create() {
249
			super.create();
250
			// update initial OK button to be disabled for new templates
251
			boolean valid= fNameText == null || fNameText.getText().trim().length() != 0;
252
			if (!valid) {
253
				StatusInfo status = new StatusInfo();
254
				status.setError(TextEditorTemplateMessages.EditTemplateDialog_error_noname);
255
				updateButtonsEnableState(status);
256
	 		}
257
		}
258
259
		/*
260
		 * @see Dialog#createDialogArea(Composite)
261
		 */
262
		protected Control createDialogArea(Composite ancestor) {
263
			Composite parent= new Composite(ancestor, SWT.NONE);
264
			GridLayout layout= new GridLayout();
265
			layout.numColumns= 2;
266
			parent.setLayout(layout);
267
			parent.setLayoutData(new GridData(GridData.FILL_BOTH));
268
269
			ModifyListener listener= new ModifyListener() {
270
				public void modifyText(ModifyEvent e) {
271
					doTextWidgetChanged(e.widget);
272
				}
273
			};
274
275
			if (fIsNameModifiable) {
276
				createLabel(parent, TextEditorTemplateMessages.EditTemplateDialog_name);
277
278
				Composite composite= new Composite(parent, SWT.NONE);
279
				composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
280
				layout= new GridLayout();
281
				layout.numColumns= 4;
282
				layout.marginWidth= 0;
283
				layout.marginHeight= 0;
284
				composite.setLayout(layout);
285
286
				fNameText= createText(composite);
287
				fNameText.addModifyListener(listener);
288
				fNameText.addFocusListener(new FocusListener() {
289
290
					public void focusGained(FocusEvent e) {
291
					}
292
293
					public void focusLost(FocusEvent e) {
294
						if (fSuppressError) {
295
							fSuppressError= false;
296
							updateButtons();
297
						}
298
					}
299
				});
300
301
				createLabel(composite, TextEditorTemplateMessages.EditTemplateDialog_context);
302
				fContextCombo= new Combo(composite, SWT.READ_ONLY);
303
304
				for (int i= 0; i < fContextTypes.length; i++) {
305
					fContextCombo.add(fContextTypes[i][1]);
306
				}
307
308
				fContextCombo.addModifyListener(listener);
309
				
310
				fAutoInsertCheckbox= createCheckbox(composite, TextEditorTemplateMessages.EditTemplateDialog_autoinsert);
311
				fAutoInsertCheckbox.setSelection(fOriginalTemplate.isAutoInsertable());
312
			}
313
314
			createLabel(parent, TextEditorTemplateMessages.EditTemplateDialog_description);
315
316
			int descFlags= fIsNameModifiable ? SWT.BORDER : SWT.BORDER | SWT.READ_ONLY;
317
			fDescriptionText= new Text(parent, descFlags );
318
			fDescriptionText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
319
320
			fDescriptionText.addModifyListener(listener);
321
322
			Label patternLabel= createLabel(parent, TextEditorTemplateMessages.EditTemplateDialog_pattern);
323
			patternLabel.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING));
324
			fPatternEditor= createEditor(parent, fOriginalTemplate.getPattern());
325
326
			Label filler= new Label(parent, SWT.NONE);
327
			filler.setLayoutData(new GridData());
328
329
			Composite composite= new Composite(parent, SWT.NONE);
330
			layout= new GridLayout();
331
			layout.marginWidth= 0;
332
			layout.marginHeight= 0;
333
			composite.setLayout(layout);
334
			composite.setLayoutData(new GridData());
335
336
			fInsertVariableButton= new Button(composite, SWT.NONE);
337
			fInsertVariableButton.setLayoutData(getButtonGridData(fInsertVariableButton));
338
			fInsertVariableButton.setText(TextEditorTemplateMessages.EditTemplateDialog_insert_variable);
339
			fInsertVariableButton.addSelectionListener(new SelectionListener() {
340
				public void widgetSelected(SelectionEvent e) {
341
					fPatternEditor.getTextWidget().setFocus();
342
					fPatternEditor.doOperation(ISourceViewer.CONTENTASSIST_PROPOSALS);
343
				}
344
345
				public void widgetDefaultSelected(SelectionEvent e) {}
346
			});
347
348
			fDescriptionText.setText(fOriginalTemplate.getDescription());
349
			if (fIsNameModifiable) {
350
				fNameText.setText(fOriginalTemplate.getName());
351
				fNameText.addModifyListener(listener);
352
				fContextCombo.select(getIndex(fOriginalTemplate.getContextTypeId()));
353
			} else {
354
				fPatternEditor.getControl().setFocus();
355
			}
356
			initializeActions();
357
358
			applyDialogFont(parent);
359
			return composite;
360
		}
361
362
		private void doTextWidgetChanged(Widget w) {
363
			if (w == fNameText) {
364
				fSuppressError= false;
365
				updateButtons();
366
			} else if (w == fContextCombo) {
367
				String contextId= getContextId();
368
				fTemplateProcessor.setContextType(fContextTypeRegistry.getContextType(contextId));
369
			} else if (w == fDescriptionText) {
370
				// oh, nothing
371
			}
372
		}
373
374
		private String getContextId() {
375
			if (fContextCombo != null && !fContextCombo.isDisposed()) {
376
				String name= fContextCombo.getText();
377
				for (int i= 0; i < fContextTypes.length; i++) {
378
					if (name.equals(fContextTypes[i][1])) {
379
						return fContextTypes[i][0];
380
					}
381
				}
382
			}
383
384
			return fOriginalTemplate.getContextTypeId();
385
		}
386
387
		private void doSourceChanged(IDocument document) {
388
			String text= document.get();
389
			fValidationStatus.setOK();
390
			TemplateContextType contextType= fContextTypeRegistry.getContextType(getContextId());
391
			if (contextType != null) {
392
				try {
393
					contextType.validate(text);
394
				} catch (TemplateException e) {
395
					fValidationStatus.setError(e.getLocalizedMessage());
396
				}
397
			}
398
399
			updateUndoAction();
400
			updateButtons();
401
		}
402
403
		private static GridData getButtonGridData(Button button) {
404
			GridData data= new GridData(GridData.FILL_HORIZONTAL);
405
			// TODO get some button hints.
406
//			data.heightHint= SWTUtil.getButtonHeightHint(button);
407
408
			return data;
409
		}
410
411
		private static Label createLabel(Composite parent, String name) {
412
			Label label= new Label(parent, SWT.NULL);
413
			label.setText(name);
414
			label.setLayoutData(new GridData());
415
416
			return label;
417
		}
418
419
		private static Text createText(Composite parent) {
420
			Text text= new Text(parent, SWT.BORDER);
421
			text.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
422
423
			return text;
424
		}
425
426
		private static Button createCheckbox(Composite parent, String name) {
427
			Button button= new Button(parent, SWT.CHECK);
428
			button.setText(name);
429
			button.setLayoutData(new GridData());
430
			
431
			return button;
432
		}
433
		
434
		private SourceViewer createEditor(Composite parent, String pattern) {
435
			SourceViewer viewer= createViewer(parent);
436
			viewer.setEditable(true);
437
			
438
			IDocument document= viewer.getDocument();
439
			if (document != null)
440
				document.set(pattern);
441
			else {
442
				document= new Document(pattern);
443
				viewer.setDocument(document);
444
			}
445
446
			int nLines= document.getNumberOfLines();
447
			if (nLines < 5) {
448
				nLines= 5;
449
			} else if (nLines > 12) {
450
				nLines= 12;
451
			}
452
453
			Control control= viewer.getControl();
454
			GridData data= new GridData(GridData.FILL_BOTH);
455
			data.widthHint= convertWidthInCharsToPixels(80);
456
			data.heightHint= convertHeightInCharsToPixels(nLines);
457
			control.setLayoutData(data);
458
459
			viewer.addTextListener(new ITextListener() {
460
				public void textChanged(TextEvent event) {
461
					if (event .getDocumentEvent() != null)
462
						doSourceChanged(event.getDocumentEvent().getDocument());
463
				}
464
			});
465
466
			viewer.addSelectionChangedListener(new ISelectionChangedListener() {
467
				public void selectionChanged(SelectionChangedEvent event) {
468
					updateSelectionDependentActions();
469
				}
470
			});
471
472
		 	viewer.prependVerifyKeyListener(new VerifyKeyListener() {
473
				public void verifyKey(VerifyEvent event) {
474
					handleVerifyKeyPressed(event);
475
				}
476
			});
477
478
			return viewer;
479
		}
480
481
		/**
482
		 * Creates the viewer to be used to display the pattern. Subclasses may override.
483
		 *
484
		 * @param parent the parent composite of the viewer
485
		 * @return a configured <code>SourceViewer</code>
486
		 */
487
		protected SourceViewer createViewer(Composite parent) {
488
			SourceViewer viewer= new SourceViewer(parent, null, null, false, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
489
			SourceViewerConfiguration configuration= new SourceViewerConfiguration() {
490
				public IContentAssistant getContentAssistant(ISourceViewer sourceViewer) {
491
492
					ContentAssistant assistant= new ContentAssistant();
493
					assistant.enableAutoActivation(true);
494
					assistant.enableAutoInsert(true);
495
					assistant.setContentAssistProcessor(fTemplateProcessor, IDocument.DEFAULT_CONTENT_TYPE);
496
					return assistant;
497
				}
498
			};
499
			viewer.configure(configuration);
500
			return viewer;
501
		}
502
503
		private void handleVerifyKeyPressed(VerifyEvent event) {
504
			if (!event.doit)
505
				return;
506
507
			if (event.stateMask != SWT.MOD1)
508
				return;
509
510
			switch (event.character) {
511
				case ' ':
512
					fPatternEditor.doOperation(ISourceViewer.CONTENTASSIST_PROPOSALS);
513
					event.doit= false;
514
					break;
515
516
				// CTRL-Z
517
				case 'z' - 'a' + 1:
518
					fPatternEditor.doOperation(ITextOperationTarget.UNDO);
519
					event.doit= false;
520
					break;
521
			}
522
		}
523
524
		private void initializeActions() {
525
			TextViewerAction action= new TextViewerAction(fPatternEditor, ITextOperationTarget.UNDO);
526
			action.setText(TextEditorTemplateMessages.EditTemplateDialog_undo);
527
			fGlobalActions.put(ITextEditorActionConstants.UNDO, action);
528
529
			action= new TextViewerAction(fPatternEditor, ITextOperationTarget.CUT);
530
			action.setText(TextEditorTemplateMessages.EditTemplateDialog_cut);
531
			fGlobalActions.put(ITextEditorActionConstants.CUT, action);
532
533
			action= new TextViewerAction(fPatternEditor, ITextOperationTarget.COPY);
534
			action.setText(TextEditorTemplateMessages.EditTemplateDialog_copy);
535
			fGlobalActions.put(ITextEditorActionConstants.COPY, action);
536
537
			action= new TextViewerAction(fPatternEditor, ITextOperationTarget.PASTE);
538
			action.setText(TextEditorTemplateMessages.EditTemplateDialog_paste);
539
			fGlobalActions.put(ITextEditorActionConstants.PASTE, action);
540
541
			action= new TextViewerAction(fPatternEditor, ITextOperationTarget.SELECT_ALL);
542
			action.setText(TextEditorTemplateMessages.EditTemplateDialog_select_all);
543
			fGlobalActions.put(ITextEditorActionConstants.SELECT_ALL, action);
544
545
			action= new TextViewerAction(fPatternEditor, ISourceViewer.CONTENTASSIST_PROPOSALS);
546
			action.setText(TextEditorTemplateMessages.EditTemplateDialog_content_assist);
547
			fGlobalActions.put("ContentAssistProposal", action); //$NON-NLS-1$
548
549
			fSelectionActions.add(ITextEditorActionConstants.CUT);
550
			fSelectionActions.add(ITextEditorActionConstants.COPY);
551
			fSelectionActions.add(ITextEditorActionConstants.PASTE);
552
553
			// create context menu
554
			MenuManager manager= new MenuManager(null, null);
555
			manager.setRemoveAllWhenShown(true);
556
			manager.addMenuListener(new IMenuListener() {
557
				public void menuAboutToShow(IMenuManager mgr) {
558
					fillContextMenu(mgr);
559
				}
560
			});
561
562
			StyledText text= fPatternEditor.getTextWidget();
563
			Menu menu= manager.createContextMenu(text);
564
			text.setMenu(menu);
565
		}
566
567
		private void fillContextMenu(IMenuManager menu) {
568
			menu.add(new GroupMarker(ITextEditorActionConstants.GROUP_UNDO));
569
			menu.appendToGroup(ITextEditorActionConstants.GROUP_UNDO, (IAction) fGlobalActions.get(ITextEditorActionConstants.UNDO));
570
571
			menu.add(new Separator(ITextEditorActionConstants.GROUP_EDIT));
572
			menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, (IAction) fGlobalActions.get(ITextEditorActionConstants.CUT));
573
			menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, (IAction) fGlobalActions.get(ITextEditorActionConstants.COPY));
574
			menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, (IAction) fGlobalActions.get(ITextEditorActionConstants.PASTE));
575
			menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, (IAction) fGlobalActions.get(ITextEditorActionConstants.SELECT_ALL));
576
577
			menu.add(new Separator("templates")); //$NON-NLS-1$
578
			menu.appendToGroup("templates", (IAction) fGlobalActions.get("ContentAssistProposal")); //$NON-NLS-1$ //$NON-NLS-2$
579
		}
580
581
		private void updateSelectionDependentActions() {
582
			Iterator iterator= fSelectionActions.iterator();
583
			while (iterator.hasNext())
584
				updateAction((String)iterator.next());
585
		}
586
587
		private void updateUndoAction() {
588
			IAction action= (IAction) fGlobalActions.get(ITextEditorActionConstants.UNDO);
589
			if (action instanceof IUpdate)
590
				((IUpdate) action).update();
591
		}
592
593
		private void updateAction(String actionId) {
594
			IAction action= (IAction) fGlobalActions.get(actionId);
595
			if (action instanceof IUpdate)
596
				((IUpdate) action).update();
597
		}
598
599
		private int getIndex(String contextid) {
600
601
			if (contextid == null)
602
				return -1;
603
604
			for (int i= 0; i < fContextTypes.length; i++) {
605
				if (contextid.equals(fContextTypes[i][0])) {
606
					return i;
607
				}
608
			}
609
			return -1;
610
		}
611
612
		private void updateButtons() {
613
			StatusInfo status;
614
615
			boolean valid= fNameText == null || fNameText.getText().trim().length() != 0;
616
			if (!valid) {
617
				status = new StatusInfo();
618
				if (!fSuppressError) {
619
					status.setError(TextEditorTemplateMessages.EditTemplateDialog_error_noname);
620
				}
621
	 		} else {
622
	 			status= fValidationStatus;
623
	 		}
624
			updateStatus(status);
625
		}
626
627
		/*
628
		 * @since 3.1
629
		 */
630
		protected void okPressed() {
631
			String name= fNameText == null ? fOriginalTemplate.getName() : fNameText.getText();
632
			boolean isAutoInsertable= fAutoInsertCheckbox != null && fAutoInsertCheckbox.getSelection();
633
			fNewTemplate= new Template(name, fDescriptionText.getText(), getContextId(), fPatternEditor.getDocument().get(), isAutoInsertable);
634
			super.okPressed();
635
		}
636
637
		/**
638
		 * Returns the created template.
639
		 *
640
		 * @return the created template
641
		 * @since 3.1
642
		 */
643
		public Template getTemplate() {
644
			return fNewTemplate;
645
		}
646
		
647
		/**
648
		 * Returns the content assist processor that
649
		 * suggests template variables.
650
		 * 
651
		 * @return the processor to suggest variables
652
		 * @since 3.3
653
		 */
654
		protected IContentAssistProcessor getTemplateProcessor() {
655
			return fTemplateProcessor;
656
		}
657
658
		/*
659
		 * @see org.eclipse.jface.dialogs.Dialog#getDialogBoundsSettings()
660
		 * @since 3.2
661
		 */
662
		protected IDialogSettings getDialogBoundsSettings() {
663
			String sectionName= getClass().getName() + "_dialogBounds"; //$NON-NLS-1$
664
			IDialogSettings settings= TextEditorPlugin.getDefault().getDialogSettings();
665
			IDialogSettings section= settings.getSection(sectionName);
666
			if (section == null)
667
				section= settings.addNewSection(sectionName);
668
			return section;
669
		}
670
671
	}
672
	
673
	
674
	/**
675
	 * Label provider for templates.
98
	 * Label provider for templates.
676
	 */
99
	 */
677
	private class TemplateLabelProvider extends LabelProvider implements ITableLabelProvider {
100
	private class TemplateLabelProvider extends LabelProvider implements ITableLabelProvider {
(-)src/org/eclipse/ui/texteditor/templates/TemplatesPage.java (+1289 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2007 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
10
 *******************************************************************************/
11
package org.eclipse.ui.texteditor.templates;
12
13
import java.io.IOException;
14
import java.util.ArrayList;
15
import java.util.Arrays;
16
import java.util.Iterator;
17
import java.util.List;
18
19
import org.eclipse.jface.action.Action;
20
import org.eclipse.jface.action.IAction;
21
import org.eclipse.jface.action.IMenuListener;
22
import org.eclipse.jface.action.IMenuManager;
23
import org.eclipse.jface.action.IToolBarManager;
24
import org.eclipse.jface.action.MenuManager;
25
import org.eclipse.jface.action.Separator;
26
import org.eclipse.jface.dialogs.Dialog;
27
import org.eclipse.jface.dialogs.MessageDialog;
28
import org.eclipse.jface.layout.TreeColumnLayout;
29
import org.eclipse.jface.preference.IPreferenceStore;
30
import org.eclipse.jface.resource.JFaceResources;
31
import org.eclipse.jface.text.Document;
32
import org.eclipse.jface.text.IDocument;
33
import org.eclipse.jface.text.source.SourceViewer;
34
import org.eclipse.jface.text.source.SourceViewerConfiguration;
35
import org.eclipse.jface.text.templates.ContextTypeRegistry;
36
import org.eclipse.jface.text.templates.Template;
37
import org.eclipse.jface.text.templates.TemplateContextType;
38
import org.eclipse.jface.text.templates.persistence.TemplatePersistenceData;
39
import org.eclipse.jface.text.templates.persistence.TemplateStore;
40
import org.eclipse.jface.util.IPropertyChangeListener;
41
import org.eclipse.jface.util.PropertyChangeEvent;
42
import org.eclipse.jface.viewers.ColumnWeightData;
43
import org.eclipse.jface.viewers.DoubleClickEvent;
44
import org.eclipse.jface.viewers.IDoubleClickListener;
45
import org.eclipse.jface.viewers.ISelectionChangedListener;
46
import org.eclipse.jface.viewers.IStructuredSelection;
47
import org.eclipse.jface.viewers.ITableLabelProvider;
48
import org.eclipse.jface.viewers.ITreeContentProvider;
49
import org.eclipse.jface.viewers.LabelProvider;
50
import org.eclipse.jface.viewers.SelectionChangedEvent;
51
import org.eclipse.jface.viewers.StructuredSelection;
52
import org.eclipse.jface.viewers.TreeViewer;
53
import org.eclipse.jface.viewers.Viewer;
54
import org.eclipse.jface.viewers.ViewerComparator;
55
import org.eclipse.jface.window.Window;
56
import org.eclipse.swt.SWT;
57
import org.eclipse.swt.dnd.Clipboard;
58
import org.eclipse.swt.dnd.DND;
59
import org.eclipse.swt.dnd.DragSourceAdapter;
60
import org.eclipse.swt.dnd.DragSourceEvent;
61
import org.eclipse.swt.dnd.DropTargetAdapter;
62
import org.eclipse.swt.dnd.DropTargetEvent;
63
import org.eclipse.swt.dnd.TextTransfer;
64
import org.eclipse.swt.dnd.Transfer;
65
import org.eclipse.swt.graphics.FontMetrics;
66
import org.eclipse.swt.graphics.GC;
67
import org.eclipse.swt.graphics.Image;
68
import org.eclipse.swt.layout.GridData;
69
import org.eclipse.swt.layout.GridLayout;
70
import org.eclipse.swt.widgets.Composite;
71
import org.eclipse.swt.widgets.Control;
72
import org.eclipse.swt.widgets.Label;
73
import org.eclipse.swt.widgets.Menu;
74
import org.eclipse.swt.widgets.Shell;
75
import org.eclipse.swt.widgets.Tree;
76
import org.eclipse.swt.widgets.TreeColumn;
77
import org.eclipse.swt.widgets.TreeItem;
78
import org.eclipse.ui.IActionBars;
79
import org.eclipse.ui.IWorkbenchActionConstants;
80
import org.eclipse.ui.IWorkbenchPartSite;
81
import org.eclipse.ui.actions.ActionFactory;
82
import org.eclipse.ui.dialogs.PreferencesUtil;
83
import org.eclipse.ui.dnd.IDragAndDropService;
84
import org.eclipse.ui.internal.texteditor.TextEditorPlugin;
85
import org.eclipse.ui.part.Page;
86
import org.eclipse.ui.views.templates.ITemplatesPage;
87
88
/**
89
 * An abstract base class for template pages for use with TextEditor.
90
 * <p>
91
 * Clients who are defining an editor may elect to provide a corresponding
92
 * templates page. This templates page will be presented to the user via the
93
 * Templates View (the user decides whether their workbench window contains this
94
 * view) whenever that editor is active. This class should be subclassed.
95
 * </p>
96
 * <p>
97
 * Internally, a TemplatesPage uses the template store to display different
98
 * categories. A link to editor mode on the templates page allows to filtering
99
 * of the categories to only that are supported in this context.
100
 * </p>
101
 * Since: 3.4
102
 */
103
public abstract class TemplatesPage extends Page implements ITemplatesPage {
104
105
	/**
106
	 * Link to editor action setting
107
	 */
108
	private static final String LINK_ACTION_PREF_ID = TextEditorPlugin.PLUGIN_ID
109
			+ ".templates.templatesPage.linkAction"; //$NON-NLS-1$
110
	/**
111
	 * Show disabled actions setting
112
	 */
113
	private static final String SHOW_DISABLED_ACTION_PREF_ID = TextEditorPlugin.PLUGIN_ID
114
			+ ".templates.templatesPage.showDisabledAction"; //$NON-NLS-1$
115
	/**
116
	 * Show new dialog on drop setting
117
	 */
118
	private static final String SHOW_NEW_DIALOG_ACTION_PREF_ID = TextEditorPlugin.PLUGIN_ID
119
			+ ".templates.templatesPage.showNewDialogAction"; //$NON-NLS-1$;
120
121
	/**
122
	 * The ID for the popup menu for this templates page
123
	 */
124
	private static final String POPUP_MENU_ID = "org.eclipse.ui.texteditor.templates.PopupMenu"; //$NON-NLS-1$
125
126
	/**
127
	 * Drop support for the editor linked to this page. When a user drops a
128
	 * template into the active editor, the template is applied at the drop
129
	 * position.
130
	 */
131
	private final class EditorDropTarget extends DropTargetAdapter {
132
		/*
133
		 * (non-Javadoc)
134
		 * 
135
		 * @see org.eclipse.swt.dnd.DropTargetAdapter#dragEnter(org.eclipse.swt.dnd.DropTargetEvent)
136
		 */
137
		public void dragEnter(DropTargetEvent event) {
138
			super.dragEnter(event);
139
			if (event.detail == DND.DROP_DEFAULT)
140
				event.detail = DND.DROP_COPY;
141
		}
142
143
		/*
144
		 * (non-Javadoc)
145
		 * 
146
		 * @see org.eclipse.swt.dnd.DropTargetAdapter#dragOperationChanged(org.eclipse.swt.dnd.DropTargetEvent)
147
		 */
148
		public void dragOperationChanged(DropTargetEvent event) {
149
			if (event.detail == DND.DROP_DEFAULT)
150
				event.detail = DND.DROP_COPY;
151
		}
152
153
		/*
154
		 * (non-Javadoc)
155
		 * 
156
		 * @see org.eclipse.swt.dnd.DropTargetAdapter#dragOver(org.eclipse.swt.dnd.DropTargetEvent)
157
		 */
158
		public void dragOver(DropTargetEvent event) {
159
			event.feedback |= DND.FEEDBACK_SCROLL;
160
		}
161
162
		/*
163
		 * (non-Javadoc)
164
		 * 
165
		 * @see org.eclipse.swt.dnd.DropTargetAdapter#drop(org.eclipse.swt.dnd.DropTargetEvent)
166
		 */
167
		public void drop(DropTargetEvent event) {
168
			insertTemplate(getSelectedTemplate());
169
		}
170
	}
171
172
	/**
173
	 * Comparator for the viewer. Sorts the templates by name and then
174
	 * description and context types by names.
175
	 */
176
	private static final class TemplateViewerComparator extends
177
			ViewerComparator {
178
		/*
179
		 * (non-Javadoc)
180
		 * 
181
		 * @see org.eclipse.jface.viewers.ViewerComparator#compare(org.eclipse.jface.viewers.Viewer,
182
		 *      java.lang.Object, java.lang.Object)
183
		 */
184
		public int compare(Viewer viewer, Object object1, Object object2) {
185
			if ((object1 instanceof TemplatePersistenceData)
186
					&& (object2 instanceof TemplatePersistenceData)) {
187
				Template left = ((TemplatePersistenceData) object1)
188
						.getTemplate();
189
				Template right = ((TemplatePersistenceData) object2)
190
						.getTemplate();
191
				int result = left.getName()
192
						.compareToIgnoreCase(right.getName());
193
				if (result != 0)
194
					return result;
195
				return left.getDescription().compareToIgnoreCase(
196
						right.getDescription());
197
			}
198
			if ((object1 instanceof TemplateContextType)
199
					&& (object2 instanceof TemplateContextType)) {
200
				return ((TemplateContextType) object1).getName()
201
						.compareToIgnoreCase(
202
								((TemplateContextType) object1).getName());
203
			}
204
			return super.compare(viewer, object1, object2);
205
		}
206
207
		/*
208
		 * (non-Javadoc)
209
		 * 
210
		 * @see org.eclipse.jface.viewers.ViewerComparator#isSorterProperty(java.lang.Object,
211
		 *      java.lang.String)
212
		 */
213
		public boolean isSorterProperty(Object element, String property) {
214
			return true;
215
		}
216
	}
217
218
	/**
219
	 * Label provider for templates.
220
	 */
221
	private class TemplateLabelProvider extends LabelProvider implements
222
			ITableLabelProvider {
223
224
		/*
225
		 * @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnImage(java.lang.Object,
226
		 *      int)
227
		 */
228
		public Image getColumnImage(Object element, int columnIndex) {
229
			return null;
230
		}
231
232
		/*
233
		 * @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnText(java.lang.Object,
234
		 *      int)
235
		 */
236
		public String getColumnText(Object element, int columnIndex) {
237
			if (element instanceof TemplatePersistenceData)
238
				return getTemplateColumnText(
239
						((TemplatePersistenceData) element).getTemplate(),
240
						columnIndex);
241
			return getContextColumnText((TemplateContextType) element,
242
					columnIndex);
243
		}
244
245
		/**
246
		 * Return the column text for a template
247
		 * 
248
		 * @param template
249
		 * @param columnIndex
250
		 * @return the column text
251
		 */
252
		private String getTemplateColumnText(Template template, int columnIndex) {
253
			switch (columnIndex) {
254
			case 0:
255
				return template.getName();
256
			case 1:
257
				return template.getDescription();
258
			default:
259
				return ""; //$NON-NLS-1$
260
			}
261
		}
262
263
		/**
264
		 * Return the column text for a context
265
		 * 
266
		 * @param contextType
267
		 * @param columnIndex
268
		 * @return the column text
269
		 */
270
		private String getContextColumnText(TemplateContextType contextType,
271
				int columnIndex) {
272
			switch (columnIndex) {
273
			case 0:
274
				return contextType.getName();
275
			case 1:
276
				return TextEditorTemplateMessages.TemplatesPage_context_description;
277
			default:
278
				return ""; //$NON-NLS-1$
279
			}
280
		}
281
282
	}
283
284
	/**
285
	 * Content provider for templates. Provides all the templates defined for
286
	 * this editor and optionally the disabled ones.
287
	 */
288
	private class TemplatesContentProvider implements ITreeContentProvider {
289
		/*
290
		 * (non-Javadoc)
291
		 * 
292
		 * @see org.eclipse.jface.viewers.ITreeContentProvider#getChildren(java.lang.Object)
293
		 */
294
		public Object[] getChildren(Object parentElement) {
295
			if (parentElement instanceof TemplatePersistenceData)
296
				return new Object[0];
297
			else if (parentElement instanceof TemplateContextType) {
298
				TemplateContextType contextType = (TemplateContextType) parentElement;
299
				return getTemplates(contextType.getId());
300
			}
301
			return null;
302
		}
303
304
		/**
305
		 * Get the templates for a given contextId. if ShowDisabled is selected
306
		 * the disabled templates are also included.
307
		 * 
308
		 * @param contextId
309
		 * @return the templates
310
		 */
311
		private TemplatePersistenceData[] getTemplates(String contextId) {
312
			List templateList = new ArrayList();
313
			TemplatePersistenceData[] datas = fTemplateStore
314
					.getTemplateData(false);
315
			boolean showDisabled = fShowDisabledAction.isChecked();
316
			for (int i = 0; i < datas.length; i++) {
317
				if ((showDisabled || datas[i].isEnabled())
318
						&& datas[i].getTemplate().getContextTypeId().equals(
319
								contextId))
320
					templateList.add(datas[i]);
321
			}
322
			return (TemplatePersistenceData[]) templateList
323
					.toArray(new TemplatePersistenceData[templateList.size()]);
324
		}
325
326
		/*
327
		 * (non-Javadoc)
328
		 * 
329
		 * @see org.eclipse.jface.viewers.ITreeContentProvider#getParent(java.lang.Object)
330
		 */
331
		public Object getParent(Object element) {
332
			if (element instanceof TemplatePersistenceData) {
333
				TemplatePersistenceData templateData = (TemplatePersistenceData) element;
334
				return fContextTypeRegistry.getContextType(templateData
335
						.getTemplate().getContextTypeId());
336
			}
337
			return null;
338
		}
339
340
		/*
341
		 * (non-Javadoc)
342
		 * 
343
		 * @see org.eclipse.jface.viewers.ITreeContentProvider#hasChildren(java.lang.Object)
344
		 */
345
		public boolean hasChildren(Object element) {
346
			if (element instanceof TemplateContextType)
347
				return true;
348
			return false;
349
		}
350
351
		/*
352
		 * (non-Javadoc)
353
		 * 
354
		 * @see org.eclipse.jface.viewers.IStructuredContentProvider#getElements(java.lang.Object)
355
		 */
356
		public Object[] getElements(Object inputElement) {
357
			List contextTypes = new ArrayList();
358
359
			for (Iterator iterator = fContextTypeRegistry.contextTypes(); iterator
360
					.hasNext();) {
361
				TemplateContextType contextType = (TemplateContextType) iterator
362
						.next();
363
				if (isActiveContext(contextType) || !fLinkAction.isChecked())
364
					contextTypes.add(contextType);
365
			}
366
			return contextTypes.toArray(new TemplateContextType[contextTypes
367
					.size()]);
368
		}
369
370
		/**
371
		 * Checks whether given context type is active for displaying the
372
		 * templates
373
		 * 
374
		 * @param contextType
375
		 * @return true if context is active
376
		 */
377
		private boolean isActiveContext(TemplateContextType contextType) {
378
			return fActiveTypes == null
379
					|| fActiveTypes.contains(contextType.getId());
380
		}
381
382
		/*
383
		 * (non-Javadoc)
384
		 * 
385
		 * @see org.eclipse.jface.viewers.IContentProvider#dispose()
386
		 */
387
		public void dispose() {
388
		}
389
390
		/*
391
		 * (non-Javadoc)
392
		 * 
393
		 * @see org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse.jface.viewers.Viewer,
394
		 *      java.lang.Object, java.lang.Object)
395
		 */
396
		public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
397
		}
398
	}
399
400
	/**
401
	 * Show/Hide new dialog
402
	 */
403
	private static final int SHOW_DIALOG = 0;
404
	private static final int HIDE_DIALOG = 1;
405
406
	/** The viewer displays the pattern of selected template. */
407
	private SourceViewer fPatternViewer;
408
	/** The store for our templates. */
409
	private TemplateStore fTemplateStore;
410
	/** The context type registry. */
411
	private ContextTypeRegistry fContextTypeRegistry;
412
413
	/** The control for this page book view */
414
	private Composite fControl;
415
416
	/* Actions */
417
	private Action fInsertAction;
418
	private Action fAddAction;
419
	private Action fEditAction;
420
	private Action fRemoveAction;
421
	private Action fLinkAction;
422
	private Action fExpandCollapseAction;
423
	private Action fPreferencePageAction;
424
	private Action fShowDisabledAction;
425
	private Action fShowNewDialogOnDropAction;
426
427
	/* Clipboard actions */
428
	private Action fPasteAction;
429
	private Action fCopyAction;
430
431
	/** Currently selected templates */
432
	private ArrayList fSelectedTemplateList = new ArrayList();
433
434
	/** Current active context types for the editor */
435
	private List fActiveTypes;
436
437
	/* Preference stores */
438
	/**
439
	 * Preference store to store the dialog setting for this page
440
	 */
441
	private IPreferenceStore fPreferenceStore;
442
	/**
443
	 * The template stores preference page. Used to listen to the changes and
444
	 * update the view. Needed when the user selects Preferences and updates the
445
	 * templates.
446
	 */
447
	private IPreferenceStore fTemplatePreferenceStore;
448
449
	/* Controls */
450
	private Tree fTemplatesTree;
451
	private TreeViewer fTreeViewer;
452
453
	/**
454
	 * Creates a new template preference page.
455
	 */
456
	protected TemplatesPage() {
457
		super();
458
		fPreferenceStore = TextEditorPlugin.getDefault().getPreferenceStore();
459
	}
460
461
	/**
462
	 * Returns the template store.
463
	 * 
464
	 * @return the template store
465
	 */
466
	public TemplateStore getTemplateStore() {
467
		return fTemplateStore;
468
	}
469
470
	/**
471
	 * Returns the context type registry.
472
	 * 
473
	 * @return the context type registry
474
	 */
475
	public ContextTypeRegistry getContextTypeRegistry() {
476
		return fContextTypeRegistry;
477
	}
478
479
	/**
480
	 * Sets the template store.
481
	 * 
482
	 * @param store
483
	 *            the template store
484
	 * @param templatePreferenceStore
485
	 *            the preference store used for this template store
486
	 */
487
	public void setTemplateStore(TemplateStore store,
488
			IPreferenceStore templatePreferenceStore) {
489
		fTemplateStore = store;
490
		fTemplatePreferenceStore = templatePreferenceStore;
491
		if (fTemplatePreferenceStore != null)
492
			fTemplatePreferenceStore
493
					.addPropertyChangeListener(new IPropertyChangeListener() {
494
						public void propertyChange(PropertyChangeEvent event) {
495
							refresh();
496
						}
497
					});
498
	}
499
500
	/**
501
	 * Sets the context type registry.
502
	 * 
503
	 * @param registry
504
	 *            the new context type registry
505
	 */
506
	public void setContextTypeRegistry(ContextTypeRegistry registry) {
507
		fContextTypeRegistry = registry;
508
	}
509
510
	/*
511
	 * (non-Javadoc)
512
	 * 
513
	 * @see org.eclipse.ui.part.Page#createControl(org.eclipse.swt.widgets.Composite)
514
	 */
515
	public void createControl(Composite ancestor) {
516
		setupActions();
517
518
		fControl = new Composite(ancestor, SWT.NONE);
519
		GridLayout layout = new GridLayout();
520
		layout.numColumns = 2;
521
		layout.marginHeight = 0;
522
		layout.marginWidth = 0;
523
		fControl.setLayout(layout);
524
		Dialog.applyDialogFont(fControl);
525
526
		createTemplateTree();
527
		createPatternViewer(fControl);
528
529
		hookContextMenu();
530
		initializeDND();
531
		updateButtons();
532
533
		fControl.layout(true, true);
534
	}
535
536
	/**
537
	 * Create the tree control to display template information
538
	 */
539
	private void createTemplateTree() {
540
		Composite treeComposite = new Composite(fControl, SWT.NONE);
541
		GridData data = new GridData(GridData.FILL_BOTH);
542
		treeComposite.setLayoutData(data);
543
544
		TreeColumnLayout columnLayout = new TreeColumnLayout();
545
		treeComposite.setLayout(columnLayout);
546
		fTemplatesTree = new Tree(treeComposite, SWT.H_SCROLL | SWT.V_SCROLL
547
				| SWT.MULTI | SWT.FULL_SELECTION);
548
		fTemplatesTree.setHeaderVisible(true);
549
		fTemplatesTree.setLinesVisible(true);
550
551
		GC gc = new GC(getShell());
552
		gc.setFont(JFaceResources.getDialogFont());
553
554
		TreeColumn columnName = new TreeColumn(fTemplatesTree, SWT.NONE);
555
		columnName
556
				.setText(TextEditorTemplateMessages.TemplatesPage_column_name);
557
		int minWidth = gc
558
				.stringExtent(TextEditorTemplateMessages.TemplatesPage_column_name).x + 10;
559
		columnLayout.setColumnData(columnName, new ColumnWeightData(2,
560
				minWidth, true));
561
562
		TreeColumn columnDescription = new TreeColumn(fTemplatesTree, SWT.NONE);
563
		columnDescription
564
				.setText(TextEditorTemplateMessages.TemplatesPage_column_description);
565
		minWidth = gc
566
				.stringExtent(TextEditorTemplateMessages.TemplatesPage_column_description).x + 10;
567
		columnLayout.setColumnData(columnDescription, new ColumnWeightData(3,
568
				minWidth, true));
569
570
		gc.dispose();
571
572
		data = new GridData(GridData.FILL_BOTH);
573
		data.grabExcessHorizontalSpace = true;
574
		data.grabExcessVerticalSpace = true;
575
		/*
576
		 * these hints should not be zero. the grabExcess will ensure that the
577
		 * tree is sized appropriately the the pattern viewer is displayed below
578
		 * it.
579
		 */
580
		data.heightHint = 5;
581
		data.widthHint = 5;
582
		fTemplatesTree.setLayoutData(data);
583
		createTreeViewer();
584
	}
585
586
	/**
587
	 * Create the viewer for the tree control and configure it.
588
	 */
589
	private void createTreeViewer() {
590
		fTreeViewer = new TreeViewer(fTemplatesTree);
591
		fTreeViewer.setLabelProvider(new TemplateLabelProvider());
592
		fTreeViewer.setContentProvider(new TemplatesContentProvider());
593
594
		fTreeViewer.setComparator(new TemplateViewerComparator());
595
		fTreeViewer.setInput(fTemplateStore);
596
		fTreeViewer.addDoubleClickListener(new IDoubleClickListener() {
597
			public void doubleClick(DoubleClickEvent e) {
598
				updateSelectedTemplate();
599
				insertTemplate(getSelectedTemplate());
600
			}
601
		});
602
603
		fTreeViewer
604
				.addSelectionChangedListener(new ISelectionChangedListener() {
605
					public void selectionChanged(SelectionChangedEvent e) {
606
						updateSelectedTemplate();
607
						updateButtons();
608
					}
609
				});
610
		fTreeViewer.expandAll();
611
		setDisableItemColors();
612
	}
613
614
	/**
615
	 * Sets all templates in the tree that are disabled to grey.
616
	 */
617
	private void setDisableItemColors() {
618
		TreeItem[] items = fTemplatesTree.getItems();
619
		for (int i = 0; i < items.length; i++) {
620
			TreeItem[] items2 = items[i].getItems();
621
			for (int j = 0; j < items2.length; j++) {
622
				TemplatePersistenceData templateData = (TemplatePersistenceData) items2[j]
623
						.getData();
624
				if (!templateData.isEnabled())
625
					items2[j].setForeground(getShell().getDisplay()
626
							.getSystemColor(SWT.COLOR_GRAY));
627
			}
628
		}
629
	}
630
631
	/**
632
	 * Update the selected template list and update the pattern viewer
633
	 */
634
	private void updateSelectedTemplate() {
635
		IStructuredSelection selection = (IStructuredSelection) fTreeViewer
636
				.getSelection();
637
638
		fSelectedTemplateList.clear();
639
		for (Iterator iterator = selection.iterator(); iterator.hasNext();) {
640
			Object item = iterator.next();
641
			if (item instanceof TemplateContextType) {
642
				fSelectedTemplateList.clear();
643
				break;
644
			}
645
			fSelectedTemplateList.add(item);
646
647
		}
648
		if (isSingleTemplateSelected())
649
			updateViewerInput(getSelectedTemplate());
650
		else
651
			fPatternViewer.getDocument().set(""); //$NON-NLS-1$
652
	}
653
654
	/**
655
	 * Checks whether only one template is selected in the tree
656
	 * 
657
	 * @return true if only single template is selected
658
	 */
659
	private boolean isSingleTemplateSelected() {
660
		return fSelectedTemplateList.size() == 1;
661
	}
662
663
	/**
664
	 * Get the selected template. Note: should always precede with a check for
665
	 * isSingleTemplateSelected
666
	 * 
667
	 * @return the template (Not the data)
668
	 */
669
	private Template getSelectedTemplate() {
670
		return ((TemplatePersistenceData) fSelectedTemplateList.get(0))
671
				.getTemplate();
672
	}
673
674
	/**
675
	 * Create a viewer to display the pattern
676
	 * 
677
	 * @param parent
678
	 */
679
	private void createPatternViewer(Composite parent) {
680
		Label previewLabel = new Label(parent, SWT.NONE);
681
		previewLabel.setText(TextEditorTemplateMessages.TemplatesPage_preview);
682
		GridData data = new GridData();
683
		data.horizontalSpan = 2;
684
		previewLabel.setLayoutData(data);
685
686
		fPatternViewer = createViewer(parent);
687
		fPatternViewer.setEditable(false);
688
689
		Control control = fPatternViewer.getControl();
690
		data = new GridData(GridData.FILL_BOTH);
691
		data.horizontalSpan = 2;
692
693
		Dialog.applyDialogFont(control);
694
		GC gc = new GC(control);
695
		data.heightHint = convertHeightInCharsToPixels(gc, 5);
696
		data.grabExcessVerticalSpace = false;
697
		data.verticalAlignment = SWT.FILL;
698
		gc.dispose();
699
700
		control.setLayoutData(data);
701
	}
702
703
	/**
704
	 * Setup the actions
705
	 */
706
	private void setupActions() {
707
		IActionBars actionBars = getSite().getActionBars();
708
		IToolBarManager toolBarManager = actionBars.getToolBarManager();
709
		IMenuManager menuManager = actionBars.getMenuManager();
710
711
		fInsertAction = new Action(
712
				TextEditorTemplateMessages.TemplatesPage_insert) {
713
			public void run() {
714
				insertTemplate(getSelectedTemplate());
715
			}
716
		};
717
718
		fAddAction = new Action() {
719
			public void run() {
720
				addTemplate();
721
			}
722
		};
723
		fAddAction.setText(TextEditorTemplateMessages.TemplatesPage_new);
724
		fAddAction
725
				.setImageDescriptor(TemplateViewImages
726
						.getImageDescriptor(ITemplateViewImageConstants.IMG_TEMPLATE_NEW));
727
		toolBarManager.add(fAddAction);
728
729
		fEditAction = new Action() {
730
			public void run() {
731
				editTemplate();
732
			}
733
		};
734
		fEditAction.setText(TextEditorTemplateMessages.TemplatesPage_edit);
735
		fEditAction
736
				.setImageDescriptor(TemplateViewImages
737
						.getImageDescriptor(ITemplateViewImageConstants.IMG_TEMPLATE_EDIT));
738
		toolBarManager.add(fEditAction);
739
740
		fRemoveAction = new Action() {
741
			public void run() {
742
				removeTemplate();
743
			}
744
		};
745
		fRemoveAction.setText(TextEditorTemplateMessages.TemplatesPage_remove);
746
		fRemoveAction
747
				.setImageDescriptor(TemplateViewImages
748
						.getImageDescriptor(ITemplateViewImageConstants.IMG_TEMPLATE_DELETE));
749
		toolBarManager.add(fRemoveAction);
750
751
		toolBarManager.add(new Separator());
752
753
		fLinkAction = new Action(
754
				TextEditorTemplateMessages.TemplatesPage_link_to_editor,
755
				IAction.AS_CHECK_BOX) {
756
			public void run() {
757
				fPreferenceStore.setValue(LINK_ACTION_PREF_ID, fLinkAction
758
						.isChecked());
759
				refresh();
760
			}
761
		};
762
		fLinkAction
763
				.setImageDescriptor(TemplateViewImages
764
						.getImageDescriptor(ITemplateViewImageConstants.IMG_TEMPLATE_LINK));
765
		fLinkAction
766
				.setChecked(fPreferenceStore.getBoolean(LINK_ACTION_PREF_ID));
767
		toolBarManager.add(fLinkAction);
768
769
		fExpandCollapseAction = new Action(
770
				TextEditorTemplateMessages.TemplatesPage_collapse_expand) {
771
			public void run() {
772
				Object[] vee = fTreeViewer.getVisibleExpandedElements();
773
				boolean collapse = vee.length != 0;
774
				if (collapse)
775
					fTreeViewer.collapseAll();
776
				else
777
					fTreeViewer.expandAll();
778
			}
779
		};
780
		fExpandCollapseAction
781
				.setImageDescriptor(TemplateViewImages
782
						.getImageDescriptor(ITemplateViewImageConstants.IMG_TEMPLATE_COLLAPSE_EXPAND));
783
		toolBarManager.add(fExpandCollapseAction);
784
785
		if (getPreferencePageId() != null) {
786
			fPreferencePageAction = new Action() {
787
				public void run() {
788
					showPreferencePage();
789
				}
790
			};
791
			fPreferencePageAction
792
					.setText(TextEditorTemplateMessages.TemplatesPage_preference_page);
793
			menuManager.add(fPreferencePageAction);
794
		}
795
		menuManager.add(new Separator());
796
797
		fShowDisabledAction = new Action(
798
				TextEditorTemplateMessages.TemplatesPage_show_disabled,
799
				IAction.AS_CHECK_BOX) {
800
			public void run() {
801
				fPreferenceStore.setValue(SHOW_DISABLED_ACTION_PREF_ID,
802
						fShowDisabledAction.isChecked());
803
				refresh();
804
			}
805
		};
806
		fPreferenceStore.setDefault(SHOW_DISABLED_ACTION_PREF_ID, false);
807
		fShowDisabledAction.setChecked(fPreferenceStore
808
				.getBoolean(SHOW_DISABLED_ACTION_PREF_ID));
809
		menuManager.add(fShowDisabledAction);
810
811
		fShowNewDialogOnDropAction = new Action(
812
				TextEditorTemplateMessages.TemplatesPage_show_new_dialog,
813
				IAction.AS_CHECK_BOX) {
814
			public void run() {
815
				fPreferenceStore.setValue(SHOW_NEW_DIALOG_ACTION_PREF_ID,
816
						fShowNewDialogOnDropAction.isChecked());
817
			}
818
		};
819
		fPreferenceStore.setDefault(SHOW_NEW_DIALOG_ACTION_PREF_ID, true);
820
		fShowDisabledAction.setChecked(fPreferenceStore
821
				.getBoolean(SHOW_NEW_DIALOG_ACTION_PREF_ID));
822
		menuManager.add(fShowNewDialogOnDropAction);
823
824
		menuManager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
825
826
		fPasteAction = new Action() {
827
			public void run() {
828
				Clipboard clipBoard = new Clipboard(getShell().getDisplay());
829
				Object contents = clipBoard.getContents(TextTransfer
830
						.getInstance());
831
				if (contents == null)
832
					return;
833
				final String text = (String) contents;
834
				String contextId = getContextId();
835
				final Template template = new Template(
836
						TextEditorTemplateMessages.TemplatesPage_snippet,
837
						TextEditorTemplateMessages.TemplatesPage_paste_description,
838
						contextId, text, true);
839
				getShell().getDisplay().asyncExec(new Runnable() {
840
					public void run() {
841
						addTemplate(template, HIDE_DIALOG);
842
					}
843
				});
844
845
			}
846
847
			private String getContextId() {
848
				if (isSingleTemplateSelected())
849
					return getSelectedTemplate().getContextTypeId();
850
				IStructuredSelection selection = (IStructuredSelection) fTreeViewer
851
						.getSelection();
852
				if (selection.isEmpty())
853
					return getFirstContextTypeId();
854
				Object element = selection.getFirstElement();
855
				if (element instanceof TemplateContextType)
856
					return ((TemplateContextType) element).getId();
857
				return ((TemplatePersistenceData) element).getTemplate()
858
						.getContextTypeId();
859
			}
860
		};
861
		actionBars.setGlobalActionHandler(ActionFactory.PASTE.getId(),
862
				fPasteAction);
863
864
		fCopyAction = new Action() {
865
			public void run() {
866
				if (!isSingleTemplateSelected())
867
					return;
868
				Template[] templates = new Template[] { getSelectedTemplate() };
869
				Clipboard clipBoard = new Clipboard(getShell().getDisplay());
870
				clipBoard.setContents(new Object[] { templates },
871
						new Transfer[] { TemplateTransfer.getInstance() });
872
			}
873
		};
874
		actionBars.setGlobalActionHandler(ActionFactory.COPY.getId(),
875
				fCopyAction);
876
	}
877
878
	/**
879
	 * Setup the context menu for the viewer.
880
	 */
881
	private void hookContextMenu() {
882
		MenuManager menuMgr = new MenuManager(POPUP_MENU_ID);
883
		menuMgr.setRemoveAllWhenShown(true);
884
		menuMgr.addMenuListener(new IMenuListener() {
885
			public void menuAboutToShow(IMenuManager manager) {
886
				fillContextMenu(manager);
887
			}
888
		});
889
		Menu menu = menuMgr.createContextMenu(fTreeViewer.getControl());
890
		fTreeViewer.getControl().setMenu(menu);
891
		getSite().registerContextMenu(POPUP_MENU_ID, menuMgr, fTreeViewer);
892
	}
893
894
	/**
895
	 * Fill up the context menu
896
	 * 
897
	 * @param manager
898
	 */
899
	protected void fillContextMenu(IMenuManager manager) {
900
		manager.add(fInsertAction);
901
		manager.add(new Separator());
902
		manager.add(fAddAction);
903
		manager.add(fEditAction);
904
		manager.add(fRemoveAction);
905
		// Other plug-ins can contribute there actions here
906
		manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
907
	}
908
909
	/**
910
	 * Show the preference templates preference page
911
	 */
912
	private void showPreferencePage() {
913
		PreferencesUtil.createPreferenceDialogOn(getShell(),
914
				getPreferencePageId(), null, null).open();
915
	}
916
917
	/**
918
	 * Get the preference page ID for the templates for the given editor.
919
	 * Subclasses should override.
920
	 * 
921
	 * @return id of the preference page
922
	 */
923
	protected String getPreferencePageId() {
924
		return null;
925
	}
926
927
	/**
928
	 * Helper to find the size for pattern viewer
929
	 * 
930
	 * @param gc
931
	 * @param chars
932
	 * @return the hieght in pixels
933
	 */
934
	private int convertHeightInCharsToPixels(GC gc, int chars) {
935
		FontMetrics fontMetrics = gc.getFontMetrics();
936
		return fontMetrics.getHeight() * chars;
937
	}
938
939
	/**
940
	 * Get the shell
941
	 * 
942
	 * @return the shell for this view site
943
	 */
944
	protected Shell getShell() {
945
		return getSite().getShell();
946
	}
947
948
	/**
949
	 * Creates, configures and returns a source viewer to present the template
950
	 * pattern on the preference page. Clients may override to provide a custom
951
	 * source viewer featuring e.g. syntax coloring.
952
	 * 
953
	 * @param parent
954
	 *            the parent control
955
	 * @return a configured source viewer
956
	 */
957
	protected SourceViewer createViewer(Composite parent) {
958
		SourceViewer viewer = new SourceViewer(parent, null, null, false,
959
				SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
960
		SourceViewerConfiguration configuration = new SourceViewerConfiguration();
961
		viewer.configure(configuration);
962
		IDocument document = new Document();
963
		viewer.setDocument(document);
964
		return viewer;
965
	}
966
967
	/**
968
	 * Updates the pattern viewer.
969
	 * 
970
	 * @param template
971
	 */
972
	protected void updateViewerInput(Template template) {
973
		if (template != null)
974
			fPatternViewer.getDocument().set(template.getPattern());
975
		else
976
			fPatternViewer.getDocument().set(""); //$NON-NLS-1$
977
	}
978
979
	/**
980
	 * Updates the buttons.
981
	 */
982
	private void updateButtons() {
983
		fCopyAction.setEnabled(isSingleTemplateSelected());
984
		fInsertAction.setEnabled(isSingleTemplateSelected());
985
		fEditAction.setEnabled(isSingleTemplateSelected());
986
		fRemoveAction.setEnabled(fSelectedTemplateList.size() != 0);
987
	}
988
989
	/**
990
	 * Add a template
991
	 */
992
	private void addTemplate() {
993
		String id = getFirstContextTypeId();
994
		if (id != null) {
995
			Template template = new Template("", "", id, "", true); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
996
997
			addTemplate(template, SHOW_DIALOG);
998
		}
999
	}
1000
1001
	/**
1002
	 * Get the first context type from the registry.
1003
	 * 
1004
	 * @return id of the context type
1005
	 */
1006
	private String getFirstContextTypeId() {
1007
		Iterator it = fContextTypeRegistry.contextTypes();
1008
		if (it.hasNext())
1009
			return ((TemplateContextType) it.next()).getId();
1010
		return null;
1011
	}
1012
1013
	/**
1014
	 * Add a template
1015
	 * 
1016
	 * Setting ui to SHOW_DIALOG will force a New dialog. Setting it to
1017
	 * MAY_HIDE_DIALOG will respect the show new dialog on drop option.
1018
	 * 
1019
	 * @param template
1020
	 * @param ui
1021
	 */
1022
	private void addTemplate(Template template, int ui) {
1023
		Template newTemplate;
1024
		if (ui == SHOW_DIALOG || fShowNewDialogOnDropAction.isChecked())
1025
			newTemplate = editTemplate(template, false, true);
1026
		else
1027
			newTemplate = template;
1028
		if (newTemplate != null) {
1029
			TemplatePersistenceData data = new TemplatePersistenceData(
1030
					newTemplate, true);
1031
			fTemplateStore.add(data);
1032
			saveTemplateStore();
1033
			fSelectedTemplateList.clear();
1034
			fSelectedTemplateList.add(data);
1035
			changeSelection();
1036
		}
1037
	}
1038
1039
	/**
1040
	 * Save the template store
1041
	 */
1042
	private void saveTemplateStore() {
1043
		try {
1044
			fTemplateStore.save();
1045
		} catch (IOException e) {
1046
			e.printStackTrace();
1047
			MessageDialog
1048
					.openError(
1049
							getShell(),
1050
							TextEditorTemplateMessages.TemplatesPage_save_error_message,
1051
							e.getMessage());
1052
		}
1053
	}
1054
1055
	/**
1056
	 * Change selection in the viewer. oldData will contain the earlier selected
1057
	 * template and fCurrentTemplateData will hold the current selection. Either
1058
	 * can be null.
1059
	 * 
1060
	 */
1061
	private void changeSelection() {
1062
		fTreeViewer.refresh();
1063
		if (isSingleTemplateSelected())
1064
			fTreeViewer.setSelection(new StructuredSelection(
1065
					fSelectedTemplateList.get(0)), true);
1066
		else
1067
			fTreeViewer.setSelection(new StructuredSelection());
1068
		updateSelectedTemplate();
1069
	}
1070
1071
	/**
1072
	 * Creates the edit dialog. Subclasses may override this method to provide a
1073
	 * custom dialog.
1074
	 * 
1075
	 * @param template
1076
	 *            the template being edited
1077
	 * @param edit
1078
	 *            whether the dialog should be editable
1079
	 * @param isNameModifiable
1080
	 *            whether the template name may be modified
1081
	 * @return the created or modified template, or <code>null</code> if the
1082
	 *         edition failed
1083
	 * @since 3.1
1084
	 */
1085
	protected Template editTemplate(Template template, boolean edit,
1086
			boolean isNameModifiable) {
1087
		EditTemplateDialog dialog = new EditTemplateDialog(getShell(),
1088
				template, edit, isNameModifiable, fContextTypeRegistry);
1089
		if (dialog.open() == Window.OK) {
1090
			return dialog.getTemplate();
1091
		}
1092
		return null;
1093
	}
1094
1095
	/**
1096
	 * Edit the current template
1097
	 */
1098
	private void editTemplate() {
1099
		Template oldTemplate = getSelectedTemplate();
1100
		Template newTemplate = editTemplate(new Template(oldTemplate), true,
1101
				true);
1102
		if (newTemplate != null) {
1103
			if (!newTemplate.getName().equals(oldTemplate.getName())
1104
					&& MessageDialog
1105
							.openQuestion(
1106
									getShell(),
1107
									TextEditorTemplateMessages.TemplatesPage_question_create_new_title,
1108
									TextEditorTemplateMessages.TemplatesPage_question_create_new_message)) {
1109
				fSelectedTemplateList.clear();
1110
				TemplatePersistenceData templateData = new TemplatePersistenceData(
1111
						newTemplate, true);
1112
				fSelectedTemplateList.add(templateData);
1113
				fTemplateStore.add(templateData);
1114
			} else {
1115
				((TemplatePersistenceData) fSelectedTemplateList.get(0))
1116
						.setTemplate(newTemplate);
1117
			}
1118
			changeSelection();
1119
		}
1120
		saveTemplateStore();
1121
	}
1122
1123
	/**
1124
	 * Remove the currently selected templates
1125
	 */
1126
	private void removeTemplate() {
1127
		if (!MessageDialog.openQuestion(getShell(),
1128
				TextEditorTemplateMessages.TemplatesPage_remove_title,
1129
				TextEditorTemplateMessages.TemplatesPage_remove_message))
1130
			return;
1131
		for (Iterator iterator = fSelectedTemplateList.iterator(); iterator
1132
				.hasNext();) {
1133
			TemplatePersistenceData data = (TemplatePersistenceData) iterator
1134
					.next();
1135
			fTemplateStore.delete(data);
1136
		}
1137
		saveTemplateStore();
1138
		fSelectedTemplateList.clear();
1139
		changeSelection();
1140
	}
1141
1142
	/**
1143
	 * Get the pattern viewer. Subclass can override
1144
	 * 
1145
	 * @return the viewer
1146
	 */
1147
	protected SourceViewer getViewer() {
1148
		return fPatternViewer;
1149
	}
1150
1151
	/*
1152
	 * (non-Javadoc)
1153
	 * 
1154
	 * @see org.eclipse.ui.part.Page#getControl()
1155
	 */
1156
	public Control getControl() {
1157
		return fControl;
1158
	}
1159
1160
	/**
1161
	 * Subclasses should override and facilitate inserting the template code
1162
	 * into the active editor.
1163
	 * 
1164
	 * @param template
1165
	 */
1166
	public void insertTemplate(Template template) {
1167
	}
1168
1169
	/**
1170
	 * The caret position in the editor has moved into a new context type. It is
1171
	 * the subclasses responsibility to see that this is called only when needed
1172
	 * by keeping track of editor contents (eg. partitions).
1173
	 * 
1174
	 * @param ids
1175
	 */
1176
	protected void contextTypeChanged(String[] ids) {
1177
		fActiveTypes = Arrays.asList(ids);
1178
		if (fLinkAction != null && fLinkAction.isChecked())
1179
			refresh();
1180
	}
1181
1182
	/**
1183
	 * Setup the drop target for the table
1184
	 */
1185
	private void initializeDND() {
1186
		DragSourceAdapter dragListener = new DragSourceAdapter() {
1187
			public void dragSetData(DragSourceEvent event) {
1188
				if (isSingleTemplateSelected()
1189
						&& TemplateTransfer.getInstance().isSupportedType(
1190
								event.dataType)) {
1191
					event.data = new Template[] { getSelectedTemplate() };
1192
				}
1193
			}
1194
		};
1195
		fTreeViewer
1196
				.addDragSupport(DND.DROP_COPY,
1197
						new Transfer[] { TemplateTransfer.getInstance() },
1198
						dragListener);
1199
		DropTargetAdapter dropListener = new DropTargetAdapter() {
1200
			TextTransfer textTransfer = TextTransfer.getInstance();
1201
1202
			public void dragEnter(DropTargetEvent event) {
1203
				if (event.detail == DND.DROP_DEFAULT)
1204
					event.detail = DND.DROP_COPY;
1205
			}
1206
1207
			public void dragOperationChanged(DropTargetEvent event) {
1208
				if (event.detail == DND.DROP_DEFAULT)
1209
					event.detail = DND.DROP_COPY;
1210
			}
1211
1212
			public void dragOver(DropTargetEvent event) {
1213
				event.detail = DND.DROP_NONE;
1214
				if (event.item == null)
1215
					return;
1216
				int index = 0;
1217
				while (index < event.dataTypes.length) {
1218
					if (textTransfer.isSupportedType(event.dataTypes[index]))
1219
						break;
1220
					index++;
1221
				}
1222
				if (index < event.dataTypes.length) {
1223
					event.currentDataType = event.dataTypes[index];
1224
					event.detail = DND.DROP_COPY;
1225
					return;
1226
				}
1227
			}
1228
1229
			public void drop(DropTargetEvent event) {
1230
				if (event.item == null)
1231
					return;
1232
				TreeItem item = (TreeItem) event.item;
1233
				String contextId;
1234
				if (item.getParentItem() == null)
1235
					contextId = findContextIdByName(item.getText(0));
1236
				else
1237
					contextId = findContextIdByName(item.getParentItem()
1238
							.getText(0));
1239
				if (textTransfer.isSupportedType(event.currentDataType)) {
1240
					String text = (String) event.data;
1241
					final Template template = new Template(
1242
							TextEditorTemplateMessages.TemplatesPage_snippet,
1243
							TextEditorTemplateMessages.TemplatesPage_paste_description,
1244
							contextId, text, true);
1245
					getShell().getDisplay().asyncExec(new Runnable() {
1246
						public void run() {
1247
							addTemplate(template, HIDE_DIALOG);
1248
						}
1249
					});
1250
				}
1251
			}
1252
1253
			private String findContextIdByName(String contextName) {
1254
				String contextId = null;
1255
				for (Iterator iterator = fContextTypeRegistry.contextTypes(); iterator
1256
						.hasNext();) {
1257
					TemplateContextType contextType = (TemplateContextType) iterator
1258
							.next();
1259
					if (contextType.getName().equals(contextName))
1260
						contextId = contextType.getId();
1261
				}
1262
				return contextId;
1263
			}
1264
		};
1265
		fTreeViewer.addDropSupport(DND.DROP_COPY, new Transfer[] { TextTransfer
1266
				.getInstance() }, dropListener);
1267
	}
1268
1269
	/**
1270
	 * Setup the editor site as a drop target. Should be invoked by the
1271
	 * subclasses for the D&D to work with the editor.
1272
	 * 
1273
	 * @param site
1274
	 * @param viewer
1275
	 */
1276
	protected void setupEditorDropTarget(IWorkbenchPartSite site, Control viewer) {
1277
		IDragAndDropService dndService = (IDragAndDropService) site
1278
				.getService(IDragAndDropService.class);
1279
		EditorDropTarget editorDropTarget = new EditorDropTarget();
1280
		dndService.addMergedDropTarget(viewer, DND.DROP_COPY,
1281
				new Transfer[] { TemplateTransfer.getInstance() },
1282
				editorDropTarget);
1283
	}
1284
1285
	private void refresh() {
1286
		fTreeViewer.refresh();
1287
		setDisableItemColors();
1288
	}
1289
}
(-)src/org/eclipse/ui/texteditor/templates/EditTemplateDialog.java (+598 lines)
Added Link Here
1
package org.eclipse.ui.texteditor.templates;
2
3
import java.util.ArrayList;
4
import java.util.HashMap;
5
import java.util.Iterator;
6
import java.util.List;
7
import java.util.Map;
8
9
import org.eclipse.jface.action.Action;
10
import org.eclipse.jface.action.GroupMarker;
11
import org.eclipse.jface.action.IAction;
12
import org.eclipse.jface.action.IMenuListener;
13
import org.eclipse.jface.action.IMenuManager;
14
import org.eclipse.jface.action.MenuManager;
15
import org.eclipse.jface.action.Separator;
16
import org.eclipse.jface.dialogs.IDialogSettings;
17
import org.eclipse.jface.dialogs.StatusDialog;
18
import org.eclipse.jface.text.Document;
19
import org.eclipse.jface.text.IDocument;
20
import org.eclipse.jface.text.ITextListener;
21
import org.eclipse.jface.text.ITextOperationTarget;
22
import org.eclipse.jface.text.ITextViewer;
23
import org.eclipse.jface.text.TextEvent;
24
import org.eclipse.jface.text.contentassist.ContentAssistant;
25
import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
26
import org.eclipse.jface.text.contentassist.IContentAssistant;
27
import org.eclipse.jface.text.source.ISourceViewer;
28
import org.eclipse.jface.text.source.SourceViewer;
29
import org.eclipse.jface.text.source.SourceViewerConfiguration;
30
import org.eclipse.jface.text.templates.ContextTypeRegistry;
31
import org.eclipse.jface.text.templates.Template;
32
import org.eclipse.jface.text.templates.TemplateContextType;
33
import org.eclipse.jface.text.templates.TemplateException;
34
import org.eclipse.jface.viewers.ISelectionChangedListener;
35
import org.eclipse.jface.viewers.SelectionChangedEvent;
36
import org.eclipse.swt.SWT;
37
import org.eclipse.swt.custom.StyledText;
38
import org.eclipse.swt.custom.VerifyKeyListener;
39
import org.eclipse.swt.events.FocusEvent;
40
import org.eclipse.swt.events.FocusListener;
41
import org.eclipse.swt.events.ModifyEvent;
42
import org.eclipse.swt.events.ModifyListener;
43
import org.eclipse.swt.events.SelectionEvent;
44
import org.eclipse.swt.events.SelectionListener;
45
import org.eclipse.swt.events.VerifyEvent;
46
import org.eclipse.swt.layout.GridData;
47
import org.eclipse.swt.layout.GridLayout;
48
import org.eclipse.swt.widgets.Button;
49
import org.eclipse.swt.widgets.Combo;
50
import org.eclipse.swt.widgets.Composite;
51
import org.eclipse.swt.widgets.Control;
52
import org.eclipse.swt.widgets.Label;
53
import org.eclipse.swt.widgets.Menu;
54
import org.eclipse.swt.widgets.Shell;
55
import org.eclipse.swt.widgets.Text;
56
import org.eclipse.swt.widgets.Widget;
57
import org.eclipse.ui.internal.texteditor.TextEditorPlugin;
58
import org.eclipse.ui.texteditor.ITextEditorActionConstants;
59
import org.eclipse.ui.texteditor.IUpdate;
60
61
/**
62
	 * Dialog to edit a template. Clients will usually instantiate, but
63
	 * may also extend.
64
	 *
65
	 * @since 3.3
66
	 */
67
	public class EditTemplateDialog extends StatusDialog {
68
69
		private class TextViewerAction extends Action implements IUpdate {
70
71
			private int fOperationCode= -1;
72
			private ITextOperationTarget fOperationTarget;
73
74
			/**
75
			 * Creates a new action.
76
			 *
77
			 * @param viewer the viewer
78
			 * @param operationCode the opcode
79
			 */
80
			public TextViewerAction(ITextViewer viewer, int operationCode) {
81
				fOperationCode= operationCode;
82
				fOperationTarget= viewer.getTextOperationTarget();
83
				update();
84
			}
85
86
			/**
87
			 * Updates the enabled state of the action.
88
			 * Fires a property change if the enabled state changes.
89
			 *
90
			 * @see Action#firePropertyChange(String, Object, Object)
91
			 */
92
			public void update() {
93
94
				boolean wasEnabled= isEnabled();
95
				boolean isEnabled= (fOperationTarget != null && fOperationTarget.canDoOperation(fOperationCode));
96
				setEnabled(isEnabled);
97
98
				if (wasEnabled != isEnabled) {
99
					firePropertyChange(ENABLED, wasEnabled ? Boolean.TRUE : Boolean.FALSE, isEnabled ? Boolean.TRUE : Boolean.FALSE);
100
				}
101
			}
102
103
			/**
104
			 * @see Action#run()
105
			 */
106
			public void run() {
107
				if (fOperationCode != -1 && fOperationTarget != null) {
108
					fOperationTarget.doOperation(fOperationCode);
109
				}
110
			}
111
		}
112
113
		private final Template fOriginalTemplate;
114
115
		private Text fNameText;
116
		private Text fDescriptionText;
117
		private Combo fContextCombo;
118
		private SourceViewer fPatternEditor;
119
		private Button fInsertVariableButton;
120
		private Button fAutoInsertCheckbox;
121
		private boolean fIsNameModifiable;
122
123
		private StatusInfo fValidationStatus;
124
		private boolean fSuppressError= true; // #4354
125
		private Map fGlobalActions= new HashMap(10);
126
		private List fSelectionActions = new ArrayList(3);
127
		private String[][] fContextTypes;
128
129
		private ContextTypeRegistry fContextTypeRegistry;
130
131
		private final TemplateVariableProcessor fTemplateProcessor= new TemplateVariableProcessor();
132
133
		private Template fNewTemplate;
134
135
		/**
136
		 * Creates a new dialog.
137
		 *
138
		 * @param parent the shell parent of the dialog
139
		 * @param template the template to edit
140
		 * @param edit whether this is a new template or an existing being edited
141
		 * @param isNameModifiable whether the name of the template may be modified
142
		 * @param registry the context type registry to use
143
		 */
144
		public EditTemplateDialog(Shell parent, Template template, boolean edit, boolean isNameModifiable, ContextTypeRegistry registry) {
145
			super(parent);
146
147
			setShellStyle(getShellStyle() | SWT.MAX | SWT.RESIZE);
148
149
			String title= edit
150
				? TextEditorTemplateMessages.EditTemplateDialog_title_edit
151
				: TextEditorTemplateMessages.EditTemplateDialog_title_new;
152
			setTitle(title);
153
154
			fOriginalTemplate= template;
155
			fIsNameModifiable= isNameModifiable;
156
157
			List contexts= new ArrayList();
158
			for (Iterator it= registry.contextTypes(); it.hasNext();) {
159
				TemplateContextType type= (TemplateContextType) it.next();
160
				contexts.add(new String[] { type.getId(), type.getName() });
161
			}
162
			fContextTypes= (String[][]) contexts.toArray(new String[contexts.size()][]);
163
164
			fValidationStatus= new StatusInfo();
165
166
			fContextTypeRegistry= registry;
167
168
			TemplateContextType type= fContextTypeRegistry.getContextType(template.getContextTypeId());
169
			fTemplateProcessor.setContextType(type);
170
		}
171
172
		/*
173
		 * @see org.eclipse.ui.texteditor.templates.StatusDialog#create()
174
		 */
175
		public void create() {
176
			super.create();
177
			// update initial OK button to be disabled for new templates
178
			boolean valid= fNameText == null || fNameText.getText().trim().length() != 0;
179
			if (!valid) {
180
				StatusInfo status = new StatusInfo();
181
				status.setError(TextEditorTemplateMessages.EditTemplateDialog_error_noname);
182
				updateButtonsEnableState(status);
183
	 		}
184
		}
185
186
		/*
187
		 * @see Dialog#createDialogArea(Composite)
188
		 */
189
		protected Control createDialogArea(Composite ancestor) {
190
			Composite parent= new Composite(ancestor, SWT.NONE);
191
			GridLayout layout= new GridLayout();
192
			layout.numColumns= 2;
193
			parent.setLayout(layout);
194
			parent.setLayoutData(new GridData(GridData.FILL_BOTH));
195
196
			ModifyListener listener= new ModifyListener() {
197
				public void modifyText(ModifyEvent e) {
198
					doTextWidgetChanged(e.widget);
199
				}
200
			};
201
202
			if (fIsNameModifiable) {
203
				createLabel(parent, TextEditorTemplateMessages.EditTemplateDialog_name);
204
205
				Composite composite= new Composite(parent, SWT.NONE);
206
				composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
207
				layout= new GridLayout();
208
				layout.numColumns= 4;
209
				layout.marginWidth= 0;
210
				layout.marginHeight= 0;
211
				composite.setLayout(layout);
212
213
				fNameText= createText(composite);
214
				fNameText.addModifyListener(listener);
215
				fNameText.addFocusListener(new FocusListener() {
216
217
					public void focusGained(FocusEvent e) {
218
					}
219
220
					public void focusLost(FocusEvent e) {
221
						if (fSuppressError) {
222
							fSuppressError= false;
223
							updateButtons();
224
						}
225
					}
226
				});
227
228
				createLabel(composite, TextEditorTemplateMessages.EditTemplateDialog_context);
229
				fContextCombo= new Combo(composite, SWT.READ_ONLY);
230
231
				for (int i= 0; i < fContextTypes.length; i++) {
232
					fContextCombo.add(fContextTypes[i][1]);
233
				}
234
235
				fContextCombo.addModifyListener(listener);
236
				
237
				fAutoInsertCheckbox= createCheckbox(composite, TextEditorTemplateMessages.EditTemplateDialog_autoinsert);
238
				fAutoInsertCheckbox.setSelection(fOriginalTemplate.isAutoInsertable());
239
			}
240
241
			createLabel(parent, TextEditorTemplateMessages.EditTemplateDialog_description);
242
243
			int descFlags= fIsNameModifiable ? SWT.BORDER : SWT.BORDER | SWT.READ_ONLY;
244
			fDescriptionText= new Text(parent, descFlags );
245
			fDescriptionText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
246
247
			fDescriptionText.addModifyListener(listener);
248
249
			Label patternLabel= createLabel(parent, TextEditorTemplateMessages.EditTemplateDialog_pattern);
250
			patternLabel.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING));
251
			fPatternEditor= createEditor(parent, fOriginalTemplate.getPattern());
252
253
			Label filler= new Label(parent, SWT.NONE);
254
			filler.setLayoutData(new GridData());
255
256
			Composite composite= new Composite(parent, SWT.NONE);
257
			layout= new GridLayout();
258
			layout.marginWidth= 0;
259
			layout.marginHeight= 0;
260
			composite.setLayout(layout);
261
			composite.setLayoutData(new GridData());
262
263
			fInsertVariableButton= new Button(composite, SWT.NONE);
264
			fInsertVariableButton.setLayoutData(getButtonGridData(fInsertVariableButton));
265
			fInsertVariableButton.setText(TextEditorTemplateMessages.EditTemplateDialog_insert_variable);
266
			fInsertVariableButton.addSelectionListener(new SelectionListener() {
267
				public void widgetSelected(SelectionEvent e) {
268
					fPatternEditor.getTextWidget().setFocus();
269
					fPatternEditor.doOperation(ISourceViewer.CONTENTASSIST_PROPOSALS);
270
				}
271
272
				public void widgetDefaultSelected(SelectionEvent e) {}
273
			});
274
275
			fDescriptionText.setText(fOriginalTemplate.getDescription());
276
			if (fIsNameModifiable) {
277
				fNameText.setText(fOriginalTemplate.getName());
278
				fNameText.addModifyListener(listener);
279
				fContextCombo.select(getIndex(fOriginalTemplate.getContextTypeId()));
280
			} else {
281
				fPatternEditor.getControl().setFocus();
282
			}
283
			initializeActions();
284
285
			applyDialogFont(parent);
286
			return composite;
287
		}
288
289
		private void doTextWidgetChanged(Widget w) {
290
			if (w == fNameText) {
291
				fSuppressError= false;
292
				updateButtons();
293
			} else if (w == fContextCombo) {
294
				String contextId= getContextId();
295
				fTemplateProcessor.setContextType(fContextTypeRegistry.getContextType(contextId));
296
			} else if (w == fDescriptionText) {
297
				// oh, nothing
298
			}
299
		}
300
301
		private String getContextId() {
302
			if (fContextCombo != null && !fContextCombo.isDisposed()) {
303
				String name= fContextCombo.getText();
304
				for (int i= 0; i < fContextTypes.length; i++) {
305
					if (name.equals(fContextTypes[i][1])) {
306
						return fContextTypes[i][0];
307
					}
308
				}
309
			}
310
311
			return fOriginalTemplate.getContextTypeId();
312
		}
313
314
		private void doSourceChanged(IDocument document) {
315
			String text= document.get();
316
			fValidationStatus.setOK();
317
			TemplateContextType contextType= fContextTypeRegistry.getContextType(getContextId());
318
			if (contextType != null) {
319
				try {
320
					contextType.validate(text);
321
				} catch (TemplateException e) {
322
					fValidationStatus.setError(e.getLocalizedMessage());
323
				}
324
			}
325
326
			updateUndoAction();
327
			updateButtons();
328
		}
329
330
		private static GridData getButtonGridData(Button button) {
331
			GridData data= new GridData(GridData.FILL_HORIZONTAL);
332
			// TODO get some button hints.
333
//			data.heightHint= SWTUtil.getButtonHeightHint(button);
334
335
			return data;
336
		}
337
338
		private static Label createLabel(Composite parent, String name) {
339
			Label label= new Label(parent, SWT.NULL);
340
			label.setText(name);
341
			label.setLayoutData(new GridData());
342
343
			return label;
344
		}
345
346
		private static Text createText(Composite parent) {
347
			Text text= new Text(parent, SWT.BORDER);
348
			text.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
349
350
			return text;
351
		}
352
353
		private static Button createCheckbox(Composite parent, String name) {
354
			Button button= new Button(parent, SWT.CHECK);
355
			button.setText(name);
356
			button.setLayoutData(new GridData());
357
			
358
			return button;
359
		}
360
		
361
		private SourceViewer createEditor(Composite parent, String pattern) {
362
			SourceViewer viewer= createViewer(parent);
363
			viewer.setEditable(true);
364
			
365
			IDocument document= viewer.getDocument();
366
			if (document != null)
367
				document.set(pattern);
368
			else {
369
				document= new Document(pattern);
370
				viewer.setDocument(document);
371
			}
372
373
			int nLines= document.getNumberOfLines();
374
			if (nLines < 5) {
375
				nLines= 5;
376
			} else if (nLines > 12) {
377
				nLines= 12;
378
			}
379
380
			Control control= viewer.getControl();
381
			GridData data= new GridData(GridData.FILL_BOTH);
382
			data.widthHint= convertWidthInCharsToPixels(80);
383
			data.heightHint= convertHeightInCharsToPixels(nLines);
384
			control.setLayoutData(data);
385
386
			viewer.addTextListener(new ITextListener() {
387
				public void textChanged(TextEvent event) {
388
					if (event .getDocumentEvent() != null)
389
						doSourceChanged(event.getDocumentEvent().getDocument());
390
				}
391
			});
392
393
			viewer.addSelectionChangedListener(new ISelectionChangedListener() {
394
				public void selectionChanged(SelectionChangedEvent event) {
395
					updateSelectionDependentActions();
396
				}
397
			});
398
399
		 	viewer.prependVerifyKeyListener(new VerifyKeyListener() {
400
				public void verifyKey(VerifyEvent event) {
401
					handleVerifyKeyPressed(event);
402
				}
403
			});
404
405
			return viewer;
406
		}
407
408
		/**
409
		 * Creates the viewer to be used to display the pattern. Subclasses may override.
410
		 *
411
		 * @param parent the parent composite of the viewer
412
		 * @return a configured <code>SourceViewer</code>
413
		 */
414
		protected SourceViewer createViewer(Composite parent) {
415
			SourceViewer viewer= new SourceViewer(parent, null, null, false, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
416
			SourceViewerConfiguration configuration= new SourceViewerConfiguration() {
417
				public IContentAssistant getContentAssistant(ISourceViewer sourceViewer) {
418
419
					ContentAssistant assistant= new ContentAssistant();
420
					assistant.enableAutoActivation(true);
421
					assistant.enableAutoInsert(true);
422
					assistant.setContentAssistProcessor(fTemplateProcessor, IDocument.DEFAULT_CONTENT_TYPE);
423
					return assistant;
424
				}
425
			};
426
			viewer.configure(configuration);
427
			return viewer;
428
		}
429
430
		private void handleVerifyKeyPressed(VerifyEvent event) {
431
			if (!event.doit)
432
				return;
433
434
			if (event.stateMask != SWT.MOD1)
435
				return;
436
437
			switch (event.character) {
438
				case ' ':
439
					fPatternEditor.doOperation(ISourceViewer.CONTENTASSIST_PROPOSALS);
440
					event.doit= false;
441
					break;
442
443
				// CTRL-Z
444
				case 'z' - 'a' + 1:
445
					fPatternEditor.doOperation(ITextOperationTarget.UNDO);
446
					event.doit= false;
447
					break;
448
			}
449
		}
450
451
		private void initializeActions() {
452
			TextViewerAction action= new TextViewerAction(fPatternEditor, ITextOperationTarget.UNDO);
453
			action.setText(TextEditorTemplateMessages.EditTemplateDialog_undo);
454
			fGlobalActions.put(ITextEditorActionConstants.UNDO, action);
455
456
			action= new TextViewerAction(fPatternEditor, ITextOperationTarget.CUT);
457
			action.setText(TextEditorTemplateMessages.EditTemplateDialog_cut);
458
			fGlobalActions.put(ITextEditorActionConstants.CUT, action);
459
460
			action= new TextViewerAction(fPatternEditor, ITextOperationTarget.COPY);
461
			action.setText(TextEditorTemplateMessages.EditTemplateDialog_copy);
462
			fGlobalActions.put(ITextEditorActionConstants.COPY, action);
463
464
			action= new TextViewerAction(fPatternEditor, ITextOperationTarget.PASTE);
465
			action.setText(TextEditorTemplateMessages.EditTemplateDialog_paste);
466
			fGlobalActions.put(ITextEditorActionConstants.PASTE, action);
467
468
			action= new TextViewerAction(fPatternEditor, ITextOperationTarget.SELECT_ALL);
469
			action.setText(TextEditorTemplateMessages.EditTemplateDialog_select_all);
470
			fGlobalActions.put(ITextEditorActionConstants.SELECT_ALL, action);
471
472
			action= new TextViewerAction(fPatternEditor, ISourceViewer.CONTENTASSIST_PROPOSALS);
473
			action.setText(TextEditorTemplateMessages.EditTemplateDialog_content_assist);
474
			fGlobalActions.put("ContentAssistProposal", action); //$NON-NLS-1$
475
476
			fSelectionActions.add(ITextEditorActionConstants.CUT);
477
			fSelectionActions.add(ITextEditorActionConstants.COPY);
478
			fSelectionActions.add(ITextEditorActionConstants.PASTE);
479
480
			// create context menu
481
			MenuManager manager= new MenuManager(null, null);
482
			manager.setRemoveAllWhenShown(true);
483
			manager.addMenuListener(new IMenuListener() {
484
				public void menuAboutToShow(IMenuManager mgr) {
485
					fillContextMenu(mgr);
486
				}
487
			});
488
489
			StyledText text= fPatternEditor.getTextWidget();
490
			Menu menu= manager.createContextMenu(text);
491
			text.setMenu(menu);
492
		}
493
494
		private void fillContextMenu(IMenuManager menu) {
495
			menu.add(new GroupMarker(ITextEditorActionConstants.GROUP_UNDO));
496
			menu.appendToGroup(ITextEditorActionConstants.GROUP_UNDO, (IAction) fGlobalActions.get(ITextEditorActionConstants.UNDO));
497
498
			menu.add(new Separator(ITextEditorActionConstants.GROUP_EDIT));
499
			menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, (IAction) fGlobalActions.get(ITextEditorActionConstants.CUT));
500
			menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, (IAction) fGlobalActions.get(ITextEditorActionConstants.COPY));
501
			menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, (IAction) fGlobalActions.get(ITextEditorActionConstants.PASTE));
502
			menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, (IAction) fGlobalActions.get(ITextEditorActionConstants.SELECT_ALL));
503
504
			menu.add(new Separator("templates")); //$NON-NLS-1$
505
			menu.appendToGroup("templates", (IAction) fGlobalActions.get("ContentAssistProposal")); //$NON-NLS-1$ //$NON-NLS-2$
506
		}
507
508
		private void updateSelectionDependentActions() {
509
			Iterator iterator= fSelectionActions.iterator();
510
			while (iterator.hasNext())
511
				updateAction((String)iterator.next());
512
		}
513
514
		private void updateUndoAction() {
515
			IAction action= (IAction) fGlobalActions.get(ITextEditorActionConstants.UNDO);
516
			if (action instanceof IUpdate)
517
				((IUpdate) action).update();
518
		}
519
520
		private void updateAction(String actionId) {
521
			IAction action= (IAction) fGlobalActions.get(actionId);
522
			if (action instanceof IUpdate)
523
				((IUpdate) action).update();
524
		}
525
526
		private int getIndex(String contextid) {
527
528
			if (contextid == null)
529
				return -1;
530
531
			for (int i= 0; i < fContextTypes.length; i++) {
532
				if (contextid.equals(fContextTypes[i][0])) {
533
					return i;
534
				}
535
			}
536
			return -1;
537
		}
538
539
		private void updateButtons() {
540
			StatusInfo status;
541
542
			boolean valid= fNameText == null || fNameText.getText().trim().length() != 0;
543
			if (!valid) {
544
				status = new StatusInfo();
545
				if (!fSuppressError) {
546
					status.setError(TextEditorTemplateMessages.EditTemplateDialog_error_noname);
547
				}
548
	 		} else {
549
	 			status= fValidationStatus;
550
	 		}
551
			updateStatus(status);
552
		}
553
554
		/*
555
		 * @since 3.1
556
		 */
557
		protected void okPressed() {
558
			String name= fNameText == null ? fOriginalTemplate.getName() : fNameText.getText();
559
			boolean isAutoInsertable= fAutoInsertCheckbox != null && fAutoInsertCheckbox.getSelection();
560
			fNewTemplate= new Template(name, fDescriptionText.getText(), getContextId(), fPatternEditor.getDocument().get(), isAutoInsertable);
561
			super.okPressed();
562
		}
563
564
		/**
565
		 * Returns the created template.
566
		 *
567
		 * @return the created template
568
		 * @since 3.1
569
		 */
570
		public Template getTemplate() {
571
			return fNewTemplate;
572
		}
573
		
574
		/**
575
		 * Returns the content assist processor that
576
		 * suggests template variables.
577
		 * 
578
		 * @return the processor to suggest variables
579
		 * @since 3.3
580
		 */
581
		protected IContentAssistProcessor getTemplateProcessor() {
582
			return fTemplateProcessor;
583
		}
584
585
		/*
586
		 * @see org.eclipse.jface.dialogs.Dialog#getDialogBoundsSettings()
587
		 * @since 3.2
588
		 */
589
		protected IDialogSettings getDialogBoundsSettings() {
590
			String sectionName= this.getClass().getName() + "_dialogBounds"; //$NON-NLS-1$
591
			IDialogSettings settings= TextEditorPlugin.getDefault().getDialogSettings();
592
			IDialogSettings section= settings.getSection(sectionName);
593
			if (section == null)
594
				section= settings.addNewSection(sectionName);
595
			return section;
596
		}
597
598
	}
(-)icons/full/elcl16/edit_template.gif (+7 lines)
Added Link Here
1
GIF89aæôöüõ÷üôöûêïúðóúg}©ùúümƒ­tŠ³s‰²€•»–»ŠžÂáé÷äëø‡œÀ¢Ä‘¥Ç³ÀÖ·ÄÙ½ÉÝÞèøßè÷éïùóöûðôúöøûïôûõøüô÷ûéðù"Cgìòùõøû÷ùûÛÓ¡»´Š|p>{o>{p>†v<ƒs<q=|o>~Bš7y9Œw:©I–|8ܵVÄ£Oàȏ²Š0¯‰1¬‡2¨…3Ú=Û±NÔ²hÔ²iÚ½|Õ²iðبéÄ~öæȓ|W”]•`“xQi8Ži8l>m>pCpD’tJi9ÿÿÿ!ùN,ž€N‚ƒ„…„5ˆ‰ˆ†‚5<5Œ9=>“ƒAD:"
2
4=;6ƒ?AC®!7ƒ@ªB	8ƒE·AEÉ-„LÅL½¿ 1…K·#J.…2I$$H¾ /…3FGMõ(…0
3
 
4
ÿ
5
Rba¡`Á
6
7
ª(db…‰%Nœ(±Â!£‹ƒ;
(-)icons/full/elcl16/collapse_expand_all.gif (+5 lines)
Added Link Here
1
GIF89aÕ"·Òä>r§2]’z9¯‰1©…3 5¤ƒ4œ5¬‡2w9²Š0}q=~p=–|7p†°iªs‰²mƒ®k¬ôüÿøýÿþþÿüÿÿùýÿöüÿwŒ´uŠ²úþÿüþÿýþÿ~q=(b–ùþÿÿÿÿ!ù",p@‘P$ ‹Å¡p°. X(E„€'À	T”ášð˜ÏçĵÐi»Ý…ë!D¯×WCÄïƒBW!!W{~|!Wv—W
2
—v
3
WœuŸ¡t£J ¥§J
4
5
±±W´µ"A;
(-)src/org/eclipse/ui/texteditor/templates/ITemplateViewImageConstants.java (+19 lines)
Added Link Here
1
package org.eclipse.ui.texteditor.templates;
2
3
import org.eclipse.ui.internal.texteditor.TextEditorPlugin;
4
5
/**
6
 * Image constants for the template page
7
 * 
8
 * @author kd
9
 * 
10
 */
11
public interface ITemplateViewImageConstants {
12
	public static final String PREFIX = TextEditorPlugin.PLUGIN_ID + "."; //$NON-NLS-1$
13
14
	public final static String IMG_TEMPLATE_NEW = PREFIX + "new_template.gif"; //$NON-NLS-1$
15
	public static final String IMG_TEMPLATE_DELETE = "delete_template.gif"; //$NON-NLS-1$
16
	public final static String IMG_TEMPLATE_EDIT = PREFIX + "edit_template.gif"; //$NON-NLS-1$
17
	public static final String IMG_TEMPLATE_LINK = "link_to_editor.gif"; //$NON-NLS-1$
18
	public static final String IMG_TEMPLATE_COLLAPSE_EXPAND = "collapse_expand_all.gif"; //$NON-NLS-1$
19
}
(-)icons/full/elcl16/link_to_editor.gif (+1 lines)
Added Link Here
1
GIF89a³½„ªo¦küì±ûå—üñÃýñÃþýïüê©ýöÕº—&þøÞþøÝýøÝûì±ÿÿÿ!ù,MðÉÀ¼˜›18[wL³Th5†Á/\bx>cAì¢IHQˆp#€18ù¨<©JbʑŽv»­>à°ÀG0¿>óy¬^·;
(-)src/org/eclipse/ui/texteditor/templates/TemplateTransfer.java (+179 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2004, 2005 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
10
 *******************************************************************************/
11
package org.eclipse.ui.texteditor.templates;
12
13
import java.io.ByteArrayInputStream;
14
import java.io.ByteArrayOutputStream;
15
import java.io.DataInputStream;
16
import java.io.DataOutputStream;
17
import java.io.IOException;
18
import java.util.ArrayList;
19
20
import org.eclipse.jface.text.templates.Template;
21
import org.eclipse.swt.dnd.ByteArrayTransfer;
22
import org.eclipse.swt.dnd.TransferData;
23
24
/**
25
 * Transfer type used for clip board and DnD operations for template objects
26
 * 
27
 * @see TemplatesPage
28
 * 
29
 */
30
public class TemplateTransfer extends ByteArrayTransfer {
31
32
	private static TemplateTransfer instance;
33
34
	private static final String LOCAL_NAME = TemplateTransfer.class.getName()
35
			+ System.currentTimeMillis();
36
	private static final int LOCAL_TYPE = registerType(LOCAL_NAME);
37
38
	private static String[] names = null;
39
	private static int types[] = null;
40
41
	/**
42
	 * @return the registered Transfer instance
43
	 */
44
	public static TemplateTransfer getInstance() {
45
		if (instance == null) {
46
			instance = new TemplateTransfer();
47
			types = new int[] { LOCAL_TYPE };
48
			names = new String[] { LOCAL_NAME };
49
		}
50
		return instance;
51
	}
52
53
	/*
54
	 * (non-Javadoc)
55
	 * 
56
	 * @see org.eclipse.swt.dnd.Transfer#getTypeIds()
57
	 */
58
	protected int[] getTypeIds() {
59
		return types;
60
	}
61
62
	/*
63
	 * (non-Javadoc)
64
	 * 
65
	 * @see org.eclipse.swt.dnd.Transfer#getTypeNames()
66
	 */
67
	protected String[] getTypeNames() {
68
		return names;
69
	}
70
71
	/*
72
	 * (non-Javadoc)
73
	 * 
74
	 * @see org.eclipse.swt.dnd.ByteArrayTransfer#javaToNative(java.lang.Object,
75
	 *      org.eclipse.swt.dnd.TransferData)
76
	 */
77
	protected void javaToNative(Object object, TransferData transferData) {
78
		if (object == null || !(object instanceof Template[])
79
				|| !isSupportedType(transferData))
80
			return;
81
		ByteArrayOutputStream out = new ByteArrayOutputStream();
82
		DataOutputStream dataOut = new DataOutputStream(out);
83
		Template[] templates = (Template[]) object;
84
		for (int i = 0; i < templates.length; i++) {
85
			writeTemplate(dataOut, templates[i]);
86
		}
87
		byte[] byteArray = out.toByteArray();
88
		try {
89
			dataOut.close();
90
		} catch (IOException e) {
91
		}
92
		super.javaToNative(byteArray, transferData);
93
	}
94
95
	/**
96
	 * Write a template to the output stream
97
	 * 
98
	 * @param dataOut
99
	 * @param template
100
	 */
101
	private void writeTemplate(DataOutputStream dataOut, Template template) {
102
		try {
103
			writeString(dataOut, template.getName());
104
			writeString(dataOut, template.getDescription());
105
			writeString(dataOut, template.getContextTypeId());
106
			writeString(dataOut, template.getPattern());
107
			dataOut.writeBoolean(template.isAutoInsertable());
108
		} catch (IOException e) {
109
		}
110
	}
111
112
	/**
113
	 * Write a string to the output stream
114
	 * 
115
	 * @param dataOut
116
	 * @param name
117
	 * @throws IOException
118
	 */
119
	private void writeString(DataOutputStream dataOut, String name)
120
			throws IOException {
121
		byte[] bytes = name.getBytes();
122
		dataOut.writeInt(bytes.length);
123
		dataOut.write(bytes);
124
	}
125
126
	/*
127
	 * (non-Javadoc)
128
	 * 
129
	 * @see org.eclipse.swt.dnd.ByteArrayTransfer#nativeToJava(org.eclipse.swt.dnd.TransferData)
130
	 */
131
	protected Object nativeToJava(TransferData transferData) {
132
		byte[] bytes = (byte[]) super.nativeToJava(transferData);
133
		if (bytes == null)
134
			return null;
135
		ArrayList listTemplates = new ArrayList();
136
		ByteArrayInputStream in = new ByteArrayInputStream(bytes);
137
		DataInputStream dataIn = new DataInputStream(in);
138
		try {
139
			while (dataIn.available() > 0) {
140
				Template template = readTempate(dataIn);
141
				if (template == null)
142
					break;
143
				listTemplates.add(template);
144
			}
145
		} catch (IOException e) {
146
		} finally {
147
			try {
148
				dataIn.close();
149
			} catch (IOException e) {
150
			}
151
		}
152
		return listTemplates.toArray(new Template[listTemplates.size()]);
153
	}
154
155
	/**
156
	 * Read a template from the data input stream.
157
	 * 
158
	 * @param dataIn
159
	 * @return the template
160
	 * @throws IOException
161
	 */
162
	private Template readTempate(DataInputStream dataIn) throws IOException {
163
		return new Template(readString(dataIn), readString(dataIn),
164
				readString(dataIn), readString(dataIn), dataIn.readBoolean());
165
	}
166
167
	/**
168
	 * Read a string from the data input stream
169
	 * 
170
	 * @param dataIn
171
	 * @return the string
172
	 * @throws IOException
173
	 */
174
	private String readString(DataInputStream dataIn) throws IOException {
175
		byte[] bytes = new byte[dataIn.readInt()];
176
		dataIn.read(bytes);
177
		return new String(bytes);
178
	}
179
}
(-)icons/full/elcl16/new_template.gif (+4 lines)
Added Link Here
1
GIF89a櫤©ª£¨ª¢¨¶°µ´®³²¬±°ª¯®¨­¬¦«¬¥««¤ªª¢©²¬²°ª°·²·µ±µ³¯´¹µº¸´¹†“°†“¯…“°†”°…“¯†”¯ˆ•®…”°…”¯ˆ•­Œ—«˜«š¨•¥íùÿðúÿ™Ÿ¢óûÿöüÿìùÿïúÿëùÿîúÿñûÿšŸ¡õüÿøýÿìúÿôüÿëúÿïûÿóüÿ÷ýÿòüÿŸ£Ÿž¢ž£¦›£¥›¨¨˜­¬”¹·£¹³‹¶±Ž²®‘®«”³°šº·¢¼µŠ¶°Â¿­Á¾­¿¶ˆ³¯šº¶£ÊǸ¾­ÓÐÃËǸËǹÜÙÏÔÐÄÜÙÐäáÙàȏÝÙÏÔ²iÚ½|ÜØÏåáÙëèâåàÙëçâðìèÿÿÿ!ù\,²€\‚ƒ„…ƒFˆ‰‰†\B--TF†<3˜™UT<…=%[¢¢R›C„>%ZXZ¬Z%>„:/YWQ¹Q,?„92SNPVVN/9„74OÑKÑ$8„5*
2
IÜLIM*6„#"EDDJJE1+„ );HHõA	' „!
3
@Ž@Š„<¸°@€Ã‡!:ʀŒŠ(L¸p‚¡	4P¸€ä†4
4
;
(-)icons/full/elcl16/delete_template.gif (+5 lines)
Added Link Here
1
GIF89aÕÇ35ôqtôstórtósuØ*/à,4ß,3Ç)0æ6>å6>Å +å09òU`ôckócjóckódkÅ'Æ(Å'Æ ,òT`Å%ñ?Rð?QòHXñHXÔetߜ¨Ê]IÎn^ÊWFÊXFÉXFՈ|ÉPCܦ ÉG>ÉG?ÈG?Ç=9àa[õ}Ç=:ãROõ€~ô€~ãÄÄÿÿÿ!ù1,|À˜pH,F˜gTy`DX¨b
2
G¢*,‘\+Ò§ô!½Â%âE¨LªAàd%rXÈÃñHq
3
4
5
	H1H””E”˜B ¦C0¨C«\B±£B«¹ˆÀÁBA;
(-)src/org/eclipse/ui/texteditor/templates/TemplateViewImages.java (+154 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2006 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 * 
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
10
 *     John-Mason P. Shackelford (john-mason.shackelford@pearson.com) - bug 49380, 49445, 53547
11
 *******************************************************************************/
12
package org.eclipse.ui.texteditor.templates;
13
14
import java.net.URL;
15
16
import org.eclipse.core.runtime.FileLocator;
17
import org.eclipse.core.runtime.Path;
18
import org.eclipse.core.runtime.Platform;
19
import org.eclipse.jface.resource.ImageDescriptor;
20
import org.eclipse.jface.resource.ImageRegistry;
21
import org.eclipse.swt.graphics.Image;
22
import org.eclipse.swt.widgets.Display;
23
import org.eclipse.ui.internal.texteditor.TextEditorPlugin;
24
import org.osgi.framework.Bundle;
25
26
/**
27
 * The images provided by the texteditor plugin
28
 */
29
public class TemplateViewImages {
30
31
	/**
32
	 * The image registry containing <code>Image</code>s.
33
	 */
34
	private static ImageRegistry imageRegistry;
35
36
	private static String ICONS_PATH = "$nl$/icons/full/"; //$NON-NLS-1$
37
38
	// Use IPath and toOSString to build the names to ensure they have the
39
	// slashes correct
40
	private final static String LOCALTOOL = ICONS_PATH + "elcl16/"; //$NON-NLS-1$
41
42
	/**
43
	 * Declare all images
44
	 */
45
	private static void declareImages() {
46
		// Ant Editor images
47
		declareRegistryImage(ITemplateViewImageConstants.IMG_TEMPLATE_NEW,
48
				LOCALTOOL + "new_template.gif"); //$NON-NLS-1$
49
		declareRegistryImage(ITemplateViewImageConstants.IMG_TEMPLATE_DELETE,
50
				LOCALTOOL + "delete_template.gif"); //$NON-NLS-1$
51
		declareRegistryImage(ITemplateViewImageConstants.IMG_TEMPLATE_EDIT,
52
				LOCALTOOL + "edit_template.gif"); //$NON-NLS-1$
53
		declareRegistryImage(ITemplateViewImageConstants.IMG_TEMPLATE_LINK,
54
				LOCALTOOL + "link_to_editor.gif"); //$NON-NLS-1$
55
		declareRegistryImage(
56
				ITemplateViewImageConstants.IMG_TEMPLATE_COLLAPSE_EXPAND,
57
				LOCALTOOL + "collapse_expand_all.gif"); //$NON-NLS-1$
58
	}
59
60
	/**
61
	 * Declare an Image in the registry table.
62
	 * 
63
	 * @param key
64
	 *            The key to use when registering the image
65
	 * @param path
66
	 *            The path where the image can be found. This path is relative
67
	 *            to where this plugin class is found (i.e. typically the
68
	 *            packages directory)
69
	 */
70
	private final static void declareRegistryImage(String key, String path) {
71
		ImageDescriptor desc = ImageDescriptor.getMissingImageDescriptor();
72
		Bundle bundle = Platform.getBundle(TextEditorPlugin.PLUGIN_ID);
73
		URL url = null;
74
		if (bundle != null) {
75
			url = FileLocator.find(bundle, new Path(path), null);
76
			desc = ImageDescriptor.createFromURL(url);
77
		}
78
		imageRegistry.put(key, desc);
79
	}
80
81
	/**
82
	 * Returns the ImageRegistry.
83
	 * 
84
	 * @return image registry
85
	 */
86
	public static ImageRegistry getImageRegistry() {
87
		if (imageRegistry == null) {
88
			initializeImageRegistry();
89
		}
90
		return imageRegistry;
91
	}
92
93
	/**
94
	 * Initialize the image registry by declaring all of the required graphics.
95
	 * This involves creating JFace image descriptors describing how to
96
	 * create/find the image should it be needed. The image is not actually
97
	 * allocated until requested.
98
	 * 
99
	 * Prefix conventions Wizard Banners WIZBAN_ Preference Banners PREF_BAN_
100
	 * Property Page Banners PROPBAN_ Color toolbar CTOOL_ Enable toolbar ETOOL_
101
	 * Disable toolbar DTOOL_ Local enabled toolbar ELCL_ Local Disable toolbar
102
	 * DLCL_ Object large OBJL_ Object small OBJS_ View VIEW_ Product images
103
	 * PROD_ Misc images MISC_
104
	 * 
105
	 * Where are the images? The images (typically gifs) are found in the same
106
	 * location as this plugin class. This may mean the same package directory
107
	 * as the package holding this class. The images are declared using
108
	 * this.getClass() to ensure they are looked up via this plugin class.
109
	 * 
110
	 * @return the image registry
111
	 * @see org.eclipse.jface.resource.ImageRegistry
112
	 */
113
	public static ImageRegistry initializeImageRegistry() {
114
		imageRegistry = new ImageRegistry(getStandardDisplay());
115
		declareImages();
116
		return imageRegistry;
117
	}
118
119
	/**
120
	 * Returns the standard display to be used. The method first checks, if the
121
	 * thread calling this method has an associated display. If so, this display
122
	 * is returned. Otherwise the method returns the default display.
123
	 * 
124
	 * @return the display
125
	 */
126
	public static Display getStandardDisplay() {
127
		Display display = Display.getCurrent();
128
		if (display == null) {
129
			display = Display.getDefault();
130
		}
131
		return display;
132
	}
133
134
	/**
135
	 * Returns the <code>Image<code> identified by the given key,
136
	 * or <code>null</code> if it does not exist.
137
	 * @param key 
138
	 * @return the image
139
	 */
140
	public static Image getImage(String key) {
141
		return getImageRegistry().get(key);
142
	}
143
144
	/**
145
	 * Returns the <code>ImageDescriptor<code> identified by the given key,
146
	 * or <code>null</code> if it does not exist.
147
	 * @param key 
148
	 * @return the image descriptor
149
	 */
150
	public static ImageDescriptor getImageDescriptor(String key) {
151
		return getImageRegistry().getDescriptor(key);
152
	}
153
154
}
(-)Ant Editor/org/eclipse/ant/internal/ui/editor/AntEditorMessages.properties (+5 lines)
Lines 41-43 Link Here
41
AntAnnotationHover.multipleMarkersAtThisLine=Multiple markers at this line
41
AntAnnotationHover.multipleMarkersAtThisLine=Multiple markers at this line
42
42
43
AntEditor.3=Current text selection does not resolve to an Ant reference
43
AntEditor.3=Current text selection does not resolve to an Ant reference
44
45
Editor.Paste.label=&Paste
46
Editor.Paste.tooltip=Paste
47
Editor.Paste.image=
48
Editor.Paste.description=Paste
(-)Ant Editor/org/eclipse/ant/internal/ui/editor/AntEditor.java (-625 / +806 lines)
Lines 34-39 Link Here
34
import org.eclipse.ant.internal.ui.editor.actions.RunToLineAdapter;
34
import org.eclipse.ant.internal.ui.editor.actions.RunToLineAdapter;
35
import org.eclipse.ant.internal.ui.editor.actions.ToggleLineBreakpointAction;
35
import org.eclipse.ant.internal.ui.editor.actions.ToggleLineBreakpointAction;
36
import org.eclipse.ant.internal.ui.editor.outline.AntEditorContentOutlinePage;
36
import org.eclipse.ant.internal.ui.editor.outline.AntEditorContentOutlinePage;
37
import org.eclipse.ant.internal.ui.editor.templates.AntTemplatesPage;
37
import org.eclipse.ant.internal.ui.editor.text.AntEditorDocumentProvider;
38
import org.eclipse.ant.internal.ui.editor.text.AntEditorDocumentProvider;
38
import org.eclipse.ant.internal.ui.editor.text.AntFoldingStructureProvider;
39
import org.eclipse.ant.internal.ui.editor.text.AntFoldingStructureProvider;
39
import org.eclipse.ant.internal.ui.editor.text.IReconcilingParticipant;
40
import org.eclipse.ant.internal.ui.editor.text.IReconcilingParticipant;
Lines 71-76 Link Here
71
import org.eclipse.jface.text.ISelectionValidator;
72
import org.eclipse.jface.text.ISelectionValidator;
72
import org.eclipse.jface.text.ISynchronizable;
73
import org.eclipse.jface.text.ISynchronizable;
73
import org.eclipse.jface.text.ITextInputListener;
74
import org.eclipse.jface.text.ITextInputListener;
75
import org.eclipse.jface.text.ITextOperationTarget;
74
import org.eclipse.jface.text.ITextSelection;
76
import org.eclipse.jface.text.ITextSelection;
75
import org.eclipse.jface.text.ITextViewer;
77
import org.eclipse.jface.text.ITextViewer;
76
import org.eclipse.jface.text.Position;
78
import org.eclipse.jface.text.Position;
Lines 85-90 Link Here
85
import org.eclipse.jface.text.source.projection.IProjectionListener;
87
import org.eclipse.jface.text.source.projection.IProjectionListener;
86
import org.eclipse.jface.text.source.projection.ProjectionSupport;
88
import org.eclipse.jface.text.source.projection.ProjectionSupport;
87
import org.eclipse.jface.text.source.projection.ProjectionViewer;
89
import org.eclipse.jface.text.source.projection.ProjectionViewer;
90
import org.eclipse.jface.text.templates.Template;
88
import org.eclipse.jface.util.PropertyChangeEvent;
91
import org.eclipse.jface.util.PropertyChangeEvent;
89
import org.eclipse.jface.viewers.IPostSelectionProvider;
92
import org.eclipse.jface.viewers.IPostSelectionProvider;
90
import org.eclipse.jface.viewers.ISelection;
93
import org.eclipse.jface.viewers.ISelection;
Lines 93-98 Link Here
93
import org.eclipse.jface.viewers.IStructuredSelection;
96
import org.eclipse.jface.viewers.IStructuredSelection;
94
import org.eclipse.jface.viewers.SelectionChangedEvent;
97
import org.eclipse.jface.viewers.SelectionChangedEvent;
95
import org.eclipse.swt.custom.StyledText;
98
import org.eclipse.swt.custom.StyledText;
99
import org.eclipse.swt.dnd.Clipboard;
96
import org.eclipse.swt.events.ShellAdapter;
100
import org.eclipse.swt.events.ShellAdapter;
97
import org.eclipse.swt.events.ShellEvent;
101
import org.eclipse.swt.events.ShellEvent;
98
import org.eclipse.swt.graphics.Image;
102
import org.eclipse.swt.graphics.Image;
Lines 112-139 Link Here
112
import org.eclipse.ui.texteditor.ContentAssistAction;
116
import org.eclipse.ui.texteditor.ContentAssistAction;
113
import org.eclipse.ui.texteditor.IDocumentProvider;
117
import org.eclipse.ui.texteditor.IDocumentProvider;
114
import org.eclipse.ui.texteditor.IEditorStatusLine;
118
import org.eclipse.ui.texteditor.IEditorStatusLine;
119
import org.eclipse.ui.texteditor.ITextEditor;
115
import org.eclipse.ui.texteditor.ITextEditorActionConstants;
120
import org.eclipse.ui.texteditor.ITextEditorActionConstants;
116
import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds;
121
import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds;
122
import org.eclipse.ui.texteditor.IWorkbenchActionDefinitionIds;
123
import org.eclipse.ui.texteditor.TextEditorAction;
117
import org.eclipse.ui.texteditor.TextOperationAction;
124
import org.eclipse.ui.texteditor.TextOperationAction;
125
import org.eclipse.ui.texteditor.templates.TemplateTransfer;
118
import org.eclipse.ui.views.contentoutline.ContentOutline;
126
import org.eclipse.ui.views.contentoutline.ContentOutline;
119
import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
127
import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
128
import org.eclipse.ui.views.templates.ITemplatesPage;
120
129
121
/**
130
/**
122
 * The actual editor implementation for Eclipse's Ant integration.
131
 * The actual editor implementation for Eclipse's Ant integration.
123
 */
132
 */
124
public class AntEditor extends TextEditor implements IReconcilingParticipant, IProjectionListener {
133
public class AntEditor extends TextEditor implements IReconcilingParticipant,
134
		IProjectionListener {
135
136
	class ClipboardPasteOperation extends TextEditorAction {
137
		private ITextOperationTarget fOperationTarget;
138
		private int fOperationCode = -1;
139
140
		protected ClipboardPasteOperation(ResourceBundle bundle, String prefix,
141
				ITextEditor editor, int style) {
142
			super(bundle, prefix, editor, style);
143
		}
144
145
		public void run() {
146
			ITextEditor editor = getTextEditor();
147
			Clipboard clipboard = new Clipboard(getSite().getShell()
148
					.getDisplay());
149
			Template[] templates = (Template[]) clipboard
150
					.getContents(TemplateTransfer.getInstance());
151
			if (templates != null) {
152
				AntTemplatesPage page = (AntTemplatesPage) editor
153
						.getAdapter(ITemplatesPage.class);
154
				page.insertTemplate(templates[0]);
155
			} else
156
				fOperationTarget.doOperation(fOperationCode);
157
		}
158
159
		/*
160
		 * (non-Javadoc)
161
		 * 
162
		 * @see org.eclipse.ui.texteditor.IUpdate#update()
163
		 */
164
		public void update() {
165
			super.update();
166
		}
167
168
	}
169
125
	/**
170
	/**
126
	 * Updates the Ant outline page selection and this editor's range indicator.
171
	 * Updates the Ant outline page selection and this editor's range indicator.
127
	 * 
172
	 * 
128
	 * @since 3.0
173
	 * @since 3.0
129
	 */
174
	 */
130
	private class EditorSelectionChangedListener implements ISelectionChangedListener  {
175
	private class EditorSelectionChangedListener implements
131
		
176
			ISelectionChangedListener {
177
132
		/**
178
		/**
133
		 * Installs this selection changed listener with the given selection provider. If
179
		 * Installs this selection changed listener with the given selection
134
		 * the selection provider is a post selection provider, post selection changed
180
		 * provider. If the selection provider is a post selection provider,
135
		 * events are the preferred choice, otherwise normal selection changed events
181
		 * post selection changed events are the preferred choice, otherwise
136
		 * are requested.
182
		 * normal selection changed events are requested.
137
		 * 
183
		 * 
138
		 * @param selectionProvider
184
		 * @param selectionProvider
139
		 */
185
		 */
Lines 141-157 Link Here
141
			if (selectionProvider == null || getAntModel() == null) {
187
			if (selectionProvider == null || getAntModel() == null) {
142
				return;
188
				return;
143
			}
189
			}
144
				
190
145
			if (selectionProvider instanceof IPostSelectionProvider)  {
191
			if (selectionProvider instanceof IPostSelectionProvider) {
146
				IPostSelectionProvider provider= (IPostSelectionProvider) selectionProvider;
192
				IPostSelectionProvider provider = (IPostSelectionProvider) selectionProvider;
147
				provider.addPostSelectionChangedListener(this);
193
				provider.addPostSelectionChangedListener(this);
148
			} else  {
194
			} else {
149
				selectionProvider.addSelectionChangedListener(this);
195
				selectionProvider.addSelectionChangedListener(this);
150
			}
196
			}
151
		}
197
		}
152
198
153
		/**
199
		/**
154
		 * Removes this selection changed listener from the given selection provider.
200
		 * Removes this selection changed listener from the given selection
201
		 * provider.
155
		 * 
202
		 * 
156
		 * @param selectionProvider
203
		 * @param selectionProvider
157
		 */
204
		 */
Lines 159-201 Link Here
159
			if (selectionProvider == null || getAntModel() == null) {
206
			if (selectionProvider == null || getAntModel() == null) {
160
				return;
207
				return;
161
			}
208
			}
162
			
209
163
			if (selectionProvider instanceof IPostSelectionProvider)  {
210
			if (selectionProvider instanceof IPostSelectionProvider) {
164
				IPostSelectionProvider provider= (IPostSelectionProvider) selectionProvider;
211
				IPostSelectionProvider provider = (IPostSelectionProvider) selectionProvider;
165
				provider.removePostSelectionChangedListener(this);
212
				provider.removePostSelectionChangedListener(this);
166
			} else  {
213
			} else {
167
				selectionProvider.removeSelectionChangedListener(this);
214
				selectionProvider.removeSelectionChangedListener(this);
168
			}			
215
			}
169
		}
216
		}
170
		
217
171
		/*
218
		/*
172
		 * @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent)
219
		 * @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent)
173
		 */
220
		 */
174
		public void selectionChanged(SelectionChangedEvent event) {
221
		public void selectionChanged(SelectionChangedEvent event) {
175
			AntModel model= getAntModel();
222
			AntModel model = getAntModel();
176
			ISelection selection= event.getSelection();
223
			ISelection selection = event.getSelection();
177
			AntElementNode node= null;
224
			AntElementNode node = null;
178
			if (selection instanceof ITextSelection) {
225
			if (selection instanceof ITextSelection) {
179
				ITextSelection textSelection= (ITextSelection)selection;
226
				ITextSelection textSelection = (ITextSelection) selection;
180
				int offset= textSelection.getOffset();
227
				int offset = textSelection.getOffset();
181
				node= model.getNode(offset, false);
228
				node = model.getNode(offset, false);
182
				updateOccurrenceAnnotations(textSelection, model);
229
				updateOccurrenceAnnotations(textSelection, model);
183
			}
230
			}
184
		
231
185
			if (AntUIPlugin.getDefault().getPreferenceStore().getBoolean(IAntUIPreferenceConstants.OUTLINE_LINK_WITH_EDITOR)) {
232
			if (AntUIPlugin.getDefault().getPreferenceStore().getBoolean(
233
					IAntUIPreferenceConstants.OUTLINE_LINK_WITH_EDITOR)) {
186
				synchronizeOutlinePage(node, true);
234
				synchronizeOutlinePage(node, true);
187
			}
235
			}
188
			setSelection(node, false);
236
			setSelection(node, false);
189
		}
237
		}
190
	}
238
	}
191
	
239
192
	class StatusLineSourceViewer extends ProjectionViewer{
240
	class StatusLineSourceViewer extends ProjectionViewer {
193
		
241
194
		public StatusLineSourceViewer(Composite composite, IVerticalRuler verticalRuler, IOverviewRuler overviewRuler, int styles) {
242
		public StatusLineSourceViewer(Composite composite,
195
			super(composite, verticalRuler, overviewRuler, isOverviewRulerVisible(), styles);
243
				IVerticalRuler verticalRuler, IOverviewRuler overviewRuler,
244
				int styles) {
245
			super(composite, verticalRuler, overviewRuler,
246
					isOverviewRulerVisible(), styles);
196
		}
247
		}
197
248
198
		/* (non-Javadoc)
249
		/*
250
		 * (non-Javadoc)
251
		 * 
199
		 * @see org.eclipse.jface.text.ITextOperationTarget#doOperation(int)
252
		 * @see org.eclipse.jface.text.ITextOperationTarget#doOperation(int)
200
		 */
253
		 */
201
		public void doOperation(int operation) {
254
		public void doOperation(int operation) {
Lines 204-372 Link Here
204
			}
257
			}
205
258
206
			switch (operation) {
259
			switch (operation) {
207
				case CONTENTASSIST_PROPOSALS:
260
			case CONTENTASSIST_PROPOSALS:
208
					String msg= fContentAssistant.showPossibleCompletions();
261
				String msg = fContentAssistant.showPossibleCompletions();
209
					setStatusLineErrorMessage(msg);
262
				setStatusLineErrorMessage(msg);
210
					return;
263
				return;
211
			}
264
			}
212
			
265
213
			super.doOperation(operation);
266
			super.doOperation(operation);
214
		}
267
		}
215
	}
268
	}
216
		
269
217
	
218
	/**
270
	/**
219
	 * Finds and marks occurrence annotations.
271
	 * Finds and marks occurrence annotations.
220
	 * 
272
	 * 
221
	 * @since 3.1
273
	 * @since 3.1
222
	 */
274
	 */
223
	class OccurrencesFinderJob extends Job {
275
	class OccurrencesFinderJob extends Job {
224
		
276
225
		private IDocument fDocument;
277
		private IDocument fDocument;
226
		private ISelection fSelection;
278
		private ISelection fSelection;
227
		private ISelectionValidator fPostSelectionValidator;
279
		private ISelectionValidator fPostSelectionValidator;
228
		private boolean fCanceled= false;
280
		private boolean fCanceled = false;
229
		private IProgressMonitor fProgressMonitor;
281
		private IProgressMonitor fProgressMonitor;
230
		private List fPositions;
282
		private List fPositions;
231
		
283
232
		public OccurrencesFinderJob(IDocument document, List positions, ISelection selection) {
284
		public OccurrencesFinderJob(IDocument document, List positions,
285
				ISelection selection) {
233
			super("Occurrences Marker"); //$NON-NLS-1$
286
			super("Occurrences Marker"); //$NON-NLS-1$
234
			fDocument= document;
287
			fDocument = document;
235
			fSelection= selection;
288
			fSelection = selection;
236
			fPositions= positions;
289
			fPositions = positions;
237
			
290
238
			if (getSelectionProvider() instanceof ISelectionValidator)
291
			if (getSelectionProvider() instanceof ISelectionValidator)
239
				fPostSelectionValidator= (ISelectionValidator)getSelectionProvider(); 
292
				fPostSelectionValidator = (ISelectionValidator) getSelectionProvider();
240
		}
293
		}
241
		
294
242
		// cannot use cancel() because it is declared final
295
		// cannot use cancel() because it is declared final
243
		void doCancel() {
296
		void doCancel() {
244
			fCanceled= true;
297
			fCanceled = true;
245
			cancel();
298
			cancel();
246
		}
299
		}
247
		
300
248
		private boolean isCanceled() {
301
		private boolean isCanceled() {
249
			return fCanceled || fProgressMonitor.isCanceled()
302
			return fCanceled
250
				||  fPostSelectionValidator != null && !(fPostSelectionValidator.isValid(fSelection) || fForcedMarkOccurrencesSelection == fSelection)
303
					|| fProgressMonitor.isCanceled()
251
				|| LinkedModeModel.hasInstalledModel(fDocument);
304
					|| fPostSelectionValidator != null
305
					&& !(fPostSelectionValidator.isValid(fSelection) || fForcedMarkOccurrencesSelection == fSelection)
306
					|| LinkedModeModel.hasInstalledModel(fDocument);
252
		}
307
		}
253
		
308
254
		/*
309
		/*
255
		 * @see Job#run(org.eclipse.core.runtime.IProgressMonitor)
310
		 * @see Job#run(org.eclipse.core.runtime.IProgressMonitor)
256
		 */
311
		 */
257
		public IStatus run(IProgressMonitor progressMonitor) {
312
		public IStatus run(IProgressMonitor progressMonitor) {
258
			
313
259
			fProgressMonitor= progressMonitor;
314
			fProgressMonitor = progressMonitor;
260
			
315
261
			if (isCanceled())
316
			if (isCanceled())
262
				return Status.CANCEL_STATUS;
317
				return Status.CANCEL_STATUS;
263
			
318
264
			ITextViewer textViewer= getViewer(); 
319
			ITextViewer textViewer = getViewer();
265
			if (textViewer == null)
320
			if (textViewer == null)
266
				return Status.CANCEL_STATUS;
321
				return Status.CANCEL_STATUS;
267
			
322
268
			IDocument document= textViewer.getDocument();
323
			IDocument document = textViewer.getDocument();
269
			if (document == null)
324
			if (document == null)
270
				return Status.CANCEL_STATUS;
325
				return Status.CANCEL_STATUS;
271
			
326
272
			IDocumentProvider documentProvider= getDocumentProvider();
327
			IDocumentProvider documentProvider = getDocumentProvider();
273
			if (documentProvider == null)
328
			if (documentProvider == null)
274
				return Status.CANCEL_STATUS;
329
				return Status.CANCEL_STATUS;
275
		
330
276
			IAnnotationModel annotationModel= documentProvider.getAnnotationModel(getEditorInput());
331
			IAnnotationModel annotationModel = documentProvider
332
					.getAnnotationModel(getEditorInput());
277
			if (annotationModel == null)
333
			if (annotationModel == null)
278
				return Status.CANCEL_STATUS;
334
				return Status.CANCEL_STATUS;
279
			
335
280
			// Add occurrence annotations
336
			// Add occurrence annotations
281
			int length= fPositions.size();
337
			int length = fPositions.size();
282
			Map annotationMap= new HashMap(length);
338
			Map annotationMap = new HashMap(length);
283
			for (int i= 0; i < length; i++) {
339
			for (int i = 0; i < length; i++) {
284
				
340
285
				if (isCanceled())
341
				if (isCanceled())
286
					return Status.CANCEL_STATUS; 
342
					return Status.CANCEL_STATUS;
287
				
343
288
				String message;
344
				String message;
289
				Position position= (Position) fPositions.get(i);
345
				Position position = (Position) fPositions.get(i);
290
				
346
291
				// Create & add annotation
347
				// Create & add annotation
292
				try {
348
				try {
293
					message= document.get(position.offset, position.length);
349
					message = document.get(position.offset, position.length);
294
				} catch (BadLocationException ex) {
350
				} catch (BadLocationException ex) {
295
					// Skip this match
351
					// Skip this match
296
					continue;
352
					continue;
297
				}
353
				}
298
				annotationMap.put(
354
				annotationMap.put(new Annotation(
299
						new Annotation("org.eclipse.jdt.ui.occurrences", false, message), //$NON-NLS-1$
355
						"org.eclipse.jdt.ui.occurrences", false, message), //$NON-NLS-1$
300
						position);
356
						position);
301
			}
357
			}
302
			
358
303
			if (isCanceled()) {
359
			if (isCanceled()) {
304
				return Status.CANCEL_STATUS;
360
				return Status.CANCEL_STATUS;
305
            }
361
			}
306
			
362
307
            Object lock= getLockObject(document);
363
			Object lock = getLockObject(document);
308
            if (lock == null) {
364
			if (lock == null) {
309
                updateAnnotations(annotationModel, annotationMap);
365
				updateAnnotations(annotationModel, annotationMap);
310
            } else {
366
			} else {
311
                synchronized (lock) {
367
				synchronized (lock) {
312
                    updateAnnotations(annotationModel, annotationMap);
368
					updateAnnotations(annotationModel, annotationMap);
313
                }
369
				}
314
            }
370
			}
315
371
316
			return Status.OK_STATUS;
372
			return Status.OK_STATUS;
317
		}
373
		}
318
374
319
        private void updateAnnotations(IAnnotationModel annotationModel, Map annotationMap) {
375
		private void updateAnnotations(IAnnotationModel annotationModel,
320
            if (annotationModel instanceof IAnnotationModelExtension) {
376
				Map annotationMap) {
321
            	((IAnnotationModelExtension)annotationModel).replaceAnnotations(fOccurrenceAnnotations, annotationMap);
377
			if (annotationModel instanceof IAnnotationModelExtension) {
322
            } else {
378
				((IAnnotationModelExtension) annotationModel)
323
            	removeOccurrenceAnnotations();
379
						.replaceAnnotations(fOccurrenceAnnotations,
324
            	Iterator iter= annotationMap.entrySet().iterator();
380
								annotationMap);
325
            	while (iter.hasNext()) {
381
			} else {
326
            		Map.Entry mapEntry= (Map.Entry)iter.next(); 
382
				removeOccurrenceAnnotations();
327
            		annotationModel.addAnnotation((Annotation)mapEntry.getKey(), (Position)mapEntry.getValue());
383
				Iterator iter = annotationMap.entrySet().iterator();
328
            	}
384
				while (iter.hasNext()) {
329
            }
385
					Map.Entry mapEntry = (Map.Entry) iter.next();
330
            fOccurrenceAnnotations= (Annotation[])annotationMap.keySet().toArray(new Annotation[annotationMap.keySet().size()]);
386
					annotationModel.addAnnotation((Annotation) mapEntry
331
        }
387
							.getKey(), (Position) mapEntry.getValue());
332
	}	
388
				}
333
	
389
			}
390
			fOccurrenceAnnotations = (Annotation[]) annotationMap.keySet()
391
					.toArray(new Annotation[annotationMap.keySet().size()]);
392
		}
393
	}
394
334
	/**
395
	/**
335
	 * Cancels the occurrences finder job upon document changes.
396
	 * Cancels the occurrences finder job upon document changes.
336
	 * 
397
	 * 
337
	 * @since 3.1
398
	 * @since 3.1
338
	 */
399
	 */
339
	class OccurrencesFinderJobCanceler implements IDocumentListener, ITextInputListener {
400
	class OccurrencesFinderJobCanceler implements IDocumentListener,
401
			ITextInputListener {
340
402
341
		public void install() {
403
		public void install() {
342
			ISourceViewer sourceViewer= getSourceViewer();
404
			ISourceViewer sourceViewer = getSourceViewer();
343
			if (sourceViewer == null)
405
			if (sourceViewer == null)
344
				return;
406
				return;
345
				
407
346
			StyledText text= sourceViewer.getTextWidget();			
408
			StyledText text = sourceViewer.getTextWidget();
347
			if (text == null || text.isDisposed())
409
			if (text == null || text.isDisposed())
348
				return;
410
				return;
349
411
350
			sourceViewer.addTextInputListener(this);
412
			sourceViewer.addTextInputListener(this);
351
			
413
352
			IDocument document= sourceViewer.getDocument();
414
			IDocument document = sourceViewer.getDocument();
353
			if (document != null)
415
			if (document != null)
354
				document.addDocumentListener(this);			
416
				document.addDocumentListener(this);
355
		}
417
		}
356
		
418
357
		public void uninstall() {
419
		public void uninstall() {
358
			ISourceViewer sourceViewer= getSourceViewer();
420
			ISourceViewer sourceViewer = getSourceViewer();
359
			if (sourceViewer != null)
421
			if (sourceViewer != null)
360
				sourceViewer.removeTextInputListener(this);
422
				sourceViewer.removeTextInputListener(this);
361
423
362
			IDocumentProvider documentProvider= getDocumentProvider();
424
			IDocumentProvider documentProvider = getDocumentProvider();
363
			if (documentProvider != null) {
425
			if (documentProvider != null) {
364
				IDocument document= documentProvider.getDocument(getEditorInput());
426
				IDocument document = documentProvider
427
						.getDocument(getEditorInput());
365
				if (document != null)
428
				if (document != null)
366
					document.removeDocumentListener(this);
429
					document.removeDocumentListener(this);
367
			}
430
			}
368
		}
431
		}
369
				
370
432
371
		/*
433
		/*
372
		 * @see org.eclipse.jface.text.IDocumentListener#documentAboutToBeChanged(org.eclipse.jface.text.DocumentEvent)
434
		 * @see org.eclipse.jface.text.IDocumentListener#documentAboutToBeChanged(org.eclipse.jface.text.DocumentEvent)
Lines 383-391 Link Here
383
		}
445
		}
384
446
385
		/*
447
		/*
386
		 * @see org.eclipse.jface.text.ITextInputListener#inputDocumentAboutToBeChanged(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.IDocument)
448
		 * @see org.eclipse.jface.text.ITextInputListener#inputDocumentAboutToBeChanged(org.eclipse.jface.text.IDocument,
449
		 *      org.eclipse.jface.text.IDocument)
387
		 */
450
		 */
388
		public void inputDocumentAboutToBeChanged(IDocument oldInput, IDocument newInput) {
451
		public void inputDocumentAboutToBeChanged(IDocument oldInput,
452
				IDocument newInput) {
389
			if (oldInput == null)
453
			if (oldInput == null)
390
				return;
454
				return;
391
455
Lines 393-399 Link Here
393
		}
457
		}
394
458
395
		/*
459
		/*
396
		 * @see org.eclipse.jface.text.ITextInputListener#inputDocumentChanged(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.IDocument)
460
		 * @see org.eclipse.jface.text.ITextInputListener#inputDocumentChanged(org.eclipse.jface.text.IDocument,
461
		 *      org.eclipse.jface.text.IDocument)
397
		 */
462
		 */
398
		public void inputDocumentChanged(IDocument oldInput, IDocument newInput) {
463
		public void inputDocumentChanged(IDocument oldInput, IDocument newInput) {
399
			if (newInput == null)
464
			if (newInput == null)
Lines 401-409 Link Here
401
			newInput.addDocumentListener(this);
466
			newInput.addDocumentListener(this);
402
		}
467
		}
403
	}
468
	}
404
	
469
405
	/**
470
	/**
406
	 * Internal activation listener.
471
	 * Internal activation listener.
472
	 * 
407
	 * @since 3.1
473
	 * @since 3.1
408
	 */
474
	 */
409
	private class ActivationListener extends ShellAdapter {
475
	private class ActivationListener extends ShellAdapter {
Lines 412-425 Link Here
412
		 */
478
		 */
413
		public void shellActivated(ShellEvent e) {
479
		public void shellActivated(ShellEvent e) {
414
			if (fMarkOccurrenceAnnotations && isActivePart()) {
480
			if (fMarkOccurrenceAnnotations && isActivePart()) {
415
				ISelection selection= getSelectionProvider().getSelection();
481
				ISelection selection = getSelectionProvider().getSelection();
416
				if (selection instanceof ITextSelection) {
482
				if (selection instanceof ITextSelection) {
417
					fForcedMarkOccurrencesSelection= (ITextSelection) selection;
483
					fForcedMarkOccurrencesSelection = (ITextSelection) selection;
418
					updateOccurrenceAnnotations(fForcedMarkOccurrencesSelection, getAntModel());
484
					updateOccurrenceAnnotations(
485
							fForcedMarkOccurrencesSelection, getAntModel());
419
				}
486
				}
420
			}
487
			}
421
		}
488
		}
422
		
489
423
		/*
490
		/*
424
		 * @see org.eclipse.swt.events.ShellAdapter#shellDeactivated(org.eclipse.swt.events.ShellEvent)
491
		 * @see org.eclipse.swt.events.ShellAdapter#shellDeactivated(org.eclipse.swt.events.ShellEvent)
425
		 */
492
		 */
Lines 432-451 Link Here
432
	/**
499
	/**
433
	 * Selection changed listener for the outline view.
500
	 * Selection changed listener for the outline view.
434
	 */
501
	 */
435
    protected ISelectionChangedListener fSelectionChangedListener = new ISelectionChangedListener(){
502
	protected ISelectionChangedListener fSelectionChangedListener = new ISelectionChangedListener() {
436
        public void selectionChanged(SelectionChangedEvent event) {
503
		public void selectionChanged(SelectionChangedEvent event) {
437
        	fSelectionSetFromOutline= false;
504
			fSelectionSetFromOutline = false;
438
            doSelectionChanged(event);
505
			doSelectionChanged(event);
439
            fSelectionSetFromOutline= true;
506
			fSelectionSetFromOutline = true;
440
        }
507
		}
441
    };
508
	};
442
    
509
443
    private IAntModelListener fAntModelListener= new IAntModelListener() {
510
	private IAntModelListener fAntModelListener = new IAntModelListener() {
444
		/* (non-Javadoc)
511
		/*
512
		 * (non-Javadoc)
513
		 * 
445
		 * @see org.eclipse.ant.internal.ui.editor.outline.IDocumentModelListener#documentModelChanged(org.eclipse.ant.internal.ui.editor.outline.DocumentModelChangeEvent)
514
		 * @see org.eclipse.ant.internal.ui.editor.outline.IDocumentModelListener#documentModelChanged(org.eclipse.ant.internal.ui.editor.outline.DocumentModelChangeEvent)
446
		 */
515
		 */
447
		public void antModelChanged(AntModelChangeEvent event) {
516
		public void antModelChanged(AntModelChangeEvent event) {
448
			AntModel model= getAntModel();
517
			AntModel model = getAntModel();
449
			if (event.getModel() == model) {
518
			if (event.getModel() == model) {
450
				if (event.isPreferenceChange()) {
519
				if (event.isPreferenceChange()) {
451
					updateEditorImage(model);
520
					updateEditorImage(model);
Lines 456-470 Link Here
456
			}
525
			}
457
		}
526
		}
458
	};
527
	};
459
    
528
460
    /**
529
	/**
461
     * The page that shows the outline.
530
	 * The page that shows the outline.
462
     */
531
	 */
463
    protected AntEditorContentOutlinePage fOutlinePage;
532
	protected AntEditorContentOutlinePage fOutlinePage;
464
    
533
	protected AntTemplatesPage fTemplatesPage;
465
	
534
466
	private boolean fInitialReconcile= true;
535
	private boolean fInitialReconcile = true;
467
	
536
468
	/**
537
	/**
469
	 * The editor selection changed listener.
538
	 * The editor selection changed listener.
470
	 * 
539
	 * 
Lines 473-753 Link Here
473
	private EditorSelectionChangedListener fEditorSelectionChangedListener;
542
	private EditorSelectionChangedListener fEditorSelectionChangedListener;
474
543
475
	private ProjectionSupport fProjectionSupport;
544
	private ProjectionSupport fProjectionSupport;
476
	
545
477
	private AntFoldingStructureProvider fFoldingStructureProvider;
546
	private AntFoldingStructureProvider fFoldingStructureProvider;
478
	
479
	private boolean fSelectionSetFromOutline= false;
480
547
481
    private FoldingActionGroup fFoldingGroup;
548
	private boolean fSelectionSetFromOutline = false;
482
	
549
550
	private FoldingActionGroup fFoldingGroup;
551
483
	/**
552
	/**
484
	 * Holds the current occurrence annotations.
553
	 * Holds the current occurrence annotations.
554
	 * 
485
	 * @since 3.1
555
	 * @since 3.1
486
	 */
556
	 */
487
	private Annotation[] fOccurrenceAnnotations= null;
557
	private Annotation[] fOccurrenceAnnotations = null;
488
558
489
	private OccurrencesFinderJob fOccurrencesFinderJob;
559
	private OccurrencesFinderJob fOccurrencesFinderJob;
490
	private OccurrencesFinderJobCanceler fOccurrencesFinderJobCanceler;
560
	private OccurrencesFinderJobCanceler fOccurrencesFinderJobCanceler;
491
	
561
492
	private ITextSelection fForcedMarkOccurrencesSelection;
562
	private ITextSelection fForcedMarkOccurrencesSelection;
493
	/**
563
	/**
494
	 * The internal shell activation listener for updating occurrences.
564
	 * The internal shell activation listener for updating occurrences.
565
	 * 
495
	 * @since 3.1
566
	 * @since 3.1
496
	 */
567
	 */
497
	private ActivationListener fActivationListener= new ActivationListener();
568
	private ActivationListener fActivationListener = new ActivationListener();
498
	
569
499
	private boolean fMarkOccurrenceAnnotations;
570
	private boolean fMarkOccurrenceAnnotations;
500
	private boolean fStickyOccurrenceAnnotations;
571
	private boolean fStickyOccurrenceAnnotations;
501
    
572
502
    private AntModel fAntModel;
573
	private AntModel fAntModel;
503
  
574
504
    public AntEditor() {
575
	public AntEditor() {
505
        super();
576
		super();
506
		setSourceViewerConfiguration(new AntEditorSourceViewerConfiguration(this));
577
		setSourceViewerConfiguration(new AntEditorSourceViewerConfiguration(
578
				this));
507
		setDocumentProvider(AntUIPlugin.getDefault().getDocumentProvider());
579
		setDocumentProvider(AntUIPlugin.getDefault().getDocumentProvider());
508
		AntModelCore.getDefault().addAntModelListener(fAntModelListener);
580
		AntModelCore.getDefault().addAntModelListener(fAntModelListener);
509
		
581
510
		if (isFoldingEnabled()) {
582
		if (isFoldingEnabled()) {
511
			fFoldingStructureProvider= new AntFoldingStructureProvider(this);
583
			fFoldingStructureProvider = new AntFoldingStructureProvider(this);
512
		}
584
		}
513
    }
585
	}
586
587
	/*
588
	 * (non-Javadoc)
589
	 * 
590
	 * @see org.eclipse.ui.texteditor.AbstractTextEditor#createActions()
591
	 */
592
	protected void createActions() {
593
		super.createActions();
594
595
		ResourceBundle bundle = ResourceBundle
596
				.getBundle("org.eclipse.ant.internal.ui.editor.AntEditorMessages"); //$NON-NLS-1$
597
		IAction action = new ContentAssistAction(bundle,
598
				"ContentAssistProposal.", this); //$NON-NLS-1$
599
600
		// This action definition is associated with the accelerator Ctrl+Space
601
		action
602
				.setActionDefinitionId(ITextEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS);
603
		setAction("ContentAssistProposal", action); //$NON-NLS-1$
514
604
605
		action = new TextOperationAction(bundle,
606
				"ContentFormat.", this, ISourceViewer.FORMAT); //$NON-NLS-1$
607
		action.setActionDefinitionId(IJavaEditorActionDefinitionIds.FORMAT);
608
		setAction("ContentFormat", action); //$NON-NLS-1$
515
609
516
    /* (non-Javadoc)
610
		action = new OpenDeclarationAction(this);
517
     * @see org.eclipse.ui.texteditor.AbstractTextEditor#createActions()
611
		setAction("OpenDeclaration", action); //$NON-NLS-1$
518
     */
612
519
    protected void createActions() {
613
		fFoldingGroup = new FoldingActionGroup(this, getViewer());
520
        super.createActions();
614
521
615
		action = new RenameInFileAction(this);
522
        ResourceBundle bundle = ResourceBundle.getBundle("org.eclipse.ant.internal.ui.editor.AntEditorMessages"); //$NON-NLS-1$
523
        IAction action = new ContentAssistAction(bundle, "ContentAssistProposal.", this); //$NON-NLS-1$
524
        
525
        // This action definition is associated with the accelerator Ctrl+Space
526
        action.setActionDefinitionId(ITextEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS);
527
        setAction("ContentAssistProposal", action); //$NON-NLS-1$
528
        
529
		action = new TextOperationAction(bundle, "ContentFormat.", this, ISourceViewer.FORMAT); //$NON-NLS-1$
530
        action.setActionDefinitionId(IJavaEditorActionDefinitionIds.FORMAT);
531
        setAction("ContentFormat", action); //$NON-NLS-1$
532
        
533
        action = new OpenDeclarationAction(this);
534
        setAction("OpenDeclaration", action); //$NON-NLS-1$
535
        
536
        fFoldingGroup= new FoldingActionGroup(this, getViewer());
537
        
538
		action= new RenameInFileAction(this);
539
		action.setActionDefinitionId("org.eclipse.ant.ui.renameInFile"); //$NON-NLS-1$
616
		action.setActionDefinitionId("org.eclipse.ant.ui.renameInFile"); //$NON-NLS-1$
540
		setAction("renameInFile", action); //$NON-NLS-1$
617
		setAction("renameInFile", action); //$NON-NLS-1$
541
    }
618
619
		// Override the TextEditor paste operation to support templates
620
		action = new ClipboardPasteOperation(bundle,
621
				"Editor.Paste.", this, ITextOperationTarget.PASTE); //$NON-NLS-1$
622
		action.setActionDefinitionId(IWorkbenchActionDefinitionIds.PASTE);
623
		setAction(ITextEditorActionConstants.PASTE, action);
624
	}
542
625
543
	/*
626
	/*
544
	 *  (non-Javadoc)
627
	 * (non-Javadoc)
545
	 * @see org.eclipse.ui.editors.text.TextEditor#initializeEditor()
628
	 * 
546
	 * Called from TextEditor.<init>
629
	 * @see org.eclipse.ui.editors.text.TextEditor#initializeEditor() Called
630
	 *      from TextEditor.<init>
547
	 */
631
	 */
548
    protected void initializeEditor() {
632
	protected void initializeEditor() {
549
		super.initializeEditor();
633
		super.initializeEditor();
550
		setPreferenceStore(AntUIPlugin.getDefault().getCombinedPreferenceStore());
634
		setPreferenceStore(AntUIPlugin.getDefault()
635
				.getCombinedPreferenceStore());
551
		setCompatibilityMode(false);
636
		setCompatibilityMode(false);
552
		setHelpContextId(IAntUIHelpContextIds.ANT_EDITOR);	
637
		setHelpContextId(IAntUIHelpContextIds.ANT_EDITOR);
553
		setRulerContextMenuId("org.eclipse.ant.internal.ui.editor.AntEditor.RulerContext"); //$NON-NLS-1$
638
		setRulerContextMenuId("org.eclipse.ant.internal.ui.editor.AntEditor.RulerContext"); //$NON-NLS-1$
554
        setEditorContextMenuId("org.eclipse.ant.internal.ui.editor.AntEditor"); //$NON-NLS-1$
639
		setEditorContextMenuId("org.eclipse.ant.internal.ui.editor.AntEditor"); //$NON-NLS-1$
555
		fMarkOccurrenceAnnotations= getPreferenceStore().getBoolean(AntEditorPreferenceConstants.EDITOR_MARK_OCCURRENCES);
640
		fMarkOccurrenceAnnotations = getPreferenceStore().getBoolean(
556
		fStickyOccurrenceAnnotations= getPreferenceStore().getBoolean(AntEditorPreferenceConstants.EDITOR_STICKY_OCCURRENCES);
641
				AntEditorPreferenceConstants.EDITOR_MARK_OCCURRENCES);
557
    }
642
		fStickyOccurrenceAnnotations = getPreferenceStore().getBoolean(
558
   
643
				AntEditorPreferenceConstants.EDITOR_STICKY_OCCURRENCES);
559
	/* (non-Javadoc)
644
	}
645
646
	/*
647
	 * (non-Javadoc)
648
	 * 
560
	 * @see org.eclipse.core.runtime.IAdaptable#getAdapter(java.lang.Class)
649
	 * @see org.eclipse.core.runtime.IAdaptable#getAdapter(java.lang.Class)
561
	 */
650
	 */
562
    public Object getAdapter(Class key) {
651
	public Object getAdapter(Class key) {
563
        if (key.equals(IContentOutlinePage.class)) {
652
		if (key.equals(IContentOutlinePage.class)) {
564
			return getOutlinePage();
653
			return getOutlinePage();
565
        }
654
		}
566
        
655
567
        if (fProjectionSupport != null) { 
656
		if (key.equals(ITemplatesPage.class)) {
568
        	Object adapter= fProjectionSupport.getAdapter(getSourceViewer(), key); 
657
			return getTemplatesPage();
569
        	if (adapter != null) {
658
		}
570
            	return adapter;
571
            }
572
        }
573
659
574
        if (key == IShowInTargetList.class) {
660
		if (fProjectionSupport != null) {
661
			Object adapter = fProjectionSupport.getAdapter(getSourceViewer(),
662
					key);
663
			if (adapter != null) {
664
				return adapter;
665
			}
666
		}
667
668
		if (key == IShowInTargetList.class) {
575
			return new IShowInTargetList() {
669
			return new IShowInTargetList() {
576
				public String[] getShowInTargetIds() {
670
				public String[] getShowInTargetIds() {
577
					return new String[] { JavaUI.ID_PACKAGES, IPageLayout.ID_RES_NAV };
671
					return new String[] { JavaUI.ID_PACKAGES,
672
							IPageLayout.ID_RES_NAV };
578
				}
673
				}
579
			};
674
			};
580
		}
675
		}
581
        
676
582
        if (key == IToggleBreakpointsTarget.class) {
677
		if (key == IToggleBreakpointsTarget.class) {
583
			return new ToggleLineBreakpointAction();
678
			return new ToggleLineBreakpointAction();
584
		}
679
		}
585
        
680
586
        if (key == IRunToLineTarget.class) {
681
		if (key == IRunToLineTarget.class) {
587
			return new RunToLineAdapter();
682
			return new RunToLineAdapter();
588
		}
683
		}
589
        
684
590
        return super.getAdapter(key);
685
		return super.getAdapter(key);
591
    }
686
	}
592
687
593
	private AntEditorContentOutlinePage getOutlinePage() {
688
	private AntEditorContentOutlinePage getOutlinePage() {
594
		if (fOutlinePage == null) {
689
		if (fOutlinePage == null) {
595
			fOutlinePage= new AntEditorContentOutlinePage(AntModelCore.getDefault(), this);
690
			fOutlinePage = new AntEditorContentOutlinePage(AntModelCore
596
			fOutlinePage.addPostSelectionChangedListener(fSelectionChangedListener);
691
					.getDefault(), this);
692
			fOutlinePage
693
					.addPostSelectionChangedListener(fSelectionChangedListener);
597
			setOutlinePageInput();
694
			setOutlinePageInput();
598
		}
695
		}
599
		return fOutlinePage;
696
		return fOutlinePage;
600
	}
697
	}
601
698
602
    private void doSelectionChanged(SelectionChangedEvent selectionChangedEvent) {
699
	private AntTemplatesPage getTemplatesPage() {
603
        IStructuredSelection selection= (IStructuredSelection)selectionChangedEvent.getSelection();
700
		if (fTemplatesPage == null) {
701
			fTemplatesPage = new AntTemplatesPage(this);
702
		}
703
		return fTemplatesPage;
704
	}
705
706
	protected void handleCursorPositionChanged() {
707
		super.handleCursorPositionChanged();
708
		if (fTemplatesPage != null)
709
			fTemplatesPage.cursorPositionChanged();
710
	}
604
711
605
        if (!isActivePart() && AntUIPlugin.getActivePage() != null) {
712
	private void doSelectionChanged(SelectionChangedEvent selectionChangedEvent) {
713
		IStructuredSelection selection = (IStructuredSelection) selectionChangedEvent
714
				.getSelection();
715
716
		if (!isActivePart() && AntUIPlugin.getActivePage() != null) {
606
			AntUIPlugin.getActivePage().bringToTop(this);
717
			AntUIPlugin.getActivePage().bringToTop(this);
607
        }
718
		}
608
        
719
609
        AntElementNode selectedXmlElement = (AntElementNode)selection.getFirstElement(); 
720
		AntElementNode selectedXmlElement = (AntElementNode) selection
610
        if(selectedXmlElement != null) {
721
				.getFirstElement();
722
		if (selectedXmlElement != null) {
611
			setSelection(selectedXmlElement, !isActivePart());
723
			setSelection(selectedXmlElement, !isActivePart());
612
        }
724
		}
613
    }
725
	}
726
727
	private boolean isActivePart() {
728
		IWorkbenchPart part = getActivePart();
729
		return part != null && part.equals(this);
730
	}
731
732
	public void setSelection(AntElementNode reference, boolean moveCursor) {
733
		if (fSelectionSetFromOutline) {
734
			// the work has all just been done via a selection setting in the
735
			// outline
736
			fSelectionSetFromOutline = false;
737
			return;
738
		}
739
		if (reference == null) {
740
			if (moveCursor) {
741
				resetHighlightRange();
742
				markInNavigationHistory();
743
			}
744
			return;
745
		}
614
746
615
    private boolean isActivePart() {
616
        IWorkbenchPart part= getActivePart();
617
        return part != null && part.equals(this);
618
    }
619
    
620
    public void setSelection(AntElementNode reference, boolean moveCursor) {
621
    	if (fSelectionSetFromOutline) {
622
    		//the work has all just been done via a selection setting in the outline
623
    		fSelectionSetFromOutline= false;
624
    		return;
625
    	}
626
        if (reference == null) {
627
        	if (moveCursor) {
628
        		 resetHighlightRange();
629
                 markInNavigationHistory();
630
        	}
631
        	return;
632
        } 
633
		
634
		if (moveCursor) {
747
		if (moveCursor) {
635
			markInNavigationHistory();
748
			markInNavigationHistory();
636
		}
749
		}
637
		
638
    	while (reference.getImportNode() != null) {
639
    		reference= reference.getImportNode();
640
    	}
641
    	if (reference.isExternal()) {
642
    		return;
643
    	}
644
        
645
        ISourceViewer sourceViewer= getSourceViewer();
646
        if (sourceViewer == null) {
647
            return;
648
        }
649
        StyledText textWidget= sourceViewer.getTextWidget();
650
        if (textWidget == null) {
651
            return;
652
        }
653
            
654
        try {
655
            int offset= reference.getOffset();
656
            if (offset < 0) {
657
                return;
658
            }
659
            int length= reference.getSelectionLength();
660
            int highLightLength= reference.getLength();
661
               
662
            textWidget.setRedraw(false);
663
            
664
            if (highLightLength > 0) {
665
                setHighlightRange(offset, highLightLength, moveCursor);
666
            }
667
            
668
            if (!moveCursor) {
669
                return;
670
            }
671
                                        
672
            if (offset > -1 && length > 0) {
673
                sourceViewer.revealRange(offset, length);
674
                // Selected region begins one index after offset
675
                sourceViewer.setSelectedRange(offset, length); 
676
                markInNavigationHistory();
677
            }
678
        } catch (IllegalArgumentException x) {
679
        	AntUIPlugin.log(x);
680
        } finally {
681
            textWidget.setRedraw(true);
682
        }
683
    }
684
750
685
	/* (non-Javadoc)
751
		while (reference.getImportNode() != null) {
752
			reference = reference.getImportNode();
753
		}
754
		if (reference.isExternal()) {
755
			return;
756
		}
757
758
		ISourceViewer sourceViewer = getSourceViewer();
759
		if (sourceViewer == null) {
760
			return;
761
		}
762
		StyledText textWidget = sourceViewer.getTextWidget();
763
		if (textWidget == null) {
764
			return;
765
		}
766
767
		try {
768
			int offset = reference.getOffset();
769
			if (offset < 0) {
770
				return;
771
			}
772
			int length = reference.getSelectionLength();
773
			int highLightLength = reference.getLength();
774
775
			textWidget.setRedraw(false);
776
777
			if (highLightLength > 0) {
778
				setHighlightRange(offset, highLightLength, moveCursor);
779
			}
780
781
			if (!moveCursor) {
782
				return;
783
			}
784
785
			if (offset > -1 && length > 0) {
786
				sourceViewer.revealRange(offset, length);
787
				// Selected region begins one index after offset
788
				sourceViewer.setSelectedRange(offset, length);
789
				markInNavigationHistory();
790
			}
791
		} catch (IllegalArgumentException x) {
792
			AntUIPlugin.log(x);
793
		} finally {
794
			textWidget.setRedraw(true);
795
		}
796
	}
797
798
	/*
799
	 * (non-Javadoc)
800
	 * 
686
	 * @see org.eclipse.ui.texteditor.AbstractTextEditor#affectsTextPresentation(org.eclipse.jface.util.PropertyChangeEvent)
801
	 * @see org.eclipse.ui.texteditor.AbstractTextEditor#affectsTextPresentation(org.eclipse.jface.util.PropertyChangeEvent)
687
	 */
802
	 */
688
	protected boolean affectsTextPresentation(PropertyChangeEvent event) {
803
	protected boolean affectsTextPresentation(PropertyChangeEvent event) {
689
		return ((AntEditorSourceViewerConfiguration)getSourceViewerConfiguration()).affectsTextPresentation(event);
804
		return ((AntEditorSourceViewerConfiguration) getSourceViewerConfiguration())
805
				.affectsTextPresentation(event);
690
	}
806
	}
691
	
807
692
	/* (non-Javadoc)
808
	/*
809
	 * (non-Javadoc)
810
	 * 
693
	 * @see org.eclipse.ui.texteditor.AbstractTextEditor#handlePreferenceStoreChanged(org.eclipse.jface.util.PropertyChangeEvent)
811
	 * @see org.eclipse.ui.texteditor.AbstractTextEditor#handlePreferenceStoreChanged(org.eclipse.jface.util.PropertyChangeEvent)
694
	 */
812
	 */
695
	protected void handlePreferenceStoreChanged(PropertyChangeEvent event) {
813
	protected void handlePreferenceStoreChanged(PropertyChangeEvent event) {
696
		String property= event.getProperty();
814
		String property = event.getProperty();
697
		
815
698
		if (AbstractDecoratedTextEditorPreferenceConstants.EDITOR_TAB_WIDTH.equals(property)) {
816
		if (AbstractDecoratedTextEditorPreferenceConstants.EDITOR_TAB_WIDTH
699
			Object value= event.getNewValue();
817
				.equals(property)) {
700
			StatusLineSourceViewer viewer= (StatusLineSourceViewer) getSourceViewer();
818
			Object value = event.getNewValue();
701
			int newValue= -1;
819
			StatusLineSourceViewer viewer = (StatusLineSourceViewer) getSourceViewer();
820
			int newValue = -1;
702
			if (value instanceof Integer) {
821
			if (value instanceof Integer) {
703
				newValue=((Integer) value).intValue();
822
				newValue = ((Integer) value).intValue();
704
			} else if (value instanceof String) {
823
			} else if (value instanceof String) {
705
				newValue= Integer.parseInt((String) value);
824
				newValue = Integer.parseInt((String) value);
706
			}
825
			}
707
			if (newValue != -1) {
826
			if (newValue != -1) {
708
				viewer.getTextWidget().setTabs(newValue);
827
				viewer.getTextWidget().setTabs(newValue);
709
			}
828
			}
710
			return;
829
			return;
711
		}
830
		}
712
		
831
713
		if (AntEditorPreferenceConstants.EDITOR_MARK_OCCURRENCES.equals(property)) {
832
		if (AntEditorPreferenceConstants.EDITOR_MARK_OCCURRENCES
714
			boolean newBooleanValue= Boolean.valueOf(event.getNewValue().toString()).booleanValue();
833
				.equals(property)) {
834
			boolean newBooleanValue = Boolean.valueOf(
835
					event.getNewValue().toString()).booleanValue();
715
			if (newBooleanValue != fMarkOccurrenceAnnotations) {
836
			if (newBooleanValue != fMarkOccurrenceAnnotations) {
716
				fMarkOccurrenceAnnotations= newBooleanValue;
837
				fMarkOccurrenceAnnotations = newBooleanValue;
717
				if (fMarkOccurrenceAnnotations) {
838
				if (fMarkOccurrenceAnnotations) {
718
					installOccurrencesFinder();
839
					installOccurrencesFinder();
719
				} else {
840
				} else {
720
					uninstallOccurrencesFinder();	
841
					uninstallOccurrencesFinder();
721
				}
842
				}
722
			}
843
			}
723
			return;
844
			return;
724
		}
845
		}
725
		if (AntEditorPreferenceConstants.EDITOR_STICKY_OCCURRENCES.equals(property)) {
846
		if (AntEditorPreferenceConstants.EDITOR_STICKY_OCCURRENCES
726
			boolean newBooleanValue= Boolean.valueOf(event.getNewValue().toString()).booleanValue();
847
				.equals(property)) {
727
			fStickyOccurrenceAnnotations= newBooleanValue;
848
			boolean newBooleanValue = Boolean.valueOf(
849
					event.getNewValue().toString()).booleanValue();
850
			fStickyOccurrenceAnnotations = newBooleanValue;
728
			return;
851
			return;
729
		}
852
		}
730
853
731
		AntEditorSourceViewerConfiguration sourceViewerConfiguration= (AntEditorSourceViewerConfiguration)getSourceViewerConfiguration();
854
		AntEditorSourceViewerConfiguration sourceViewerConfiguration = (AntEditorSourceViewerConfiguration) getSourceViewerConfiguration();
732
        if (sourceViewerConfiguration != null) {
855
		if (sourceViewerConfiguration != null) {
733
            if (affectsTextPresentation(event)) {
856
			if (affectsTextPresentation(event)) {
734
                sourceViewerConfiguration.adaptToPreferenceChange(event);
857
				sourceViewerConfiguration.adaptToPreferenceChange(event);
735
            }
858
			}
736
859
737
            sourceViewerConfiguration.changeConfiguration(event);
860
			sourceViewerConfiguration.changeConfiguration(event);
738
        }					
861
		}
739
		super.handlePreferenceStoreChanged(event);
862
		super.handlePreferenceStoreChanged(event);
740
	}
863
	}
741
	
864
742
	/*
865
	/*
743
	 * @see org.eclipse.ui.editors.text.TextEditor#doSetInput(org.eclipse.ui.IEditorInput)
866
	 * @see org.eclipse.ui.editors.text.TextEditor#doSetInput(org.eclipse.ui.IEditorInput)
744
	 */
867
	 */
745
	protected void doSetInput(IEditorInput input) throws CoreException {
868
	protected void doSetInput(IEditorInput input) throws CoreException {
746
		fAntModel= null;
869
		fAntModel = null;
747
		super.doSetInput(input);
870
		super.doSetInput(input);
748
		setOutlinePageInput();
871
		setOutlinePageInput();
749
		if (fFoldingStructureProvider != null) {
872
		if (fFoldingStructureProvider != null) {
750
			fFoldingStructureProvider.setDocument(getDocumentProvider().getDocument(input));
873
			fFoldingStructureProvider.setDocument(getDocumentProvider()
874
					.getDocument(input));
751
		}
875
		}
752
	}
876
	}
753
877
Lines 756-896 Link Here
756
			fOutlinePage.setPageInput(getAntModel());
880
			fOutlinePage.setPageInput(getAntModel());
757
		}
881
		}
758
	}
882
	}
759
	
883
760
	/**
884
	/**
761
	 * Returns the Ant model for the current editor input of this editor.
885
	 * Returns the Ant model for the current editor input of this editor.
886
	 * 
762
	 * @return the Ant model for this editor or <code>null</code>
887
	 * @return the Ant model for this editor or <code>null</code>
763
	 */
888
	 */
764
	public AntModel getAntModel() {
889
	public AntModel getAntModel() {
765
        if (fAntModel == null) {
890
		if (fAntModel == null) {
766
            IDocumentProvider provider= getDocumentProvider();
891
			IDocumentProvider provider = getDocumentProvider();
767
            if (provider instanceof AntEditorDocumentProvider) {
892
			if (provider instanceof AntEditorDocumentProvider) {
768
                AntEditorDocumentProvider documentProvider= (AntEditorDocumentProvider) provider;
893
				AntEditorDocumentProvider documentProvider = (AntEditorDocumentProvider) provider;
769
                fAntModel= documentProvider.getAntModel(getEditorInput());
894
				fAntModel = documentProvider.getAntModel(getEditorInput());
770
            }
895
			}
771
        }
896
		}
772
		return fAntModel;
897
		return fAntModel;
773
	}
898
	}
774
	
899
775
	/* (non-Javadoc)
900
	/*
776
	 * @see org.eclipse.ui.texteditor.AbstractTextEditor#createSourceViewer(org.eclipse.swt.widgets.Composite, org.eclipse.jface.text.source.IVerticalRuler, int)
901
	 * (non-Javadoc)
777
	 */
902
	 * 
778
	protected ISourceViewer createSourceViewer(Composite parent, IVerticalRuler ruler, int styles) {
903
	 * @see org.eclipse.ui.texteditor.AbstractTextEditor#createSourceViewer(org.eclipse.swt.widgets.Composite,
779
		fOverviewRuler= createOverviewRuler(getSharedColors());
904
	 *      org.eclipse.jface.text.source.IVerticalRuler, int)
780
		ISourceViewer viewer= new StatusLineSourceViewer(parent, ruler, getOverviewRuler(), styles);
905
	 */
781
		//ensure decoration support has been created and configured.
906
	protected ISourceViewer createSourceViewer(Composite parent,
907
			IVerticalRuler ruler, int styles) {
908
		fOverviewRuler = createOverviewRuler(getSharedColors());
909
		ISourceViewer viewer = new StatusLineSourceViewer(parent, ruler,
910
				getOverviewRuler(), styles);
911
		// ensure decoration support has been created and configured.
782
		getSourceViewerDecorationSupport(viewer);
912
		getSourceViewerDecorationSupport(viewer);
783
		return viewer;
913
		return viewer;
784
	}
914
	}
785
	
915
786
	/**
916
	/**
787
	 * Set the given message as error message to this editor's status line.
917
	 * Set the given message as error message to this editor's status line.
788
	 * @param msg message to be set
918
	 * 
919
	 * @param msg
920
	 *            message to be set
789
	 */
921
	 */
790
	protected void setStatusLineErrorMessage(String msg) {
922
	protected void setStatusLineErrorMessage(String msg) {
791
		IEditorStatusLine statusLine= (IEditorStatusLine) getAdapter(IEditorStatusLine.class);
923
		IEditorStatusLine statusLine = (IEditorStatusLine) getAdapter(IEditorStatusLine.class);
792
		if (statusLine != null)
924
		if (statusLine != null)
793
			statusLine.setMessage(true, msg, null);	
925
			statusLine.setMessage(true, msg, null);
794
	}
926
	}
795
927
796
	public void openReferenceElement() {
928
	public void openReferenceElement() {
797
		ISelection selection= getSelectionProvider().getSelection();
929
		ISelection selection = getSelectionProvider().getSelection();
798
		Object target= null;
930
		Object target = null;
799
		if (selection instanceof ITextSelection) {
931
		if (selection instanceof ITextSelection) {
800
			ITextSelection textSelection= (ITextSelection)selection;
932
			ITextSelection textSelection = (ITextSelection) selection;
801
			ISourceViewer viewer= getSourceViewer();
933
			ISourceViewer viewer = getSourceViewer();
802
			int textOffset= textSelection.getOffset();
934
			int textOffset = textSelection.getOffset();
803
			IRegion region= XMLTextHover.getRegion(viewer, textOffset);
935
			IRegion region = XMLTextHover.getRegion(viewer, textOffset);
804
			target= findTarget(region);
936
			target = findTarget(region);
805
		}
937
		}
806
		
938
807
		openTarget(target);
939
		openTarget(target);
808
	}
940
	}
809
	
941
810
	protected void openTarget(Object node) {
942
	protected void openTarget(Object node) {
811
		String errorMessage= null;
943
		String errorMessage = null;
812
		if (node instanceof AntElementNode) {
944
		if (node instanceof AntElementNode) {
813
			errorMessage= openNode((AntElementNode) node);
945
			errorMessage = openNode((AntElementNode) node);
814
			if (errorMessage == null) {
946
			if (errorMessage == null) {
815
				return;
947
				return;
816
			}
948
			}
817
		} else if (node instanceof String){
949
		} else if (node instanceof String) {
818
			errorMessage= openInEditor((String) node, getAntModel().getEditedFile());
950
			errorMessage = openInEditor((String) node, getAntModel()
951
					.getEditedFile());
819
			if (errorMessage == null) {
952
			if (errorMessage == null) {
820
				return;
953
				return;
821
			}
954
			}
822
		}
955
		}
823
		if (errorMessage == null || errorMessage.length() == 0) {
956
		if (errorMessage == null || errorMessage.length() == 0) {
824
			errorMessage= AntEditorMessages.getString("AntEditor.3"); //$NON-NLS-1$
957
			errorMessage = AntEditorMessages.getString("AntEditor.3"); //$NON-NLS-1$
825
		}
958
		}
826
		setStatusLineErrorMessage(errorMessage);
959
		setStatusLineErrorMessage(errorMessage);
827
		getSite().getShell().getDisplay().beep();
960
		getSite().getShell().getDisplay().beep();
828
	}
961
	}
829
962
830
	/**
963
	/**
831
     * @param region The region to find the navigation target
964
	 * @param region
832
     * @return the navigation target at the specified region
965
	 *            The region to find the navigation target
833
     */
966
	 * @return the navigation target at the specified region
834
    public Object findTarget(IRegion region) {
967
	 */
835
        ISourceViewer viewer = getSourceViewer();
968
	public Object findTarget(IRegion region) {
836
        AntElementNode node= null;
969
		ISourceViewer viewer = getSourceViewer();
837
       
970
		AntElementNode node = null;
971
838
		if (region != null) {
972
		if (region != null) {
839
			IDocument document= viewer.getDocument();
973
			IDocument document = viewer.getDocument();
840
			String text= null;
974
			String text = null;
841
			try {
975
			try {
842
				text= document.get(region.getOffset(), region.getLength());
976
				text = document.get(region.getOffset(), region.getLength());
843
			} catch (BadLocationException e) {
977
			} catch (BadLocationException e) {
844
			}
978
			}
845
			if (text != null && text.length() > 0) {
979
			if (text != null && text.length() > 0) {
846
				AntModel model= getAntModel();
980
				AntModel model = getAntModel();
847
				if (model == null) {
981
				if (model == null) {
848
					return null;
982
					return null;
849
				}
983
				}
850
				node= model.getReferenceNode(text);
984
				node = model.getReferenceNode(text);
851
				if (node == null) {
985
				if (node == null) {
852
					node= model.getTargetNode(text);
986
					node = model.getTargetNode(text);
853
					if (node == null) {
987
					if (node == null) {
854
						node= model.getPropertyNode(text);
988
						node = model.getPropertyNode(text);
855
						if (node == null) {
989
						if (node == null) {
856
							String path= model.getPath(text, region.getOffset());
990
							String path = model.getPath(text, region
991
									.getOffset());
857
							if (path != null) {
992
							if (path != null) {
858
								return path;
993
								return path;
859
							}
994
							}
860
                            
995
861
                            node= model.getDefininingTaskNode(text);
996
							node = model.getDefininingTaskNode(text);
862
                            if (node == null) {
997
							if (node == null) {
863
                                node= model.getMacroDefAttributeNode(text);
998
								node = model.getMacroDefAttributeNode(text);
864
                            }
999
							}
865
						}
1000
						}
866
					} 
1001
					}
867
				}
1002
				}
868
			}
1003
			}
869
		}
1004
		}
870
		return node;
1005
		return node;
871
    }
1006
	}
872
873
1007
874
    private String openNode(AntElementNode node) {
1008
	private String openNode(AntElementNode node) {
875
		String errorMessage= null;
1009
		String errorMessage = null;
876
		if (node.isExternal()) {
1010
		if (node.isExternal()) {
877
			String path= node.getFilePath();
1011
			String path = node.getFilePath();
878
			errorMessage= openInEditor(path, null);
1012
			errorMessage = openInEditor(path, null);
879
		} else {
1013
		} else {
880
			setSelection(node, true);
1014
			setSelection(node, true);
881
		}
1015
		}
882
		return errorMessage;
1016
		return errorMessage;
883
	}
1017
	}
884
	
1018
885
	private String openInEditor(String path, File buildFile) {
1019
	private String openInEditor(String path, File buildFile) {
886
		File buildFileParent= null;
1020
		File buildFileParent = null;
887
		if (buildFile != null) {
1021
		if (buildFile != null) {
888
			buildFileParent= buildFile.getParentFile();
1022
			buildFileParent = buildFile.getParentFile();
889
		}
1023
		}
890
		IFile file= AntUtil.getFileForLocation(path, buildFileParent);
1024
		IFile file = AntUtil.getFileForLocation(path, buildFileParent);
891
		if (file != null && file.exists()) {
1025
		if (file != null && file.exists()) {
892
			try {
1026
			try {
893
				IWorkbenchPage p= getEditorSite().getPage();
1027
				IWorkbenchPage p = getEditorSite().getPage();
894
				if (p != null) {
1028
				if (p != null) {
895
					IDE.openEditor(p, file, isActivePart());
1029
					IDE.openEditor(p, file, isActivePart());
896
				}
1030
				}
Lines 899-974 Link Here
899
				return e.getLocalizedMessage();
1033
				return e.getLocalizedMessage();
900
			}
1034
			}
901
		}
1035
		}
902
        File externalFile= new File(path);
1036
		File externalFile = new File(path);
903
        if (externalFile.exists()) {
1037
		if (externalFile.exists()) {
904
            new ExternalHyperlink(externalFile, -1).linkActivated();
1038
			new ExternalHyperlink(externalFile, -1).linkActivated();
905
            return null;
1039
			return null;
906
        }
1040
		}
907
        
1041
908
		return ""; //$NON-NLS-1$
1042
		return ""; //$NON-NLS-1$
909
	}
1043
	}
910
	
1044
911
	/* (non-Javadoc)
1045
	/*
1046
	 * (non-Javadoc)
1047
	 * 
912
	 * @see org.eclipse.ui.texteditor.AbstractTextEditor#editorContextMenuAboutToShow(org.eclipse.jface.action.IMenuManager)
1048
	 * @see org.eclipse.ui.texteditor.AbstractTextEditor#editorContextMenuAboutToShow(org.eclipse.jface.action.IMenuManager)
913
	 */
1049
	 */
914
	public void editorContextMenuAboutToShow(IMenuManager menu) {
1050
	public void editorContextMenuAboutToShow(IMenuManager menu) {
915
		super.editorContextMenuAboutToShow(menu);
1051
		super.editorContextMenuAboutToShow(menu);
916
		
1052
917
		if (getAntModel() != null) {
1053
		if (getAntModel() != null) {
918
			IAction action= getAction("OpenDeclaration"); //$NON-NLS-1$
1054
			IAction action = getAction("OpenDeclaration"); //$NON-NLS-1$
919
			if (action != null) {
1055
			if (action != null) {
920
				String openGroup = "group.open"; //$NON-NLS-1$
1056
				String openGroup = "group.open"; //$NON-NLS-1$
921
	    	    menu.appendToGroup(ITextEditorActionConstants.GROUP_UNDO, new Separator(openGroup)); 
1057
				menu.appendToGroup(ITextEditorActionConstants.GROUP_UNDO,
1058
						new Separator(openGroup));
922
				menu.appendToGroup(openGroup, action);
1059
				menu.appendToGroup(openGroup, action);
923
			}
1060
			}
924
			
1061
925
			action= getAction("renameInFile"); //$NON-NLS-1$
1062
			action = getAction("renameInFile"); //$NON-NLS-1$
926
			String editGroup = "group.edit"; //$NON-NLS-1$
1063
			String editGroup = "group.edit"; //$NON-NLS-1$
927
		    menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, new Separator(editGroup)); 
1064
			menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT,
1065
					new Separator(editGroup));
928
			menu.appendToGroup(editGroup, action);
1066
			menu.appendToGroup(editGroup, action);
929
			
1067
930
			action= getAction("ContentFormat"); //$NON-NLS-1$
1068
			action = getAction("ContentFormat"); //$NON-NLS-1$
931
			menu.appendToGroup(editGroup, action);
1069
			menu.appendToGroup(editGroup, action);
932
		}
1070
		}
933
	}
1071
	}
934
	
1072
935
	/* (non-Javadoc)
1073
	/*
1074
	 * (non-Javadoc)
1075
	 * 
936
	 * @see org.eclipse.ui.IWorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite)
1076
	 * @see org.eclipse.ui.IWorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite)
937
	 */
1077
	 */
938
	public void createPartControl(Composite parent) {
1078
	public void createPartControl(Composite parent) {
939
		super.createPartControl(parent);
1079
		super.createPartControl(parent);
940
		
1080
941
		ProjectionViewer projectionViewer= (ProjectionViewer) getSourceViewer(); 
1081
		ProjectionViewer projectionViewer = (ProjectionViewer) getSourceViewer();
942
        createFoldingSupport(projectionViewer);
1082
		createFoldingSupport(projectionViewer);
943
        if (isFoldingEnabled()) {
1083
		if (isFoldingEnabled()) {
944
        	projectionViewer.doOperation(ProjectionViewer.TOGGLE);
1084
			projectionViewer.doOperation(ProjectionViewer.TOGGLE);
945
        }
1085
		}
946
        
1086
947
		if (fMarkOccurrenceAnnotations) {
1087
		if (fMarkOccurrenceAnnotations) {
948
			installOccurrencesFinder();
1088
			installOccurrencesFinder();
949
		}
1089
		}
950
		getEditorSite().getShell().addShellListener(fActivationListener);
1090
		getEditorSite().getShell().addShellListener(fActivationListener);
951
		
1091
952
		fEditorSelectionChangedListener= new EditorSelectionChangedListener();
1092
		fEditorSelectionChangedListener = new EditorSelectionChangedListener();
953
		fEditorSelectionChangedListener.install(getSelectionProvider());
1093
		fEditorSelectionChangedListener.install(getSelectionProvider());
954
	}
1094
	}
955
	
1095
956
	private void createFoldingSupport(ProjectionViewer projectionViewer) {
1096
	private void createFoldingSupport(ProjectionViewer projectionViewer) {
957
		fProjectionSupport= new ProjectionSupport(projectionViewer, getAnnotationAccess(), getSharedColors());
1097
		fProjectionSupport = new ProjectionSupport(projectionViewer,
958
    	fProjectionSupport.setHoverControlCreator(new IInformationControlCreator() {
1098
				getAnnotationAccess(), getSharedColors());
959
			public IInformationControl createInformationControl(Shell shell) {
1099
		fProjectionSupport
960
				return new AntSourceViewerInformationControl(shell);
1100
				.setHoverControlCreator(new IInformationControlCreator() {
961
			}
1101
					public IInformationControl createInformationControl(
962
		});
1102
							Shell shell) {
963
        fProjectionSupport.install();
1103
						return new AntSourceViewerInformationControl(shell);
964
		((ProjectionViewer)getViewer()).addProjectionListener(this);
1104
					}
965
        
1105
				});
966
	}
1106
		fProjectionSupport.install();
1107
		((ProjectionViewer) getViewer()).addProjectionListener(this);
967
1108
1109
	}
968
1110
969
	private boolean isFoldingEnabled() {
1111
	private boolean isFoldingEnabled() {
970
		IPreferenceStore store= getPreferenceStore();
1112
		IPreferenceStore store = getPreferenceStore();
971
		return store.getBoolean(AntEditorPreferenceConstants.EDITOR_FOLDING_ENABLED);
1113
		return store
1114
				.getBoolean(AntEditorPreferenceConstants.EDITOR_FOLDING_ENABLED);
972
	}
1115
	}
973
1116
974
	/*
1117
	/*
Lines 976-1090 Link Here
976
	 * @since 3.3
1119
	 * @since 3.3
977
	 */
1120
	 */
978
	protected boolean isTabsToSpacesConversionEnabled() {
1121
	protected boolean isTabsToSpacesConversionEnabled() {
979
		return super.isTabsToSpacesConversionEnabled(); //provide package visibility
1122
		return super.isTabsToSpacesConversionEnabled(); // provide package
1123
		// visibility
980
	}
1124
	}
981
	
1125
982
	/* (non-Javadoc)
1126
	/*
1127
	 * (non-Javadoc)
1128
	 * 
983
	 * @see org.eclipse.ui.IWorkbenchPart#dispose()
1129
	 * @see org.eclipse.ui.IWorkbenchPart#dispose()
984
	 */
1130
	 */
985
	public void dispose() {
1131
	public void dispose() {
986
		if (fEditorSelectionChangedListener != null)  {
1132
		if (fEditorSelectionChangedListener != null) {
987
			fEditorSelectionChangedListener.uninstall(getSelectionProvider());
1133
			fEditorSelectionChangedListener.uninstall(getSelectionProvider());
988
			fEditorSelectionChangedListener= null;
1134
			fEditorSelectionChangedListener = null;
989
		}
1135
		}
990
		
1136
991
		((ProjectionViewer)getViewer()).removeProjectionListener(this);
1137
		((ProjectionViewer) getViewer()).removeProjectionListener(this);
992
		if (fProjectionSupport != null) {
1138
		if (fProjectionSupport != null) {
993
			fProjectionSupport.dispose();
1139
			fProjectionSupport.dispose();
994
			fProjectionSupport= null;
1140
			fProjectionSupport = null;
995
		}
1141
		}
996
		
1142
997
		uninstallOccurrencesFinder();
1143
		uninstallOccurrencesFinder();
998
		
1144
999
		if (fActivationListener != null) {
1145
		if (fActivationListener != null) {
1000
			Shell shell= getEditorSite().getShell();
1146
			Shell shell = getEditorSite().getShell();
1001
			if (shell != null && !shell.isDisposed()) {
1147
			if (shell != null && !shell.isDisposed()) {
1002
				shell.removeShellListener(fActivationListener);
1148
				shell.removeShellListener(fActivationListener);
1003
			}
1149
			}
1004
			fActivationListener= null;
1150
			fActivationListener = null;
1005
		}
1151
		}
1006
		
1152
1007
		AntModelCore.getDefault().removeAntModelListener(fAntModelListener);
1153
		AntModelCore.getDefault().removeAntModelListener(fAntModelListener);
1008
		fAntModel= null;
1154
		fAntModel = null;
1009
		super.dispose();
1155
		super.dispose();
1010
	}
1156
	}
1011
	
1157
1012
	/* (non-Javadoc)
1158
	/*
1159
	 * (non-Javadoc)
1160
	 * 
1013
	 * @see org.eclipse.ui.ISaveablePart#doSave(org.eclipse.core.runtime.IProgressMonitor)
1161
	 * @see org.eclipse.ui.ISaveablePart#doSave(org.eclipse.core.runtime.IProgressMonitor)
1014
	 */
1162
	 */
1015
	public void doSave(IProgressMonitor monitor) {
1163
	public void doSave(IProgressMonitor monitor) {
1016
		super.doSave(monitor);
1164
		super.doSave(monitor);
1017
		AntModel model= getAntModel();
1165
		AntModel model = getAntModel();
1018
		model.updateMarkers();
1166
		model.updateMarkers();
1019
		updateEditorImage(model);
1167
		updateEditorImage(model);
1020
	}
1168
	}
1021
	
1169
1022
	private void updateEditorImage(AntModel model) {
1170
	private void updateEditorImage(AntModel model) {
1023
		Image titleImage= getTitleImage();
1171
		Image titleImage = getTitleImage();
1024
		if (titleImage == null) {
1172
		if (titleImage == null) {
1025
			return;
1173
			return;
1026
		}
1174
		}
1027
		AntProjectNode node= model.getProjectNode();
1175
		AntProjectNode node = model.getProjectNode();
1028
		if (node != null) {
1176
		if (node != null) {
1029
			postImageChange(node);
1177
			postImageChange(node);
1030
		}
1178
		}
1031
	}
1179
	}
1032
	
1180
1033
	private void updateForInitialReconcile() {
1181
	private void updateForInitialReconcile() {
1034
		IDocumentProvider provider=  getDocumentProvider();
1182
		IDocumentProvider provider = getDocumentProvider();
1035
		if (provider == null) {//disposed
1183
		if (provider == null) {// disposed
1036
			return;
1184
			return;
1037
		}
1185
		}
1038
		if (getAntModel() == null) {
1186
		if (getAntModel() == null) {
1039
			return;
1187
			return;
1040
		}
1188
		}
1041
        IDocument doc= provider.getDocument(getEditorInput());
1189
		IDocument doc = provider.getDocument(getEditorInput());
1042
        if (doc == null) {
1190
		if (doc == null) {
1043
            return; //disposed
1191
			return; // disposed
1044
        }
1192
		}
1045
        Object lock= getLockObject(doc);
1193
		Object lock = getLockObject(doc);
1046
		//ensure to synchronize so that the AntModel is not nulled out underneath in the AntEditorDocumentProvider
1194
		// ensure to synchronize so that the AntModel is not nulled out
1047
		//when the editor/doc provider are disposed
1195
		// underneath in the AntEditorDocumentProvider
1048
        if (lock == null) {
1196
		// when the editor/doc provider are disposed
1049
            updateModelForInitialReconcile();
1197
		if (lock == null) {
1050
        } else {
1198
			updateModelForInitialReconcile();
1051
            synchronized (lock) {
1199
		} else {
1052
                updateModelForInitialReconcile();
1200
			synchronized (lock) {
1053
            }
1201
				updateModelForInitialReconcile();
1054
        }
1202
			}
1055
	}
1203
		}
1056
    
1204
	}
1057
    private void updateModelForInitialReconcile() {
1205
1058
        AntModel model= getAntModel();
1206
	private void updateModelForInitialReconcile() {
1059
        if (model == null) {
1207
		AntModel model = getAntModel();
1060
            return;
1208
		if (model == null) {
1061
        }
1209
			return;
1062
1210
		}
1063
        fInitialReconcile= false;
1211
1064
        updateEditorImage(model);
1212
		fInitialReconcile = false;
1065
        model.updateForInitialReconcile();
1213
		updateEditorImage(model);
1066
    }
1214
		model.updateForInitialReconcile();
1067
    
1215
	}
1068
    private Object getLockObject(IDocument doc) {
1216
1069
        Object lock= null;
1217
	private Object getLockObject(IDocument doc) {
1070
        if (doc instanceof ISynchronizable) {
1218
		Object lock = null;
1071
            lock= ((ISynchronizable) doc).getLockObject();
1219
		if (doc instanceof ISynchronizable) {
1072
        } else {
1220
			lock = ((ISynchronizable) doc).getLockObject();
1073
            lock= getAntModel();
1221
		} else {
1074
        }
1222
			lock = getAntModel();
1075
        return lock;
1223
		}
1076
    }
1224
		return lock;
1077
	
1225
	}
1226
1078
	private void postImageChange(final AntElementNode node) {
1227
	private void postImageChange(final AntElementNode node) {
1079
		Shell shell= getSite().getShell();
1228
		Shell shell = getSite().getShell();
1080
		if (shell != null && !shell.isDisposed()) {
1229
		if (shell != null && !shell.isDisposed()) {
1081
			shell.getDisplay().asyncExec(new Runnable() {
1230
			shell.getDisplay().asyncExec(new Runnable() {
1082
				public void run() {
1231
				public void run() {
1083
					if (getSite().getShell() == null || getSite().getShell().isDisposed()) {
1232
					if (getSite().getShell() == null
1233
							|| getSite().getShell().isDisposed()) {
1084
						return;
1234
						return;
1085
					}
1235
					}
1086
					Image titleImage= getTitleImage();
1236
					Image titleImage = getTitleImage();
1087
					Image newImage= node.getImage();
1237
					Image newImage = node.getImage();
1088
					if (titleImage != newImage) {
1238
					if (titleImage != newImage) {
1089
						setTitleImage(newImage);
1239
						setTitleImage(newImage);
1090
					}
1240
					}
Lines 1097-1167 Link Here
1097
		if (getSelectionProvider() == null) {
1247
		if (getSelectionProvider() == null) {
1098
			return;
1248
			return;
1099
		}
1249
		}
1100
		AntElementNode node= getNode();
1250
		AntElementNode node = getNode();
1101
		synchronizeOutlinePage(node, checkIfOutlinePageActive);
1251
		synchronizeOutlinePage(node, checkIfOutlinePageActive);
1102
		
1252
1103
	}
1253
	}
1104
	
1254
1105
	protected void synchronize(boolean checkIfOutlinePageActive) {
1255
	protected void synchronize(boolean checkIfOutlinePageActive) {
1106
		if (getSelectionProvider() == null) {
1256
		if (getSelectionProvider() == null) {
1107
			return;
1257
			return;
1108
		}
1258
		}
1109
		AntElementNode node= getNode();
1259
		AntElementNode node = getNode();
1110
		if (AntUIPlugin.getDefault().getPreferenceStore().getBoolean(IAntUIPreferenceConstants.OUTLINE_LINK_WITH_EDITOR)) {
1260
		if (AntUIPlugin.getDefault().getPreferenceStore().getBoolean(
1261
				IAntUIPreferenceConstants.OUTLINE_LINK_WITH_EDITOR)) {
1111
			synchronizeOutlinePage(node, checkIfOutlinePageActive);
1262
			synchronizeOutlinePage(node, checkIfOutlinePageActive);
1112
		}
1263
		}
1113
		setSelection(node, false);
1264
		setSelection(node, false);
1114
		
1265
1115
	}
1266
	}
1116
	
1267
1117
	private AntElementNode getNode() {
1268
	private AntElementNode getNode() {
1118
		AntModel model= getAntModel();
1269
		AntModel model = getAntModel();
1119
		if (model == null) {
1270
		if (model == null) {
1120
			return null;
1271
			return null;
1121
		}
1272
		}
1122
		AntElementNode node= null;
1273
		AntElementNode node = null;
1123
		ISelection selection= getSelectionProvider().getSelection();
1274
		ISelection selection = getSelectionProvider().getSelection();
1124
		if (selection instanceof ITextSelection) {
1275
		if (selection instanceof ITextSelection) {
1125
			ITextSelection textSelection= (ITextSelection)selection;
1276
			ITextSelection textSelection = (ITextSelection) selection;
1126
			int offset= textSelection.getOffset();
1277
			int offset = textSelection.getOffset();
1127
			node= model.getNode(offset, false);
1278
			node = model.getNode(offset, false);
1128
		}
1279
		}
1129
		return node;
1280
		return node;
1130
	}
1281
	}
1131
	
1282
1132
	protected void synchronizeOutlinePage(AntElementNode node, boolean checkIfOutlinePageActive) {
1283
	protected void synchronizeOutlinePage(AntElementNode node,
1133
		if (fOutlinePage != null && !(checkIfOutlinePageActive && isAntOutlinePageActive())) {
1284
			boolean checkIfOutlinePageActive) {
1134
			fOutlinePage.removePostSelectionChangedListener(fSelectionChangedListener);
1285
		if (fOutlinePage != null
1286
				&& !(checkIfOutlinePageActive && isAntOutlinePageActive())) {
1287
			fOutlinePage
1288
					.removePostSelectionChangedListener(fSelectionChangedListener);
1135
			fOutlinePage.select(node);
1289
			fOutlinePage.select(node);
1136
			fOutlinePage.addPostSelectionChangedListener(fSelectionChangedListener);
1290
			fOutlinePage
1291
					.addPostSelectionChangedListener(fSelectionChangedListener);
1137
		}
1292
		}
1138
	}
1293
	}
1139
	
1294
1140
	/* (non-Javadoc)
1295
	/*
1296
	 * (non-Javadoc)
1297
	 * 
1141
	 * @see org.eclipse.ant.internal.ui.editor.text.IReconcilingParticipant#reconciled()
1298
	 * @see org.eclipse.ant.internal.ui.editor.text.IReconcilingParticipant#reconciled()
1142
	 */
1299
	 */
1143
	public void reconciled() {
1300
	public void reconciled() {
1144
		if (fInitialReconcile) {
1301
		if (fInitialReconcile) {
1145
			updateForInitialReconcile();
1302
			updateForInitialReconcile();
1146
		}
1303
		}
1147
		
1304
1148
		SourceViewerConfiguration config= getSourceViewerConfiguration();
1305
		SourceViewerConfiguration config = getSourceViewerConfiguration();
1149
		if (config == null) {
1306
		if (config == null) {
1150
			return; //editor has been disposed.
1307
			return; // editor has been disposed.
1151
		}
1308
		}
1152
		IAutoEditStrategy[] strategies= config.getAutoEditStrategies(getViewer(), null);
1309
		IAutoEditStrategy[] strategies = config.getAutoEditStrategies(
1310
				getViewer(), null);
1153
		for (int i = 0; i < strategies.length; i++) {
1311
		for (int i = 0; i < strategies.length; i++) {
1154
			IAutoEditStrategy strategy = strategies[i];
1312
			IAutoEditStrategy strategy = strategies[i];
1155
			if (strategy instanceof AntAutoEditStrategy) {
1313
			if (strategy instanceof AntAutoEditStrategy) {
1156
				((AntAutoEditStrategy)strategy).reconciled();
1314
				((AntAutoEditStrategy) strategy).reconciled();
1157
			}
1315
			}
1158
		}
1316
		}
1159
		
1317
1160
		Shell shell= getSite().getShell();
1318
		Shell shell = getSite().getShell();
1161
		if (shell != null && !shell.isDisposed()) {
1319
		if (shell != null && !shell.isDisposed()) {
1162
			shell.getDisplay().asyncExec(new Runnable() {
1320
			shell.getDisplay().asyncExec(new Runnable() {
1163
				public void run() {
1321
				public void run() {
1164
					if (getSite().getShell() == null || getSite().getShell().isDisposed()) {
1322
					if (getSite().getShell() == null
1323
							|| getSite().getShell().isDisposed()) {
1165
						return;
1324
						return;
1166
					}
1325
					}
1167
					synchronize(true);
1326
					synchronize(true);
Lines 1169-1187 Link Here
1169
			});
1328
			});
1170
		}
1329
		}
1171
	}
1330
	}
1172
	
1331
1173
	private boolean isAntOutlinePageActive() {
1332
	private boolean isAntOutlinePageActive() {
1174
		IWorkbenchPart part= getActivePart();
1333
		IWorkbenchPart part = getActivePart();
1175
		return part instanceof ContentOutline && ((ContentOutline)part).getCurrentPage() == fOutlinePage;
1334
		return part instanceof ContentOutline
1335
				&& ((ContentOutline) part).getCurrentPage() == fOutlinePage;
1176
	}
1336
	}
1177
1337
1178
	private IWorkbenchPart getActivePart() {
1338
	private IWorkbenchPart getActivePart() {
1179
		IWorkbenchWindow window= getSite().getWorkbenchWindow();
1339
		IWorkbenchWindow window = getSite().getWorkbenchWindow();
1180
		IPartService service= window.getPartService();
1340
		IPartService service = window.getPartService();
1181
		return service.getActivePart();
1341
		return service.getActivePart();
1182
	}
1342
	}
1183
	
1343
1184
	/* (non-Javadoc)
1344
	/*
1345
	 * (non-Javadoc)
1346
	 * 
1185
	 * @see org.eclipse.ui.texteditor.AbstractTextEditor#doSetSelection(org.eclipse.jface.viewers.ISelection)
1347
	 * @see org.eclipse.ui.texteditor.AbstractTextEditor#doSetSelection(org.eclipse.jface.viewers.ISelection)
1186
	 */
1348
	 */
1187
	protected void doSetSelection(ISelection selection) {
1349
	protected void doSetSelection(ISelection selection) {
Lines 1189-1259 Link Here
1189
		synchronizeOutlinePage(true);
1351
		synchronizeOutlinePage(true);
1190
	}
1352
	}
1191
1353
1192
    /**
1354
	/**
1193
     * Returns the viewer associated with this editor
1355
	 * Returns the viewer associated with this editor
1194
     * @return The viewer associated with this editor
1356
	 * 
1195
     */
1357
	 * @return The viewer associated with this editor
1196
    public ISourceViewer getViewer() {
1358
	 */
1197
        return getSourceViewer();
1359
	public ISourceViewer getViewer() {
1198
    }
1360
		return getSourceViewer();
1199
1361
	}
1200
    protected FoldingActionGroup getFoldingActionGroup() {
1362
1201
        return fFoldingGroup;
1363
	protected FoldingActionGroup getFoldingActionGroup() {
1202
    }
1364
		return fFoldingGroup;
1203
1365
	}
1204
    /* (non-Javadoc)
1366
1205
     * @see org.eclipse.jface.text.source.projection.IProjectionListener#projectionEnabled()
1367
	/*
1206
     */
1368
	 * (non-Javadoc)
1207
    public void projectionEnabled() {
1369
	 * 
1208
        fFoldingStructureProvider= new AntFoldingStructureProvider(this);
1370
	 * @see org.eclipse.jface.text.source.projection.IProjectionListener#projectionEnabled()
1209
		fFoldingStructureProvider.setDocument(getDocumentProvider().getDocument(getEditorInput()));
1371
	 */
1372
	public void projectionEnabled() {
1373
		fFoldingStructureProvider = new AntFoldingStructureProvider(this);
1374
		fFoldingStructureProvider.setDocument(getDocumentProvider()
1375
				.getDocument(getEditorInput()));
1210
		fFoldingStructureProvider.updateFoldingRegions(getAntModel());
1376
		fFoldingStructureProvider.updateFoldingRegions(getAntModel());
1211
    }
1377
	}
1212
1378
1213
    /* (non-Javadoc)
1379
	/*
1214
     * @see org.eclipse.jface.text.source.projection.IProjectionListener#projectionDisabled()
1380
	 * (non-Javadoc)
1215
     */
1381
	 * 
1216
    public void projectionDisabled() {
1382
	 * @see org.eclipse.jface.text.source.projection.IProjectionListener#projectionDisabled()
1217
        fFoldingStructureProvider= null;
1383
	 */
1218
    }
1384
	public void projectionDisabled() {
1219
    
1385
		fFoldingStructureProvider = null;
1220
    /* (non-Javadoc)
1386
	}
1387
1388
	/*
1389
	 * (non-Javadoc)
1390
	 * 
1221
	 * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#initializeKeyBindingScopes()
1391
	 * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#initializeKeyBindingScopes()
1222
	 */
1392
	 */
1223
	protected void initializeKeyBindingScopes() {
1393
	protected void initializeKeyBindingScopes() {
1224
		setKeyBindingScopes(new String[] { "org.eclipse.ant.ui.AntEditorScope" });  //$NON-NLS-1$
1394
		setKeyBindingScopes(new String[] { "org.eclipse.ant.ui.AntEditorScope" }); //$NON-NLS-1$
1225
	}
1395
	}
1226
	
1396
1227
	protected IPreferenceStore getEditorPreferenceStore() {
1397
	protected IPreferenceStore getEditorPreferenceStore() {
1228
		return getPreferenceStore();
1398
		return getPreferenceStore();
1229
	}
1399
	}
1230
	
1400
1231
	/* (non-Javadoc)
1401
	/*
1402
	 * (non-Javadoc)
1403
	 * 
1232
	 * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#collectContextMenuPreferencePages()
1404
	 * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#collectContextMenuPreferencePages()
1233
	 * @since 3.1
1405
	 * @since 3.1
1234
	 */
1406
	 */
1235
	protected String[] collectContextMenuPreferencePages() {
1407
	protected String[] collectContextMenuPreferencePages() {
1236
		String[] ids= super.collectContextMenuPreferencePages();
1408
		String[] ids = super.collectContextMenuPreferencePages();
1237
		String[] more= new String[ids.length + 6];
1409
		String[] more = new String[ids.length + 6];
1238
		more[0]= "org.eclipse.ant.ui.AntEditorPreferencePage"; //$NON-NLS-1$
1410
		more[0] = "org.eclipse.ant.ui.AntEditorPreferencePage"; //$NON-NLS-1$
1239
		more[1]= "org.eclipse.ant.ui.AntCodeFormatterPreferencePage"; //$NON-NLS-1$
1411
		more[1] = "org.eclipse.ant.ui.AntCodeFormatterPreferencePage"; //$NON-NLS-1$
1240
		more[2]= "org.eclipse.ant.ui.AntCodeAssistPreferencePage"; //$NON-NLS-1$
1412
		more[2] = "org.eclipse.ant.ui.AntCodeAssistPreferencePage"; //$NON-NLS-1$
1241
		more[3]= "org.eclipse.ant.ui.TemplatesPreferencePage"; //$NON-NLS-1$
1413
		more[3] = "org.eclipse.ant.ui.TemplatesPreferencePage"; //$NON-NLS-1$
1242
		more[4]= "org.eclipse.ant.ui.AntPreferencePage"; //$NON-NLS-1$
1414
		more[4] = "org.eclipse.ant.ui.AntPreferencePage"; //$NON-NLS-1$
1243
		more[5]= "org.eclipse.ant.ui.AntRuntimePreferencePage"; //$NON-NLS-1$
1415
		more[5] = "org.eclipse.ant.ui.AntRuntimePreferencePage"; //$NON-NLS-1$
1244
		System.arraycopy(ids, 0, more, 6, ids.length);
1416
		System.arraycopy(ids, 0, more, 6, ids.length);
1245
		return more;
1417
		return more;
1246
	}
1418
	}
1247
	
1419
1248
	/**
1420
	/**
1249
	 * Updates the occurrences annotations based
1421
	 * Updates the occurrences annotations based on the current selection.
1250
	 * on the current selection.
1251
	 * 
1422
	 * 
1252
	 * @param selection the text selection
1423
	 * @param selection
1253
	 * @param antModel the model for the buildfile
1424
	 *            the text selection
1425
	 * @param antModel
1426
	 *            the model for the buildfile
1254
	 * @since 3.1
1427
	 * @since 3.1
1255
	 */
1428
	 */
1256
	protected void updateOccurrenceAnnotations(ITextSelection selection, AntModel antModel) {
1429
	protected void updateOccurrenceAnnotations(ITextSelection selection,
1430
			AntModel antModel) {
1257
1431
1258
		if (fOccurrencesFinderJob != null)
1432
		if (fOccurrencesFinderJob != null)
1259
			fOccurrencesFinderJob.cancel();
1433
			fOccurrencesFinderJob.cancel();
Lines 1261-1367 Link Here
1261
		if (!fMarkOccurrenceAnnotations) {
1435
		if (!fMarkOccurrenceAnnotations) {
1262
			return;
1436
			return;
1263
		}
1437
		}
1264
		
1438
1265
		if (selection == null || antModel == null) {
1439
		if (selection == null || antModel == null) {
1266
			return;
1440
			return;
1267
		}
1441
		}
1268
		
1442
1269
		IDocument document= getSourceViewer().getDocument();
1443
		IDocument document = getSourceViewer().getDocument();
1270
		if (document == null) {
1444
		if (document == null) {
1271
			return;
1445
			return;
1272
		}
1446
		}
1273
		
1447
1274
		List positions= null;
1448
		List positions = null;
1275
		
1449
1276
		OccurrencesFinder finder= new OccurrencesFinder(this, antModel, document, selection.getOffset());
1450
		OccurrencesFinder finder = new OccurrencesFinder(this, antModel,
1277
		positions= finder.perform();
1451
				document, selection.getOffset());
1278
		
1452
		positions = finder.perform();
1453
1279
		if (positions == null || positions.size() == 0) {
1454
		if (positions == null || positions.size() == 0) {
1280
			if (!fStickyOccurrenceAnnotations) {
1455
			if (!fStickyOccurrenceAnnotations) {
1281
				removeOccurrenceAnnotations();
1456
				removeOccurrenceAnnotations();
1282
			}
1457
			}
1283
			return;
1458
			return;
1284
		}
1459
		}
1285
			
1460
1286
		fOccurrencesFinderJob= new OccurrencesFinderJob(document, positions, selection);
1461
		fOccurrencesFinderJob = new OccurrencesFinderJob(document, positions,
1462
				selection);
1287
		fOccurrencesFinderJob.run(new NullProgressMonitor());
1463
		fOccurrencesFinderJob.run(new NullProgressMonitor());
1288
	}
1464
	}
1289
	
1465
1290
	private void removeOccurrenceAnnotations() {
1466
	private void removeOccurrenceAnnotations() {
1291
		IDocumentProvider documentProvider= getDocumentProvider();
1467
		IDocumentProvider documentProvider = getDocumentProvider();
1292
		if (documentProvider == null) {
1468
		if (documentProvider == null) {
1293
			return;
1469
			return;
1294
		}
1470
		}
1295
		
1471
1296
		IAnnotationModel annotationModel= documentProvider.getAnnotationModel(getEditorInput());
1472
		IAnnotationModel annotationModel = documentProvider
1473
				.getAnnotationModel(getEditorInput());
1297
		if (annotationModel == null || fOccurrenceAnnotations == null) {
1474
		if (annotationModel == null || fOccurrenceAnnotations == null) {
1298
			return;
1475
			return;
1299
		}
1476
		}
1300
1477
1301
		IDocument document= documentProvider.getDocument(getEditorInput());
1478
		IDocument document = documentProvider.getDocument(getEditorInput());
1302
        Object lock= getLockObject(document);
1479
		Object lock = getLockObject(document);
1303
        if (lock == null) {
1480
		if (lock == null) {
1304
            updateAnnotationModelForRemoves(annotationModel);
1481
			updateAnnotationModelForRemoves(annotationModel);
1305
        } else {
1482
		} else {
1306
            synchronized (lock) {
1483
			synchronized (lock) {
1307
                updateAnnotationModelForRemoves(annotationModel);
1484
				updateAnnotationModelForRemoves(annotationModel);
1308
            }
1485
			}
1309
        }
1486
		}
1310
	}
1487
	}
1311
1488
1312
1489
	private void updateAnnotationModelForRemoves(
1313
    private void updateAnnotationModelForRemoves(IAnnotationModel annotationModel) {
1490
			IAnnotationModel annotationModel) {
1314
        if (annotationModel instanceof IAnnotationModelExtension) {
1491
		if (annotationModel instanceof IAnnotationModelExtension) {
1315
        	((IAnnotationModelExtension)annotationModel).replaceAnnotations(fOccurrenceAnnotations, null);
1492
			((IAnnotationModelExtension) annotationModel).replaceAnnotations(
1316
        } else {
1493
					fOccurrenceAnnotations, null);
1317
        	for (int i= 0, length= fOccurrenceAnnotations.length; i < length; i++) {
1494
		} else {
1318
        		annotationModel.removeAnnotation(fOccurrenceAnnotations[i]);
1495
			for (int i = 0, length = fOccurrenceAnnotations.length; i < length; i++) {
1319
        	}
1496
				annotationModel.removeAnnotation(fOccurrenceAnnotations[i]);
1320
        }
1497
			}
1321
        fOccurrenceAnnotations= null;
1498
		}
1322
    }
1499
		fOccurrenceAnnotations = null;
1500
	}
1323
1501
1324
	protected void installOccurrencesFinder() {
1502
	protected void installOccurrencesFinder() {
1325
		fMarkOccurrenceAnnotations= true;
1503
		fMarkOccurrenceAnnotations = true;
1326
		
1504
1327
		if (getSelectionProvider() != null) {
1505
		if (getSelectionProvider() != null) {
1328
			ISelection selection= getSelectionProvider().getSelection();
1506
			ISelection selection = getSelectionProvider().getSelection();
1329
			if (selection instanceof ITextSelection) {
1507
			if (selection instanceof ITextSelection) {
1330
				fForcedMarkOccurrencesSelection= (ITextSelection) selection;
1508
				fForcedMarkOccurrencesSelection = (ITextSelection) selection;
1331
				updateOccurrenceAnnotations(fForcedMarkOccurrencesSelection, getAntModel());
1509
				updateOccurrenceAnnotations(fForcedMarkOccurrencesSelection,
1510
						getAntModel());
1332
			}
1511
			}
1333
		}
1512
		}
1334
		if (fOccurrencesFinderJobCanceler == null) {
1513
		if (fOccurrencesFinderJobCanceler == null) {
1335
			fOccurrencesFinderJobCanceler= new OccurrencesFinderJobCanceler();
1514
			fOccurrencesFinderJobCanceler = new OccurrencesFinderJobCanceler();
1336
			fOccurrencesFinderJobCanceler.install();
1515
			fOccurrencesFinderJobCanceler.install();
1337
		}
1516
		}
1338
	}
1517
	}
1339
	
1518
1340
	protected void uninstallOccurrencesFinder() {
1519
	protected void uninstallOccurrencesFinder() {
1341
		fMarkOccurrenceAnnotations= false;
1520
		fMarkOccurrenceAnnotations = false;
1342
		
1521
1343
		if (fOccurrencesFinderJob != null) {
1522
		if (fOccurrencesFinderJob != null) {
1344
			fOccurrencesFinderJob.cancel();
1523
			fOccurrencesFinderJob.cancel();
1345
			fOccurrencesFinderJob= null;
1524
			fOccurrencesFinderJob = null;
1346
		}
1525
		}
1347
1526
1348
		if (fOccurrencesFinderJobCanceler != null) {
1527
		if (fOccurrencesFinderJobCanceler != null) {
1349
			fOccurrencesFinderJobCanceler.uninstall();
1528
			fOccurrencesFinderJobCanceler.uninstall();
1350
			fOccurrencesFinderJobCanceler= null;
1529
			fOccurrencesFinderJobCanceler = null;
1351
		}
1530
		}
1352
		
1531
1353
		removeOccurrenceAnnotations();
1532
		removeOccurrenceAnnotations();
1354
	}
1533
	}
1355
	
1534
1356
	public boolean isMarkingOccurrences() {
1535
	public boolean isMarkingOccurrences() {
1357
		return fMarkOccurrenceAnnotations;
1536
		return fMarkOccurrenceAnnotations;
1358
	}
1537
	}
1359
1538
1360
1361
	/**
1539
	/**
1362
	 * The editor has entered or exited linked mode.
1540
	 * The editor has entered or exited linked mode.
1363
	 * @param inLinkedMode whether an enter or exit has occurred
1541
	 * 
1364
	 * @param effectsOccurrences whether to change the state of the occurrences finder
1542
	 * @param inLinkedMode
1543
	 *            whether an enter or exit has occurred
1544
	 * @param effectsOccurrences
1545
	 *            whether to change the state of the occurrences finder
1365
	 */
1546
	 */
1366
	public void setInLinkedMode(boolean inLinkedMode, boolean effectsOccurrences) {
1547
	public void setInLinkedMode(boolean inLinkedMode, boolean effectsOccurrences) {
1367
		if (inLinkedMode) {
1548
		if (inLinkedMode) {
(-)Ant (+186 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2005  John-Mason P. Shackelford and others.
3
 * All rights reserved. This program and the accompanying materials 
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 * 
8
 * Contributors:
9
 * 	   John-Mason P. Shackelford - initial API and implementation
10
 *     IBM Corporation - bug fixes
11
 *******************************************************************************/
12
package org.eclipse.ant.internal.ui.editor.templates;
13
14
import org.eclipse.ant.internal.ui.AntUIPlugin;
15
import org.eclipse.ant.internal.ui.editor.AntEditor;
16
import org.eclipse.ant.internal.ui.editor.formatter.FormattingPreferences;
17
import org.eclipse.ant.internal.ui.editor.formatter.XmlFormatter;
18
import org.eclipse.ant.internal.ui.editor.text.AntDocumentSetupParticipant;
19
import org.eclipse.ant.internal.ui.preferences.AntEditorPreferenceConstants;
20
import org.eclipse.jface.resource.JFaceResources;
21
import org.eclipse.jface.text.Document;
22
import org.eclipse.jface.text.IDocument;
23
import org.eclipse.jface.text.IRegion;
24
import org.eclipse.jface.text.ITextSelection;
25
import org.eclipse.jface.text.Position;
26
import org.eclipse.jface.text.Region;
27
import org.eclipse.jface.text.source.ISourceViewer;
28
import org.eclipse.jface.text.source.SourceViewer;
29
import org.eclipse.jface.text.source.SourceViewerConfiguration;
30
import org.eclipse.jface.text.templates.ContextTypeRegistry;
31
import org.eclipse.jface.text.templates.Template;
32
import org.eclipse.jface.text.templates.TemplateContextType;
33
import org.eclipse.swt.SWT;
34
import org.eclipse.swt.graphics.Font;
35
import org.eclipse.swt.graphics.Point;
36
import org.eclipse.swt.widgets.Composite;
37
import org.eclipse.ui.PlatformUI;
38
import org.eclipse.ui.texteditor.templates.TemplatesPage;
39
40
/**
41
 * An implementation of TemplatesPage for AntEditor
42
 * 
43
 * @see TemplatesPage
44
 */
45
public class AntTemplatesPage extends TemplatesPage {
46
47
	private static final ContextTypeRegistry CONTEXT_TYPE_REGISTRY = AntTemplateAccess
48
			.getDefault().getContextTypeRegistry();
49
	private FormattingPreferences fFormattingPreferences = new FormattingPreferences();
50
	private final AntEditor fEditor;
51
	private String fCurrentId;
52
53
	/**
54
	 * Constructor
55
	 * 
56
	 * @param editor
57
	 */
58
	public AntTemplatesPage(AntEditor editor) {
59
		fEditor = editor;
60
		setTemplateStore(AntTemplateAccess.getDefault().getTemplateStore(),
61
				AntUIPlugin.getDefault().getPreferenceStore());
62
		setContextTypeRegistry(CONTEXT_TYPE_REGISTRY);
63
		cursorPositionChanged();
64
		setupEditorDropTarget(fEditor.getSite(), fEditor.getViewer()
65
				.getTextWidget());
66
	}
67
68
	/*
69
	 * (non-Javadoc)
70
	 * 
71
	 * @see org.eclipse.ui.texteditor.templates.TemplatePreferencePage#createViewer(org.eclipse.swt.widgets.Composite)
72
	 */
73
	protected SourceViewer createViewer(Composite parent) {
74
		SourceViewer viewer = new SourceViewer(parent, null, SWT.BORDER
75
				| SWT.V_SCROLL | SWT.H_SCROLL);
76
77
		SourceViewerConfiguration configuration = new AntTemplateViewerConfiguration();
78
		IDocument document = new Document();
79
		new AntDocumentSetupParticipant().setup(document);
80
		viewer.configure(configuration);
81
		viewer.setDocument(document);
82
		viewer.setEditable(false);
83
		Font font = JFaceResources.getFont(JFaceResources.TEXT_FONT);
84
		viewer.getTextWidget().setFont(font);
85
86
		return viewer;
87
	}
88
89
	/*
90
	 * (non-Javadoc)
91
	 * 
92
	 * @see org.eclipse.ui.texteditor.templates.TemplatePreferencePage#getFormatterPreferenceKey()
93
	 */
94
	protected String getFormatterPreferenceKey() {
95
		return AntEditorPreferenceConstants.TEMPLATES_USE_CODEFORMATTER;
96
	}
97
98
	/*
99
	 * @see org.eclipse.ui.texteditor.templates.TemplatePreferencePage#updateViewerInput()
100
	 */
101
	protected void updateViewerInput(Template template) {
102
		SourceViewer viewer = getViewer();
103
104
		if (AntUIPlugin.getDefault().getPreferenceStore().getBoolean(
105
				getFormatterPreferenceKey())) {
106
			String formatted = XmlFormatter.format(template.getPattern(),
107
					fFormattingPreferences);
108
			viewer.getDocument().set(formatted);
109
		} else {
110
			viewer.getDocument().set(template.getPattern());
111
		}
112
	}
113
114
	/*
115
	 * (non-Javadoc)
116
	 * 
117
	 * @see org.eclipse.ui.part.Page#setFocus()
118
	 */
119
	public void setFocus() {
120
	}
121
122
	/*
123
	 * (non-Javadoc)
124
	 * 
125
	 * @see org.eclipse.ui.texteditor.templates.TemplatesPage#getPreferencePageId()
126
	 */
127
	protected String getPreferencePageId() {
128
		return "org.eclipse.ant.ui.TemplatesPreferencePage"; //$NON-NLS-1$
129
	}
130
131
	/*
132
	 * (non-Javadoc)
133
	 * 
134
	 * @see org.eclipse.ui.texteditor.templates.TemplatesPage#insertTemplate(org.eclipse.jface.text.templates.Template)
135
	 */
136
	public void insertTemplate(Template template) {
137
		IRegion region;
138
		TemplateContextType type = CONTEXT_TYPE_REGISTRY
139
				.getContextType(template.getContextTypeId());
140
		if (type == null)
141
			return;
142
		ISourceViewer contextViewer = fEditor.getViewer();
143
		ITextSelection textSelection = (ITextSelection) contextViewer
144
				.getSelectionProvider().getSelection();
145
		region = new Region(textSelection.getOffset(), textSelection
146
				.getLength());
147
		Point selection = contextViewer.getSelectedRange();
148
		Position position;
149
		if (selection.y > 0) {
150
			position = new Position(selection.x, selection.y);
151
		} else {
152
			position = new Position(region.getOffset(), region.getLength());
153
		}
154
155
		IDocument document = contextViewer.getDocument();
156
		AntContext context = new AntContext(type, document, fEditor
157
				.getAntModel(), position);
158
		context.setVariable("selection", textSelection.getText()); //$NON-NLS-1$
159
		AntTemplateProposal proposal = new AntTemplateProposal(template,
160
				context, region, null, 100);
161
		PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage()
162
				.activate(fEditor);
163
		proposal.apply(fEditor.getViewer(), ' ', 0, region.getOffset());
164
	}
165
166
	/**
167
	 * Invoked by the editor whenever the caret position is updated
168
	 */
169
	public void cursorPositionChanged() {
170
		String id;
171
		if (fEditor.getDocumentProvider().getDocument(fEditor.getEditorInput())
172
				.getLength() == 0)
173
			id = BuildFileContextType.BUILDFILE_CONTEXT_TYPE;
174
		else
175
			id = TargetContextType.TARGET_CONTEXT_TYPE;
176
		if (id.equals(fCurrentId))
177
			return;
178
		fCurrentId = id;
179
		if (fCurrentId.equals(BuildFileContextType.BUILDFILE_CONTEXT_TYPE))
180
			contextTypeChanged(new String[] { BuildFileContextType.BUILDFILE_CONTEXT_TYPE });
181
		else
182
			contextTypeChanged(new String[] {
183
					TargetContextType.TARGET_CONTEXT_TYPE,
184
					TaskContextType.TASK_CONTEXT_TYPE });
185
	}
186
}

Return to bug 69581