-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathUniversalEditor.java
More file actions
1912 lines (1615 loc) · 82.8 KB
/
UniversalEditor.java
File metadata and controls
1912 lines (1615 loc) · 82.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*******************************************************************************
* Copyright (c) 2007 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Robert Fuhrer (rfuhrer@watson.ibm.com) - initial API and implementation
*******************************************************************************/
package org.eclipse.imp.editor;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IResourceChangeListener;
import org.eclipse.core.resources.IResourceDelta;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Status;
import org.eclipse.debug.ui.actions.IToggleBreakpointsTarget;
import org.eclipse.debug.ui.actions.ToggleBreakpointAction;
import org.eclipse.help.IContextProvider;
import org.eclipse.imp.actions.QuickMenuAction;
import org.eclipse.imp.actions.RulerEnableDisableBreakpointAction;
import org.eclipse.imp.core.ErrorHandler;
import org.eclipse.imp.editor.internal.AnnotationCreator;
import org.eclipse.imp.editor.internal.EditorErrorTickUpdater;
import org.eclipse.imp.editor.internal.FoldingController;
import org.eclipse.imp.editor.internal.ProblemMarkerManager;
import org.eclipse.imp.editor.internal.ToggleBreakpointsAdapter;
import org.eclipse.imp.help.IMPHelp;
import org.eclipse.imp.language.ILanguageService;
import org.eclipse.imp.language.Language;
import org.eclipse.imp.language.LanguageRegistry;
import org.eclipse.imp.language.ServiceFactory;
import org.eclipse.imp.model.ISourceProject;
import org.eclipse.imp.model.ModelFactory;
import org.eclipse.imp.model.ModelFactory.ModelException;
import org.eclipse.imp.parser.IMessageHandler;
import org.eclipse.imp.parser.IModelListener;
import org.eclipse.imp.parser.IParseController;
import org.eclipse.imp.preferences.IPreferencesService;
import org.eclipse.imp.preferences.PreferenceCache;
import org.eclipse.imp.preferences.PreferenceConstants;
import org.eclipse.imp.preferences.PreferencesService;
import org.eclipse.imp.preferences.IPreferencesService.BooleanPreferenceListener;
import org.eclipse.imp.preferences.IPreferencesService.IntegerPreferenceListener;
import org.eclipse.imp.preferences.IPreferencesService.PreferenceServiceListener;
import org.eclipse.imp.preferences.IPreferencesService.StringPreferenceListener;
import org.eclipse.imp.runtime.RuntimePlugin;
import org.eclipse.imp.services.IASTFindReplaceTarget;
import org.eclipse.imp.services.IAnnotationTypeInfo;
import org.eclipse.imp.services.IEditorInputResolver;
import org.eclipse.imp.services.IEditorService;
import org.eclipse.imp.services.ILanguageActionsContributor;
import org.eclipse.imp.services.ILanguageSyntaxProperties;
import org.eclipse.imp.services.IOccurrenceMarker;
import org.eclipse.imp.services.IRefactoringContributor;
import org.eclipse.imp.services.IToggleBreakpointsHandler;
import org.eclipse.imp.services.ITokenColorer;
import org.eclipse.imp.ui.DefaultPartListener;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.commands.ActionHandler;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferenceConverter;
import org.eclipse.jface.resource.FontRegistry;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.DocumentEvent;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IDocumentListener;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.text.ITextViewerExtension;
import org.eclipse.jface.text.ITextViewerExtension5;
import org.eclipse.jface.text.ITypedRegion;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.Region;
import org.eclipse.jface.text.TextPresentation;
import org.eclipse.jface.text.TextUtilities;
import org.eclipse.jface.text.formatter.ContentFormatter;
import org.eclipse.jface.text.presentation.IPresentationDamager;
import org.eclipse.jface.text.presentation.IPresentationRepairer;
import org.eclipse.jface.text.source.Annotation;
import org.eclipse.jface.text.source.DefaultCharacterPairMatcher;
import org.eclipse.jface.text.source.IAnnotationModel;
import org.eclipse.jface.text.source.IAnnotationModelListener;
import org.eclipse.jface.text.source.ICharacterPairMatcher;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.text.source.IVerticalRuler;
import org.eclipse.jface.text.source.projection.ProjectionAnnotationModel;
import org.eclipse.jface.text.source.projection.ProjectionSupport;
import org.eclipse.jface.text.source.projection.ProjectionViewer;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.custom.VerifyKeyListener;
import org.eclipse.swt.events.VerifyEvent;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.IPropertyListener;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.SubActionBars;
import org.eclipse.ui.actions.ActionContext;
import org.eclipse.ui.editors.text.TextEditor;
import org.eclipse.ui.handlers.IHandlerActivation;
import org.eclipse.ui.handlers.IHandlerService;
import org.eclipse.ui.internal.WorkbenchPlugin;
import org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants;
import org.eclipse.ui.texteditor.AbstractTextEditor;
import org.eclipse.ui.texteditor.ContentAssistAction;
import org.eclipse.ui.texteditor.IDocumentProvider;
import org.eclipse.ui.texteditor.IEditorStatusLine;
import org.eclipse.ui.texteditor.ITextEditorActionConstants;
import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds;
import org.eclipse.ui.texteditor.MarkerAnnotation;
import org.eclipse.ui.texteditor.SourceViewerDecorationSupport;
import org.eclipse.ui.texteditor.TextOperationAction;
import org.eclipse.ui.texteditor.spelling.SpellingService;
import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
/**
* An Eclipse editor, which is not enhanced using API; rather, we publish extension
* points for outline, content assist, hover help, etc.
*
* @author Chris Laffra
* @author Robert M. Fuhrer
*/
public class UniversalEditor extends TextEditor implements IASTFindReplaceTarget {
public static final String MESSAGE_BUNDLE= "org.eclipse.imp.editor.messages";
public static final String EDITOR_ID= RuntimePlugin.IMP_RUNTIME + ".impEditor";
public static final String PARSE_ANNOTATION_TYPE= "org.eclipse.imp.editor.parseAnnotation";
/**
* Annotation ID for a parser annotation w/ severity = error. Must match the ID of the
* corresponding annotationTypes extension in the plugin.xml.
*/
public static final String PARSE_ANNOTATION_TYPE_ERROR= "org.eclipse.imp.editor.parseAnnotation.error";
/**
* Annotation ID for a parser annotation w/ severity = warning. Must match the ID of the
* corresponding annotationTypes extension in the plugin.xml.
*/
public static final String PARSE_ANNOTATION_TYPE_WARNING= "org.eclipse.imp.editor.parseAnnotation.warning";
/**
* Annotation ID for a parser annotation w/ severity = info. Must match the ID of the
* corresponding annotationTypes extension in the plugin.xml.
*/
public static final String PARSE_ANNOTATION_TYPE_INFO= "org.eclipse.imp.editor.parseAnnotation.info";
/** Preference key for matching brackets */
protected final static String MATCHING_BRACKETS= PreferenceConstants.EDITOR_MATCHING_BRACKETS;
/** Preference key for matching brackets color */
protected final static String MATCHING_BRACKETS_COLOR= PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR;
private Language fLanguage;
private ParserScheduler fParserScheduler;
protected LanguageServiceManager fLanguageServiceManager;
protected ServiceControllerManager fServiceControllerManager;
private IDocumentProvider fZipDocProvider;
private ProjectionAnnotationModel fAnnotationModel;
private ProblemMarkerManager fProblemMarkerManager;
private ICharacterPairMatcher fBracketMatcher;
private SubActionBars fActionBars;
private DefaultPartListener fRefreshContributions;
private IPreferencesService fLangSpecificPrefs;
private PreferenceServiceListener fFontListener;
private PreferenceServiceListener fTabListener;
private PreferenceServiceListener fSpacesForTabsListener;
private IPropertyChangeListener fPropertyListener;
private ToggleBreakpointAction fToggleBreakpointAction;
private IAction fEnableDisableBreakpointAction;
private ToggleBreakpointsAdapter fBreakpointHandler;
private IResourceChangeListener fResourceListener;
private IDocumentListener fDocumentListener;
private FoldingActionGroup fFoldingActionGroup;
private GenerateActionGroup fGenerateActionGroup;
private OpenEditorActionGroup fOpenEditorActionGroup;
private static final String BUNDLE_FOR_CONSTRUCTED_KEYS= MESSAGE_BUNDLE;//$NON-NLS-1$
private static final String IMP_EDITOR_CONTEXT= RuntimePlugin.IMP_RUNTIME + ".imp_editor_context";
public static ResourceBundle fgBundleForConstructedKeys= ResourceBundle.getBundle(BUNDLE_FOR_CONSTRUCTED_KEYS);
public static final String IMP_CODING_ACTION_SET = RuntimePlugin.IMP_RUNTIME + ".codingActionSet";
public static final String IMP_OPEN_ACTION_SET = RuntimePlugin.IMP_RUNTIME + ".openActionSet";
public UniversalEditor() {
// RuntimePlugin.EDITOR_START_TIME= System.currentTimeMillis();
if (PreferenceCache.emitMessages)
RuntimePlugin.getInstance().writeInfoMsg("Creating UniversalEditor instance");
// SMS 4 Apr 2007
// Do not set preference store with store obtained from plugin; one is
// already defined for the parent text editor and populated with relevant
// preferences
// setPreferenceStore(RuntimePlugin.getInstance().getPreferenceStore());
setSourceViewerConfiguration(createSourceViewerConfiguration());
configureInsertMode(SMART_INSERT, true);
setInsertMode(SMART_INSERT);
fProblemMarkerManager= new ProblemMarkerManager();
}
/**
* Sub-classes may override this method to extend the behavior provided by IMP's
* standard StructuredSourceViewerConfiguration.
* @return the StructuredSourceViewerConfiguration to use with this editor
*/
protected StructuredSourceViewerConfiguration createSourceViewerConfiguration() {
return new StructuredSourceViewerConfiguration(getPreferenceStore(), this);
}
public Language getLanguage() {
return fLanguage;
}
public LanguageServiceManager getLanguageServiceManager() {
return fLanguageServiceManager;
}
public IPreferencesService getLanguageSpecificPreferences() {
return fLangSpecificPrefs;
}
@SuppressWarnings("rawtypes")
public Object getAdapter(Class required) {
if (IContentOutlinePage.class.equals(required)) {
return fServiceControllerManager == null ? null : fServiceControllerManager.getOutlineController();
}
if (IToggleBreakpointsTarget.class.equals(required)) {
IToggleBreakpointsHandler bkptHandler = fLanguageServiceManager == null ? null : fLanguageServiceManager.getToggleBreakpointsHandler();
if (bkptHandler != null) {
if (fBreakpointHandler == null) {
fBreakpointHandler= new ToggleBreakpointsAdapter(this, bkptHandler);
}
return fBreakpointHandler;
}
}
if (IRegionSelectionService.class.equals(required)) {
return fRegionSelector;
}
if (IContextProvider.class.equals(required)) {
return IMPHelp.getHelpContextProvider(this, fLanguageServiceManager, IMP_EDITOR_CONTEXT);
}
// This was intended to simplify a bit of test code. Unfortunately, it breaks the editor
// in the presence of search hits, since the search UI classes actually look for an editor
// that adapts to IAnnotationModel, and behave differently, and this interacts badly with
// the projection (i.e. folding) support. Go figure.
// if (IAnnotationModel.class.equals(required)) {
// return fAnnotationModel;
// }
return super.getAdapter(required);
}
protected void createActions() {
super.createActions();
final ResourceBundle bundle= ResourceBundle.getBundle(MESSAGE_BUNDLE);
Action action= new ContentAssistAction(bundle, "ContentAssistProposal.", this);
action.setActionDefinitionId(ITextEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS);
setAction("ContentAssistProposal", action);
markAsStateDependentAction("ContentAssistProposal", true);
// Not sure how to hook this up - the following class has all the right enablement logic,
// but it doesn't implement IAction... How to register it as an action here???
// fToggleBreakpointAction= new AbstractRulerActionDelegate() {
// protected IAction createAction(ITextEditor editor, IVerticalRulerInfo rulerInfo) {
// return new ToggleBreakpointAction(UniversalEditor.this, getDocumentProvider().getDocument(getEditorInput()), getVerticalRuler());
// }
// }
fToggleBreakpointAction= new ToggleBreakpointAction(this, getDocumentProvider().getDocument(getEditorInput()), getVerticalRuler());
setAction("ToggleBreakpoint", action);
fEnableDisableBreakpointAction= new RulerEnableDisableBreakpointAction(this, getVerticalRuler());
setAction("ToggleBreakpoint", action);
action= new TextOperationAction(bundle, "Format.", this, ISourceViewer.FORMAT); //$NON-NLS-1$
action.setActionDefinitionId(IEditorActionDefinitionIds.FORMAT);
setAction("Format", action); //$NON-NLS-1$
markAsStateDependentAction("Format", true); //$NON-NLS-1$
markAsSelectionDependentAction("Format", true); //$NON-NLS-1$
// PlatformUI.getWorkbench().getHelpSystem().setHelp(action, IJavaHelpContextIds.FORMAT_ACTION);
action= new TextOperationAction(bundle, "ShowOutline.", this, StructuredSourceViewer.SHOW_OUTLINE, true /* runsOnReadOnly */); //$NON-NLS-1$
action.setActionDefinitionId(IEditorActionDefinitionIds.SHOW_OUTLINE);
setAction(IEditorActionDefinitionIds.SHOW_OUTLINE, action); //$NON-NLS-1$
// PlatformUI.getWorkbench().getHelpSystem().setHelp(action, IJavaHelpContextIds.SHOW_OUTLINE_ACTION);
action= new TextOperationAction(bundle, "ToggleComment.", this, StructuredSourceViewer.TOGGLE_COMMENT); //$NON-NLS-1$
action.setActionDefinitionId(IEditorActionDefinitionIds.TOGGLE_COMMENT);
setAction(IEditorActionDefinitionIds.TOGGLE_COMMENT, action); //$NON-NLS-1$
// PlatformUI.getWorkbench().getHelpSystem().setHelp(action, IJavaHelpContextIds.TOGGLE_COMMENT_ACTION);
action= new TextOperationAction(bundle, "CorrectIndentation.", this, StructuredSourceViewer.CORRECT_INDENTATION); //$NON-NLS-1$
action.setActionDefinitionId(IEditorActionDefinitionIds.CORRECT_INDENTATION);
setAction(IEditorActionDefinitionIds.CORRECT_INDENTATION, action); //$NON-NLS-1$
action= new GotoMatchingFenceAction(this);
action.setActionDefinitionId(IEditorActionDefinitionIds.GOTO_MATCHING_FENCE);
setAction(IEditorActionDefinitionIds.GOTO_MATCHING_FENCE, action);
action= new GotoPreviousTargetAction(this);
action.setActionDefinitionId(IEditorActionDefinitionIds.GOTO_PREVIOUS_TARGET);
setAction(IEditorActionDefinitionIds.GOTO_PREVIOUS_TARGET, action);
action= new GotoNextTargetAction(this);
action.setActionDefinitionId(IEditorActionDefinitionIds.GOTO_NEXT_TARGET);
setAction(IEditorActionDefinitionIds.GOTO_NEXT_TARGET, action);
action= new SelectEnclosingAction(this);
action.setActionDefinitionId(IEditorActionDefinitionIds.SELECT_ENCLOSING);
setAction(IEditorActionDefinitionIds.SELECT_ENCLOSING, action);
fFoldingActionGroup= new FoldingActionGroup(this, this.getSourceViewer());
fGenerateActionGroup= new GenerateActionGroup(this, ITextEditorActionConstants.GROUP_EDIT);
fOpenEditorActionGroup = new OpenEditorActionGroup(this);
installQuickAccessAction();
}
protected void initializeKeyBindingScopes() {
setKeyBindingScopes(new String[] { RuntimePlugin.SOURCE_EDITOR_SCOPE });
}
private QuickMenuAction fQuickAccessAction;
private IHandlerActivation fQuickAccessHandlerActivation;
private IHandlerService fHandlerService;
private static final String QUICK_MENU_ID= "org.eclipse.imp.runtime.editor.refactor.quickMenu"; //$NON-NLS-1$
private final class AnnotationUpdater implements IProblemChangedListener {
public void problemsChanged(IResource[] changedResources, boolean isMarkerChange) {
// TODO Work-around to remove annotations that were resolved by changes to other resources.
// It would be better to match the markers to the annotations, and decide which
// annotations to remove.
if (fParserScheduler != null) {
if (!isMarkerChange) {
fParserScheduler.schedule(50);
}
}
}
}
private class RefactorQuickAccessAction extends QuickMenuAction {
public RefactorQuickAccessAction() {
super(QUICK_MENU_ID);
}
protected void fillMenu(IMenuManager menu) {
contributeRefactoringActions(menu);
}
}
private void installQuickAccessAction() {
fHandlerService= (IHandlerService) getSite().getService(IHandlerService.class);
if (fHandlerService != null) {
fQuickAccessAction= new RefactorQuickAccessAction();
fQuickAccessHandlerActivation= fHandlerService.activateHandler(fQuickAccessAction.getActionDefinitionId(), new ActionHandler(fQuickAccessAction));
}
}
protected void editorContextMenuAboutToShow(IMenuManager menu) {
super.editorContextMenuAboutToShow(menu);
contributeRefactoringActions(menu);
contributeLanguageActions(menu);
ActionContext context= new ActionContext(getSelectionProvider().getSelection());
fOpenEditorActionGroup.setContext(context);
fOpenEditorActionGroup.fillContextMenu(menu);
fOpenEditorActionGroup.setContext(null);
fGenerateActionGroup.setContext(context);
fGenerateActionGroup.fillContextMenu(menu);
fGenerateActionGroup.setContext(null);
}
private void contributeRefactoringActions(IMenuManager menu) {
Set<IRefactoringContributor> contributors= fLanguageServiceManager.getRefactoringContributors();
if (contributors != null && !contributors.isEmpty()) {
List<IAction> editorActions= new ArrayList<IAction>();
for (Iterator<IRefactoringContributor> iter= contributors.iterator(); iter.hasNext(); ) {
IRefactoringContributor con= iter.next();
try {
IAction[] conActions= con.getEditorRefactoringActions(this);
for (int i= 0; i < conActions.length; i++)
editorActions.add(conActions[i]);
} catch (LinkageError e) {
RuntimePlugin.getInstance().logException("Unable to create refactoring actions for contributor " + con, e);
} catch (Exception e) {
RuntimePlugin.getInstance().logException("Unable to create refactoring actions for contributor " + con, e);
}
}
Separator refGroup= new Separator("group.refactor");
IMenuManager refMenu= new MenuManager("Refac&tor", "org.eclipse.imp.refactor");
menu.add(refGroup);
menu.appendToGroup("group.refactor", refMenu);
for (Iterator<IAction> actionIter= editorActions.iterator(); actionIter.hasNext(); ) {
refMenu.add(actionIter.next());
}
}
}
private void contributeLanguageActions(IMenuManager menu) {
Set<ILanguageActionsContributor> actionContributors= fLanguageServiceManager.getActionContributors();
if (!actionContributors.isEmpty()) {
menu.add(new Separator());
}
for(ILanguageActionsContributor con : actionContributors) {
try {
con.contributeToEditorMenu(this, menu);
} catch (LinkageError e) {
RuntimePlugin.getInstance().logException("Unable to create editor actions for contributor " + con, e);
} catch(Exception e) {
RuntimePlugin.getInstance().logException("Unable to create editor actions for contributor " + con, e);
}
}
}
/* (non-Javadoc)
* @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#isOverviewRulerVisible()
*/
protected boolean isOverviewRulerVisible() {
return true;
}
protected void rulerContextMenuAboutToShow(IMenuManager menu) {
addDebugActions(menu);
super.rulerContextMenuAboutToShow(menu);
IMenuManager foldingMenu= new MenuManager("Folding", "projection"); //$NON-NLS-1$
menu.appendToGroup(ITextEditorActionConstants.GROUP_RULERS, foldingMenu);
IAction action;
// action= getAction("FoldingToggle"); //$NON-NLS-1$
// foldingMenu.add(action);
action= getAction("FoldingExpandAll"); //$NON-NLS-1$
foldingMenu.add(action);
action= getAction("FoldingCollapseAll"); //$NON-NLS-1$
foldingMenu.add(action);
action= getAction("FoldingRestore"); //$NON-NLS-1$
foldingMenu.add(action);
action= getAction("FoldingCollapseMembers"); //$NON-NLS-1$
foldingMenu.add(action);
action= getAction("FoldingCollapseComments"); //$NON-NLS-1$
foldingMenu.add(action);
}
private void addDebugActions(IMenuManager menu) {
menu.add(fToggleBreakpointAction);
menu.add(fEnableDisableBreakpointAction);
}
/**
* Sets the given message as error message to this editor's status line.
*
* @param msg message to be set
*/
protected void setStatusLineErrorMessage(String msg) {
IEditorStatusLine statusLine= (IEditorStatusLine) getAdapter(IEditorStatusLine.class);
if (statusLine != null)
statusLine.setMessage(true, msg, null);
}
/**
* Sets the given message as message to this editor's status line.
*
* @param msg message to be set
* @since 3.0
*/
protected void setStatusLineMessage(String msg) {
IEditorStatusLine statusLine= (IEditorStatusLine) getAdapter(IEditorStatusLine.class);
if (statusLine != null)
statusLine.setMessage(false, msg, null);
}
public ProblemMarkerManager getProblemMarkerManager() {
return fProblemMarkerManager;
}
public void updatedTitleImage(Image image) {
setTitleImage(image);
}
/**
* Jumps to the next enabled annotation according to the given direction.
* An annotation type is enabled if it is configured to be in the
* Next/Previous tool bar drop down menu and if it is checked.
*
* @param forward <code>true</code> if search direction is forward, <code>false</code> if backward
*/
public Annotation gotoAnnotation(boolean forward) {
ITextSelection selection= (ITextSelection) getSelectionProvider().getSelection();
Position position= new Position(0, 0);
Annotation annotation= getNextAnnotation(selection.getOffset(), selection.getLength(), forward, position);
if (false /* delayed - see bug 18316 */) {
selectAndReveal(position.getOffset(), position.getLength());
} else /* no delay - see bug 18316 */{
setStatusLineErrorMessage(null);
setStatusLineMessage(null);
if (annotation != null) {
updateAnnotationViews(annotation);
selectAndReveal(position.getOffset(), position.getLength());
setStatusLineMessage(annotation.getText());
}
}
return annotation;
}
/**
* Returns the annotation closest to the given range respecting the given
* direction. If an annotation is found, the annotations current position
* is copied into the provided annotation position.
*
* @param offset the region offset
* @param length the region length
* @param forward <code>true</code> for forwards, <code>false</code> for backward
* @param annotationPosition the position of the found annotation
* @return the found annotation
*/
private Annotation getNextAnnotation(final int offset, final int length, boolean forward, Position annotationPosition) {
Annotation nextAnnotation= null;
Position nextAnnotationPosition= null;
Annotation containingAnnotation= null;
Position containingAnnotationPosition= null;
boolean currentAnnotation= false;
IDocument document= getDocumentProvider().getDocument(getEditorInput());
int endOfDocument= document.getLength();
int distance= Integer.MAX_VALUE;
IAnnotationModel model= getDocumentProvider().getAnnotationModel(getEditorInput());
for(Iterator<Annotation> e= model.getAnnotationIterator(); e.hasNext(); ) {
Annotation a= (Annotation) e.next();
if (!(a instanceof MarkerAnnotation) && !isParseAnnotation(a))
continue;
Position p= model.getPosition(a);
if (p == null)
continue;
if (forward && p.offset == offset || !forward && p.offset + p.getLength() == offset + length) {// || p.includes(offset)) {
if (containingAnnotation == null
|| (forward && p.length >= containingAnnotationPosition.length || !forward && p.length >= containingAnnotationPosition.length)) {
containingAnnotation= a;
containingAnnotationPosition= p;
currentAnnotation= p.length == length;
}
} else {
int currentDistance= forward ? p.getOffset() - offset : offset + length - (p.getOffset() + p.length);
if (currentDistance < 0)
currentDistance= endOfDocument + currentDistance;
if (currentDistance < distance || currentDistance == distance && p.length < nextAnnotationPosition.length) {
distance= currentDistance;
nextAnnotation= a;
nextAnnotationPosition= p;
}
}
}
if (containingAnnotationPosition != null && (!currentAnnotation || nextAnnotation == null)) {
annotationPosition.setOffset(containingAnnotationPosition.getOffset());
annotationPosition.setLength(containingAnnotationPosition.getLength());
return containingAnnotation;
}
if (nextAnnotationPosition != null) {
annotationPosition.setOffset(nextAnnotationPosition.getOffset());
annotationPosition.setLength(nextAnnotationPosition.getLength());
}
return nextAnnotation;
}
/**
* Updates the annotation views that show the given annotation.
*
* @param annotation the annotation
*/
private void updateAnnotationViews(Annotation annotation) {
IMarker marker= null;
if (annotation instanceof MarkerAnnotation)
marker= ((MarkerAnnotation) annotation).getMarker();
else if (marker != null /* && !marker.equals(fLastMarkerTarget) */) {
try {
boolean isProblem= marker.isSubtypeOf(IMarker.PROBLEM);
IWorkbenchPage page= getSite().getPage();
IViewPart view= page.findView(isProblem ? IPageLayout.ID_PROBLEM_VIEW : IPageLayout.ID_TASK_LIST); //$NON-NLS-1$ //$NON-NLS-2$
if (view != null) {
Method method= view.getClass().getMethod("setSelection", new Class[] { IStructuredSelection.class, boolean.class }); //$NON-NLS-1$
method.invoke(view, new Object[] { new StructuredSelection(marker), Boolean.TRUE });
}
} catch (CoreException x) {
} catch (NoSuchMethodException x) {
} catch (IllegalAccessException x) {
} catch (InvocationTargetException x) {
}
// ignore exceptions, don't update any of the lists, just set status line
}
}
@Override
public IDocumentProvider getDocumentProvider() {
IEditorInput editorInput= getEditorInput();
if (ZipStorageEditorDocumentProvider.canHandle(editorInput)) {
if (fZipDocProvider == null) {
fZipDocProvider= new ZipStorageEditorDocumentProvider();
}
return fZipDocProvider;
}
return super.getDocumentProvider();
}
public void createPartControl(Composite parent) {
fLanguage= LanguageRegistry.findLanguage(getEditorInput(), getDocumentProvider());
// SMS 10 Oct 2008: null check added per bug #242949
if (fLanguage == null) {
// throw new IllegalArgumentException("No language support found for files of type '" +
// EditorInputUtils.getPath(getEditorInput()).getFileExtension() + "'");
}
// Create language service extensions now, since some services could
// get accessed via super.createPartControl() (in particular, while
// setting up the ISourceViewer).
if (fLanguage != null) {
fLanguageServiceManager= new LanguageServiceManager(fLanguage);
fLanguageServiceManager.initialize(this);
fServiceControllerManager= new ServiceControllerManager(this, fLanguageServiceManager);
fServiceControllerManager.initialize();
if (fLanguageServiceManager.getParseController() != null) {
initializeParseController();
findLanguageSpecificPreferences();
}
}
// RMF 07 June 2010 - Not sure why the "run the spell checker" pref would get set, but
// it does seem to, which gives lots of annoying squigglies all over the place...
getPreferenceStore().setValue(SpellingService.PREFERENCE_SPELLING_ENABLED, false);
super.createPartControl(parent);
if (fLanguageServiceManager != null && fLanguageServiceManager.getParseController() != null) {
fServiceControllerManager.setSourceViewer(getSourceViewer());
initiateServiceControllers();
}
// SMS 4 Apr 2007: Call no longer needed because preferences for the
// overview ruler are now obtained from appropriate preference store directly
//setupOverviewRulerAnnotations();
// SMS 4 Apr 2007: Also should not need this, since we're not using
// the plugin's store (for this purpose)
//AbstractDecoratedTextEditorPreferenceConstants.initializeDefaultValues(RuntimePlugin.getInstance().getPreferenceStore());
setTitleImageFromLanguageIcon();
setSourceFontFromPreference();
setupBracketCloser();
setupSourcePrefListeners();
initializeEditorContributors();
watchForSourceMove();
if (isEditable() && getResourceDocumentMapListener() != null) {
IResourceDocumentMapListener rdml = getResourceDocumentMapListener();
rdml.registerDocument(getDocumentProvider().getDocument(getEditorInput()), EditorInputUtils.getFile(getEditorInput()), this);
}
}
private void initializeParseController() {
// Initialize the parse controller now, since the initialization of other things (like the context help support) might depend on it being so.
IEditorInput editorInput= getEditorInput();
IFile file = null;
IPath filePath = null;
IEditorInputResolver editorInputResolver= fLanguageServiceManager.getEditorInputResolver();
if (fLanguageServiceManager != null && editorInputResolver != null) {
file = editorInputResolver.getFile(editorInput);
filePath = editorInputResolver.getPath(editorInput);
} else {
file = EditorInputUtils.getFile(editorInput);
filePath = EditorInputUtils.getPath(editorInput);
}
try {
IProject project= (file != null && file.exists()) ? file.getProject() : null;
ISourceProject srcProject= (project != null) ? ModelFactory.open(project) : null;
fLanguageServiceManager.getParseController().initialize(filePath, srcProject, fAnnotationCreator);
// TODO Need to do the following to give the strategy access to project-specific preference settings
// if (fLanguageServiceManager.getAutoEditStrategies().size() > 0) {
// Set<org.eclipse.imp.services.IAutoEditStrategy> strategies= fLanguageServiceManager.getAutoEditStrategies();
// for(org.eclipse.imp.services.IAutoEditStrategy strategy: strategies) {
// strategy.setProject(project);
// }
// }
} catch (ModelException e) {
ErrorHandler.reportError("Error initializing parser for input " + editorInput.getName() + ":", e);
}
}
private void findLanguageSpecificPreferences() {
ISourceProject srcProject = fLanguageServiceManager.getParseController().getProject();
if (srcProject != null) {
IProject project= srcProject.getRawProject();
fLangSpecificPrefs= new PreferencesService(project, fLanguage.getName());
} else {
fLangSpecificPrefs= new PreferencesService(null, fLanguage.getName());
}
// Now propagate the setting of "spaces for tabs" from either the language-specific preference store,
// or the IMP runtime's preference store to the UniversalEditor's preference store, where
// AbstractDecoratedTextEditor.isTabsToSpacesConversionEnabled() will look.
boolean spacesForTabs= RuntimePlugin.getInstance().getPreferenceStore().getBoolean(PreferenceConstants.P_SPACES_FOR_TABS);
getPreferenceStore().setValue(AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SPACES_FOR_TABS, spacesForTabs);
}
private void setupSourcePrefListeners() {
// If there are no language-specific preferences, use the settings on the IMP preferences page
if (fLangSpecificPrefs == null ||
!fLangSpecificPrefs.isDefined(PreferenceConstants.P_SOURCE_FONT) ||
!fLangSpecificPrefs.isDefined(PreferenceConstants.P_TAB_WIDTH) ||
!fLangSpecificPrefs.isDefined(PreferenceConstants.P_SPACES_FOR_TABS)) {
fPropertyListener= new IPropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
if (event.getProperty().equals(PreferenceConstants.P_SOURCE_FONT) &&
!fLangSpecificPrefs.isDefined(PreferenceConstants.P_SOURCE_FONT)) {
FontData[] newValue= (FontData[]) event.getNewValue();
String fontDescriptor= newValue[0].toString();
handleFontChange(newValue, fontDescriptor);
} else if (event.getProperty().equals(PreferenceConstants.P_TAB_WIDTH) &&
!fLangSpecificPrefs.isDefined(PreferenceConstants.P_TAB_WIDTH)) {
handleTabsChange(((Integer) event.getNewValue()).intValue());
} else if (event.getProperty().equals(PreferenceConstants.P_SPACES_FOR_TABS) &&
!fLangSpecificPrefs.isDefined(PreferenceConstants.P_SPACES_FOR_TABS)) {
handleSpacesForTabsChange(((Boolean) event.getNewValue()).booleanValue());
}
}
};
RuntimePlugin.getInstance().getPreferenceStore().addPropertyChangeListener(fPropertyListener);
}
// TODO Perhaps add a flavor of IMP PreferenceListener that notifies for a change to any preference key?
// Then the following listeners could become just one, at the expense of casting the pref values.
if (fLangSpecificPrefs != null) {
fFontListener= new StringPreferenceListener(fLangSpecificPrefs, PreferenceConstants.P_SOURCE_FONT) {
@Override
public void changed(String oldValue, String newValue) {
FontData[] fontData= PreferenceConverter.readFontData(newValue);
handleFontChange(fontData, newValue);
}
};
}
if (fLangSpecificPrefs != null) {
fTabListener= new IntegerPreferenceListener(fLangSpecificPrefs, PreferenceConstants.P_TAB_WIDTH) {
@Override
public void changed(int oldValue, int newValue) {
handleTabsChange(newValue);
}
};
}
if (fLangSpecificPrefs != null) {
fSpacesForTabsListener= new BooleanPreferenceListener(fLangSpecificPrefs, PreferenceConstants.P_SPACES_FOR_TABS) {
@Override
public void changed(boolean oldValue, boolean newValue) {
handleSpacesForTabsChange(newValue);
}
};
}
}
private void handleTabsChange(int newTab) {
if (getSourceViewer() != null) {
getSourceViewer().getTextWidget().setTabs(newTab);
}
}
private void handleSpacesForTabsChange(boolean newValue) {
if (getSourceViewer() == null) {
return;
}
// RMF 13 Oct 2010 - The base class tabs-to-spaces converter even translates tabs to
// spaces before the auto-edit strategy sees the document change commands, which makes
// handling auto-indent nearly impossible (it never actually sees a tab). Anyway, the
// auto-edit strategy provides the desired behavior itself, so this isn't even needed.
// if (newValue) {
// installTabsToSpacesConverter();
// } else {
// uninstallTabsToSpacesConverter();
// }
// Apparently un/installing the tabs-to-spaces converter isn't enough - shift left/right needs
// the "indent prefixes" to be computed properly, which relies on the preference store having
// the right value for AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SPACES_FOR_TABS.
getPreferenceStore().setValue(AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SPACES_FOR_TABS, newValue);
}
private void handleFontChange(FontData[] fontData, String fontDescriptor) {
FontRegistry fontRegistry= RuntimePlugin.getInstance().getFontRegistry();
if (!fontRegistry.hasValueFor(fontDescriptor)) {
fontRegistry.put(fontDescriptor, fontData);
}
Font sourceFont= fontRegistry.get(fontDescriptor);
if (sourceFont != null && getSourceViewer() != null) {
getSourceViewer().getTextWidget().setFont(sourceFont);
}
}
private void watchDocument(final long reparse_schedule_delay) {
if (fLanguageServiceManager.getParseController() == null) {
return;
}
IDocument doc= getDocumentProvider().getDocument(getEditorInput());
doc.addDocumentListener(fDocumentListener= new IDocumentListener() {
public void documentAboutToBeChanged(DocumentEvent event) {}
public void documentChanged(DocumentEvent event) {
fParserScheduler.cancel();
fParserScheduler.schedule(reparse_schedule_delay);
}
});
}
private class BracketInserter implements VerifyKeyListener {
private final Map<String,String> fFencePairs= new HashMap<String, String>();
private final String fOpenFences;
private final Map<Character,Boolean> fCloseFenceMap= new HashMap<Character, Boolean>();
// private final String CATEGORY= toString();
// private IPositionUpdater fUpdater= new ExclusivePositionUpdater(CATEGORY);
public BracketInserter() {
String[][] pairs= fLanguageServiceManager.getParseController().getSyntaxProperties().getFences();
StringBuilder sb= new StringBuilder();
for(int i= 0; i < pairs.length; i++) {
sb.append(pairs[i][0]);
fFencePairs.put(pairs[i][0], pairs[i][1]);
}
fOpenFences= sb.toString();
}
public void setCloseFenceEnabled(char openingFence, boolean enabled) {
fCloseFenceMap.put(openingFence, enabled);
}
public void setCloseFencesEnabled(boolean enabled) {
for(int i= 0; i < fOpenFences.length(); i++) {
fCloseFenceMap.put(fOpenFences.charAt(i), enabled);
}
}
/*
* @see org.eclipse.swt.custom.VerifyKeyListener#verifyKey(org.eclipse.swt.events.VerifyEvent)
*/
public void verifyKey(VerifyEvent event) {
// early pruning to slow down normal typing as little as possible
if (!event.doit || getInsertMode() != SMART_INSERT)
return;
if (fOpenFences.indexOf(event.character) < 0) {
return;
}
final ISourceViewer sourceViewer= getSourceViewer();
IDocument document= sourceViewer.getDocument();
final Point selection= sourceViewer.getSelectedRange();
final int offset= selection.x;
final int length= selection.y;
try {
// IRegion startLine= document.getLineInformationOfOffset(offset);
// IRegion endLine= document.getLineInformationOfOffset(offset + length);
// TODO Ask the parser/scanner whether the close fence is valid here
// (i.e. whether it would recover by inserting the matching close fence character)
// Right now, naively insert the closing fence regardless.
ITypedRegion partition= TextUtilities.getPartition(document, getSourceViewerConfiguration().getConfiguredDocumentPartitioning(sourceViewer), offset, true);
if (!IDocument.DEFAULT_CONTENT_TYPE.equals(partition.getType()))
return;
if (!validateEditorInputState())
return;
final String inputStr= new String(new char[] { event.character });
final String closingFence= fFencePairs.get(inputStr);
final StringBuffer buffer= new StringBuffer();
buffer.append(inputStr);
buffer.append(closingFence);
document.replace(offset, length, buffer.toString());
sourceViewer.setSelectedRange(offset + inputStr.length(), 0);
event.doit= false;
} catch (BadLocationException e) {
RuntimePlugin.getInstance().logException(e.getMessage(), e);
}
}
}
private BracketInserter fBracketInserter;
private final String CLOSE_FENCES= PreferenceConstants.EDITOR_CLOSE_FENCES;
private void setupBracketCloser() {
if (true) return; // Bug #536: Disable for now, until we can be more intelligent about when to overwrite an existing (subsequent) close-fence char.
IParseController parseController= fLanguageServiceManager.getParseController();
if (parseController == null || parseController.getSyntaxProperties() == null || parseController.getSyntaxProperties().getFences() == null) {
return;
}