1 package net.sourceforge.phpeclipse.phpeditor;
3 /**********************************************************************
4 Copyright (c) 2000, 2002 IBM Corp. and others.
5 All rights reserved. This program and the accompanying materials
6 are made available under the terms of the Common Public License v1.0
7 which accompanies this distribution, and is available at
8 http://www.eclipse.org/legal/cpl-v10.html
11 IBM Corporation - Initial implementation
13 **********************************************************************/
14 import java.lang.reflect.InvocationTargetException;
15 import java.lang.reflect.Method;
16 import java.text.BreakIterator;
17 import java.text.CharacterIterator;
18 import java.util.ArrayList;
19 import java.util.HashMap;
20 import java.util.Iterator;
21 import java.util.List;
23 import java.util.ResourceBundle;
24 import java.util.StringTokenizer;
26 import net.sourceforge.phpdt.core.ICompilationUnit;
27 import net.sourceforge.phpdt.core.IImportContainer;
28 import net.sourceforge.phpdt.core.IImportDeclaration;
29 import net.sourceforge.phpdt.core.IJavaElement;
30 import net.sourceforge.phpdt.core.IJavaProject;
31 import net.sourceforge.phpdt.core.IMember;
32 import net.sourceforge.phpdt.core.ISourceRange;
33 import net.sourceforge.phpdt.core.ISourceReference;
34 import net.sourceforge.phpdt.core.JavaCore;
35 import net.sourceforge.phpdt.core.JavaModelException;
36 import net.sourceforge.phpdt.core.compiler.ITerminalSymbols;
37 import net.sourceforge.phpdt.core.compiler.InvalidInputException;
38 import net.sourceforge.phpdt.internal.compiler.parser.Scanner;
39 import net.sourceforge.phpdt.internal.compiler.parser.SyntaxError;
40 import net.sourceforge.phpdt.internal.core.CompilationUnit;
41 import net.sourceforge.phpdt.internal.ui.actions.CompositeActionGroup;
42 import net.sourceforge.phpdt.internal.ui.actions.FoldingActionGroup;
43 import net.sourceforge.phpdt.internal.ui.actions.SelectionConverter;
44 import net.sourceforge.phpdt.internal.ui.text.CustomSourceInformationControl;
45 import net.sourceforge.phpdt.internal.ui.text.DocumentCharacterIterator;
46 import net.sourceforge.phpdt.internal.ui.text.HTMLTextPresenter;
47 import net.sourceforge.phpdt.internal.ui.text.IPHPPartitions;
48 import net.sourceforge.phpdt.internal.ui.text.JavaWordFinder;
49 import net.sourceforge.phpdt.internal.ui.text.JavaWordIterator;
50 import net.sourceforge.phpdt.internal.ui.text.PHPPairMatcher;
51 import net.sourceforge.phpdt.internal.ui.text.PreferencesAdapter;
52 import net.sourceforge.phpdt.internal.ui.text.java.JavaExpandHover;
53 import net.sourceforge.phpdt.internal.ui.viewsupport.ISelectionListenerWithAST;
54 import net.sourceforge.phpdt.internal.ui.viewsupport.IViewPartInputProvider;
55 import net.sourceforge.phpdt.internal.ui.viewsupport.SelectionListenerWithASTManager;
56 import net.sourceforge.phpdt.ui.IContextMenuConstants;
57 import net.sourceforge.phpdt.ui.JavaUI;
58 import net.sourceforge.phpdt.ui.PreferenceConstants;
59 import net.sourceforge.phpdt.ui.actions.GotoMatchingBracketAction;
60 import net.sourceforge.phpdt.ui.actions.OpenEditorActionGroup;
61 import net.sourceforge.phpdt.ui.text.JavaTextTools;
62 import net.sourceforge.phpdt.ui.text.PHPSourceViewerConfiguration;
63 import net.sourceforge.phpdt.ui.text.folding.IJavaFoldingStructureProvider;
64 import net.sourceforge.phpeclipse.PHPeclipsePlugin;
65 import net.sourceforge.phpeclipse.ui.editor.BrowserUtil;
66 import net.sourceforge.phpeclipse.webbrowser.views.BrowserView;
68 import org.eclipse.core.resources.IMarker;
69 import org.eclipse.core.resources.IResource;
70 import org.eclipse.core.runtime.CoreException;
71 import org.eclipse.core.runtime.IProgressMonitor;
72 import org.eclipse.core.runtime.IStatus;
73 import org.eclipse.core.runtime.NullProgressMonitor;
74 import org.eclipse.core.runtime.Preferences;
75 import org.eclipse.core.runtime.Status;
76 import org.eclipse.core.runtime.jobs.Job;
77 import org.eclipse.jface.action.Action;
78 import org.eclipse.jface.action.GroupMarker;
79 import org.eclipse.jface.action.IAction;
80 import org.eclipse.jface.action.MenuManager;
81 import org.eclipse.jface.action.Separator;
82 import org.eclipse.jface.preference.IPreferenceStore;
83 import org.eclipse.jface.preference.PreferenceConverter;
84 import org.eclipse.jface.text.BadLocationException;
85 import org.eclipse.jface.text.DefaultInformationControl;
86 import org.eclipse.jface.text.DocumentEvent;
87 import org.eclipse.jface.text.IDocument;
88 import org.eclipse.jface.text.IDocumentExtension4;
89 import org.eclipse.jface.text.IDocumentListener;
90 import org.eclipse.jface.text.IInformationControl;
91 import org.eclipse.jface.text.IInformationControlCreator;
92 import org.eclipse.jface.text.IRegion;
93 import org.eclipse.jface.text.ISelectionValidator;
94 import org.eclipse.jface.text.ISynchronizable;
95 import org.eclipse.jface.text.ITextHover;
96 import org.eclipse.jface.text.ITextInputListener;
97 import org.eclipse.jface.text.ITextPresentationListener;
98 import org.eclipse.jface.text.ITextSelection;
99 import org.eclipse.jface.text.ITextViewer;
100 import org.eclipse.jface.text.ITextViewerExtension2;
101 import org.eclipse.jface.text.ITextViewerExtension3;
102 import org.eclipse.jface.text.ITextViewerExtension4;
103 import org.eclipse.jface.text.ITextViewerExtension5;
104 import org.eclipse.jface.text.ITypedRegion;
105 import org.eclipse.jface.text.Position;
106 import org.eclipse.jface.text.Region;
107 import org.eclipse.jface.text.TextPresentation;
108 import org.eclipse.jface.text.TextSelection;
109 import org.eclipse.jface.text.TextUtilities;
110 import org.eclipse.jface.text.information.IInformationProvider;
111 import org.eclipse.jface.text.information.InformationPresenter;
112 import org.eclipse.jface.text.link.LinkedModeModel;
113 import org.eclipse.jface.text.reconciler.IReconciler;
114 import org.eclipse.jface.text.source.Annotation;
115 import org.eclipse.jface.text.source.AnnotationRulerColumn;
116 import org.eclipse.jface.text.source.CompositeRuler;
117 import org.eclipse.jface.text.source.IAnnotationModel;
118 import org.eclipse.jface.text.source.IAnnotationModelExtension;
119 import org.eclipse.jface.text.source.IOverviewRuler;
120 import org.eclipse.jface.text.source.ISourceViewer;
121 import org.eclipse.jface.text.source.ISourceViewerExtension2;
122 import org.eclipse.jface.text.source.IVerticalRuler;
123 import org.eclipse.jface.text.source.OverviewRuler;
124 import org.eclipse.jface.text.source.SourceViewerConfiguration;
125 import org.eclipse.jface.text.source.projection.ProjectionSupport;
126 import org.eclipse.jface.text.source.projection.ProjectionViewer;
127 import org.eclipse.jface.util.IPropertyChangeListener;
128 import org.eclipse.jface.util.ListenerList;
129 import org.eclipse.jface.util.PropertyChangeEvent;
130 import org.eclipse.jface.viewers.DoubleClickEvent;
131 import org.eclipse.jface.viewers.IDoubleClickListener;
132 import org.eclipse.jface.viewers.IPostSelectionProvider;
133 import org.eclipse.jface.viewers.ISelection;
134 import org.eclipse.jface.viewers.ISelectionChangedListener;
135 import org.eclipse.jface.viewers.ISelectionProvider;
136 import org.eclipse.jface.viewers.IStructuredSelection;
137 import org.eclipse.jface.viewers.SelectionChangedEvent;
138 import org.eclipse.jface.viewers.StructuredSelection;
139 import org.eclipse.swt.SWT;
140 import org.eclipse.swt.custom.BidiSegmentEvent;
141 import org.eclipse.swt.custom.BidiSegmentListener;
142 import org.eclipse.swt.custom.ST;
143 import org.eclipse.swt.custom.StyleRange;
144 import org.eclipse.swt.custom.StyledText;
145 import org.eclipse.swt.events.FocusEvent;
146 import org.eclipse.swt.events.FocusListener;
147 import org.eclipse.swt.events.KeyEvent;
148 import org.eclipse.swt.events.KeyListener;
149 import org.eclipse.swt.events.MouseEvent;
150 import org.eclipse.swt.events.MouseListener;
151 import org.eclipse.swt.events.MouseMoveListener;
152 import org.eclipse.swt.events.PaintEvent;
153 import org.eclipse.swt.events.PaintListener;
154 import org.eclipse.swt.graphics.Color;
155 import org.eclipse.swt.graphics.Cursor;
156 import org.eclipse.swt.graphics.GC;
157 import org.eclipse.swt.graphics.Image;
158 import org.eclipse.swt.graphics.Point;
159 import org.eclipse.swt.graphics.RGB;
160 import org.eclipse.swt.widgets.Composite;
161 import org.eclipse.swt.widgets.Control;
162 import org.eclipse.swt.widgets.Display;
163 import org.eclipse.swt.widgets.Shell;
164 import org.eclipse.ui.IEditorInput;
165 import org.eclipse.ui.IEditorPart;
166 import org.eclipse.ui.IPageLayout;
167 import org.eclipse.ui.IPartService;
168 import org.eclipse.ui.ISelectionListener;
169 import org.eclipse.ui.IViewPart;
170 import org.eclipse.ui.IWindowListener;
171 import org.eclipse.ui.IWorkbenchPage;
172 import org.eclipse.ui.IWorkbenchPart;
173 import org.eclipse.ui.IWorkbenchWindow;
174 import org.eclipse.ui.PlatformUI;
175 import org.eclipse.ui.actions.ActionContext;
176 import org.eclipse.ui.actions.ActionGroup;
177 import org.eclipse.ui.editors.text.DefaultEncodingSupport;
178 import org.eclipse.ui.editors.text.EditorsUI;
179 import org.eclipse.ui.editors.text.IEncodingSupport;
180 import org.eclipse.ui.part.FileEditorInput;
181 import org.eclipse.ui.part.IShowInSource;
182 import org.eclipse.ui.part.IShowInTargetList;
183 import org.eclipse.ui.part.ShowInContext;
184 import org.eclipse.ui.texteditor.AbstractDecoratedTextEditor;
185 import org.eclipse.ui.texteditor.AnnotationPreference;
186 import org.eclipse.ui.texteditor.ChainedPreferenceStore;
187 import org.eclipse.ui.texteditor.IDocumentProvider;
188 import org.eclipse.ui.texteditor.IEditorStatusLine;
189 import org.eclipse.ui.texteditor.ITextEditorActionConstants;
190 import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds;
191 import org.eclipse.ui.texteditor.IUpdate;
192 import org.eclipse.ui.texteditor.MarkerAnnotation;
193 import org.eclipse.ui.texteditor.SourceViewerDecorationSupport;
194 import org.eclipse.ui.texteditor.TextEditorAction;
195 import org.eclipse.ui.texteditor.TextNavigationAction;
196 import org.eclipse.ui.texteditor.TextOperationAction;
197 import org.eclipse.ui.views.contentoutline.ContentOutline;
198 import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
199 import org.eclipse.ui.views.tasklist.TaskList;
202 * PHP specific text editor.
204 public abstract class PHPEditor extends AbstractDecoratedTextEditor implements IViewPartInputProvider, IShowInTargetList,
206 // extends StatusTextEditor implements IViewPartInputProvider { // extends
210 * Internal implementation class for a change listener.
214 protected abstract class AbstractSelectionChangedListener implements ISelectionChangedListener {
217 * Installs this selection changed listener with the given selection
218 * provider. If the selection provider is a post selection provider, post
219 * selection changed events are the preferred choice, otherwise normal
220 * selection changed events are requested.
222 * @param selectionProvider
224 public void install(ISelectionProvider selectionProvider) {
225 if (selectionProvider == null)
228 if (selectionProvider instanceof IPostSelectionProvider) {
229 IPostSelectionProvider provider = (IPostSelectionProvider) selectionProvider;
230 provider.addPostSelectionChangedListener(this);
232 selectionProvider.addSelectionChangedListener(this);
237 * Removes this selection changed listener from the given selection
240 * @param selectionProvider
241 * the selection provider
243 public void uninstall(ISelectionProvider selectionProvider) {
244 if (selectionProvider == null)
247 if (selectionProvider instanceof IPostSelectionProvider) {
248 IPostSelectionProvider provider = (IPostSelectionProvider) selectionProvider;
249 provider.removePostSelectionChangedListener(this);
251 selectionProvider.removeSelectionChangedListener(this);
257 * Updates the Java outline page selection and this editor's range indicator.
261 private class EditorSelectionChangedListener extends AbstractSelectionChangedListener {
264 * @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent)
266 public void selectionChanged(SelectionChangedEvent event) {
267 // XXX: see https://bugs.eclipse.org/bugs/show_bug.cgi?id=56161
268 PHPEditor.this.selectionChanged();
273 * "Smart" runnable for updating the outline page's selection.
275 // class OutlinePageSelectionUpdater implements Runnable {
277 // /** Has the runnable already been posted? */
278 // private boolean fPosted = false;
280 // public OutlinePageSelectionUpdater() {
284 // * @see Runnable#run()
286 // public void run() {
287 // synchronizeOutlinePageSelection();
292 // * Posts this runnable into the event queue.
294 // public void post() {
298 // Shell shell = getSite().getShell();
299 // if (shell != null & !shell.isDisposed()) {
301 // shell.getDisplay().asyncExec(this);
305 class SelectionChangedListener implements ISelectionChangedListener {
306 public void selectionChanged(SelectionChangedEvent event) {
307 doSelectionChanged(event);
312 * Adapts an options {@link java.util.Map}to
313 * {@link org.eclipse.jface.preference.IPreferenceStore}.
315 * This preference store is read-only i.e. write access throws an
316 * {@link java.lang.UnsupportedOperationException}.
321 private static class OptionsAdapter implements IPreferenceStore {
324 * A property change event filter.
326 public interface IPropertyChangeEventFilter {
329 * Should the given event be filtered?
332 * The property change event.
333 * @return <code>true</code> iff the given event should be filtered.
335 public boolean isFiltered(PropertyChangeEvent event);
340 * Property change listener. Listens for events in the options Map and fires
341 * a {@link org.eclipse.jface.util.PropertyChangeEvent}on this adapter with
342 * arguments from the received event.
344 private class PropertyChangeListener implements IPropertyChangeListener {
349 public void propertyChange(PropertyChangeEvent event) {
350 if (getFilter().isFiltered(event))
353 if (event.getNewValue() == null)
354 fOptions.remove(event.getProperty());
356 fOptions.put(event.getProperty(), event.getNewValue());
358 firePropertyChangeEvent(event.getProperty(), event.getOldValue(), event.getNewValue());
362 /** Listeners on this adapter */
363 private ListenerList fListeners = new ListenerList();
365 /** Listener on the adapted options Map */
366 private IPropertyChangeListener fListener = new PropertyChangeListener();
368 /** Adapted options Map */
369 private Map fOptions;
371 /** Preference store through which events are received. */
372 private IPreferenceStore fMockupPreferenceStore;
374 /** Property event filter. */
375 private IPropertyChangeEventFilter fFilter;
378 * Initialize with the given options.
381 * The options to wrap
382 * @param mockupPreferenceStore
383 * the mock-up preference store
385 * the property change filter
387 public OptionsAdapter(Map options, IPreferenceStore mockupPreferenceStore, IPropertyChangeEventFilter filter) {
388 fMockupPreferenceStore = mockupPreferenceStore;
396 public void addPropertyChangeListener(IPropertyChangeListener listener) {
397 if (fListeners.size() == 0)
398 fMockupPreferenceStore.addPropertyChangeListener(fListener);
399 fListeners.add(listener);
405 public void removePropertyChangeListener(IPropertyChangeListener listener) {
406 fListeners.remove(listener);
407 if (fListeners.size() == 0)
408 fMockupPreferenceStore.removePropertyChangeListener(fListener);
414 public boolean contains(String name) {
415 return fOptions.containsKey(name);
421 public void firePropertyChangeEvent(String name, Object oldValue, Object newValue) {
422 PropertyChangeEvent event = new PropertyChangeEvent(this, name, oldValue, newValue);
423 Object[] listeners = fListeners.getListeners();
424 for (int i = 0; i < listeners.length; i++)
425 ((IPropertyChangeListener) listeners[i]).propertyChange(event);
431 public boolean getBoolean(String name) {
432 boolean value = BOOLEAN_DEFAULT_DEFAULT;
433 String s = (String) fOptions.get(name);
435 value = s.equals(TRUE);
442 public boolean getDefaultBoolean(String name) {
443 return BOOLEAN_DEFAULT_DEFAULT;
449 public double getDefaultDouble(String name) {
450 return DOUBLE_DEFAULT_DEFAULT;
456 public float getDefaultFloat(String name) {
457 return FLOAT_DEFAULT_DEFAULT;
463 public int getDefaultInt(String name) {
464 return INT_DEFAULT_DEFAULT;
470 public long getDefaultLong(String name) {
471 return LONG_DEFAULT_DEFAULT;
477 public String getDefaultString(String name) {
478 return STRING_DEFAULT_DEFAULT;
484 public double getDouble(String name) {
485 double value = DOUBLE_DEFAULT_DEFAULT;
486 String s = (String) fOptions.get(name);
489 value = new Double(s).doubleValue();
490 } catch (NumberFormatException e) {
499 public float getFloat(String name) {
500 float value = FLOAT_DEFAULT_DEFAULT;
501 String s = (String) fOptions.get(name);
504 value = new Float(s).floatValue();
505 } catch (NumberFormatException e) {
514 public int getInt(String name) {
515 int value = INT_DEFAULT_DEFAULT;
516 String s = (String) fOptions.get(name);
519 value = new Integer(s).intValue();
520 } catch (NumberFormatException e) {
529 public long getLong(String name) {
530 long value = LONG_DEFAULT_DEFAULT;
531 String s = (String) fOptions.get(name);
534 value = new Long(s).longValue();
535 } catch (NumberFormatException e) {
544 public String getString(String name) {
545 String value = (String) fOptions.get(name);
547 value = STRING_DEFAULT_DEFAULT;
554 public boolean isDefault(String name) {
561 public boolean needsSaving() {
562 return !fOptions.isEmpty();
568 public void putValue(String name, String value) {
569 throw new UnsupportedOperationException();
575 public void setDefault(String name, double value) {
576 throw new UnsupportedOperationException();
582 public void setDefault(String name, float value) {
583 throw new UnsupportedOperationException();
589 public void setDefault(String name, int value) {
590 throw new UnsupportedOperationException();
596 public void setDefault(String name, long value) {
597 throw new UnsupportedOperationException();
603 public void setDefault(String name, String defaultObject) {
604 throw new UnsupportedOperationException();
610 public void setDefault(String name, boolean value) {
611 throw new UnsupportedOperationException();
617 public void setToDefault(String name) {
618 throw new UnsupportedOperationException();
624 public void setValue(String name, double value) {
625 throw new UnsupportedOperationException();
631 public void setValue(String name, float value) {
632 throw new UnsupportedOperationException();
638 public void setValue(String name, int value) {
639 throw new UnsupportedOperationException();
645 public void setValue(String name, long value) {
646 throw new UnsupportedOperationException();
652 public void setValue(String name, String value) {
653 throw new UnsupportedOperationException();
659 public void setValue(String name, boolean value) {
660 throw new UnsupportedOperationException();
664 * Returns the adapted options Map.
666 * @return Returns the adapted options Map.
668 public Map getOptions() {
673 * Returns the mock-up preference store, events are received through this
676 * @return Returns the mock-up preference store.
678 public IPreferenceStore getMockupPreferenceStore() {
679 return fMockupPreferenceStore;
683 * Set the event filter to the given filter.
688 public void setFilter(IPropertyChangeEventFilter filter) {
693 * Returns the event filter.
695 * @return The event filter.
697 public IPropertyChangeEventFilter getFilter() {
705 // class MouseClickListener implements KeyListener, MouseListener,
706 // MouseMoveListener, FocusListener, PaintListener,
707 // IPropertyChangeListener, IDocumentListener, ITextInputListener {
709 // /** The session is active. */
710 // private boolean fActive;
712 // /** The currently active style range. */
713 // private IRegion fActiveRegion;
715 // /** The currently active style range as position. */
716 // private Position fRememberedPosition;
718 // /** The hand cursor. */
719 // private Cursor fCursor;
721 // /** The link color. */
722 // private Color fColor;
724 // /** The key modifier mask. */
725 // private int fKeyModifierMask;
727 // public void deactivate() {
728 // deactivate(false);
731 // public void deactivate(boolean redrawAll) {
735 // repairRepresentation(redrawAll);
739 // public void install() {
741 // ISourceViewer sourceViewer = getSourceViewer();
742 // if (sourceViewer == null)
745 // StyledText text = sourceViewer.getTextWidget();
746 // if (text == null || text.isDisposed())
749 // updateColor(sourceViewer);
751 // sourceViewer.addTextInputListener(this);
753 // IDocument document = sourceViewer.getDocument();
754 // if (document != null)
755 // document.addDocumentListener(this);
757 // text.addKeyListener(this);
758 // text.addMouseListener(this);
759 // text.addMouseMoveListener(this);
760 // text.addFocusListener(this);
761 // text.addPaintListener(this);
763 // updateKeyModifierMask();
765 // IPreferenceStore preferenceStore = getPreferenceStore();
766 // preferenceStore.addPropertyChangeListener(this);
769 // private void updateKeyModifierMask() {
770 // String modifiers =
771 // getPreferenceStore().getString(BROWSER_LIKE_LINKS_KEY_MODIFIER);
772 // fKeyModifierMask = computeStateMask(modifiers);
773 // if (fKeyModifierMask == -1) {
774 // // Fallback to stored state mask
775 // fKeyModifierMask =
776 // getPreferenceStore().getInt(BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK);
781 // private int computeStateMask(String modifiers) {
782 // if (modifiers == null)
785 // if (modifiers.length() == 0)
788 // int stateMask = 0;
789 // StringTokenizer modifierTokenizer = new StringTokenizer(modifiers, ",;.:+-*
791 // while (modifierTokenizer.hasMoreTokens()) {
793 // EditorUtility.findLocalizedModifier(modifierTokenizer.nextToken());
794 // if (modifier == 0 || (stateMask & modifier) == modifier)
796 // stateMask = stateMask | modifier;
801 // public void uninstall() {
803 // if (fColor != null) {
808 // if (fCursor != null) {
809 // fCursor.dispose();
813 // ISourceViewer sourceViewer = getSourceViewer();
814 // if (sourceViewer == null)
817 // sourceViewer.removeTextInputListener(this);
819 // IDocument document = sourceViewer.getDocument();
820 // if (document != null)
821 // document.removeDocumentListener(this);
823 // IPreferenceStore preferenceStore = getPreferenceStore();
824 // if (preferenceStore != null)
825 // preferenceStore.removePropertyChangeListener(this);
827 // StyledText text = sourceViewer.getTextWidget();
828 // if (text == null || text.isDisposed())
831 // text.removeKeyListener(this);
832 // text.removeMouseListener(this);
833 // text.removeMouseMoveListener(this);
834 // text.removeFocusListener(this);
835 // text.removePaintListener(this);
839 // * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
841 // public void propertyChange(PropertyChangeEvent event) {
842 // if (event.getProperty().equals(PHPEditor.LINK_COLOR)) {
843 // ISourceViewer viewer = getSourceViewer();
844 // if (viewer != null)
845 // updateColor(viewer);
846 // } else if (event.getProperty().equals(BROWSER_LIKE_LINKS_KEY_MODIFIER)) {
847 // updateKeyModifierMask();
851 // private void updateColor(ISourceViewer viewer) {
852 // if (fColor != null)
855 // StyledText text = viewer.getTextWidget();
856 // if (text == null || text.isDisposed())
859 // Display display = text.getDisplay();
860 // fColor = createColor(getPreferenceStore(), PHPEditor.LINK_COLOR, display);
864 // * Creates a color from the information stored in the given preference
865 // store. Returns <code>null</code> if there is no such
866 // * information available.
868 // private Color createColor(IPreferenceStore store, String key, Display
873 // if (store.contains(key)) {
875 // if (store.isDefault(key))
876 // rgb = PreferenceConverter.getDefaultColor(store, key);
878 // rgb = PreferenceConverter.getColor(store, key);
881 // return new Color(display, rgb);
887 // private void repairRepresentation() {
888 // repairRepresentation(false);
891 // private void repairRepresentation(boolean redrawAll) {
893 // if (fActiveRegion == null)
896 // ISourceViewer viewer = getSourceViewer();
897 // if (viewer != null) {
898 // resetCursor(viewer);
900 // int offset = fActiveRegion.getOffset();
901 // int length = fActiveRegion.getLength();
904 // if (!redrawAll && viewer instanceof ITextViewerExtension2)
905 // ((ITextViewerExtension2) viewer).invalidateTextPresentation(offset,
908 // viewer.invalidateTextPresentation();
910 // // remove underline
911 // if (viewer instanceof ITextViewerExtension3) {
912 // ITextViewerExtension3 extension = (ITextViewerExtension3) viewer;
913 // offset = extension.modelOffset2WidgetOffset(offset);
915 // offset -= viewer.getVisibleRegion().getOffset();
918 // StyledText text = viewer.getTextWidget();
920 // text.redrawRange(offset, length, true);
921 // } catch (IllegalArgumentException x) {
922 // PHPeclipsePlugin.log(x);
926 // fActiveRegion = null;
929 // // will eventually be replaced by a method provided by jdt.core
930 // private IRegion selectWord(IDocument document, int anchor) {
933 // int offset = anchor;
936 // while (offset >= 0) {
937 // c = document.getChar(offset);
938 // if (!Scanner.isPHPIdentifierPart(c))
943 // int start = offset;
946 // int length = document.getLength();
948 // while (offset < length) {
949 // c = document.getChar(offset);
950 // if (!Scanner.isPHPIdentifierPart(c))
958 // return new Region(start, 0);
960 // return new Region(start + 1, end - start - 1);
962 // } catch (BadLocationException x) {
967 // IRegion getCurrentTextRegion(ISourceViewer viewer) {
969 // int offset = getCurrentTextOffset(viewer);
974 // // IJavaElement input= SelectionConverter.getInput(PHPEditor.this);
975 // // if (input == null)
980 // // IJavaElement[] elements= null;
981 // // synchronized (input) {
982 // // elements= ((ICodeAssist) input).codeSelect(offset, 0);
985 // // if (elements == null || elements.length == 0)
988 // // return selectWord(viewer.getDocument(), offset);
990 // // } catch (JavaModelException e) {
995 // private int getCurrentTextOffset(ISourceViewer viewer) {
998 // StyledText text = viewer.getTextWidget();
999 // if (text == null || text.isDisposed())
1002 // Display display = text.getDisplay();
1003 // Point absolutePosition = display.getCursorLocation();
1004 // Point relativePosition = text.toControl(absolutePosition);
1006 // int widgetOffset = text.getOffsetAtLocation(relativePosition);
1007 // if (viewer instanceof ITextViewerExtension3) {
1008 // ITextViewerExtension3 extension = (ITextViewerExtension3) viewer;
1009 // return extension.widgetOffset2ModelOffset(widgetOffset);
1011 // return widgetOffset + viewer.getVisibleRegion().getOffset();
1014 // } catch (IllegalArgumentException e) {
1019 // private void highlightRegion(ISourceViewer viewer, IRegion region) {
1021 // if (region.equals(fActiveRegion))
1024 // repairRepresentation();
1026 // StyledText text = viewer.getTextWidget();
1027 // if (text == null || text.isDisposed())
1030 // // highlight region
1034 // if (viewer instanceof ITextViewerExtension3) {
1035 // ITextViewerExtension3 extension = (ITextViewerExtension3) viewer;
1036 // IRegion widgetRange = extension.modelRange2WidgetRange(region);
1037 // if (widgetRange == null)
1040 // offset = widgetRange.getOffset();
1041 // length = widgetRange.getLength();
1044 // offset = region.getOffset() - viewer.getVisibleRegion().getOffset();
1045 // length = region.getLength();
1048 // StyleRange oldStyleRange = text.getStyleRangeAtOffset(offset);
1049 // Color foregroundColor = fColor;
1050 // Color backgroundColor = oldStyleRange == null ? text.getBackground() :
1051 // oldStyleRange.background;
1052 // StyleRange styleRange = new StyleRange(offset, length, foregroundColor,
1053 // backgroundColor);
1054 // text.setStyleRange(styleRange);
1057 // text.redrawRange(offset, length, true);
1059 // fActiveRegion = region;
1062 // private void activateCursor(ISourceViewer viewer) {
1063 // StyledText text = viewer.getTextWidget();
1064 // if (text == null || text.isDisposed())
1066 // Display display = text.getDisplay();
1067 // if (fCursor == null)
1068 // fCursor = new Cursor(display, SWT.CURSOR_HAND);
1069 // text.setCursor(fCursor);
1072 // private void resetCursor(ISourceViewer viewer) {
1073 // StyledText text = viewer.getTextWidget();
1074 // if (text != null && !text.isDisposed())
1075 // text.setCursor(null);
1077 // if (fCursor != null) {
1078 // fCursor.dispose();
1085 // org.eclipse.swt.events.KeyListener#keyPressed(org.eclipse.swt.events.KeyEvent)
1087 // public void keyPressed(KeyEvent event) {
1094 // if (event.keyCode != fKeyModifierMask) {
1101 // // removed for #25871
1103 // // ISourceViewer viewer= getSourceViewer();
1104 // // if (viewer == null)
1107 // // IRegion region= getCurrentTextRegion(viewer);
1108 // // if (region == null)
1111 // // highlightRegion(viewer, region);
1112 // // activateCursor(viewer);
1117 // org.eclipse.swt.events.KeyListener#keyReleased(org.eclipse.swt.events.KeyEvent)
1119 // public void keyReleased(KeyEvent event) {
1129 // org.eclipse.swt.events.MouseListener#mouseDoubleClick(org.eclipse.swt.events.MouseEvent)
1131 // public void mouseDoubleClick(MouseEvent e) {
1136 // org.eclipse.swt.events.MouseListener#mouseDown(org.eclipse.swt.events.MouseEvent)
1138 // public void mouseDown(MouseEvent event) {
1143 // if (event.stateMask != fKeyModifierMask) {
1148 // if (event.button != 1) {
1156 // org.eclipse.swt.events.MouseListener#mouseUp(org.eclipse.swt.events.MouseEvent)
1158 // public void mouseUp(MouseEvent e) {
1163 // if (e.button != 1) {
1168 // boolean wasActive = fCursor != null;
1173 // IAction action = getAction("OpenEditor"); //$NON-NLS-1$
1174 // if (action != null)
1181 // org.eclipse.swt.events.MouseMoveListener#mouseMove(org.eclipse.swt.events.MouseEvent)
1183 // public void mouseMove(MouseEvent event) {
1185 // if (event.widget instanceof Control && !((Control)
1186 // event.widget).isFocusControl()) {
1192 // if (event.stateMask != fKeyModifierMask)
1194 // // modifier was already pressed
1198 // ISourceViewer viewer = getSourceViewer();
1199 // if (viewer == null) {
1204 // StyledText text = viewer.getTextWidget();
1205 // if (text == null || text.isDisposed()) {
1210 // if ((event.stateMask & SWT.BUTTON1) != 0 && text.getSelectionCount() != 0)
1216 // IRegion region = getCurrentTextRegion(viewer);
1217 // if (region == null || region.getLength() == 0) {
1218 // repairRepresentation();
1222 // highlightRegion(viewer, region);
1223 // activateCursor(viewer);
1228 // org.eclipse.swt.events.FocusListener#focusGained(org.eclipse.swt.events.FocusEvent)
1230 // public void focusGained(FocusEvent e) {
1235 // org.eclipse.swt.events.FocusListener#focusLost(org.eclipse.swt.events.FocusEvent)
1237 // public void focusLost(FocusEvent event) {
1243 // org.eclipse.jface.text.IDocumentListener#documentAboutToBeChanged(org.eclipse.jface.text.DocumentEvent)
1245 // public void documentAboutToBeChanged(DocumentEvent event) {
1246 // if (fActive && fActiveRegion != null) {
1247 // fRememberedPosition = new Position(fActiveRegion.getOffset(),
1248 // fActiveRegion.getLength());
1250 // event.getDocument().addPosition(fRememberedPosition);
1251 // } catch (BadLocationException x) {
1252 // fRememberedPosition = null;
1259 // org.eclipse.jface.text.IDocumentListener#documentChanged(org.eclipse.jface.text.DocumentEvent)
1261 // public void documentChanged(DocumentEvent event) {
1262 // if (fRememberedPosition != null && !fRememberedPosition.isDeleted()) {
1263 // event.getDocument().removePosition(fRememberedPosition);
1264 // fActiveRegion = new Region(fRememberedPosition.getOffset(),
1265 // fRememberedPosition.getLength());
1267 // fRememberedPosition = null;
1269 // ISourceViewer viewer = getSourceViewer();
1270 // if (viewer != null) {
1271 // StyledText widget = viewer.getTextWidget();
1272 // if (widget != null && !widget.isDisposed()) {
1273 // widget.getDisplay().asyncExec(new Runnable() {
1274 // public void run() {
1284 // org.eclipse.jface.text.ITextInputListener#inputDocumentAboutToBeChanged(org.eclipse.jface.text.IDocument,
1285 // * org.eclipse.jface.text.IDocument)
1287 // public void inputDocumentAboutToBeChanged(IDocument oldInput, IDocument
1289 // if (oldInput == null)
1292 // oldInput.removeDocumentListener(this);
1297 // org.eclipse.jface.text.ITextInputListener#inputDocumentChanged(org.eclipse.jface.text.IDocument,
1298 // * org.eclipse.jface.text.IDocument)
1300 // public void inputDocumentChanged(IDocument oldInput, IDocument newInput) {
1301 // if (newInput == null)
1303 // newInput.addDocumentListener(this);
1307 // * @see PaintListener#paintControl(PaintEvent)
1309 // public void paintControl(PaintEvent event) {
1310 // if (fActiveRegion == null)
1313 // ISourceViewer viewer = getSourceViewer();
1314 // if (viewer == null)
1317 // StyledText text = viewer.getTextWidget();
1318 // if (text == null || text.isDisposed())
1324 // if (viewer instanceof ITextViewerExtension3) {
1326 // ITextViewerExtension3 extension = (ITextViewerExtension3) viewer;
1327 // IRegion widgetRange = extension.modelRange2WidgetRange(new Region(offset,
1329 // if (widgetRange == null)
1332 // offset = widgetRange.getOffset();
1333 // length = widgetRange.getLength();
1337 // IRegion region = viewer.getVisibleRegion();
1338 // if (!includes(region, fActiveRegion))
1341 // offset = fActiveRegion.getOffset() - region.getOffset();
1342 // length = fActiveRegion.getLength();
1345 // // support for bidi
1346 // Point minLocation = getMinimumLocation(text, offset, length);
1347 // Point maxLocation = getMaximumLocation(text, offset, length);
1349 // int x1 = minLocation.x;
1350 // int x2 = minLocation.x + maxLocation.x - minLocation.x - 1;
1351 // int y = minLocation.y + text.getLineHeight() - 1;
1353 // GC gc = event.gc;
1354 // if (fColor != null && !fColor.isDisposed())
1355 // gc.setForeground(fColor);
1356 // gc.drawLine(x1, y, x2, y);
1359 // private boolean includes(IRegion region, IRegion position) {
1360 // return position.getOffset() >= region.getOffset()
1361 // && position.getOffset() + position.getLength() <= region.getOffset() +
1362 // region.getLength();
1365 // private Point getMinimumLocation(StyledText text, int offset, int length) {
1366 // Point minLocation = new Point(Integer.MAX_VALUE, Integer.MAX_VALUE);
1368 // for (int i = 0; i <= length; i++) {
1369 // Point location = text.getLocationAtOffset(offset + i);
1371 // if (location.x < minLocation.x)
1372 // minLocation.x = location.x;
1373 // if (location.y < minLocation.y)
1374 // minLocation.y = location.y;
1377 // return minLocation;
1380 // private Point getMaximumLocation(StyledText text, int offset, int length) {
1381 // Point maxLocation = new Point(Integer.MIN_VALUE, Integer.MIN_VALUE);
1383 // for (int i = 0; i <= length; i++) {
1384 // Point location = text.getLocationAtOffset(offset + i);
1386 // if (location.x > maxLocation.x)
1387 // maxLocation.x = location.x;
1388 // if (location.y > maxLocation.y)
1389 // maxLocation.y = location.y;
1392 // return maxLocation;
1398 class MouseClickListener implements KeyListener, MouseListener, MouseMoveListener, FocusListener, PaintListener,
1399 IPropertyChangeListener, IDocumentListener, ITextInputListener, ITextPresentationListener {
1401 /** The session is active. */
1402 private boolean fActive;
1404 /** The currently active style range. */
1405 private IRegion fActiveRegion;
1407 /** The currently active style range as position. */
1408 private Position fRememberedPosition;
1410 /** The hand cursor. */
1411 private Cursor fCursor;
1413 /** The link color. */
1414 private Color fColor;
1416 /** The key modifier mask. */
1417 private int fKeyModifierMask;
1419 public void deactivate() {
1423 public void deactivate(boolean redrawAll) {
1427 repairRepresentation(redrawAll);
1431 public void install() {
1432 ISourceViewer sourceViewer = getSourceViewer();
1433 if (sourceViewer == null)
1436 StyledText text = sourceViewer.getTextWidget();
1437 if (text == null || text.isDisposed())
1440 updateColor(sourceViewer);
1442 sourceViewer.addTextInputListener(this);
1444 IDocument document = sourceViewer.getDocument();
1445 if (document != null)
1446 document.addDocumentListener(this);
1448 text.addKeyListener(this);
1449 text.addMouseListener(this);
1450 text.addMouseMoveListener(this);
1451 text.addFocusListener(this);
1452 text.addPaintListener(this);
1454 ((ITextViewerExtension4) sourceViewer).addTextPresentationListener(this);
1456 updateKeyModifierMask();
1458 IPreferenceStore preferenceStore = getPreferenceStore();
1459 preferenceStore.addPropertyChangeListener(this);
1462 private void updateKeyModifierMask() {
1463 String modifiers = getPreferenceStore().getString(BROWSER_LIKE_LINKS_KEY_MODIFIER);
1464 fKeyModifierMask = computeStateMask(modifiers);
1465 if (fKeyModifierMask == -1) {
1466 // Fall back to stored state mask
1467 fKeyModifierMask = getPreferenceStore().getInt(BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK);
1471 private int computeStateMask(String modifiers) {
1472 if (modifiers == null)
1475 if (modifiers.length() == 0)
1479 StringTokenizer modifierTokenizer = new StringTokenizer(modifiers, ",;.:+-* "); //$NON-NLS-1$
1480 while (modifierTokenizer.hasMoreTokens()) {
1481 int modifier = EditorUtility.findLocalizedModifier(modifierTokenizer.nextToken());
1482 if (modifier == 0 || (stateMask & modifier) == modifier)
1484 stateMask = stateMask | modifier;
1489 public void uninstall() {
1491 if (fColor != null) {
1496 if (fCursor != null) {
1501 ISourceViewer sourceViewer = getSourceViewer();
1502 if (sourceViewer != null)
1503 sourceViewer.removeTextInputListener(this);
1505 IDocumentProvider documentProvider = getDocumentProvider();
1506 if (documentProvider != null) {
1507 IDocument document = documentProvider.getDocument(getEditorInput());
1508 if (document != null)
1509 document.removeDocumentListener(this);
1512 IPreferenceStore preferenceStore = getPreferenceStore();
1513 if (preferenceStore != null)
1514 preferenceStore.removePropertyChangeListener(this);
1516 if (sourceViewer == null)
1519 StyledText text = sourceViewer.getTextWidget();
1520 if (text == null || text.isDisposed())
1523 text.removeKeyListener(this);
1524 text.removeMouseListener(this);
1525 text.removeMouseMoveListener(this);
1526 text.removeFocusListener(this);
1527 text.removePaintListener(this);
1529 ((ITextViewerExtension4) sourceViewer).removeTextPresentationListener(this);
1533 * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
1535 public void propertyChange(PropertyChangeEvent event) {
1536 if (event.getProperty().equals(PHPEditor.LINK_COLOR)) {
1537 ISourceViewer viewer = getSourceViewer();
1539 updateColor(viewer);
1540 } else if (event.getProperty().equals(BROWSER_LIKE_LINKS_KEY_MODIFIER)) {
1541 updateKeyModifierMask();
1545 private void updateColor(ISourceViewer viewer) {
1549 StyledText text = viewer.getTextWidget();
1550 if (text == null || text.isDisposed())
1553 Display display = text.getDisplay();
1554 fColor = createColor(getPreferenceStore(), PHPEditor.LINK_COLOR, display);
1558 * Creates a color from the information stored in the given preference
1562 * the preference store
1567 * @return the color or <code>null</code> if there is no such information
1570 private Color createColor(IPreferenceStore store, String key, Display display) {
1574 if (store.contains(key)) {
1576 if (store.isDefault(key))
1577 rgb = PreferenceConverter.getDefaultColor(store, key);
1579 rgb = PreferenceConverter.getColor(store, key);
1582 return new Color(display, rgb);
1588 private void repairRepresentation() {
1589 repairRepresentation(false);
1592 private void repairRepresentation(boolean redrawAll) {
1594 if (fActiveRegion == null)
1597 int offset = fActiveRegion.getOffset();
1598 int length = fActiveRegion.getLength();
1599 fActiveRegion = null;
1601 ISourceViewer viewer = getSourceViewer();
1602 if (viewer != null) {
1604 resetCursor(viewer);
1606 // Invalidate ==> remove applied text presentation
1607 if (!redrawAll && viewer instanceof ITextViewerExtension2)
1608 ((ITextViewerExtension2) viewer).invalidateTextPresentation(offset, length);
1610 viewer.invalidateTextPresentation();
1613 if (viewer instanceof ITextViewerExtension5) {
1614 ITextViewerExtension5 extension = (ITextViewerExtension5) viewer;
1615 offset = extension.modelOffset2WidgetOffset(offset);
1617 offset -= viewer.getVisibleRegion().getOffset();
1620 StyledText text = viewer.getTextWidget();
1622 text.redrawRange(offset, length, false);
1623 } catch (IllegalArgumentException x) {
1624 // JavaPlugin.log(x);
1629 // will eventually be replaced by a method provided by jdt.core
1630 private IRegion selectWord(IDocument document, int anchor) {
1633 int offset = anchor;
1636 while (offset >= 0) {
1637 c = document.getChar(offset);
1638 if (!Scanner.isPHPIdentifierPart(c) && c != '$')
1646 int length = document.getLength();
1648 while (offset < length) {
1649 c = document.getChar(offset);
1650 if (!Scanner.isPHPIdentifierPart(c) && c != '$')
1658 return new Region(start, 0);
1660 return new Region(start + 1, end - start - 1);
1662 } catch (BadLocationException x) {
1667 IRegion getCurrentTextRegion(ISourceViewer viewer) {
1669 int offset = getCurrentTextOffset(viewer);
1673 IJavaElement input = SelectionConverter.getInput(PHPEditor.this);
1679 // IJavaElement[] elements= null;
1680 // synchronized (input) {
1681 // elements= ((ICodeAssist) input).codeSelect(offset, 0);
1684 // if (elements == null || elements.length == 0)
1687 return selectWord(viewer.getDocument(), offset);
1689 // } catch (JavaModelException e) {
1694 private int getCurrentTextOffset(ISourceViewer viewer) {
1697 StyledText text = viewer.getTextWidget();
1698 if (text == null || text.isDisposed())
1701 Display display = text.getDisplay();
1702 Point absolutePosition = display.getCursorLocation();
1703 Point relativePosition = text.toControl(absolutePosition);
1705 int widgetOffset = text.getOffsetAtLocation(relativePosition);
1706 if (viewer instanceof ITextViewerExtension5) {
1707 ITextViewerExtension5 extension = (ITextViewerExtension5) viewer;
1708 return extension.widgetOffset2ModelOffset(widgetOffset);
1710 return widgetOffset + viewer.getVisibleRegion().getOffset();
1713 } catch (IllegalArgumentException e) {
1718 public void applyTextPresentation(TextPresentation textPresentation) {
1719 if (fActiveRegion == null)
1721 IRegion region = textPresentation.getExtent();
1722 if (fActiveRegion.getOffset() + fActiveRegion.getLength() >= region.getOffset()
1723 && region.getOffset() + region.getLength() > fActiveRegion.getOffset())
1724 textPresentation.mergeStyleRange(new StyleRange(fActiveRegion.getOffset(), fActiveRegion.getLength(), fColor, null));
1727 private void highlightRegion(ISourceViewer viewer, IRegion region) {
1729 if (region.equals(fActiveRegion))
1732 repairRepresentation();
1734 StyledText text = viewer.getTextWidget();
1735 if (text == null || text.isDisposed())
1741 if (viewer instanceof ITextViewerExtension5) {
1742 ITextViewerExtension5 extension = (ITextViewerExtension5) viewer;
1743 IRegion widgetRange = extension.modelRange2WidgetRange(region);
1744 if (widgetRange == null)
1747 offset = widgetRange.getOffset();
1748 length = widgetRange.getLength();
1751 offset = region.getOffset() - viewer.getVisibleRegion().getOffset();
1752 length = region.getLength();
1754 text.redrawRange(offset, length, false);
1756 // Invalidate region ==> apply text presentation
1757 fActiveRegion = region;
1758 if (viewer instanceof ITextViewerExtension2)
1759 ((ITextViewerExtension2) viewer).invalidateTextPresentation(region.getOffset(), region.getLength());
1761 viewer.invalidateTextPresentation();
1764 private void activateCursor(ISourceViewer viewer) {
1765 StyledText text = viewer.getTextWidget();
1766 if (text == null || text.isDisposed())
1768 Display display = text.getDisplay();
1769 if (fCursor == null)
1770 fCursor = new Cursor(display, SWT.CURSOR_HAND);
1771 text.setCursor(fCursor);
1774 private void resetCursor(ISourceViewer viewer) {
1775 StyledText text = viewer.getTextWidget();
1776 if (text != null && !text.isDisposed())
1777 text.setCursor(null);
1779 if (fCursor != null) {
1786 * @see org.eclipse.swt.events.KeyListener#keyPressed(org.eclipse.swt.events.KeyEvent)
1788 public void keyPressed(KeyEvent event) {
1795 if (event.keyCode != fKeyModifierMask) {
1802 // removed for #25871
1804 // ISourceViewer viewer= getSourceViewer();
1805 // if (viewer == null)
1808 // IRegion region= getCurrentTextRegion(viewer);
1809 // if (region == null)
1812 // highlightRegion(viewer, region);
1813 // activateCursor(viewer);
1817 * @see org.eclipse.swt.events.KeyListener#keyReleased(org.eclipse.swt.events.KeyEvent)
1819 public void keyReleased(KeyEvent event) {
1828 * @see org.eclipse.swt.events.MouseListener#mouseDoubleClick(org.eclipse.swt.events.MouseEvent)
1830 public void mouseDoubleClick(MouseEvent e) {
1834 * @see org.eclipse.swt.events.MouseListener#mouseDown(org.eclipse.swt.events.MouseEvent)
1836 public void mouseDown(MouseEvent event) {
1841 if (event.stateMask != fKeyModifierMask) {
1846 if (event.button != 1) {
1853 * @see org.eclipse.swt.events.MouseListener#mouseUp(org.eclipse.swt.events.MouseEvent)
1855 public void mouseUp(MouseEvent e) {
1860 if (e.button != 1) {
1865 boolean wasActive = fCursor != null;
1870 IAction action = getAction("OpenEditor"); //$NON-NLS-1$
1877 * @see org.eclipse.swt.events.MouseMoveListener#mouseMove(org.eclipse.swt.events.MouseEvent)
1879 public void mouseMove(MouseEvent event) {
1881 if (event.widget instanceof Control && !((Control) event.widget).isFocusControl()) {
1887 if (event.stateMask != fKeyModifierMask)
1889 // modifier was already pressed
1893 ISourceViewer viewer = getSourceViewer();
1894 if (viewer == null) {
1899 StyledText text = viewer.getTextWidget();
1900 if (text == null || text.isDisposed()) {
1905 if ((event.stateMask & SWT.BUTTON1) != 0 && text.getSelectionCount() != 0) {
1910 IRegion region = getCurrentTextRegion(viewer);
1911 if (region == null || region.getLength() == 0) {
1912 repairRepresentation();
1916 highlightRegion(viewer, region);
1917 activateCursor(viewer);
1921 * @see org.eclipse.swt.events.FocusListener#focusGained(org.eclipse.swt.events.FocusEvent)
1923 public void focusGained(FocusEvent e) {
1927 * @see org.eclipse.swt.events.FocusListener#focusLost(org.eclipse.swt.events.FocusEvent)
1929 public void focusLost(FocusEvent event) {
1934 * @see org.eclipse.jface.text.IDocumentListener#documentAboutToBeChanged(org.eclipse.jface.text.DocumentEvent)
1936 public void documentAboutToBeChanged(DocumentEvent event) {
1937 if (fActive && fActiveRegion != null) {
1938 fRememberedPosition = new Position(fActiveRegion.getOffset(), fActiveRegion.getLength());
1940 event.getDocument().addPosition(fRememberedPosition);
1941 } catch (BadLocationException x) {
1942 fRememberedPosition = null;
1948 * @see org.eclipse.jface.text.IDocumentListener#documentChanged(org.eclipse.jface.text.DocumentEvent)
1950 public void documentChanged(DocumentEvent event) {
1951 if (fRememberedPosition != null) {
1952 if (!fRememberedPosition.isDeleted()) {
1954 event.getDocument().removePosition(fRememberedPosition);
1955 fActiveRegion = new Region(fRememberedPosition.getOffset(), fRememberedPosition.getLength());
1956 fRememberedPosition = null;
1958 ISourceViewer viewer = getSourceViewer();
1959 if (viewer != null) {
1960 StyledText widget = viewer.getTextWidget();
1961 if (widget != null && !widget.isDisposed()) {
1962 widget.getDisplay().asyncExec(new Runnable() {
1971 fActiveRegion = null;
1972 fRememberedPosition = null;
1979 * @see org.eclipse.jface.text.ITextInputListener#inputDocumentAboutToBeChanged(org.eclipse.jface.text.IDocument,
1980 * org.eclipse.jface.text.IDocument)
1982 public void inputDocumentAboutToBeChanged(IDocument oldInput, IDocument newInput) {
1983 if (oldInput == null)
1986 oldInput.removeDocumentListener(this);
1990 * @see org.eclipse.jface.text.ITextInputListener#inputDocumentChanged(org.eclipse.jface.text.IDocument,
1991 * org.eclipse.jface.text.IDocument)
1993 public void inputDocumentChanged(IDocument oldInput, IDocument newInput) {
1994 if (newInput == null)
1996 newInput.addDocumentListener(this);
2000 * @see PaintListener#paintControl(PaintEvent)
2002 public void paintControl(PaintEvent event) {
2003 if (fActiveRegion == null)
2006 ISourceViewer viewer = getSourceViewer();
2010 StyledText text = viewer.getTextWidget();
2011 if (text == null || text.isDisposed())
2017 if (viewer instanceof ITextViewerExtension5) {
2019 ITextViewerExtension5 extension = (ITextViewerExtension5) viewer;
2020 IRegion widgetRange = extension.modelRange2WidgetRange(fActiveRegion);
2021 if (widgetRange == null)
2024 offset = widgetRange.getOffset();
2025 length = widgetRange.getLength();
2029 IRegion region = viewer.getVisibleRegion();
2030 if (!includes(region, fActiveRegion))
2033 offset = fActiveRegion.getOffset() - region.getOffset();
2034 length = fActiveRegion.getLength();
2038 Point minLocation = getMinimumLocation(text, offset, length);
2039 Point maxLocation = getMaximumLocation(text, offset, length);
2041 int x1 = minLocation.x;
2042 int x2 = minLocation.x + maxLocation.x - minLocation.x - 1;
2043 int y = minLocation.y + text.getLineHeight() - 1;
2046 if (fColor != null && !fColor.isDisposed())
2047 gc.setForeground(fColor);
2048 gc.drawLine(x1, y, x2, y);
2051 private boolean includes(IRegion region, IRegion position) {
2052 return position.getOffset() >= region.getOffset()
2053 && position.getOffset() + position.getLength() <= region.getOffset() + region.getLength();
2056 private Point getMinimumLocation(StyledText text, int offset, int length) {
2057 Point minLocation = new Point(Integer.MAX_VALUE, Integer.MAX_VALUE);
2059 for (int i = 0; i <= length; i++) {
2060 Point location = text.getLocationAtOffset(offset + i);
2062 if (location.x < minLocation.x)
2063 minLocation.x = location.x;
2064 if (location.y < minLocation.y)
2065 minLocation.y = location.y;
2071 private Point getMaximumLocation(StyledText text, int offset, int length) {
2072 Point maxLocation = new Point(Integer.MIN_VALUE, Integer.MIN_VALUE);
2074 for (int i = 0; i <= length; i++) {
2075 Point location = text.getLocationAtOffset(offset + i);
2077 if (location.x > maxLocation.x)
2078 maxLocation.x = location.x;
2079 if (location.y > maxLocation.y)
2080 maxLocation.y = location.y;
2088 * This action dispatches into two behaviours: If there is no current text
2089 * hover, the javadoc is displayed using information presenter. If there is a
2090 * current text hover, it is converted into a information presenter in order
2091 * to make it sticky.
2093 class InformationDispatchAction extends TextEditorAction {
2095 /** The wrapped text operation action. */
2096 private final TextOperationAction fTextOperationAction;
2099 * Creates a dispatch action.
2101 public InformationDispatchAction(ResourceBundle resourceBundle, String prefix, final TextOperationAction textOperationAction) {
2102 super(resourceBundle, prefix, PHPEditor.this);
2103 if (textOperationAction == null)
2104 throw new IllegalArgumentException();
2105 fTextOperationAction = textOperationAction;
2109 * @see org.eclipse.jface.action.IAction#run()
2113 ISourceViewer sourceViewer = getSourceViewer();
2114 if (sourceViewer == null) {
2115 fTextOperationAction.run();
2119 if (!(sourceViewer instanceof ITextViewerExtension2)) {
2120 fTextOperationAction.run();
2124 ITextViewerExtension2 textViewerExtension2 = (ITextViewerExtension2) sourceViewer;
2126 // does a text hover exist?
2127 ITextHover textHover = textViewerExtension2.getCurrentTextHover();
2128 if (textHover == null) {
2129 fTextOperationAction.run();
2133 Point hoverEventLocation = textViewerExtension2.getHoverEventLocation();
2134 int offset = computeOffsetAtLocation(sourceViewer, hoverEventLocation.x, hoverEventLocation.y);
2136 fTextOperationAction.run();
2141 // get the text hover content
2142 IDocument document = sourceViewer.getDocument();
2143 String contentType = document.getContentType(offset);
2145 final IRegion hoverRegion = textHover.getHoverRegion(sourceViewer, offset);
2146 if (hoverRegion == null)
2149 final String hoverInfo = textHover.getHoverInfo(sourceViewer, hoverRegion);
2151 // with information provider
2152 IInformationProvider informationProvider = new IInformationProvider() {
2154 * @see org.eclipse.jface.text.information.IInformationProvider#getSubject(org.eclipse.jface.text.ITextViewer,
2157 public IRegion getSubject(ITextViewer textViewer, int offset) {
2162 * @see org.eclipse.jface.text.information.IInformationProvider#getInformation(org.eclipse.jface.text.ITextViewer,
2163 * org.eclipse.jface.text.IRegion)
2165 public String getInformation(ITextViewer textViewer, IRegion subject) {
2170 fInformationPresenter.setOffset(offset);
2171 fInformationPresenter.setInformationProvider(informationProvider, contentType);
2172 fInformationPresenter.showInformation();
2174 } catch (BadLocationException e) {
2178 // modified version from TextViewer
2179 private int computeOffsetAtLocation(ITextViewer textViewer, int x, int y) {
2181 StyledText styledText = textViewer.getTextWidget();
2182 IDocument document = textViewer.getDocument();
2184 if (document == null)
2188 int widgetLocation = styledText.getOffsetAtLocation(new Point(x, y));
2189 if (textViewer instanceof ITextViewerExtension3) {
2190 ITextViewerExtension3 extension = (ITextViewerExtension3) textViewer;
2191 return extension.widgetOffset2ModelOffset(widgetLocation);
2193 IRegion visibleRegion = textViewer.getVisibleRegion();
2194 return widgetLocation + visibleRegion.getOffset();
2196 } catch (IllegalArgumentException e) {
2204 * This action implements smart home.
2206 * Instead of going to the start of a line it does the following: - if smart
2207 * home/end is enabled and the caret is after the line's first non-whitespace
2208 * then the caret is moved directly before it, taking JavaDoc and multi-line
2209 * comments into account. - if the caret is before the line's first
2210 * non-whitespace the caret is moved to the beginning of the line - if the
2211 * caret is at the beginning of the line see first case.
2215 protected class SmartLineStartAction extends LineStartAction {
2218 * Creates a new smart line start action
2221 * the styled text widget
2223 * a boolean flag which tells if the text up to the beginning of
2224 * the line should be selected
2226 public SmartLineStartAction(final StyledText textWidget, final boolean doSelect) {
2227 super(textWidget, doSelect);
2231 * @see org.eclipse.ui.texteditor.AbstractTextEditor.LineStartAction#getLineStartPosition(java.lang.String,
2232 * int, java.lang.String)
2234 protected int getLineStartPosition(final IDocument document, final String line, final int length, final int offset) {
2236 String type = IDocument.DEFAULT_CONTENT_TYPE;
2238 type = TextUtilities.getContentType(document, IPHPPartitions.PHP_PARTITIONING, offset, true);
2239 } catch (BadLocationException exception) {
2240 // Should not happen
2243 int index = super.getLineStartPosition(document, line, length, offset);
2244 if (type.equals(IPHPPartitions.PHP_PHPDOC_COMMENT) || type.equals(IPHPPartitions.PHP_MULTILINE_COMMENT)) {
2245 if (index < length - 1 && line.charAt(index) == '*' && line.charAt(index + 1) != '/') {
2248 } while (index < length && Character.isWhitespace(line.charAt(index)));
2251 if (index < length - 1 && line.charAt(index) == '/' && line.charAt(index + 1) == '/') {
2255 } while (index < length && Character.isWhitespace(line.charAt(index)));
2263 * Text navigation action to navigate to the next sub-word.
2267 protected abstract class NextSubWordAction extends TextNavigationAction {
2269 protected JavaWordIterator fIterator = new JavaWordIterator();
2272 * Creates a new next sub-word action.
2275 * Action code for the default operation. Must be an action code
2277 * @see org.eclipse.swt.custom.ST.
2279 protected NextSubWordAction(int code) {
2280 super(getSourceViewer().getTextWidget(), code);
2284 * @see org.eclipse.jface.action.IAction#run()
2287 // Check whether we are in a java code partition and the preference is
2289 final IPreferenceStore store = getPreferenceStore();
2290 if (!store.getBoolean(PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION)) {
2295 final ISourceViewer viewer = getSourceViewer();
2296 final IDocument document = viewer.getDocument();
2297 fIterator.setText((CharacterIterator) new DocumentCharacterIterator(document));
2298 int position = widgetOffset2ModelOffset(viewer, viewer.getTextWidget().getCaretOffset());
2302 int next = findNextPosition(position);
2303 if (next != BreakIterator.DONE) {
2304 setCaretPosition(next);
2305 getTextWidget().showSelection();
2306 fireSelectionChanged();
2312 * Finds the next position after the given position.
2315 * the current position
2316 * @return the next position
2318 protected int findNextPosition(int position) {
2319 ISourceViewer viewer = getSourceViewer();
2321 while (position != BreakIterator.DONE && widget == -1) { // TODO:
2323 position = fIterator.following(position);
2324 if (position != BreakIterator.DONE)
2325 widget = modelOffset2WidgetOffset(viewer, position);
2331 * Sets the caret position to the sub-word boundary given with
2332 * <code>position</code>.
2335 * Position where the action should move the caret
2337 protected abstract void setCaretPosition(int position);
2341 * Text navigation action to navigate to the next sub-word.
2345 protected class NavigateNextSubWordAction extends NextSubWordAction {
2348 * Creates a new navigate next sub-word action.
2350 public NavigateNextSubWordAction() {
2351 super(ST.WORD_NEXT);
2355 * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor.NextSubWordAction#setCaretPosition(int)
2357 protected void setCaretPosition(final int position) {
2358 getTextWidget().setCaretOffset(modelOffset2WidgetOffset(getSourceViewer(), position));
2363 * Text operation action to delete the next sub-word.
2367 protected class DeleteNextSubWordAction extends NextSubWordAction implements IUpdate {
2370 * Creates a new delete next sub-word action.
2372 public DeleteNextSubWordAction() {
2373 super(ST.DELETE_WORD_NEXT);
2377 * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor.NextSubWordAction#setCaretPosition(int)
2379 protected void setCaretPosition(final int position) {
2380 if (!validateEditorInputState())
2383 final ISourceViewer viewer = getSourceViewer();
2384 final int caret = widgetOffset2ModelOffset(viewer, viewer.getTextWidget().getCaretOffset());
2387 viewer.getDocument().replace(caret, position - caret, ""); //$NON-NLS-1$
2388 } catch (BadLocationException exception) {
2389 // Should not happen
2394 * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor.NextSubWordAction#findNextPosition(int)
2396 protected int findNextPosition(int position) {
2397 return fIterator.following(position);
2401 * @see org.eclipse.ui.texteditor.IUpdate#update()
2403 public void update() {
2404 setEnabled(isEditorInputModifiable());
2409 * Text operation action to select the next sub-word.
2413 protected class SelectNextSubWordAction extends NextSubWordAction {
2416 * Creates a new select next sub-word action.
2418 public SelectNextSubWordAction() {
2419 super(ST.SELECT_WORD_NEXT);
2423 * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor.NextSubWordAction#setCaretPosition(int)
2425 protected void setCaretPosition(final int position) {
2426 final ISourceViewer viewer = getSourceViewer();
2428 final StyledText text = viewer.getTextWidget();
2429 if (text != null && !text.isDisposed()) {
2431 final Point selection = text.getSelection();
2432 final int caret = text.getCaretOffset();
2433 final int offset = modelOffset2WidgetOffset(viewer, position);
2435 if (caret == selection.x)
2436 text.setSelectionRange(selection.y, offset - selection.y);
2438 text.setSelectionRange(selection.x, offset - selection.x);
2444 * Text navigation action to navigate to the previous sub-word.
2448 protected abstract class PreviousSubWordAction extends TextNavigationAction {
2450 protected JavaWordIterator fIterator = new JavaWordIterator();
2453 * Creates a new previous sub-word action.
2456 * Action code for the default operation. Must be an action code
2458 * @see org.eclipse.swt.custom.ST.
2460 protected PreviousSubWordAction(final int code) {
2461 super(getSourceViewer().getTextWidget(), code);
2465 * @see org.eclipse.jface.action.IAction#run()
2468 // Check whether we are in a java code partition and the preference is
2470 final IPreferenceStore store = getPreferenceStore();
2471 if (!store.getBoolean(PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION)) {
2476 final ISourceViewer viewer = getSourceViewer();
2477 final IDocument document = viewer.getDocument();
2478 fIterator.setText((CharacterIterator) new DocumentCharacterIterator(document));
2479 int position = widgetOffset2ModelOffset(viewer, viewer.getTextWidget().getCaretOffset());
2483 int previous = findPreviousPosition(position);
2484 if (previous != BreakIterator.DONE) {
2485 setCaretPosition(previous);
2486 getTextWidget().showSelection();
2487 fireSelectionChanged();
2493 * Finds the previous position before the given position.
2496 * the current position
2497 * @return the previous position
2499 protected int findPreviousPosition(int position) {
2500 ISourceViewer viewer = getSourceViewer();
2502 while (position != BreakIterator.DONE && widget == -1) { // TODO:
2504 position = fIterator.preceding(position);
2505 if (position != BreakIterator.DONE)
2506 widget = modelOffset2WidgetOffset(viewer, position);
2512 * Sets the caret position to the sub-word boundary given with
2513 * <code>position</code>.
2516 * Position where the action should move the caret
2518 protected abstract void setCaretPosition(int position);
2522 * Text navigation action to navigate to the previous sub-word.
2526 protected class NavigatePreviousSubWordAction extends PreviousSubWordAction {
2529 * Creates a new navigate previous sub-word action.
2531 public NavigatePreviousSubWordAction() {
2532 super(ST.WORD_PREVIOUS);
2536 * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#setCaretPosition(int)
2538 protected void setCaretPosition(final int position) {
2539 getTextWidget().setCaretOffset(modelOffset2WidgetOffset(getSourceViewer(), position));
2544 * Text operation action to delete the previous sub-word.
2548 protected class DeletePreviousSubWordAction extends PreviousSubWordAction implements IUpdate {
2551 * Creates a new delete previous sub-word action.
2553 public DeletePreviousSubWordAction() {
2554 super(ST.DELETE_WORD_PREVIOUS);
2558 * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#setCaretPosition(int)
2560 protected void setCaretPosition(final int position) {
2561 if (!validateEditorInputState())
2564 final ISourceViewer viewer = getSourceViewer();
2565 final int caret = widgetOffset2ModelOffset(viewer, viewer.getTextWidget().getCaretOffset());
2568 viewer.getDocument().replace(position, caret - position, ""); //$NON-NLS-1$
2569 } catch (BadLocationException exception) {
2570 // Should not happen
2575 * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#findPreviousPosition(int)
2577 protected int findPreviousPosition(int position) {
2578 return fIterator.preceding(position);
2582 * @see org.eclipse.ui.texteditor.IUpdate#update()
2584 public void update() {
2585 setEnabled(isEditorInputModifiable());
2590 * Text operation action to select the previous sub-word.
2594 protected class SelectPreviousSubWordAction extends PreviousSubWordAction {
2597 * Creates a new select previous sub-word action.
2599 public SelectPreviousSubWordAction() {
2600 super(ST.SELECT_WORD_PREVIOUS);
2604 * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#setCaretPosition(int)
2606 protected void setCaretPosition(final int position) {
2607 final ISourceViewer viewer = getSourceViewer();
2609 final StyledText text = viewer.getTextWidget();
2610 if (text != null && !text.isDisposed()) {
2612 final Point selection = text.getSelection();
2613 final int caret = text.getCaretOffset();
2614 final int offset = modelOffset2WidgetOffset(viewer, position);
2616 if (caret == selection.x)
2617 text.setSelectionRange(selection.y, offset - selection.y);
2619 text.setSelectionRange(selection.x, offset - selection.x);
2624 // static protected class AnnotationAccess implements IAnnotationAccess {
2627 // org.eclipse.jface.text.source.IAnnotationAccess#getType(org.eclipse.jface.text.source.Annotation)
2629 // public Object getType(Annotation annotation) {
2630 // if (annotation instanceof IJavaAnnotation) {
2631 // IJavaAnnotation javaAnnotation = (IJavaAnnotation) annotation;
2632 // // if (javaAnnotation.isRelevant())
2633 // // return javaAnnotation.getAnnotationType();
2640 // org.eclipse.jface.text.source.IAnnotationAccess#isMultiLine(org.eclipse.jface.text.source.Annotation)
2642 // public boolean isMultiLine(Annotation annotation) {
2648 // org.eclipse.jface.text.source.IAnnotationAccess#isTemporary(org.eclipse.jface.text.source.Annotation)
2650 // public boolean isTemporary(Annotation annotation) {
2651 // if (annotation instanceof IJavaAnnotation) {
2652 // IJavaAnnotation javaAnnotation = (IJavaAnnotation) annotation;
2653 // if (javaAnnotation.isRelevant())
2654 // return javaAnnotation.isTemporary();
2660 private class PropertyChangeListener implements org.eclipse.core.runtime.Preferences.IPropertyChangeListener {
2662 * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
2664 public void propertyChange(org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) {
2665 handlePreferencePropertyChanged(event);
2670 * Finds and marks occurrence annotations.
2674 class OccurrencesFinderJob extends Job {
2676 private IDocument fDocument;
2678 private ISelection fSelection;
2680 private ISelectionValidator fPostSelectionValidator;
2682 private boolean fCanceled = false;
2684 private IProgressMonitor fProgressMonitor;
2686 private Position[] fPositions;
2688 public OccurrencesFinderJob(IDocument document, Position[] positions, ISelection selection) {
2689 super(PHPEditorMessages.JavaEditor_markOccurrences_job_name);
2690 fDocument = document;
2691 fSelection = selection;
2692 fPositions = positions;
2694 if (getSelectionProvider() instanceof ISelectionValidator)
2695 fPostSelectionValidator = (ISelectionValidator) getSelectionProvider();
2698 // cannot use cancel() because it is declared final
2704 private boolean isCanceled() {
2705 return fCanceled || fProgressMonitor.isCanceled() || fPostSelectionValidator != null
2706 && !(fPostSelectionValidator.isValid(fSelection) || fForcedMarkOccurrencesSelection == fSelection)
2707 || LinkedModeModel.hasInstalledModel(fDocument);
2711 * @see Job#run(org.eclipse.core.runtime.IProgressMonitor)
2713 public IStatus run(IProgressMonitor progressMonitor) {
2715 fProgressMonitor = progressMonitor;
2718 return Status.CANCEL_STATUS;
2720 ITextViewer textViewer = getViewer();
2721 if (textViewer == null)
2722 return Status.CANCEL_STATUS;
2724 IDocument document = textViewer.getDocument();
2725 if (document == null)
2726 return Status.CANCEL_STATUS;
2728 IDocumentProvider documentProvider = getDocumentProvider();
2729 if (documentProvider == null)
2730 return Status.CANCEL_STATUS;
2732 IAnnotationModel annotationModel = documentProvider.getAnnotationModel(getEditorInput());
2733 if (annotationModel == null)
2734 return Status.CANCEL_STATUS;
2736 // Add occurrence annotations
2737 int length = fPositions.length;
2738 Map annotationMap = new HashMap(length);
2739 for (int i = 0; i < length; i++) {
2742 return Status.CANCEL_STATUS;
2745 Position position = fPositions[i];
2747 // Create & add annotation
2749 message = document.get(position.offset, position.length);
2750 } catch (BadLocationException ex) {
2754 annotationMap.put(new Annotation("net.sourceforge.phpdt.ui.occurrences", false, message), //$NON-NLS-1$
2759 return Status.CANCEL_STATUS;
2761 synchronized (getLockObject(annotationModel)) {
2762 if (annotationModel instanceof IAnnotationModelExtension) {
2763 ((IAnnotationModelExtension) annotationModel).replaceAnnotations(fOccurrenceAnnotations, annotationMap);
2765 removeOccurrenceAnnotations();
2766 Iterator iter = annotationMap.entrySet().iterator();
2767 while (iter.hasNext()) {
2768 Map.Entry mapEntry = (Map.Entry) iter.next();
2769 annotationModel.addAnnotation((Annotation) mapEntry.getKey(), (Position) mapEntry.getValue());
2772 fOccurrenceAnnotations = (Annotation[]) annotationMap.keySet().toArray(new Annotation[annotationMap.keySet().size()]);
2775 return Status.OK_STATUS;
2780 * Cancels the occurrences finder job upon document changes.
2784 class OccurrencesFinderJobCanceler implements IDocumentListener, ITextInputListener {
2786 public void install() {
2787 ISourceViewer sourceViewer = getSourceViewer();
2788 if (sourceViewer == null)
2791 StyledText text = sourceViewer.getTextWidget();
2792 if (text == null || text.isDisposed())
2795 sourceViewer.addTextInputListener(this);
2797 IDocument document = sourceViewer.getDocument();
2798 if (document != null)
2799 document.addDocumentListener(this);
2802 public void uninstall() {
2803 ISourceViewer sourceViewer = getSourceViewer();
2804 if (sourceViewer != null)
2805 sourceViewer.removeTextInputListener(this);
2807 IDocumentProvider documentProvider = getDocumentProvider();
2808 if (documentProvider != null) {
2809 IDocument document = documentProvider.getDocument(getEditorInput());
2810 if (document != null)
2811 document.removeDocumentListener(this);
2816 * @see org.eclipse.jface.text.IDocumentListener#documentAboutToBeChanged(org.eclipse.jface.text.DocumentEvent)
2818 public void documentAboutToBeChanged(DocumentEvent event) {
2819 if (fOccurrencesFinderJob != null)
2820 fOccurrencesFinderJob.doCancel();
2824 * @see org.eclipse.jface.text.IDocumentListener#documentChanged(org.eclipse.jface.text.DocumentEvent)
2826 public void documentChanged(DocumentEvent event) {
2830 * @see org.eclipse.jface.text.ITextInputListener#inputDocumentAboutToBeChanged(org.eclipse.jface.text.IDocument,
2831 * org.eclipse.jface.text.IDocument)
2833 public void inputDocumentAboutToBeChanged(IDocument oldInput, IDocument newInput) {
2834 if (oldInput == null)
2837 oldInput.removeDocumentListener(this);
2841 * @see org.eclipse.jface.text.ITextInputListener#inputDocumentChanged(org.eclipse.jface.text.IDocument,
2842 * org.eclipse.jface.text.IDocument)
2844 public void inputDocumentChanged(IDocument oldInput, IDocument newInput) {
2845 if (newInput == null)
2847 newInput.addDocumentListener(this);
2852 * Internal activation listener.
2856 private class ActivationListener implements IWindowListener {
2859 * @see org.eclipse.ui.IWindowListener#windowActivated(org.eclipse.ui.IWorkbenchWindow)
2862 public void windowActivated(IWorkbenchWindow window) {
2863 if (window == getEditorSite().getWorkbenchWindow() && fMarkOccurrenceAnnotations && isActivePart()) {
2864 fForcedMarkOccurrencesSelection = getSelectionProvider().getSelection();
2865 SelectionListenerWithASTManager.getDefault().forceSelectionChange(PHPEditor.this,
2866 (ITextSelection) fForcedMarkOccurrencesSelection);
2871 * @see org.eclipse.ui.IWindowListener#windowDeactivated(org.eclipse.ui.IWorkbenchWindow)
2874 public void windowDeactivated(IWorkbenchWindow window) {
2875 if (window == getEditorSite().getWorkbenchWindow() && fMarkOccurrenceAnnotations && isActivePart())
2876 removeOccurrenceAnnotations();
2880 * @see org.eclipse.ui.IWindowListener#windowClosed(org.eclipse.ui.IWorkbenchWindow)
2883 public void windowClosed(IWorkbenchWindow window) {
2887 * @see org.eclipse.ui.IWindowListener#windowOpened(org.eclipse.ui.IWorkbenchWindow)
2890 public void windowOpened(IWorkbenchWindow window) {
2895 * Updates the selection in the editor's widget with the selection of the
2898 class OutlineSelectionChangedListener extends AbstractSelectionChangedListener {
2899 public void selectionChanged(SelectionChangedEvent event) {
2900 doSelectionChanged(event);
2905 * The internal shell activation listener for updating occurrences.
2909 private ActivationListener fActivationListener = new ActivationListener();
2911 private ISelectionListenerWithAST fPostSelectionListenerWithAST;
2913 private OccurrencesFinderJob fOccurrencesFinderJob;
2915 /** The occurrences finder job canceler */
2916 private OccurrencesFinderJobCanceler fOccurrencesFinderJobCanceler;
2919 * Holds the current occurrence annotations.
2923 private Annotation[] fOccurrenceAnnotations = null;
2926 * Tells whether all occurrences of the element at the current caret location
2927 * are automatically marked in this editor.
2931 private boolean fMarkOccurrenceAnnotations;
2934 * The selection used when forcing occurrence marking through code.
2938 private ISelection fForcedMarkOccurrencesSelection;
2941 * The document modification stamp at the time when the last occurrence
2942 * marking took place.
2946 private long fMarkOccurrenceModificationStamp = IDocumentExtension4.UNKNOWN_MODIFICATION_STAMP;
2949 * The region of the word under the caret used to when computing the current
2950 * occurrence markings.
2954 private IRegion fMarkOccurrenceTargetRegion;
2957 * Tells whether the occurrence annotations are sticky i.e. whether they stay
2958 * even if there's no valid Java element at the current caret position. Only
2959 * valid if {@link #fMarkOccurrenceAnnotations} is <code>true</code>.
2963 private boolean fStickyOccurrenceAnnotations;
2965 /** Preference key for showing the line number ruler */
2966 // private final static String LINE_NUMBER_RULER =
2967 // PreferenceConstants.EDITOR_LINE_NUMBER_RULER;
2968 /** Preference key for the foreground color of the line numbers */
2969 // private final static String LINE_NUMBER_COLOR =
2970 // PreferenceConstants.EDITOR_LINE_NUMBER_RULER_COLOR;
2971 /** Preference key for the link color */
2972 private final static String LINK_COLOR = PreferenceConstants.EDITOR_LINK_COLOR;
2974 /** Preference key for compiler task tags */
2975 private final static String COMPILER_TASK_TAGS = JavaCore.COMPILER_TASK_TAGS;
2977 // protected PHPActionGroup fActionGroups;
2978 // /** The outline page */
2979 // private AbstractContentOutlinePage fOutlinePage;
2980 /** The outline page */
2981 protected JavaOutlinePage fOutlinePage;
2983 /** Outliner context menu Id */
2984 protected String fOutlinerContextMenuId;
2987 * Indicates whether this editor should react on outline page selection
2990 private int fIgnoreOutlinePageSelection;
2992 /** The outline page selection updater */
2993 // private OutlinePageSelectionUpdater fUpdater;
2994 // protected PHPSyntaxParserThread fValidationThread = null;
2995 // private IPreferenceStore fPHPPrefStore;
2996 /** The selection changed listener */
2997 // protected ISelectionChangedListener fSelectionChangedListener = new
2998 // SelectionChangedListener();
3000 * The editor selection changed listener.
3004 private EditorSelectionChangedListener fEditorSelectionChangedListener;
3006 /** The selection changed listener */
3007 protected AbstractSelectionChangedListener fOutlineSelectionChangedListener = new OutlineSelectionChangedListener();
3009 /** The editor's bracket matcher */
3010 private PHPPairMatcher fBracketMatcher = new PHPPairMatcher(BRACKETS);
3012 /** The line number ruler column */
3013 // private LineNumberRulerColumn fLineNumberRulerColumn;
3014 /** This editor's encoding support */
3015 private DefaultEncodingSupport fEncodingSupport;
3017 /** The mouse listener */
3018 private MouseClickListener fMouseListener;
3021 * Indicates whether this editor is about to update any annotation views.
3025 private boolean fIsUpdatingAnnotationViews = false;
3028 * The marker that served as last target for a goto marker request.
3032 private IMarker fLastMarkerTarget = null;
3034 protected CompositeActionGroup fActionGroups;
3036 protected CompositeActionGroup fContextMenuGroup;
3039 * This editor's projection support
3043 private ProjectionSupport fProjectionSupport;
3046 * This editor's projection model updater
3050 private IJavaFoldingStructureProvider fProjectionModelUpdater;
3053 * The override and implements indicator manager for this editor.
3057 // protected OverrideIndicatorManager fOverrideIndicatorManager;
3059 * The action group for folding.
3063 private FoldingActionGroup fFoldingGroup;
3065 /** The information presenter. */
3066 private InformationPresenter fInformationPresenter;
3068 /** The annotation access */
3069 // protected IAnnotationAccess fAnnotationAccess = new AnnotationAccess();
3070 /** The overview ruler */
3071 protected OverviewRuler isOverviewRulerVisible;
3073 /** The source viewer decoration support */
3074 // protected SourceViewerDecorationSupport fSourceViewerDecorationSupport;
3075 /** The overview ruler */
3076 // protected OverviewRuler fOverviewRuler;
3077 /** The preference property change listener for java core. */
3078 private org.eclipse.core.runtime.Preferences.IPropertyChangeListener fPropertyChangeListener = new PropertyChangeListener();
3081 * Returns the most narrow java element including the given offset
3084 * the offset inside of the requested element
3086 abstract protected IJavaElement getElementAt(int offset);
3089 * Returns the java element of this editor's input corresponding to the given
3092 abstract protected IJavaElement getCorrespondingElement(IJavaElement element);
3095 * Sets the input of the editor's outline page.
3097 abstract protected void setOutlinePageInput(JavaOutlinePage page, IEditorInput input);
3100 * Default constructor.
3102 public PHPEditor() {
3107 * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#initializeKeyBindingScopes()
3109 protected void initializeKeyBindingScopes() {
3110 setKeyBindingScopes(new String[] { "net.sourceforge.phpdt.ui.phpEditorScope" }); //$NON-NLS-1$
3114 * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#initializeEditor()
3116 protected void initializeEditor() {
3118 // JavaTextTools textTools =
3119 // PHPeclipsePlugin.getDefault().getJavaTextTools();
3120 // setSourceViewerConfiguration(new PHPSourceViewerConfiguration(textTools,
3121 // this, IPHPPartitions.PHP_PARTITIONING)); //,
3122 // IJavaPartitions.JAVA_PARTITIONING));
3123 IPreferenceStore store = createCombinedPreferenceStore(null);
3124 setPreferenceStore(store);
3125 JavaTextTools textTools = PHPeclipsePlugin.getDefault().getJavaTextTools();
3126 setSourceViewerConfiguration(new PHPSourceViewerConfiguration(textTools.getColorManager(), store, this,
3127 IPHPPartitions.PHP_PARTITIONING));
3129 // TODO changed in 3.x ?
3130 // setRangeIndicator(new DefaultRangeIndicator());
3132 // (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE))
3133 // fUpdater = new OutlinePageSelectionUpdater();
3136 // IPreferenceStore store= createCombinedPreferenceStore(null);
3137 // setPreferenceStore(store);
3138 // JavaTextTools textTools=
3139 // PHPeclipsePlugin.getDefault().getJavaTextTools();
3140 // setSourceViewerConfiguration(new
3141 // JavaSourceViewerConfiguration(textTools.getColorManager(), store,
3142 // this, IJavaPartitions.JAVA_PARTITIONING));
3143 fMarkOccurrenceAnnotations = store.getBoolean(PreferenceConstants.EDITOR_MARK_OCCURRENCES);
3144 fStickyOccurrenceAnnotations = store.getBoolean(PreferenceConstants.EDITOR_STICKY_OCCURRENCES);
3145 // fMarkTypeOccurrences=
3146 // store.getBoolean(PreferenceConstants.EDITOR_MARK_TYPE_OCCURRENCES);
3147 // fMarkMethodOccurrences=
3148 // store.getBoolean(PreferenceConstants.EDITOR_MARK_METHOD_OCCURRENCES);
3149 // fMarkConstantOccurrences=
3150 // store.getBoolean(PreferenceConstants.EDITOR_MARK_CONSTANT_OCCURRENCES);
3151 // fMarkFieldOccurrences=
3152 // store.getBoolean(PreferenceConstants.EDITOR_MARK_FIELD_OCCURRENCES);
3153 // fMarkLocalVariableypeOccurrences=
3154 // store.getBoolean(PreferenceConstants.EDITOR_MARK_LOCAL_VARIABLE_OCCURRENCES);
3156 // store.getBoolean(PreferenceConstants.EDITOR_MARK_EXCEPTION_OCCURRENCES);
3157 // fMarkImplementors=
3158 // store.getBoolean(PreferenceConstants.EDITOR_MARK_IMPLEMENTORS);
3159 // fMarkMethodExitPoints=
3160 // store.getBoolean(PreferenceConstants.EDITOR_MARK_METHOD_EXIT_POINTS);
3165 * @see org.eclipse.ui.texteditor.AbstractTextEditor#updatePropertyDependentActions()
3167 protected void updatePropertyDependentActions() {
3168 super.updatePropertyDependentActions();
3169 if (fEncodingSupport != null)
3170 fEncodingSupport.reset();
3174 * Update the hovering behavior depending on the preferences.
3176 private void updateHoverBehavior() {
3177 SourceViewerConfiguration configuration = getSourceViewerConfiguration();
3178 String[] types = configuration.getConfiguredContentTypes(getSourceViewer());
3180 for (int i = 0; i < types.length; i++) {
3182 String t = types[i];
3184 int[] stateMasks = configuration.getConfiguredTextHoverStateMasks(getSourceViewer(), t);
3186 ISourceViewer sourceViewer = getSourceViewer();
3187 if (sourceViewer instanceof ITextViewerExtension2) {
3188 if (stateMasks != null) {
3189 for (int j = 0; j < stateMasks.length; j++) {
3190 int stateMask = stateMasks[j];
3191 ITextHover textHover = configuration.getTextHover(sourceViewer, t, stateMask);
3192 ((ITextViewerExtension2) sourceViewer).setTextHover(textHover, t, stateMask);
3195 ITextHover textHover = configuration.getTextHover(sourceViewer, t);
3196 ((ITextViewerExtension2) sourceViewer).setTextHover(textHover, t, ITextViewerExtension2.DEFAULT_HOVER_STATE_MASK);
3199 sourceViewer.setTextHover(configuration.getTextHover(sourceViewer, t), t);
3203 public void updatedTitleImage(Image image) {
3204 setTitleImage(image);
3208 * @see net.sourceforge.phpdt.internal.ui.viewsupport.IViewPartInputProvider#getViewPartInput()
3210 public Object getViewPartInput() {
3211 return getEditorInput().getAdapter(IResource.class);
3215 * @see org.eclipse.ui.texteditor.AbstractTextEditor#doSetSelection(ISelection)
3217 protected void doSetSelection(ISelection selection) {
3218 super.doSetSelection(selection);
3219 synchronizeOutlinePageSelection();
3222 boolean isFoldingEnabled() {
3223 return PHPeclipsePlugin.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_FOLDING_ENABLED);
3227 * @see org.eclipse.ui.IWorkbenchPart#createPartControl(org.eclipse.swt.
3228 * widgets.Composite)
3230 public void createPartControl(Composite parent) {
3231 super.createPartControl(parent);
3233 // fSourceViewerDecorationSupport.install(getPreferenceStore());
3235 ProjectionViewer projectionViewer = (ProjectionViewer) getSourceViewer();
3237 fProjectionSupport = new ProjectionSupport(projectionViewer, getAnnotationAccess(), getSharedColors());
3238 fProjectionSupport.addSummarizableAnnotationType("org.eclipse.ui.workbench.texteditor.error"); //$NON-NLS-1$
3239 fProjectionSupport.addSummarizableAnnotationType("org.eclipse.ui.workbench.texteditor.warning"); //$NON-NLS-1$
3240 fProjectionSupport.setHoverControlCreator(new IInformationControlCreator() {
3241 public IInformationControl createInformationControl(Shell shell) {
3242 return new CustomSourceInformationControl(shell, IDocument.DEFAULT_CONTENT_TYPE);
3245 fProjectionSupport.install();
3247 fProjectionModelUpdater = PHPeclipsePlugin.getDefault().getFoldingStructureProviderRegistry().getCurrentFoldingProvider();
3248 if (fProjectionModelUpdater != null)
3249 fProjectionModelUpdater.install(this, projectionViewer);
3251 if (isFoldingEnabled())
3252 projectionViewer.doOperation(ProjectionViewer.TOGGLE);
3253 Preferences preferences = PHPeclipsePlugin.getDefault().getPluginPreferences();
3254 preferences.addPropertyChangeListener(fPropertyChangeListener);
3256 IInformationControlCreator informationControlCreator = new IInformationControlCreator() {
3257 public IInformationControl createInformationControl(Shell parent) {
3258 boolean cutDown = false;
3259 int style = cutDown ? SWT.NONE : (SWT.V_SCROLL | SWT.H_SCROLL);
3260 return new DefaultInformationControl(parent, SWT.RESIZE, style, new HTMLTextPresenter(cutDown));
3264 fInformationPresenter = new InformationPresenter(informationControlCreator);
3265 fInformationPresenter.setSizeConstraints(60, 10, true, true);
3266 fInformationPresenter.install(getSourceViewer());
3268 fEditorSelectionChangedListener = new EditorSelectionChangedListener();
3269 fEditorSelectionChangedListener.install(getSelectionProvider());
3271 if (isBrowserLikeLinks())
3272 enableBrowserLikeLinks();
3274 if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE))
3275 enableOverwriteMode(false);
3277 if (fMarkOccurrenceAnnotations)
3278 installOccurrencesFinder();
3280 PlatformUI.getWorkbench().addWindowListener(fActivationListener);
3285 private void setWordWrap() {
3286 if (getSourceViewer() != null) {
3287 getSourceViewer().getTextWidget().setWordWrap(
3288 PHPeclipsePlugin.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_WRAP_WORDS));
3292 protected void configureSourceViewerDecorationSupport(SourceViewerDecorationSupport support) {
3294 support.setCharacterPairMatcher(fBracketMatcher);
3295 support.setMatchingCharacterPainterPreferenceKeys(MATCHING_BRACKETS, MATCHING_BRACKETS_COLOR);
3297 super.configureSourceViewerDecorationSupport(support);
3301 * @see org.eclipse.ui.texteditor.AbstractTextEditor#gotoMarker(org.eclipse.core.resources.IMarker)
3303 public void gotoMarker(IMarker marker) {
3304 fLastMarkerTarget = marker;
3305 if (!fIsUpdatingAnnotationViews) {
3306 super.gotoMarker(marker);
3311 * Jumps to the next enabled annotation according to the given direction. An
3312 * annotation type is enabled if it is configured to be in the Next/Previous
3313 * tool bar drop down menu and if it is checked.
3316 * <code>true</code> if search direction is forward,
3317 * <code>false</code> if backward
3319 public void gotoAnnotation(boolean forward) {
3320 ITextSelection selection = (ITextSelection) getSelectionProvider().getSelection();
3321 Position position = new Position(0, 0);
3322 if (false /* delayed - see bug 18316 */) {
3323 getNextAnnotation(selection.getOffset(), selection.getLength(), forward, position);
3324 selectAndReveal(position.getOffset(), position.getLength());
3325 } else /* no delay - see bug 18316 */{
3326 Annotation annotation = getNextAnnotation(selection.getOffset(), selection.getLength(), forward, position);
3327 setStatusLineErrorMessage(null);
3328 setStatusLineMessage(null);
3329 if (annotation != null) {
3330 updateAnnotationViews(annotation);
3331 selectAndReveal(position.getOffset(), position.getLength());
3332 setStatusLineMessage(annotation.getText());
3338 * Returns the lock object for the given annotation model.
3340 * @param annotationModel
3341 * the annotation model
3342 * @return the annotation model's lock object
3345 private Object getLockObject(IAnnotationModel annotationModel) {
3346 if (annotationModel instanceof ISynchronizable)
3347 return ((ISynchronizable) annotationModel).getLockObject();
3349 return annotationModel;
3353 * Updates the annotation views that show the given annotation.
3358 private void updateAnnotationViews(Annotation annotation) {
3359 IMarker marker = null;
3360 if (annotation instanceof MarkerAnnotation)
3361 marker = ((MarkerAnnotation) annotation).getMarker();
3362 else if (annotation instanceof IJavaAnnotation) {
3363 Iterator e = ((IJavaAnnotation) annotation).getOverlaidIterator();
3365 while (e.hasNext()) {
3366 Object o = e.next();
3367 if (o instanceof MarkerAnnotation) {
3368 marker = ((MarkerAnnotation) o).getMarker();
3375 if (marker != null && !marker.equals(fLastMarkerTarget)) {
3377 boolean isProblem = marker.isSubtypeOf(IMarker.PROBLEM);
3378 IWorkbenchPage page = getSite().getPage();
3379 IViewPart view = page.findView(isProblem ? IPageLayout.ID_PROBLEM_VIEW : IPageLayout.ID_TASK_LIST); //$NON-NLS-1$ //$NON-NLS-2$
3381 Method method = view.getClass().getMethod("setSelection", new Class[] { IStructuredSelection.class, boolean.class }); //$NON-NLS-1$
3382 method.invoke(view, new Object[] { new StructuredSelection(marker), Boolean.TRUE });
3384 } catch (CoreException x) {
3385 } catch (NoSuchMethodException x) {
3386 } catch (IllegalAccessException x) {
3387 } catch (InvocationTargetException x) {
3389 // ignore exceptions, don't update any of the lists, just set status line
3394 * Returns this document's complete text.
3396 * @return the document's complete text
3398 public String get() {
3399 IDocument doc = this.getDocumentProvider().getDocument(this.getEditorInput());
3404 * Sets the outliner's context menu ID.
3406 protected void setOutlinerContextMenuId(String menuId) {
3407 fOutlinerContextMenuId = menuId;
3411 * Returns the standard action group of this editor.
3413 protected ActionGroup getActionGroup() {
3414 return fActionGroups;
3417 // public JavaOutlinePage getfOutlinePage() {
3418 // return fOutlinePage;
3422 * The <code>PHPEditor</code> implementation of this
3423 * <code>AbstractTextEditor</code> method extend the actions to add those
3424 * specific to the receiver
3426 protected void createActions() {
3427 super.createActions();
3429 ActionGroup oeg, ovg, jsg, sg;
3430 fActionGroups = new CompositeActionGroup(new ActionGroup[] { oeg = new OpenEditorActionGroup(this),
3431 // sg= new ShowActionGroup(this),
3432 // ovg= new OpenViewActionGroup(this),
3433 // jsg= new JavaSearchActionGroup(this)
3435 fContextMenuGroup = new CompositeActionGroup(new ActionGroup[] { oeg });
3436 // , ovg, sg, jsg});
3438 fFoldingGroup = new FoldingActionGroup(this, getViewer());
3440 // ResourceAction resAction = new
3441 // TextOperationAction(PHPEditorMessages.getResourceBundle(),
3442 // "ShowJavaDoc.", this, ISourceViewer.INFORMATION, true); //$NON-NLS-1$
3444 // InformationDispatchAction(PHPEditorMessages.getResourceBundle(),
3445 // "ShowJavaDoc.", (TextOperationAction) resAction); //$NON-NLS-1$
3446 // resAction.setActionDefinitionId(net.sourceforge.phpdt.ui.actions.PHPEditorActionDefinitionIds.SHOW_JAVADOC);
3447 // setAction("ShowJavaDoc", resAction); //$NON-NLS-1$
3449 // WorkbenchHelp.setHelp(resAction,
3450 // IJavaHelpContextIds.SHOW_JAVADOC_ACTION);
3452 Action action = new GotoMatchingBracketAction(this);
3453 action.setActionDefinitionId(PHPEditorActionDefinitionIds.GOTO_MATCHING_BRACKET);
3454 setAction(GotoMatchingBracketAction.GOTO_MATCHING_BRACKET, action);
3457 // TextOperationAction(PHPEditorMessages.getResourceBundle(),"ShowOutline.",
3458 // this, JavaSourceViewer.SHOW_OUTLINE, true); //$NON-NLS-1$
3459 // action.setActionDefinitionId(PHPEditorActionDefinitionIds.SHOW_OUTLINE);
3460 // setAction(PHPEditorActionDefinitionIds.SHOW_OUTLINE, action);
3461 // // WorkbenchHelp.setHelp(action,
3462 // IJavaHelpContextIds.SHOW_OUTLINE_ACTION);
3465 // TextOperationAction(PHPEditorMessages.getResourceBundle(),"OpenStructure.",
3466 // this, JavaSourceViewer.OPEN_STRUCTURE, true); //$NON-NLS-1$
3467 // action.setActionDefinitionId(PHPEditorActionDefinitionIds.SHOW_OUTLINE.OPEN_STRUCTURE);
3468 // setAction(PHPEditorActionDefinitionIds.SHOW_OUTLINE.OPEN_STRUCTURE,
3470 // // WorkbenchHelp.setHelp(action,
3471 // IJavaHelpContextIds.OPEN_STRUCTURE_ACTION);
3474 // TextOperationAction(PHPEditorMessages.getResourceBundle(),"OpenHierarchy.",
3475 // this, JavaSourceViewer.SHOW_HIERARCHY, true); //$NON-NLS-1$
3476 // action.setActionDefinitionId(PHPEditorActionDefinitionIds.SHOW_OUTLINE.OPEN_HIERARCHY);
3477 // setAction(PHPEditorActionDefinitionIds.SHOW_OUTLINE.OPEN_HIERARCHY,
3479 // // WorkbenchHelp.setHelp(action,
3480 // IJavaHelpContextIds.OPEN_HIERARCHY_ACTION);
3482 fEncodingSupport = new DefaultEncodingSupport();
3483 fEncodingSupport.initialize(this);
3485 // fSelectionHistory= new SelectionHistory(this);
3487 // action= new StructureSelectEnclosingAction(this, fSelectionHistory);
3488 // action.setActionDefinitionId(PHPEditorActionDefinitionIds.SELECT_ENCLOSING);
3489 // setAction(StructureSelectionAction.ENCLOSING, action);
3491 // action= new StructureSelectNextAction(this, fSelectionHistory);
3492 // action.setActionDefinitionId(PHPEditorActionDefinitionIds.SELECT_NEXT);
3493 // setAction(StructureSelectionAction.NEXT, action);
3495 // action= new StructureSelectPreviousAction(this, fSelectionHistory);
3496 // action.setActionDefinitionId(PHPEditorActionDefinitionIds.SELECT_PREVIOUS);
3497 // setAction(StructureSelectionAction.PREVIOUS, action);
3499 // StructureSelectHistoryAction historyAction= new
3500 // StructureSelectHistoryAction(this, fSelectionHistory);
3501 // historyAction.setActionDefinitionId(PHPEditorActionDefinitionIds.SELECT_LAST);
3502 // setAction(StructureSelectionAction.HISTORY, historyAction);
3503 // fSelectionHistory.setHistoryAction(historyAction);
3505 // action= GoToNextPreviousMemberAction.newGoToNextMemberAction(this);
3506 // action.setActionDefinitionId(PHPEditorActionDefinitionIds.GOTO_NEXT_MEMBER);
3507 // setAction(GoToNextPreviousMemberAction.NEXT_MEMBER, action);
3510 // GoToNextPreviousMemberAction.newGoToPreviousMemberAction(this);
3511 // action.setActionDefinitionId(PHPEditorActionDefinitionIds.GOTO_PREVIOUS_MEMBER);
3512 // setAction(GoToNextPreviousMemberAction.PREVIOUS_MEMBER, action);
3514 // action= new QuickFormatAction();
3515 // action.setActionDefinitionId(PHPEditorActionDefinitionIds.QUICK_FORMAT);
3516 // setAction(IJavaEditorActionDefinitionIds.QUICK_FORMAT, action);
3518 // action= new RemoveOccurrenceAnnotations(this);
3519 // action.setActionDefinitionId(PHPEditorActionDefinitionIds.REMOVE_OCCURRENCE_ANNOTATIONS);
3520 // setAction("RemoveOccurrenceAnnotations", action); //$NON-NLS-1$
3522 // add annotation actions
3523 action = new JavaSelectMarkerRulerAction2(PHPEditorMessages.getResourceBundle(), "Editor.RulerAnnotationSelection.", this); //$NON-NLS-1$
3524 setAction("AnnotationAction", action); //$NON-NLS-1$
3527 private void internalDoSetInput(IEditorInput input) throws CoreException {
3528 super.doSetInput(input);
3530 if (getSourceViewer() instanceof JavaSourceViewer) {
3531 JavaSourceViewer viewer = (JavaSourceViewer) getSourceViewer();
3532 if (viewer.getReconciler() == null) {
3533 IReconciler reconciler = getSourceViewerConfiguration().getReconciler(viewer);
3534 if (reconciler != null) {
3535 reconciler.install(viewer);
3536 viewer.setReconciler(reconciler);
3541 if (fEncodingSupport != null)
3542 fEncodingSupport.reset();
3544 setOutlinePageInput(fOutlinePage, input);
3546 if (fProjectionModelUpdater != null)
3547 fProjectionModelUpdater.initialize();
3549 // if (isShowingOverrideIndicators())
3550 // installOverrideIndicator(false);
3554 * @see org.eclipse.ui.texteditor.AbstractTextEditor#setPreferenceStore(org.eclipse.jface.preference.IPreferenceStore)
3557 protected void setPreferenceStore(IPreferenceStore store) {
3558 super.setPreferenceStore(store);
3559 if (getSourceViewerConfiguration() instanceof PHPSourceViewerConfiguration) {
3560 JavaTextTools textTools = PHPeclipsePlugin.getDefault().getJavaTextTools();
3561 setSourceViewerConfiguration(new PHPSourceViewerConfiguration(textTools.getColorManager(), store, this,
3562 IPHPPartitions.PHP_PARTITIONING));
3564 if (getSourceViewer() instanceof JavaSourceViewer)
3565 ((JavaSourceViewer) getSourceViewer()).setPreferenceStore(store);
3569 * The <code>PHPEditor</code> implementation of this
3570 * <code>AbstractTextEditor</code> method performs any extra disposal
3571 * actions required by the php editor.
3573 public void dispose() {
3574 if (fProjectionModelUpdater != null) {
3575 fProjectionModelUpdater.uninstall();
3576 fProjectionModelUpdater = null;
3579 if (fProjectionSupport != null) {
3580 fProjectionSupport.dispose();
3581 fProjectionSupport = null;
3583 // PHPEditorEnvironment.disconnect(this);
3584 if (fOutlinePage != null)
3585 fOutlinePage.setInput(null);
3587 if (fActionGroups != null)
3588 fActionGroups.dispose();
3590 if (isBrowserLikeLinks())
3591 disableBrowserLikeLinks();
3593 // cancel possible running computation
3594 fMarkOccurrenceAnnotations = false;
3595 uninstallOccurrencesFinder();
3597 uninstallOverrideIndicator();
3599 if (fActivationListener != null) {
3600 PlatformUI.getWorkbench().removeWindowListener(fActivationListener);
3601 fActivationListener = null;
3604 if (fEncodingSupport != null) {
3605 fEncodingSupport.dispose();
3606 fEncodingSupport = null;
3609 if (fPropertyChangeListener != null) {
3610 Preferences preferences = PHPeclipsePlugin.getDefault().getPluginPreferences();
3611 preferences.removePropertyChangeListener(fPropertyChangeListener);
3612 fPropertyChangeListener = null;
3615 // if (fSourceViewerDecorationSupport != null) {
3616 // fSourceViewerDecorationSupport.dispose();
3617 // fSourceViewerDecorationSupport = null;
3620 if (fBracketMatcher != null) {
3621 fBracketMatcher.dispose();
3622 fBracketMatcher = null;
3625 if (fEditorSelectionChangedListener != null) {
3626 fEditorSelectionChangedListener.uninstall(getSelectionProvider());
3627 fEditorSelectionChangedListener = null;
3634 * The <code>PHPEditor</code> implementation of this
3635 * <code>AbstractTextEditor</code> method performs any extra revert behavior
3636 * required by the php editor.
3638 // public void doRevertToSaved() {
3639 // super.doRevertToSaved();
3640 // if (fOutlinePage != null)
3641 // fOutlinePage.update();
3644 * The <code>PHPEditor</code> implementation of this
3645 * <code>AbstractTextEditor</code> method performs any extra save behavior
3646 * required by the php editor.
3648 // public void doSave(IProgressMonitor monitor) {
3649 // super.doSave(monitor);
3650 // compile or not, according to the user preferences
3651 // IPreferenceStore store = getPreferenceStore();
3652 // the parse on save was changed to the eclipse "builders" concept
3653 // if (store.getBoolean(PHPeclipsePlugin.PHP_PARSE_ON_SAVE)) {
3654 // IAction a = PHPParserAction.getInstance();
3658 // if (SWT.getPlatform().equals("win32")) {
3659 // IAction a = ShowExternalPreviewAction.getInstance();
3663 // if (fOutlinePage != null)
3664 // fOutlinePage.update();
3667 * The <code>PHPEditor</code> implementation of this
3668 * <code>AbstractTextEditor</code> method performs any extra save as
3669 * behavior required by the php editor.
3671 // public void doSaveAs() {
3672 // super.doSaveAs();
3673 // if (fOutlinePage != null)
3674 // fOutlinePage.update();
3677 * @see StatusTextEditor#getStatusHeader(IStatus)
3679 protected String getStatusHeader(IStatus status) {
3680 if (fEncodingSupport != null) {
3681 String message = fEncodingSupport.getStatusHeader(status);
3682 if (message != null)
3685 return super.getStatusHeader(status);
3689 * @see StatusTextEditor#getStatusBanner(IStatus)
3691 protected String getStatusBanner(IStatus status) {
3692 if (fEncodingSupport != null) {
3693 String message = fEncodingSupport.getStatusBanner(status);
3694 if (message != null)
3697 return super.getStatusBanner(status);
3701 * @see StatusTextEditor#getStatusMessage(IStatus)
3703 protected String getStatusMessage(IStatus status) {
3704 if (fEncodingSupport != null) {
3705 String message = fEncodingSupport.getStatusMessage(status);
3706 if (message != null)
3709 return super.getStatusMessage(status);
3713 * The <code>PHPEditor</code> implementation of this
3714 * <code>AbstractTextEditor</code> method performs sets the input of the
3715 * outline page after AbstractTextEditor has set input.
3717 // protected void doSetInput(IEditorInput input) throws CoreException {
3718 // super.doSetInput(input);
3719 // if (fEncodingSupport != null)
3720 // fEncodingSupport.reset();
3721 // setOutlinePageInput(fOutlinePage, input);
3724 * @see AbstractTextEditor#doSetInput
3726 protected void doSetInput(IEditorInput input) throws CoreException {
3727 ISourceViewer sourceViewer = getSourceViewer();
3728 if (!(sourceViewer instanceof ISourceViewerExtension2)) {
3729 setPreferenceStore(createCombinedPreferenceStore(input));
3730 internalDoSetInput(input);
3734 // uninstall & unregister preference store listener
3735 if (isBrowserLikeLinks())
3736 disableBrowserLikeLinks();
3737 getSourceViewerDecorationSupport(sourceViewer).uninstall();
3738 ((ISourceViewerExtension2) sourceViewer).unconfigure();
3740 setPreferenceStore(createCombinedPreferenceStore(input));
3742 // install & register preference store listener
3743 sourceViewer.configure(getSourceViewerConfiguration());
3744 getSourceViewerDecorationSupport(sourceViewer).install(getPreferenceStore());
3745 if (isBrowserLikeLinks())
3746 enableBrowserLikeLinks();
3748 internalDoSetInput(input);
3752 * @see org.phpeclipse.phpdt.internal.ui.viewsupport.IViewPartInputProvider#getViewPartInput()
3754 // public Object getViewPartInput() {
3755 // return getEditorInput().getAdapter(IFile.class);
3758 * The <code>PHPEditor</code> implementation of this
3759 * <code>AbstractTextEditor</code> method adds any PHPEditor specific
3762 public void editorContextMenuAboutToShow(MenuManager menu) {
3763 super.editorContextMenuAboutToShow(menu);
3764 menu.appendToGroup(ITextEditorActionConstants.GROUP_UNDO, new Separator(IContextMenuConstants.GROUP_OPEN));
3765 menu.insertAfter(IContextMenuConstants.GROUP_OPEN, new GroupMarker(IContextMenuConstants.GROUP_SHOW));
3767 ActionContext context = new ActionContext(getSelectionProvider().getSelection());
3768 fContextMenuGroup.setContext(context);
3769 fContextMenuGroup.fillContextMenu(menu);
3770 fContextMenuGroup.setContext(null);
3771 // addAction(menu, ITextEditorActionConstants.GROUP_EDIT, "Format");
3774 // ActionContext context =
3775 // new ActionContext(getSelectionProvider().getSelection());
3776 // fContextMenuGroup.setContext(context);
3777 // fContextMenuGroup.fillContextMenu(menu);
3778 // fContextMenuGroup.setContext(null);
3782 * Creates the outline page used with this editor.
3784 protected JavaOutlinePage createOutlinePage() {
3785 JavaOutlinePage page = new JavaOutlinePage(fOutlinerContextMenuId, this);
3786 fOutlineSelectionChangedListener.install(page);
3787 setOutlinePageInput(page, getEditorInput());
3792 * Informs the editor that its outliner has been closed.
3794 public void outlinePageClosed() {
3795 if (fOutlinePage != null) {
3796 fOutlineSelectionChangedListener.uninstall(fOutlinePage);
3797 fOutlinePage = null;
3798 resetHighlightRange();
3803 * Synchronizes the outliner selection with the given element position in the
3807 * the java element to select
3809 protected void synchronizeOutlinePage(ISourceReference element) {
3810 synchronizeOutlinePage(element, true);
3814 * Synchronizes the outliner selection with the given element position in the
3818 * the java element to select
3819 * @param checkIfOutlinePageActive
3820 * <code>true</code> if check for active outline page needs to be
3823 protected void synchronizeOutlinePage(ISourceReference element, boolean checkIfOutlinePageActive) {
3824 if (fOutlinePage != null && element != null && !(checkIfOutlinePageActive && isJavaOutlinePageActive())) {
3825 fOutlineSelectionChangedListener.uninstall(fOutlinePage);
3826 fOutlinePage.select(element);
3827 fOutlineSelectionChangedListener.install(fOutlinePage);
3832 * Synchronizes the outliner selection with the actual cursor position in the
3835 public void synchronizeOutlinePageSelection() {
3836 synchronizeOutlinePage(computeHighlightRangeSourceReference());
3838 // ISourceViewer sourceViewer = getSourceViewer();
3839 // if (sourceViewer == null || fOutlinePage == null)
3842 // StyledText styledText = sourceViewer.getTextWidget();
3843 // if (styledText == null)
3847 // if (sourceViewer instanceof ITextViewerExtension3) {
3848 // ITextViewerExtension3 extension = (ITextViewerExtension3)
3851 // extension.widgetOffset2ModelOffset(styledText.getCaretOffset());
3853 // int offset = sourceViewer.getVisibleRegion().getOffset();
3854 // caret = offset + styledText.getCaretOffset();
3857 // IJavaElement element = getElementAt(caret);
3858 // if (element instanceof ISourceReference) {
3859 // fOutlinePage.removeSelectionChangedListener(fSelectionChangedListener);
3860 // fOutlinePage.select((ISourceReference) element);
3861 // fOutlinePage.addSelectionChangedListener(fSelectionChangedListener);
3865 protected void setSelection(ISourceReference reference, boolean moveCursor) {
3867 ISelection selection = getSelectionProvider().getSelection();
3868 if (selection instanceof TextSelection) {
3869 TextSelection textSelection = (TextSelection) selection;
3870 if (textSelection.getOffset() != 0 || textSelection.getLength() != 0)
3871 markInNavigationHistory();
3874 if (reference != null) {
3876 StyledText textWidget = null;
3878 ISourceViewer sourceViewer = getSourceViewer();
3879 if (sourceViewer != null)
3880 textWidget = sourceViewer.getTextWidget();
3882 if (textWidget == null)
3887 ISourceRange range = reference.getSourceRange();
3891 int offset = range.getOffset();
3892 int length = range.getLength();
3894 if (offset < 0 || length < 0)
3897 textWidget.setRedraw(false);
3899 setHighlightRange(offset, length, moveCursor);
3907 if (reference instanceof IMember) {
3908 range = ((IMember) reference).getNameRange();
3909 if (range != null) {
3910 offset = range.getOffset();
3911 length = range.getLength();
3914 // else if (reference instanceof IImportDeclaration) {
3915 // String name= ((IImportDeclaration)
3916 // reference).getElementName();
3917 // if (name != null && name.length() > 0) {
3918 // String content= reference.getSource();
3919 // if (content != null) {
3920 // offset= range.getOffset() + content.indexOf(name);
3921 // length= name.length();
3924 // } else if (reference instanceof IPackageDeclaration) {
3925 // String name= ((IPackageDeclaration)
3926 // reference).getElementName();
3927 // if (name != null && name.length() > 0) {
3928 // String content= reference.getSource();
3929 // if (content != null) {
3930 // offset= range.getOffset() + content.indexOf(name);
3931 // length= name.length();
3936 if (offset > -1 && length > 0) {
3937 sourceViewer.revealRange(offset, length);
3938 sourceViewer.setSelectedRange(offset, length);
3941 } catch (JavaModelException x) {
3942 } catch (IllegalArgumentException x) {
3944 if (textWidget != null)
3945 textWidget.setRedraw(true);
3948 } else if (moveCursor) {
3949 resetHighlightRange();
3952 markInNavigationHistory();
3955 public void setSelection(IJavaElement element) {
3956 if (element == null || element instanceof ICompilationUnit) { // ||
3962 * If the element is an ICompilationUnit this unit is either the input of
3963 * this editor or not being displayed. In both cases, nothing should
3964 * happened. (http://dev.eclipse.org/bugs/show_bug.cgi?id=5128)
3969 IJavaElement corresponding = getCorrespondingElement(element);
3970 if (corresponding instanceof ISourceReference) {
3971 ISourceReference reference = (ISourceReference) corresponding;
3972 // set highlight range
3973 setSelection(reference, true);
3974 // set outliner selection
3975 if (fOutlinePage != null) {
3976 fOutlineSelectionChangedListener.uninstall(fOutlinePage);
3977 fOutlinePage.select(reference);
3978 fOutlineSelectionChangedListener.install(fOutlinePage);
3983 public synchronized void editingScriptStarted() {
3984 ++fIgnoreOutlinePageSelection;
3987 public synchronized void editingScriptEnded() {
3988 --fIgnoreOutlinePageSelection;
3991 public synchronized boolean isEditingScriptRunning() {
3992 return (fIgnoreOutlinePageSelection > 0);
3996 * The <code>PHPEditor</code> implementation of this
3997 * <code>AbstractTextEditor</code> method performs gets the java content
3998 * outline page if request is for a an outline page.
4000 public Object getAdapter(Class required) {
4002 if (IContentOutlinePage.class.equals(required)) {
4003 if (fOutlinePage == null)
4004 fOutlinePage = createOutlinePage();
4005 return fOutlinePage;
4008 if (IEncodingSupport.class.equals(required))
4009 return fEncodingSupport;
4011 if (required == IShowInTargetList.class) {
4012 return new IShowInTargetList() {
4013 public String[] getShowInTargetIds() {
4014 return new String[] { JavaUI.ID_PACKAGES, IPageLayout.ID_OUTLINE, IPageLayout.ID_RES_NAV };
4019 if (fProjectionSupport != null) {
4020 Object adapter = fProjectionSupport.getAdapter(getSourceViewer(), required);
4021 if (adapter != null)
4025 return super.getAdapter(required);
4028 // public Object getAdapter(Class required) {
4029 // if (IContentOutlinePage.class.equals(required)) {
4030 // if (fOutlinePage == null) {
4031 // fOutlinePage = new PHPContentOutlinePage(getDocumentProvider(), this);
4032 // if (getEditorInput() != null)
4033 // fOutlinePage.setInput(getEditorInput());
4035 // return fOutlinePage;
4038 // if (IEncodingSupport.class.equals(required))
4039 // return fEncodingSupport;
4041 // return super.getAdapter(required);
4044 protected void doSelectionChanged(SelectionChangedEvent event) {
4045 ISourceReference reference = null;
4047 ISelection selection = event.getSelection();
4048 Iterator iter = ((IStructuredSelection) selection).iterator();
4049 while (iter.hasNext()) {
4050 Object o = iter.next();
4051 if (o instanceof ISourceReference) {
4052 reference = (ISourceReference) o;
4057 if (!isActivePart() && PHPeclipsePlugin.getActivePage() != null)
4058 PHPeclipsePlugin.getActivePage().bringToTop(this);
4061 editingScriptStarted();
4062 setSelection(reference, !isActivePart());
4064 editingScriptEnded();
4069 * @see AbstractTextEditor#adjustHighlightRange(int, int)
4071 protected void adjustHighlightRange(int offset, int length) {
4075 IJavaElement element = getElementAt(offset);
4076 while (element instanceof ISourceReference) {
4077 ISourceRange range = ((ISourceReference) element).getSourceRange();
4078 if (offset < range.getOffset() + range.getLength() && range.getOffset() < offset + length) {
4080 ISourceViewer viewer = getSourceViewer();
4081 if (viewer instanceof ITextViewerExtension5) {
4082 ITextViewerExtension5 extension = (ITextViewerExtension5) viewer;
4083 extension.exposeModelRange(new Region(range.getOffset(), range.getLength()));
4086 setHighlightRange(range.getOffset(), range.getLength(), true);
4087 if (fOutlinePage != null) {
4088 fOutlineSelectionChangedListener.uninstall(fOutlinePage);
4089 fOutlinePage.select((ISourceReference) element);
4090 fOutlineSelectionChangedListener.install(fOutlinePage);
4095 element = element.getParent();
4098 } catch (JavaModelException x) {
4099 PHPeclipsePlugin.log(x.getStatus());
4102 ISourceViewer viewer = getSourceViewer();
4103 if (viewer instanceof ITextViewerExtension5) {
4104 ITextViewerExtension5 extension = (ITextViewerExtension5) viewer;
4105 extension.exposeModelRange(new Region(offset, length));
4107 resetHighlightRange();
4112 protected boolean isActivePart() {
4113 IWorkbenchWindow window = getSite().getWorkbenchWindow();
4114 IPartService service = window.getPartService();
4115 IWorkbenchPart part = service.getActivePart();
4116 return part != null && part.equals(this);
4119 // public void openContextHelp() {
4121 // this.getDocumentProvider().getDocument(this.getEditorInput());
4122 // ITextSelection selection = (ITextSelection)
4123 // this.getSelectionProvider().getSelection();
4124 // int pos = selection.getOffset();
4125 // String word = getFunctionName(doc, pos);
4126 // openContextHelp(word);
4129 // private void openContextHelp(String word) {
4133 // public static void open(String word) {
4134 // IHelp help = WorkbenchHelp.getHelpSupport();
4135 // if (help != null) {
4136 // IHelpResource helpResource = new PHPFunctionHelpResource(word);
4137 // WorkbenchHelp.getHelpSupport().displayHelpResource(helpResource);
4139 // // showMessage(shell, dialogTitle, ActionMessages.getString("Open help
4140 // not available"), false); //$NON-NLS-1$
4144 // private String getFunctionName(IDocument doc, int pos) {
4145 // Point word = PHPWordExtractor.findWord(doc, pos);
4146 // if (word != null) {
4148 // return doc.get(word.x, word.y).replace('_', '-');
4149 // } catch (BadLocationException e) {
4156 * @see AbstractTextEditor#handlePreferenceStoreChanged(PropertyChangeEvent)
4158 protected void handlePreferenceStoreChanged(PropertyChangeEvent event) {
4162 ISourceViewer sourceViewer = getSourceViewer();
4163 if (sourceViewer == null)
4166 String property = event.getProperty();
4168 if (PreferenceConstants.EDITOR_TAB_WIDTH.equals(property)) {
4169 Object value = event.getNewValue();
4170 if (value instanceof Integer) {
4171 sourceViewer.getTextWidget().setTabs(((Integer) value).intValue());
4172 } else if (value instanceof String) {
4174 sourceViewer.getTextWidget().setTabs(Integer.parseInt((String) value));
4175 } catch (NumberFormatException e) {
4176 // bug #1038071 - set default tab:
4177 sourceViewer.getTextWidget().setTabs(80);
4183 // if (OVERVIEW_RULER.equals(property)) {
4184 // if (isOverviewRulerVisible())
4185 // showOverviewRuler();
4187 // hideOverviewRuler();
4191 // if (LINE_NUMBER_RULER.equals(property)) {
4192 // if (isLineNumberRulerVisible())
4193 // showLineNumberRuler();
4195 // hideLineNumberRuler();
4199 // if (fLineNumberRulerColumn != null
4200 // && (LINE_NUMBER_COLOR.equals(property) ||
4201 // PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT.equals(property) ||
4202 // PREFERENCE_COLOR_BACKGROUND.equals(property))) {
4204 // initializeLineNumberRulerColumn(fLineNumberRulerColumn);
4207 if (isJavaEditorHoverProperty(property))
4208 updateHoverBehavior();
4210 if (BROWSER_LIKE_LINKS.equals(property)) {
4211 if (isBrowserLikeLinks())
4212 enableBrowserLikeLinks();
4214 disableBrowserLikeLinks();
4218 if (PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE.equals(property)) {
4219 if (event.getNewValue() instanceof Boolean) {
4220 Boolean disable = (Boolean) event.getNewValue();
4221 enableOverwriteMode(!disable.booleanValue());
4226 boolean newBooleanValue = false;
4227 Object newValue = event.getNewValue();
4228 if (newValue != null)
4229 newBooleanValue = Boolean.valueOf(newValue.toString()).booleanValue();
4231 if (PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE.equals(property)) {
4232 if (newBooleanValue)
4237 if (PreferenceConstants.EDITOR_MARK_OCCURRENCES.equals(property)) {
4238 if (newBooleanValue != fMarkOccurrenceAnnotations) {
4239 fMarkOccurrenceAnnotations = newBooleanValue;
4240 if (!fMarkOccurrenceAnnotations)
4241 uninstallOccurrencesFinder();
4243 installOccurrencesFinder();
4248 if (PreferenceConstants.EDITOR_STICKY_OCCURRENCES.equals(property)) {
4249 fStickyOccurrenceAnnotations = newBooleanValue;
4255 // (PreferenceConstants.EDITOR_STICKY_OCCURRENCES.equals(property))
4257 // if (event.getNewValue() instanceof Boolean) {
4258 // boolean stickyOccurrenceAnnotations=
4259 // ((Boolean)event.getNewValue()).booleanValue();
4260 // if (stickyOccurrenceAnnotations != fStickyOccurrenceAnnotations)
4263 ((PHPSourceViewerConfiguration) getSourceViewerConfiguration()).handlePropertyChangeEvent(event);
4265 // if (affectsOverrideIndicatorAnnotations(event)) {
4266 // if (isShowingOverrideIndicators()) {
4267 // if (fOverrideIndicatorManager == null)
4268 // installOverrideIndicator(true);
4270 // if (fOverrideIndicatorManager != null)
4271 // uninstallOverrideIndicator();
4276 if (PreferenceConstants.EDITOR_FOLDING_PROVIDER.equals(property)) {
4277 if (sourceViewer instanceof ProjectionViewer) {
4278 ProjectionViewer projectionViewer = (ProjectionViewer) sourceViewer;
4279 if (fProjectionModelUpdater != null)
4280 fProjectionModelUpdater.uninstall();
4281 // either freshly enabled or provider changed
4282 fProjectionModelUpdater = PHPeclipsePlugin.getDefault().getFoldingStructureProviderRegistry().getCurrentFoldingProvider();
4283 if (fProjectionModelUpdater != null) {
4284 fProjectionModelUpdater.install(this, projectionViewer);
4290 super.handlePreferenceStoreChanged(event);
4296 // AbstractTextEditor#handlePreferenceStoreChanged(PropertyChangeEvent)
4298 // protected void handlePreferenceStoreChanged(PropertyChangeEvent event) {
4302 // ISourceViewer sourceViewer = getSourceViewer();
4303 // if (sourceViewer == null)
4306 // String property = event.getProperty();
4309 // (JavaSourceViewerConfiguration.PREFERENCE_TAB_WIDTH.equals(property)) {
4310 // // Object value= event.getNewValue();
4311 // // if (value instanceof Integer) {
4312 // // sourceViewer.getTextWidget().setTabs(((Integer) value).intValue());
4313 // // } else if (value instanceof String) {
4314 // // sourceViewer.getTextWidget().setTabs(Integer.parseInt((String)
4320 // if (IPreferenceConstants.LINE_NUMBER_RULER.equals(property)) {
4321 // if (isLineNumberRulerVisible())
4322 // showLineNumberRuler();
4324 // hideLineNumberRuler();
4328 // if (fLineNumberRulerColumn != null
4329 // && (IPreferenceConstants.LINE_NUMBER_COLOR.equals(property)
4330 // || PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT.equals(property)
4331 // || PREFERENCE_COLOR_BACKGROUND.equals(property))) {
4333 // initializeLineNumberRulerColumn(fLineNumberRulerColumn);
4337 // super.handlePreferenceStoreChanged(event);
4341 // private boolean isJavaEditorHoverProperty(String property) {
4342 // return PreferenceConstants.EDITOR_DEFAULT_HOVER.equals(property)
4343 // || PreferenceConstants.EDITOR_NONE_HOVER.equals(property)
4344 // || PreferenceConstants.EDITOR_CTRL_HOVER.equals(property)
4345 // || PreferenceConstants.EDITOR_SHIFT_HOVER.equals(property)
4346 // || PreferenceConstants.EDITOR_CTRL_ALT_HOVER.equals(property)
4347 // || PreferenceConstants.EDITOR_CTRL_SHIFT_HOVER.equals(property)
4348 // || PreferenceConstants.EDITOR_CTRL_ALT_SHIFT_HOVER.equals(property)
4349 // || PreferenceConstants.EDITOR_ALT_SHIFT_HOVER.equals(property);
4353 * Shows the line number ruler column.
4355 // private void showLineNumberRuler() {
4356 // IVerticalRuler v = getVerticalRuler();
4357 // if (v instanceof CompositeRuler) {
4358 // CompositeRuler c = (CompositeRuler) v;
4359 // c.addDecorator(1, createLineNumberRulerColumn());
4362 private boolean isJavaEditorHoverProperty(String property) {
4363 return PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS.equals(property);
4367 * Return whether the browser like links should be enabled according to the
4368 * preference store settings.
4370 * @return <code>true</code> if the browser like links should be enabled
4372 private boolean isBrowserLikeLinks() {
4373 IPreferenceStore store = getPreferenceStore();
4374 return store.getBoolean(BROWSER_LIKE_LINKS);
4378 * Enables browser like links.
4380 private void enableBrowserLikeLinks() {
4381 if (fMouseListener == null) {
4382 fMouseListener = new MouseClickListener();
4383 fMouseListener.install();
4388 * Disables browser like links.
4390 private void disableBrowserLikeLinks() {
4391 if (fMouseListener != null) {
4392 fMouseListener.uninstall();
4393 fMouseListener = null;
4398 * Handles a property change event describing a change of the java core's
4399 * preferences and updates the preference related editor properties.
4402 * the property change event
4404 protected void handlePreferencePropertyChanged(org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) {
4405 if (COMPILER_TASK_TAGS.equals(event.getProperty())) {
4406 ISourceViewer sourceViewer = getSourceViewer();
4407 if (sourceViewer != null
4408 && affectsTextPresentation(new PropertyChangeEvent(event.getSource(), event.getProperty(), event.getOldValue(), event
4410 sourceViewer.invalidateTextPresentation();
4412 if (PreferenceConstants.EDITOR_WRAP_WORDS.equals(event.getProperty())) {
4418 * Return whether the line number ruler column should be visible according to
4419 * the preference store settings.
4421 * @return <code>true</code> if the line numbers should be visible
4423 // protected boolean isLineNumberRulerVisible() {
4424 // IPreferenceStore store = getPreferenceStore();
4425 // return store.getBoolean(LINE_NUMBER_RULER);
4428 * Hides the line number ruler column.
4430 // private void hideLineNumberRuler() {
4431 // IVerticalRuler v = getVerticalRuler();
4432 // if (v instanceof CompositeRuler) {
4433 // CompositeRuler c = (CompositeRuler) v;
4435 // c.removeDecorator(1);
4436 // } catch (Throwable e) {
4441 * @see AbstractTextEditor#handleCursorPositionChanged()
4443 // protected void handleCursorPositionChanged() {
4444 // super.handleCursorPositionChanged();
4445 // if (!isEditingScriptRunning() && fUpdater != null)
4449 * @see org.eclipse.ui.texteditor.AbstractTextEditor#handleElementContentReplaced()
4451 protected void handleElementContentReplaced() {
4452 super.handleElementContentReplaced();
4453 if (fProjectionModelUpdater != null)
4454 fProjectionModelUpdater.initialize();
4458 * Initializes the given line number ruler column from the preference store.
4460 * @param rulerColumn
4461 * the ruler column to be initialized
4463 // protected void initializeLineNumberRulerColumn(LineNumberRulerColumn
4465 // JavaTextTools textTools =
4466 // PHPeclipsePlugin.getDefault().getJavaTextTools();
4467 // IColorManager manager = textTools.getColorManager();
4469 // IPreferenceStore store = getPreferenceStore();
4470 // if (store != null) {
4473 // // foreground color
4474 // if (store.contains(LINE_NUMBER_COLOR)) {
4475 // if (store.isDefault(LINE_NUMBER_COLOR))
4476 // rgb = PreferenceConverter.getDefaultColor(store, LINE_NUMBER_COLOR);
4478 // rgb = PreferenceConverter.getColor(store, LINE_NUMBER_COLOR);
4480 // rulerColumn.setForeground(manager.getColor(rgb));
4483 // // background color
4484 // if (!store.getBoolean(PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT)) {
4485 // if (store.contains(PREFERENCE_COLOR_BACKGROUND)) {
4486 // if (store.isDefault(PREFERENCE_COLOR_BACKGROUND))
4487 // rgb = PreferenceConverter.getDefaultColor(store,
4488 // PREFERENCE_COLOR_BACKGROUND);
4490 // rgb = PreferenceConverter.getColor(store, PREFERENCE_COLOR_BACKGROUND);
4493 // rulerColumn.setBackground(manager.getColor(rgb));
4497 * Creates a new line number ruler column that is appropriately initialized.
4499 // protected IVerticalRulerColumn createLineNumberRulerColumn() {
4500 // fLineNumberRulerColumn = new LineNumberRulerColumn();
4501 // initializeLineNumberRulerColumn(fLineNumberRulerColumn);
4502 // return fLineNumberRulerColumn;
4505 * @see AbstractTextEditor#createVerticalRuler()
4507 // protected IVerticalRuler createVerticalRuler() {
4508 // CompositeRuler ruler = new CompositeRuler();
4509 // ruler.addDecorator(0, new AnnotationRulerColumn(VERTICAL_RULER_WIDTH));
4510 // if (isLineNumberRulerVisible())
4511 // ruler.addDecorator(1, createLineNumberRulerColumn());
4514 // private static IRegion getSignedSelection(ITextViewer viewer) {
4516 // StyledText text = viewer.getTextWidget();
4517 // int caretOffset = text.getCaretOffset();
4518 // Point selection = text.getSelection();
4521 // int offset, length;
4522 // if (caretOffset == selection.x) {
4523 // offset = selection.y;
4524 // length = selection.x - selection.y;
4528 // offset = selection.x;
4529 // length = selection.y - selection.x;
4532 // return new Region(offset, length);
4534 protected IRegion getSignedSelection(ISourceViewer sourceViewer) {
4535 StyledText text = sourceViewer.getTextWidget();
4536 Point selection = text.getSelectionRange();
4538 if (text.getCaretOffset() == selection.x) {
4539 selection.x = selection.x + selection.y;
4540 selection.y = -selection.y;
4543 selection.x = widgetOffset2ModelOffset(sourceViewer, selection.x);
4545 return new Region(selection.x, selection.y);
4548 /** Preference key for matching brackets */
4549 protected final static String MATCHING_BRACKETS = PreferenceConstants.EDITOR_MATCHING_BRACKETS;
4551 /** Preference key for matching brackets color */
4552 protected final static String MATCHING_BRACKETS_COLOR = PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR;
4554 /** Preference key for highlighting current line */
4555 // protected final static String CURRENT_LINE =
4556 // PreferenceConstants.EDITOR_CURRENT_LINE;
4557 /** Preference key for highlight color of current line */
4558 // protected final static String CURRENT_LINE_COLOR =
4559 // PreferenceConstants.EDITOR_CURRENT_LINE_COLOR;
4560 /** Preference key for showing print marging ruler */
4561 // protected final static String PRINT_MARGIN =
4562 // PreferenceConstants.EDITOR_PRINT_MARGIN;
4563 /** Preference key for print margin ruler color */
4564 // protected final static String PRINT_MARGIN_COLOR =
4565 // PreferenceConstants.EDITOR_PRINT_MARGIN_COLOR;
4566 /** Preference key for print margin ruler column */
4567 // protected final static String PRINT_MARGIN_COLUMN =
4568 // PreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN;
4569 /** Preference key for error indication */
4570 // protected final static String ERROR_INDICATION =
4571 // PreferenceConstants.EDITOR_PROBLEM_INDICATION;
4572 /** Preference key for error color */
4573 // protected final static String ERROR_INDICATION_COLOR =
4574 // PreferenceConstants.EDITOR_PROBLEM_INDICATION_COLOR;
4575 /** Preference key for warning indication */
4576 // protected final static String WARNING_INDICATION =
4577 // PreferenceConstants.EDITOR_WARNING_INDICATION;
4578 /** Preference key for warning color */
4579 // protected final static String WARNING_INDICATION_COLOR =
4580 // PreferenceConstants.EDITOR_WARNING_INDICATION_COLOR;
4581 /** Preference key for task indication */
4582 protected final static String TASK_INDICATION = PreferenceConstants.EDITOR_TASK_INDICATION;
4584 /** Preference key for task color */
4585 protected final static String TASK_INDICATION_COLOR = PreferenceConstants.EDITOR_TASK_INDICATION_COLOR;
4587 /** Preference key for bookmark indication */
4588 protected final static String BOOKMARK_INDICATION = PreferenceConstants.EDITOR_BOOKMARK_INDICATION;
4590 /** Preference key for bookmark color */
4591 protected final static String BOOKMARK_INDICATION_COLOR = PreferenceConstants.EDITOR_BOOKMARK_INDICATION_COLOR;
4593 /** Preference key for search result indication */
4594 protected final static String SEARCH_RESULT_INDICATION = PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION;
4596 /** Preference key for search result color */
4597 protected final static String SEARCH_RESULT_INDICATION_COLOR = PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_COLOR;
4599 /** Preference key for unknown annotation indication */
4600 protected final static String UNKNOWN_INDICATION = PreferenceConstants.EDITOR_UNKNOWN_INDICATION;
4602 /** Preference key for unknown annotation color */
4603 protected final static String UNKNOWN_INDICATION_COLOR = PreferenceConstants.EDITOR_UNKNOWN_INDICATION_COLOR;
4605 /** Preference key for shwoing the overview ruler */
4606 protected final static String OVERVIEW_RULER = PreferenceConstants.EDITOR_OVERVIEW_RULER;
4608 /** Preference key for error indication in overview ruler */
4609 protected final static String ERROR_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_ERROR_INDICATION_IN_OVERVIEW_RULER;
4611 /** Preference key for warning indication in overview ruler */
4612 protected final static String WARNING_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_WARNING_INDICATION_IN_OVERVIEW_RULER;
4614 /** Preference key for task indication in overview ruler */
4615 protected final static String TASK_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_TASK_INDICATION_IN_OVERVIEW_RULER;
4617 /** Preference key for bookmark indication in overview ruler */
4618 protected final static String BOOKMARK_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_BOOKMARK_INDICATION_IN_OVERVIEW_RULER;
4620 /** Preference key for search result indication in overview ruler */
4621 protected final static String SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER;
4623 /** Preference key for unknown annotation indication in overview ruler */
4624 protected final static String UNKNOWN_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_UNKNOWN_INDICATION_IN_OVERVIEW_RULER;
4626 // /** Preference key for compiler task tags */
4627 // private final static String COMPILER_TASK_TAGS=
4628 // JavaCore.COMPILER_TASK_TAGS;
4629 /** Preference key for browser like links */
4630 private final static String BROWSER_LIKE_LINKS = PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS;
4632 /** Preference key for key modifier of browser like links */
4633 private final static String BROWSER_LIKE_LINKS_KEY_MODIFIER = PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER;
4636 * Preference key for key modifier mask of browser like links. The value is
4637 * only used if the value of <code>EDITOR_BROWSER_LIKE_LINKS</code> cannot
4638 * be resolved to valid SWT modifier bits.
4642 private final static String BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK = PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK;
4644 private final static char[] BRACKETS = { '{', '}', '(', ')', '[', ']' };
4646 private static boolean isBracket(char character) {
4647 for (int i = 0; i != BRACKETS.length; ++i)
4648 if (character == BRACKETS[i])
4653 private static boolean isSurroundedByBrackets(IDocument document, int offset) {
4654 if (offset == 0 || offset == document.getLength())
4658 return isBracket(document.getChar(offset - 1)) && isBracket(document.getChar(offset));
4660 } catch (BadLocationException e) {
4665 // protected void configureSourceViewerDecorationSupport() {
4667 // fSourceViewerDecorationSupport.setCharacterPairMatcher(fBracketMatcher);
4669 // fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(
4670 // AnnotationType.UNKNOWN,
4671 // UNKNOWN_INDICATION_COLOR,
4672 // UNKNOWN_INDICATION,
4673 // UNKNOWN_INDICATION_IN_OVERVIEW_RULER,
4675 // fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(
4676 // AnnotationType.BOOKMARK,
4677 // BOOKMARK_INDICATION_COLOR,
4678 // BOOKMARK_INDICATION,
4679 // BOOKMARK_INDICATION_IN_OVERVIEW_RULER,
4681 // fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(
4682 // AnnotationType.TASK,
4683 // TASK_INDICATION_COLOR,
4685 // TASK_INDICATION_IN_OVERVIEW_RULER,
4687 // fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(
4688 // AnnotationType.SEARCH,
4689 // SEARCH_RESULT_INDICATION_COLOR,
4690 // SEARCH_RESULT_INDICATION,
4691 // SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER,
4693 // fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(
4694 // AnnotationType.WARNING,
4695 // WARNING_INDICATION_COLOR,
4696 // WARNING_INDICATION,
4697 // WARNING_INDICATION_IN_OVERVIEW_RULER,
4699 // fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(
4700 // AnnotationType.ERROR,
4701 // ERROR_INDICATION_COLOR,
4702 // ERROR_INDICATION,
4703 // ERROR_INDICATION_IN_OVERVIEW_RULER,
4706 // fSourceViewerDecorationSupport.setCursorLinePainterPreferenceKeys(CURRENT_LINE,
4707 // CURRENT_LINE_COLOR);
4708 // fSourceViewerDecorationSupport.setMarginPainterPreferenceKeys(PRINT_MARGIN,
4709 // PRINT_MARGIN_COLOR, PRINT_MARGIN_COLUMN);
4710 // fSourceViewerDecorationSupport.setMatchingCharacterPainterPreferenceKeys(MATCHING_BRACKETS,
4711 // MATCHING_BRACKETS_COLOR);
4713 // fSourceViewerDecorationSupport.setSymbolicFontName(getFontPropertyPreferenceKey());
4717 * Returns the Java element wrapped by this editors input.
4719 * @return the Java element wrapped by this editors input.
4722 abstract protected IJavaElement getInputJavaElement();
4724 protected void updateStatusLine() {
4725 ITextSelection selection = (ITextSelection) getSelectionProvider().getSelection();
4726 Annotation annotation = getAnnotation(selection.getOffset(), selection.getLength());
4727 setStatusLineErrorMessage(null);
4728 setStatusLineMessage(null);
4729 if (annotation != null) {
4731 fIsUpdatingAnnotationViews = true;
4732 updateAnnotationViews(annotation);
4734 fIsUpdatingAnnotationViews = false;
4736 if (annotation instanceof IJavaAnnotation && ((IJavaAnnotation) annotation).isProblem())
4737 setStatusLineMessage(annotation.getText());
4742 * Jumps to the matching bracket.
4744 public void gotoMatchingBracket() {
4746 ISourceViewer sourceViewer = getSourceViewer();
4747 IDocument document = sourceViewer.getDocument();
4748 if (document == null)
4751 IRegion selection = getSignedSelection(sourceViewer);
4753 int selectionLength = Math.abs(selection.getLength());
4754 if (selectionLength > 1) {
4755 setStatusLineErrorMessage(PHPEditorMessages.getString("GotoMatchingBracket.error.invalidSelection")); //$NON-NLS-1$
4756 sourceViewer.getTextWidget().getDisplay().beep();
4761 int sourceCaretOffset = selection.getOffset() + selection.getLength();
4762 if (isSurroundedByBrackets(document, sourceCaretOffset))
4763 sourceCaretOffset -= selection.getLength();
4765 IRegion region = fBracketMatcher.match(document, sourceCaretOffset);
4766 if (region == null) {
4767 setStatusLineErrorMessage(PHPEditorMessages.getString("GotoMatchingBracket.error.noMatchingBracket")); //$NON-NLS-1$
4768 sourceViewer.getTextWidget().getDisplay().beep();
4772 int offset = region.getOffset();
4773 int length = region.getLength();
4778 int anchor = fBracketMatcher.getAnchor();
4779 int targetOffset = (PHPPairMatcher.RIGHT == anchor) ? offset : offset + length - 1;
4781 boolean visible = false;
4782 if (sourceViewer instanceof ITextViewerExtension3) {
4783 ITextViewerExtension3 extension = (ITextViewerExtension3) sourceViewer;
4784 visible = (extension.modelOffset2WidgetOffset(targetOffset) > -1);
4786 IRegion visibleRegion = sourceViewer.getVisibleRegion();
4787 visible = (targetOffset >= visibleRegion.getOffset() && targetOffset < visibleRegion.getOffset() + visibleRegion.getLength());
4791 setStatusLineErrorMessage(PHPEditorMessages.getString("GotoMatchingBracket.error.bracketOutsideSelectedElement")); //$NON-NLS-1$
4792 sourceViewer.getTextWidget().getDisplay().beep();
4796 if (selection.getLength() < 0)
4797 targetOffset -= selection.getLength();
4799 sourceViewer.setSelectedRange(targetOffset, selection.getLength());
4800 sourceViewer.revealRange(targetOffset, selection.getLength());
4804 * Ses the given message as error message to this editor's status line.
4809 protected void setStatusLineErrorMessage(String msg) {
4810 IEditorStatusLine statusLine = (IEditorStatusLine) getAdapter(IEditorStatusLine.class);
4811 if (statusLine != null)
4812 statusLine.setMessage(true, msg, null);
4816 * Sets the given message as message to this editor's status line.
4822 protected void setStatusLineMessage(String msg) {
4823 IEditorStatusLine statusLine = (IEditorStatusLine) getAdapter(IEditorStatusLine.class);
4824 if (statusLine != null)
4825 statusLine.setMessage(false, msg, null);
4829 * Returns the annotation closest to the given range respecting the given
4830 * direction. If an annotation is found, the annotations current position is
4831 * copied into the provided annotation position.
4838 * <code>true</code> for forwards, <code>false</code> for
4840 * @param annotationPosition
4841 * the position of the found annotation
4842 * @return the found annotation
4844 private Annotation getNextAnnotation(final int offset, final int length, boolean forward, Position annotationPosition) {
4846 Annotation nextAnnotation = null;
4847 Position nextAnnotationPosition = null;
4848 Annotation containingAnnotation = null;
4849 Position containingAnnotationPosition = null;
4850 boolean currentAnnotation = false;
4852 IDocument document = getDocumentProvider().getDocument(getEditorInput());
4853 int endOfDocument = document.getLength();
4854 int distance = Integer.MAX_VALUE;
4856 IAnnotationModel model = getDocumentProvider().getAnnotationModel(getEditorInput());
4857 Iterator e = new JavaAnnotationIterator(model, true, true);
4858 while (e.hasNext()) {
4859 Annotation a = (Annotation) e.next();
4860 if ((a instanceof IJavaAnnotation) && ((IJavaAnnotation) a).hasOverlay() || !isNavigationTarget(a))
4863 Position p = model.getPosition(a);
4867 if (forward && p.offset == offset || !forward && p.offset + p.getLength() == offset + length) {// ||
4868 // p.includes(offset))
4870 if (containingAnnotation == null
4871 || (forward && p.length >= containingAnnotationPosition.length || !forward
4872 && p.length >= containingAnnotationPosition.length)) {
4873 containingAnnotation = a;
4874 containingAnnotationPosition = p;
4875 currentAnnotation = p.length == length;
4878 int currentDistance = 0;
4881 currentDistance = p.getOffset() - offset;
4882 if (currentDistance < 0)
4883 currentDistance = endOfDocument + currentDistance;
4885 if (currentDistance < distance || currentDistance == distance && p.length < nextAnnotationPosition.length) {
4886 distance = currentDistance;
4888 nextAnnotationPosition = p;
4891 currentDistance = offset + length - (p.getOffset() + p.length);
4892 if (currentDistance < 0)
4893 currentDistance = endOfDocument + currentDistance;
4895 if (currentDistance < distance || currentDistance == distance && p.length < nextAnnotationPosition.length) {
4896 distance = currentDistance;
4898 nextAnnotationPosition = p;
4903 if (containingAnnotationPosition != null && (!currentAnnotation || nextAnnotation == null)) {
4904 annotationPosition.setOffset(containingAnnotationPosition.getOffset());
4905 annotationPosition.setLength(containingAnnotationPosition.getLength());
4906 return containingAnnotation;
4908 if (nextAnnotationPosition != null) {
4909 annotationPosition.setOffset(nextAnnotationPosition.getOffset());
4910 annotationPosition.setLength(nextAnnotationPosition.getLength());
4913 return nextAnnotation;
4917 * Returns the annotation overlapping with the given range or
4918 * <code>null</code>.
4924 * @return the found annotation or <code>null</code>
4927 private Annotation getAnnotation(int offset, int length) {
4928 IAnnotationModel model = getDocumentProvider().getAnnotationModel(getEditorInput());
4929 Iterator e = new JavaAnnotationIterator(model, true, true);
4930 while (e.hasNext()) {
4931 Annotation a = (Annotation) e.next();
4932 if (!isNavigationTarget(a))
4935 Position p = model.getPosition(a);
4936 if (p != null && p.overlapsWith(offset, length))
4944 * Returns whether the given annotation is configured as a target for the "Go
4945 * to Next/Previous Annotation" actions
4949 * @return <code>true</code> if this is a target, <code>false</code>
4953 private boolean isNavigationTarget(Annotation annotation) {
4954 Preferences preferences = EditorsUI.getPluginPreferences();
4955 AnnotationPreference preference = getAnnotationPreferenceLookup().getAnnotationPreference(annotation);
4957 // String key= forward ? preference.getIsGoToNextNavigationTargetKey() :
4958 // preference.getIsGoToPreviousNavigationTargetKey();
4959 String key = preference == null ? null : preference.getIsGoToNextNavigationTargetKey();
4960 return (key != null && preferences.getBoolean(key));
4964 * Returns a segmentation of the line of the given document appropriate for
4965 * bidi rendering. The default implementation returns only the string literals
4966 * of a php code line as segments.
4971 * the offset of the line
4972 * @return the line's bidi segmentation
4973 * @throws BadLocationException
4974 * in case lineOffset is not valid in document
4976 public static int[] getBidiLineSegments(IDocument document, int lineOffset) throws BadLocationException {
4978 IRegion line = document.getLineInformationOfOffset(lineOffset);
4979 ITypedRegion[] linePartitioning = document.computePartitioning(lineOffset, line.getLength());
4981 List segmentation = new ArrayList();
4982 for (int i = 0; i < linePartitioning.length; i++) {
4983 if (IPHPPartitions.PHP_STRING_DQ.equals(linePartitioning[i].getType())) {
4984 segmentation.add(linePartitioning[i]);
4985 } else if (IPHPPartitions.PHP_STRING_HEREDOC.equals(linePartitioning[i].getType())) {
4986 segmentation.add(linePartitioning[i]);
4990 if (segmentation.size() == 0)
4993 int size = segmentation.size();
4994 int[] segments = new int[size * 2 + 1];
4997 for (int i = 0; i < size; i++) {
4998 ITypedRegion segment = (ITypedRegion) segmentation.get(i);
5003 int offset = segment.getOffset() - lineOffset;
5004 if (offset > segments[j - 1])
5005 segments[j++] = offset;
5007 if (offset + segment.getLength() >= line.getLength())
5010 segments[j++] = offset + segment.getLength();
5013 if (j < segments.length) {
5014 int[] result = new int[j];
5015 System.arraycopy(segments, 0, result, 0, j);
5023 * Returns a segmentation of the given line appropriate for bidi rendering.
5024 * The default implementation returns only the string literals of a php code
5028 * the offset of the line
5030 * the content of the line
5031 * @return the line's bidi segmentation
5033 protected int[] getBidiLineSegments(int lineOffset, String line) {
5034 IDocumentProvider provider = getDocumentProvider();
5035 if (provider != null && line != null && line.length() > 0) {
5036 IDocument document = provider.getDocument(getEditorInput());
5037 if (document != null)
5039 return getBidiLineSegments(document, lineOffset);
5040 } catch (BadLocationException x) {
5048 * @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int)
5050 // protected final ISourceViewer createSourceViewer(
5051 // Composite parent,
5052 // IVerticalRuler ruler,
5054 // ISourceViewer viewer = createJavaSourceViewer(parent, ruler, styles);
5055 // StyledText text = viewer.getTextWidget();
5056 // text.addBidiSegmentListener(new BidiSegmentListener() {
5057 // public void lineGetSegments(BidiSegmentEvent event) {
5058 // event.segments = getBidiLineSegments(event.lineOffset, event.lineText);
5061 // // JavaUIHelp.setHelp(this, text, IJavaHelpContextIds.JAVA_EDITOR);
5064 public final ISourceViewer getViewer() {
5065 return getSourceViewer();
5068 // protected void showOverviewRuler() {
5069 // if (fOverviewRuler != null) {
5070 // if (getSourceViewer() instanceof ISourceViewerExtension) {
5071 // ((ISourceViewerExtension)
5072 // getSourceViewer()).showAnnotationsOverview(true);
5073 // fSourceViewerDecorationSupport.updateOverviewDecorations();
5078 // protected void hideOverviewRuler() {
5079 // if (getSourceViewer() instanceof ISourceViewerExtension) {
5080 // fSourceViewerDecorationSupport.hideAnnotationOverview();
5081 // ((ISourceViewerExtension)
5082 // getSourceViewer()).showAnnotationsOverview(false);
5086 // protected boolean isOverviewRulerVisible() {
5087 // IPreferenceStore store = getPreferenceStore();
5088 // return store.getBoolean(OVERVIEW_RULER);
5091 * @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int)
5093 // protected ISourceViewer createJavaSourceViewer(
5094 // Composite parent,
5095 // IVerticalRuler ruler,
5096 // IOverviewRuler overviewRuler,
5097 // boolean isOverviewRulerVisible,
5099 // return new SourceViewer(parent, ruler, overviewRuler,
5100 // isOverviewRulerVisible(), styles);
5103 * @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int)
5105 protected ISourceViewer createJavaSourceViewer(Composite parent, IVerticalRuler verticalRuler, IOverviewRuler overviewRuler,
5106 boolean isOverviewRulerVisible, int styles, IPreferenceStore store) {
5107 return new JavaSourceViewer(parent, verticalRuler, getOverviewRuler(), isOverviewRulerVisible(), styles, store);
5111 * @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int)
5113 protected final ISourceViewer createSourceViewer(Composite parent, IVerticalRuler verticalRuler, int styles) {
5115 ISourceViewer viewer = createJavaSourceViewer(parent, verticalRuler, getOverviewRuler(), isOverviewRulerVisible(), styles,
5116 getPreferenceStore());
5118 StyledText text = viewer.getTextWidget();
5119 text.addBidiSegmentListener(new BidiSegmentListener() {
5120 public void lineGetSegments(BidiSegmentEvent event) {
5121 event.segments = getBidiLineSegments(event.lineOffset, event.lineText);
5125 // JavaUIHelp.setHelp(this, text, IJavaHelpContextIds.JAVA_EDITOR);
5127 // ensure source viewer decoration support has been created and
5129 getSourceViewerDecorationSupport(viewer);
5135 * @see AbstractTextEditor#affectsTextPresentation(PropertyChangeEvent)
5137 protected boolean affectsTextPresentation(PropertyChangeEvent event) {
5138 return ((PHPSourceViewerConfiguration) getSourceViewerConfiguration()).affectsTextPresentation(event)
5139 || super.affectsTextPresentation(event);
5143 // protected boolean affectsTextPresentation(PropertyChangeEvent event) {
5144 // JavaTextTools textTools = PHPeclipsePlugin.getDefault().getJavaTextTools();
5145 // return textTools.affectsBehavior(event);
5148 * Creates and returns the preference store for this Java editor with the
5152 * The editor input for which to create the preference store
5153 * @return the preference store for this editor
5157 private IPreferenceStore createCombinedPreferenceStore(IEditorInput input) {
5158 List stores = new ArrayList(3);
5160 IJavaProject project = EditorUtility.getJavaProject(input);
5161 if (project != null)
5162 stores.add(new OptionsAdapter(project.getOptions(false), PHPeclipsePlugin.getDefault().getMockupPreferenceStore(),
5163 new OptionsAdapter.IPropertyChangeEventFilter() {
5165 public boolean isFiltered(PropertyChangeEvent event) {
5166 IJavaElement inputJavaElement = getInputJavaElement();
5167 IJavaProject javaProject = inputJavaElement != null ? inputJavaElement.getJavaProject() : null;
5168 if (javaProject == null)
5171 return !javaProject.getProject().equals(event.getSource());
5176 stores.add(PHPeclipsePlugin.getDefault().getPreferenceStore());
5177 stores.add(new PreferencesAdapter(JavaCore.getPlugin().getPluginPreferences()));
5178 stores.add(EditorsUI.getPreferenceStore());
5180 return new ChainedPreferenceStore((IPreferenceStore[]) stores.toArray(new IPreferenceStore[stores.size()]));
5184 * Jumps to the error next according to the given direction.
5186 public void gotoError(boolean forward) {
5188 ISelectionProvider provider = getSelectionProvider();
5190 ITextSelection s = (ITextSelection) provider.getSelection();
5191 Position errorPosition = new Position(0, 0);
5192 IJavaAnnotation nextError = getNextError(s.getOffset(), forward, errorPosition);
5194 if (nextError != null) {
5196 IMarker marker = null;
5197 if (nextError instanceof MarkerAnnotation)
5198 marker = ((MarkerAnnotation) nextError).getMarker();
5200 Iterator e = nextError.getOverlaidIterator();
5202 while (e.hasNext()) {
5203 Object o = e.next();
5204 if (o instanceof MarkerAnnotation) {
5205 marker = ((MarkerAnnotation) o).getMarker();
5212 if (marker != null) {
5213 IWorkbenchPage page = getSite().getPage();
5214 IViewPart view = view = page.findView("org.eclipse.ui.views.TaskList"); //$NON-NLS-1$
5215 if (view instanceof TaskList) {
5216 StructuredSelection ss = new StructuredSelection(marker);
5217 ((TaskList) view).setSelection(ss, true);
5221 selectAndReveal(errorPosition.getOffset(), errorPosition.getLength());
5222 // setStatusLineErrorMessage(nextError.getMessage());
5226 setStatusLineErrorMessage(null);
5231 private IJavaAnnotation getNextError(int offset, boolean forward, Position errorPosition) {
5233 IJavaAnnotation nextError = null;
5234 Position nextErrorPosition = null;
5236 IDocument document = getDocumentProvider().getDocument(getEditorInput());
5237 int endOfDocument = document.getLength();
5240 IAnnotationModel model = getDocumentProvider().getAnnotationModel(getEditorInput());
5241 Iterator e = new JavaAnnotationIterator(model, false);
5242 while (e.hasNext()) {
5244 IJavaAnnotation a = (IJavaAnnotation) e.next();
5245 if (a.hasOverlay() || !a.isProblem())
5248 Position p = model.getPosition((Annotation) a);
5249 if (!p.includes(offset)) {
5251 int currentDistance = 0;
5254 currentDistance = p.getOffset() - offset;
5255 if (currentDistance < 0)
5256 currentDistance = endOfDocument - offset + p.getOffset();
5258 currentDistance = offset - p.getOffset();
5259 if (currentDistance < 0)
5260 currentDistance = offset + endOfDocument - p.getOffset();
5263 if (nextError == null || currentDistance < distance) {
5264 distance = currentDistance;
5266 nextErrorPosition = p;
5271 if (nextErrorPosition != null) {
5272 errorPosition.setOffset(nextErrorPosition.getOffset());
5273 errorPosition.setLength(nextErrorPosition.getLength());
5279 protected void uninstallOverrideIndicator() {
5280 // if (fOverrideIndicatorManager != null) {
5281 // fOverrideIndicatorManager.removeAnnotations();
5282 // fOverrideIndicatorManager= null;
5286 protected void installOverrideIndicator(boolean waitForReconcilation) {
5287 uninstallOverrideIndicator();
5288 IAnnotationModel model = getDocumentProvider().getAnnotationModel(getEditorInput());
5289 final IJavaElement inputElement = getInputJavaElement();
5291 if (model == null || inputElement == null)
5294 // fOverrideIndicatorManager= new OverrideIndicatorManager(model,
5295 // inputElement, null);
5297 // if (provideAST) {
5299 // Job(JavaEditorMessages.getString("OverrideIndicatorManager.intallJob")) {
5303 // org.eclipse.core.runtime.jobs.Job#run(org.eclipse.core.runtime.IProgressMonitor)
5306 // protected IStatus run(IProgressMonitor monitor) {
5307 // CompilationUnit ast=
5308 // JavaPlugin.getDefault().getASTProvider().getAST(inputElement, true,
5310 // if (fOverrideIndicatorManager != null) // editor might have been closed
5312 // fOverrideIndicatorManager.reconciled(ast, true, monitor);
5313 // return Status.OK_STATUS;
5316 // job.setPriority(Job.DECORATE);
5317 // job.setSystem(true);
5323 * Tells whether override indicators are shown.
5325 * @return <code>true</code> if the override indicators are shown
5328 // protected boolean isShowingOverrideIndicators() {
5329 // AnnotationPreference preference=
5330 // getAnnotationPreferenceLookup().getAnnotationPreference(OverrideIndicatorManager.ANNOTATION_TYPE);
5331 // IPreferenceStore store= getPreferenceStore();
5332 // return getBoolean(store, preference.getHighlightPreferenceKey())
5333 // || getBoolean(store, preference.getVerticalRulerPreferenceKey())
5334 // || getBoolean(store, preference.getOverviewRulerPreferenceKey())
5335 // || getBoolean(store, preference.getTextPreferenceKey());
5338 * Returns the boolean preference for the given key.
5341 * the preference store
5343 * the preference key
5344 * @return <code>true</code> if the key exists in the store and its value is
5348 private boolean getBoolean(IPreferenceStore store, String key) {
5349 return key != null && store.getBoolean(key);
5352 protected boolean isPrefQuickDiffAlwaysOn() {
5353 return false; // never show change ruler for the non-editable java editor.
5354 // Overridden in subclasses like PHPUnitEditor
5358 * @see org.eclipse.ui.texteditor.AbstractTextEditor#createNavigationActions()
5360 protected void createNavigationActions() {
5361 super.createNavigationActions();
5363 final StyledText textWidget = getSourceViewer().getTextWidget();
5365 IAction action = new SmartLineStartAction(textWidget, false);
5366 action.setActionDefinitionId(ITextEditorActionDefinitionIds.LINE_START);
5367 setAction(ITextEditorActionDefinitionIds.LINE_START, action);
5369 action = new SmartLineStartAction(textWidget, true);
5370 action.setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_LINE_START);
5371 setAction(ITextEditorActionDefinitionIds.SELECT_LINE_START, action);
5373 action = new NavigatePreviousSubWordAction();
5374 action.setActionDefinitionId(ITextEditorActionDefinitionIds.WORD_PREVIOUS);
5375 setAction(ITextEditorActionDefinitionIds.WORD_PREVIOUS, action);
5376 textWidget.setKeyBinding(SWT.CTRL | SWT.ARROW_LEFT, SWT.NULL);
5378 action = new NavigateNextSubWordAction();
5379 action.setActionDefinitionId(ITextEditorActionDefinitionIds.WORD_NEXT);
5380 setAction(ITextEditorActionDefinitionIds.WORD_NEXT, action);
5381 textWidget.setKeyBinding(SWT.CTRL | SWT.ARROW_RIGHT, SWT.NULL);
5383 action = new SelectPreviousSubWordAction();
5384 action.setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_WORD_PREVIOUS);
5385 setAction(ITextEditorActionDefinitionIds.SELECT_WORD_PREVIOUS, action);
5386 textWidget.setKeyBinding(SWT.CTRL | SWT.SHIFT | SWT.ARROW_LEFT, SWT.NULL);
5388 action = new SelectNextSubWordAction();
5389 action.setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_WORD_NEXT);
5390 setAction(ITextEditorActionDefinitionIds.SELECT_WORD_NEXT, action);
5391 textWidget.setKeyBinding(SWT.CTRL | SWT.SHIFT | SWT.ARROW_RIGHT, SWT.NULL);
5395 * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#createCompositeRuler()
5397 protected CompositeRuler createCompositeRuler() {
5398 if (!getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_ANNOTATION_ROLL_OVER))
5399 return super.createCompositeRuler();
5401 CompositeRuler ruler = new CompositeRuler();
5402 AnnotationRulerColumn column = new AnnotationRulerColumn(VERTICAL_RULER_WIDTH, getAnnotationAccess());
5403 column.setHover(new JavaExpandHover(ruler, getAnnotationAccess(), new IDoubleClickListener() {
5405 public void doubleClick(DoubleClickEvent event) {
5406 // for now: just invoke ruler double click action
5407 triggerAction(ITextEditorActionConstants.RULER_DOUBLE_CLICK);
5410 private void triggerAction(String actionID) {
5411 IAction action = getAction(actionID);
5412 if (action != null) {
5413 if (action instanceof IUpdate)
5414 ((IUpdate) action).update();
5415 // hack to propagate line change
5416 if (action instanceof ISelectionListener) {
5417 ((ISelectionListener) action).selectionChanged(null, null);
5419 if (action.isEnabled())
5425 ruler.addDecorator(0, column);
5427 if (isLineNumberRulerVisible())
5428 ruler.addDecorator(1, createLineNumberRulerColumn());
5429 else if (isPrefQuickDiffAlwaysOn())
5430 ruler.addDecorator(1, createChangeRulerColumn());
5436 * Returns the folding action group, or <code>null</code> if there is none.
5438 * @return the folding action group, or <code>null</code> if there is none
5441 protected FoldingActionGroup getFoldingActionGroup() {
5442 return fFoldingGroup;
5446 * @see org.eclipse.ui.texteditor.AbstractTextEditor#performRevert()
5448 protected void performRevert() {
5449 ProjectionViewer projectionViewer = (ProjectionViewer) getSourceViewer();
5450 projectionViewer.setRedraw(false);
5453 boolean projectionMode = projectionViewer.isProjectionMode();
5454 if (projectionMode) {
5455 projectionViewer.disableProjection();
5456 if (fProjectionModelUpdater != null)
5457 fProjectionModelUpdater.uninstall();
5460 super.performRevert();
5462 if (projectionMode) {
5463 if (fProjectionModelUpdater != null)
5464 fProjectionModelUpdater.install(this, projectionViewer);
5465 projectionViewer.enableProjection();
5469 projectionViewer.setRedraw(true);
5474 * React to changed selection.
5478 protected void selectionChanged() {
5479 if (getSelectionProvider() == null)
5481 ISourceReference element = computeHighlightRangeSourceReference();
5482 if (getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE))
5483 synchronizeOutlinePage(element);
5484 setSelection(element, false);
5488 private boolean isJavaOutlinePageActive() {
5489 IWorkbenchPart part = getActivePart();
5490 return part instanceof ContentOutline && ((ContentOutline) part).getCurrentPage() == fOutlinePage;
5493 private IWorkbenchPart getActivePart() {
5494 IWorkbenchWindow window = getSite().getWorkbenchWindow();
5495 IPartService service = window.getPartService();
5496 IWorkbenchPart part = service.getActivePart();
5501 * Computes and returns the source reference that includes the caret and
5502 * serves as provider for the outline page selection and the editor range
5505 * @return the computed source reference
5508 protected ISourceReference computeHighlightRangeSourceReference() {
5509 ISourceViewer sourceViewer = getSourceViewer();
5510 if (sourceViewer == null)
5513 StyledText styledText = sourceViewer.getTextWidget();
5514 if (styledText == null)
5518 if (sourceViewer instanceof ITextViewerExtension5) {
5519 ITextViewerExtension5 extension = (ITextViewerExtension5) sourceViewer;
5520 caret = extension.widgetOffset2ModelOffset(styledText.getCaretOffset());
5522 int offset = sourceViewer.getVisibleRegion().getOffset();
5523 caret = offset + styledText.getCaretOffset();
5526 IJavaElement element = getElementAt(caret, false);
5528 if (!(element instanceof ISourceReference))
5531 if (element.getElementType() == IJavaElement.IMPORT_DECLARATION) {
5533 IImportDeclaration declaration = (IImportDeclaration) element;
5534 IImportContainer container = (IImportContainer) declaration.getParent();
5535 ISourceRange srcRange = null;
5538 srcRange = container.getSourceRange();
5539 } catch (JavaModelException e) {
5542 if (srcRange != null && srcRange.getOffset() == caret)
5546 return (ISourceReference) element;
5550 * Returns the most narrow java element including the given offset.
5553 * the offset inside of the requested element
5555 * <code>true</code> if editor input should be reconciled in
5557 * @return the most narrow java element
5560 protected IJavaElement getElementAt(int offset, boolean reconcile) {
5561 return getElementAt(offset);
5564 public ShowInContext getShowInContext() {
5565 FileEditorInput fei = (FileEditorInput) getEditorInput();
5566 ShowInContext context = BrowserUtil.getShowInContext(fei.getFile(), false, "");
5567 if (context != null) {
5570 return new ShowInContext(fei.getFile(), null);
5573 public String[] getShowInTargetIds() {
5574 return new String[] { BrowserView.ID_BROWSER };
5578 * Updates the occurrences annotations based on the current selection.
5581 * the text selection
5583 * the compilation unit AST
5586 protected void updateOccurrenceAnnotations(ITextSelection selection) {// ,
5591 if (fOccurrencesFinderJob != null)
5592 fOccurrencesFinderJob.cancel();
5594 if (!fMarkOccurrenceAnnotations)
5597 // if (astRoot == null || selection == null)
5598 if (selection == null)
5601 IDocument document = getSourceViewer().getDocument();
5602 if (document == null)
5605 fMarkOccurrenceTargetRegion = null;
5606 if (document instanceof IDocumentExtension4) {
5607 int offset = selection.getOffset();
5608 long currentModificationStamp = ((IDocumentExtension4) document).getModificationStamp();
5609 if (fMarkOccurrenceTargetRegion != null && currentModificationStamp == fMarkOccurrenceModificationStamp) {
5610 if (fMarkOccurrenceTargetRegion.getOffset() <= offset
5611 && offset <= fMarkOccurrenceTargetRegion.getOffset() + fMarkOccurrenceTargetRegion.getLength())
5614 fMarkOccurrenceTargetRegion = JavaWordFinder.findWord(document, offset);
5615 fMarkOccurrenceModificationStamp = currentModificationStamp;
5618 if (fMarkOccurrenceTargetRegion == null || fMarkOccurrenceTargetRegion.getLength() == 0) {
5622 List matches = null;
5624 if (matches == null) {
5626 matches = new ArrayList();
5628 Scanner fScanner = new Scanner();
5629 fScanner.setSource(document.get().toCharArray());
5630 fScanner.setPHPMode(false);
5634 wordStr = document.get(fMarkOccurrenceTargetRegion.getOffset(), fMarkOccurrenceTargetRegion.getLength());
5635 if (wordStr != null) {
5636 word = wordStr.toCharArray();
5637 int fToken = ITerminalSymbols.TokenNameEOF;
5639 fToken = fScanner.getNextToken();
5640 while (fToken != ITerminalSymbols.TokenNameEOF) { // && fToken !=
5641 // TokenNameERROR) {
5642 if (fToken == ITerminalSymbols.TokenNameVariable || fToken == ITerminalSymbols.TokenNameIdentifier) {
5644 if (fScanner.equalsCurrentTokenSource(word)) {
5645 matches.add(new Region(fScanner.getCurrentTokenStartPosition(), fScanner.getCurrentTokenEndPosition()
5646 - fScanner.getCurrentTokenStartPosition() + 1));
5649 fToken = fScanner.getNextToken();
5651 } catch (InvalidInputException e) {
5653 } catch (SyntaxError e) {
5657 } catch (BadLocationException e1) {
5659 } catch (Exception e) {
5660 e.printStackTrace();
5666 if (matches == null || matches.size() == 0) {
5667 if (!fStickyOccurrenceAnnotations)
5668 removeOccurrenceAnnotations();
5672 Position[] positions = new Position[matches.size()];
5674 for (Iterator each = matches.iterator(); each.hasNext();) {
5675 IRegion currentNode = (IRegion) each.next();
5676 positions[i++] = new Position(currentNode.getOffset(), currentNode.getLength());
5679 fOccurrencesFinderJob = new OccurrencesFinderJob(document, positions, selection);
5680 // fOccurrencesFinderJob.setPriority(Job.DECORATE);
5681 // fOccurrencesFinderJob.setSystem(true);
5682 // fOccurrencesFinderJob.schedule();
5683 fOccurrencesFinderJob.run(new NullProgressMonitor());
5686 protected void installOccurrencesFinder() {
5687 fMarkOccurrenceAnnotations = true;
5689 fPostSelectionListenerWithAST = new ISelectionListenerWithAST() {
5690 public void selectionChanged(IEditorPart part, ITextSelection selection) { // ,
5694 updateOccurrenceAnnotations(selection);// , astRoot);
5697 SelectionListenerWithASTManager.getDefault().addListener(this, fPostSelectionListenerWithAST);
5698 if (getSelectionProvider() != null) {
5699 fForcedMarkOccurrencesSelection = getSelectionProvider().getSelection();
5700 SelectionListenerWithASTManager.getDefault().forceSelectionChange(this, (ITextSelection) fForcedMarkOccurrencesSelection);
5703 if (fOccurrencesFinderJobCanceler == null) {
5704 fOccurrencesFinderJobCanceler = new OccurrencesFinderJobCanceler();
5705 fOccurrencesFinderJobCanceler.install();
5709 protected void uninstallOccurrencesFinder() {
5710 fMarkOccurrenceAnnotations = false;
5712 if (fOccurrencesFinderJob != null) {
5713 fOccurrencesFinderJob.cancel();
5714 fOccurrencesFinderJob = null;
5717 if (fOccurrencesFinderJobCanceler != null) {
5718 fOccurrencesFinderJobCanceler.uninstall();
5719 fOccurrencesFinderJobCanceler = null;
5722 if (fPostSelectionListenerWithAST != null) {
5723 SelectionListenerWithASTManager.getDefault().removeListener(this, fPostSelectionListenerWithAST);
5724 fPostSelectionListenerWithAST = null;
5727 removeOccurrenceAnnotations();
5730 protected boolean isMarkingOccurrences() {
5731 return fMarkOccurrenceAnnotations;
5734 void removeOccurrenceAnnotations() {
5735 fMarkOccurrenceModificationStamp = IDocumentExtension4.UNKNOWN_MODIFICATION_STAMP;
5736 fMarkOccurrenceTargetRegion = null;
5738 IDocumentProvider documentProvider = getDocumentProvider();
5739 if (documentProvider == null)
5742 IAnnotationModel annotationModel = documentProvider.getAnnotationModel(getEditorInput());
5743 if (annotationModel == null || fOccurrenceAnnotations == null)
5746 synchronized (getLockObject(annotationModel)) {
5747 if (annotationModel instanceof IAnnotationModelExtension) {
5748 ((IAnnotationModelExtension) annotationModel).replaceAnnotations(fOccurrenceAnnotations, null);
5750 for (int i = 0, length = fOccurrenceAnnotations.length; i < length; i++)
5751 annotationModel.removeAnnotation(fOccurrenceAnnotations[i]);
5753 fOccurrenceAnnotations = null;