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.ui.actions.CompositeActionGroup;
41 import net.sourceforge.phpdt.internal.ui.actions.FoldingActionGroup;
42 import net.sourceforge.phpdt.internal.ui.actions.SelectionConverter;
43 import net.sourceforge.phpdt.internal.ui.text.CustomSourceInformationControl;
44 import net.sourceforge.phpdt.internal.ui.text.DocumentCharacterIterator;
45 import net.sourceforge.phpdt.internal.ui.text.HTMLTextPresenter;
46 import net.sourceforge.phpdt.internal.ui.text.IPHPPartitions;
47 import net.sourceforge.phpdt.internal.ui.text.JavaWordFinder;
48 import net.sourceforge.phpdt.internal.ui.text.JavaWordIterator;
49 import net.sourceforge.phpdt.internal.ui.text.PHPPairMatcher;
50 import net.sourceforge.phpdt.internal.ui.text.PreferencesAdapter;
51 import net.sourceforge.phpdt.internal.ui.text.java.hover.JavaExpandHover;
52 import net.sourceforge.phpdt.internal.ui.viewsupport.ISelectionListenerWithAST;
53 import net.sourceforge.phpdt.internal.ui.viewsupport.IViewPartInputProvider;
54 import net.sourceforge.phpdt.internal.ui.viewsupport.SelectionListenerWithASTManager;
55 import net.sourceforge.phpdt.ui.IContextMenuConstants;
56 import net.sourceforge.phpdt.ui.JavaUI;
57 import net.sourceforge.phpdt.ui.PreferenceConstants;
58 import net.sourceforge.phpdt.ui.actions.GotoMatchingBracketAction;
59 import net.sourceforge.phpdt.ui.actions.OpenEditorActionGroup;
60 import net.sourceforge.phpdt.ui.text.JavaTextTools;
61 import net.sourceforge.phpdt.ui.text.PHPSourceViewerConfiguration;
62 import net.sourceforge.phpdt.ui.text.folding.IJavaFoldingStructureProvider;
63 import net.sourceforge.phpeclipse.PHPeclipsePlugin;
64 import net.sourceforge.phpeclipse.ui.editor.BrowserUtil;
65 import net.sourceforge.phpeclipse.webbrowser.views.BrowserView;
67 import org.eclipse.core.resources.IMarker;
68 import org.eclipse.core.resources.IResource;
69 import org.eclipse.core.runtime.CoreException;
70 import org.eclipse.core.runtime.IProgressMonitor;
71 import org.eclipse.core.runtime.IStatus;
72 import org.eclipse.core.runtime.NullProgressMonitor;
73 import org.eclipse.core.runtime.Preferences;
74 import org.eclipse.core.runtime.Status;
75 import org.eclipse.core.runtime.jobs.Job;
76 import org.eclipse.jface.action.Action;
77 import org.eclipse.jface.action.GroupMarker;
78 import org.eclipse.jface.action.IAction;
79 import org.eclipse.jface.action.MenuManager;
80 import org.eclipse.jface.action.Separator;
81 import org.eclipse.jface.preference.IPreferenceStore;
82 import org.eclipse.jface.preference.PreferenceConverter;
83 import org.eclipse.jface.text.BadLocationException;
84 import org.eclipse.jface.text.DefaultInformationControl;
85 import org.eclipse.jface.text.DocumentEvent;
86 import org.eclipse.jface.text.IDocument;
87 import org.eclipse.jface.text.IDocumentExtension4;
88 import org.eclipse.jface.text.IDocumentListener;
89 import org.eclipse.jface.text.IInformationControl;
90 import org.eclipse.jface.text.IInformationControlCreator;
91 import org.eclipse.jface.text.IRegion;
92 import org.eclipse.jface.text.ISelectionValidator;
93 import org.eclipse.jface.text.ISynchronizable;
94 import org.eclipse.jface.text.ITextHover;
95 import org.eclipse.jface.text.ITextInputListener;
96 import org.eclipse.jface.text.ITextPresentationListener;
97 import org.eclipse.jface.text.ITextSelection;
98 import org.eclipse.jface.text.ITextViewer;
99 import org.eclipse.jface.text.ITextViewerExtension2;
100 import org.eclipse.jface.text.ITextViewerExtension4;
101 import org.eclipse.jface.text.ITextViewerExtension5;
102 import org.eclipse.jface.text.ITypedRegion;
103 import org.eclipse.jface.text.Position;
104 import org.eclipse.jface.text.Region;
105 import org.eclipse.jface.text.TextPresentation;
106 import org.eclipse.jface.text.TextSelection;
107 import org.eclipse.jface.text.TextUtilities;
108 import org.eclipse.jface.text.information.IInformationProvider;
109 import org.eclipse.jface.text.information.InformationPresenter;
110 import org.eclipse.jface.text.link.LinkedModeModel;
111 import org.eclipse.jface.text.reconciler.IReconciler;
112 import org.eclipse.jface.text.source.Annotation;
113 import org.eclipse.jface.text.source.AnnotationRulerColumn;
114 import org.eclipse.jface.text.source.CompositeRuler;
115 import org.eclipse.jface.text.source.IAnnotationModel;
116 import org.eclipse.jface.text.source.IAnnotationModelExtension;
117 import org.eclipse.jface.text.source.IOverviewRuler;
118 import org.eclipse.jface.text.source.ISourceViewer;
119 import org.eclipse.jface.text.source.ISourceViewerExtension2;
120 import org.eclipse.jface.text.source.IVerticalRuler;
121 import org.eclipse.jface.text.source.IVerticalRulerColumn;
122 import org.eclipse.jface.text.source.OverviewRuler;
123 import org.eclipse.jface.text.source.SourceViewerConfiguration;
124 import org.eclipse.jface.text.source.projection.ProjectionSupport;
125 import org.eclipse.jface.text.source.projection.ProjectionViewer;
126 import org.eclipse.jface.util.IPropertyChangeListener;
127 import org.eclipse.jface.util.ListenerList;
128 import org.eclipse.jface.util.PropertyChangeEvent;
129 import org.eclipse.jface.viewers.DoubleClickEvent;
130 import org.eclipse.jface.viewers.IDoubleClickListener;
131 import org.eclipse.jface.viewers.IPostSelectionProvider;
132 import org.eclipse.jface.viewers.ISelection;
133 import org.eclipse.jface.viewers.ISelectionChangedListener;
134 import org.eclipse.jface.viewers.ISelectionProvider;
135 import org.eclipse.jface.viewers.IStructuredSelection;
136 import org.eclipse.jface.viewers.SelectionChangedEvent;
137 import org.eclipse.jface.viewers.StructuredSelection;
138 import org.eclipse.swt.SWT;
139 import org.eclipse.swt.custom.BidiSegmentEvent;
140 import org.eclipse.swt.custom.BidiSegmentListener;
141 import org.eclipse.swt.custom.ST;
142 import org.eclipse.swt.custom.StyleRange;
143 import org.eclipse.swt.custom.StyledText;
144 import org.eclipse.swt.events.FocusEvent;
145 import org.eclipse.swt.events.FocusListener;
146 import org.eclipse.swt.events.KeyEvent;
147 import org.eclipse.swt.events.KeyListener;
148 import org.eclipse.swt.events.MouseEvent;
149 import org.eclipse.swt.events.MouseListener;
150 import org.eclipse.swt.events.MouseMoveListener;
151 import org.eclipse.swt.events.PaintEvent;
152 import org.eclipse.swt.events.PaintListener;
153 import org.eclipse.swt.graphics.Color;
154 import org.eclipse.swt.graphics.Cursor;
155 import org.eclipse.swt.graphics.GC;
156 import org.eclipse.swt.graphics.Image;
157 import org.eclipse.swt.graphics.Point;
158 import org.eclipse.swt.graphics.RGB;
159 import org.eclipse.swt.widgets.Composite;
160 import org.eclipse.swt.widgets.Control;
161 import org.eclipse.swt.widgets.Display;
162 import org.eclipse.swt.widgets.Shell;
163 import org.eclipse.ui.IEditorInput;
164 import org.eclipse.ui.IEditorPart;
165 import org.eclipse.ui.IPageLayout;
166 import org.eclipse.ui.IPartService;
167 import org.eclipse.ui.ISelectionListener;
168 import org.eclipse.ui.IViewPart;
169 import org.eclipse.ui.IWindowListener;
170 import org.eclipse.ui.IWorkbenchPage;
171 import org.eclipse.ui.IWorkbenchPart;
172 import org.eclipse.ui.IWorkbenchWindow;
173 import org.eclipse.ui.PlatformUI;
174 import org.eclipse.ui.actions.ActionContext;
175 import org.eclipse.ui.actions.ActionGroup;
176 import org.eclipse.ui.editors.text.DefaultEncodingSupport;
177 import org.eclipse.ui.editors.text.EditorsUI;
178 import org.eclipse.ui.editors.text.IEncodingSupport;
179 import org.eclipse.ui.part.FileEditorInput;
180 import org.eclipse.ui.part.IShowInSource;
181 import org.eclipse.ui.part.IShowInTargetList;
182 import org.eclipse.ui.part.ShowInContext;
183 import org.eclipse.ui.texteditor.AbstractDecoratedTextEditor;
184 import org.eclipse.ui.texteditor.AnnotationPreference;
185 import org.eclipse.ui.texteditor.ChainedPreferenceStore;
186 import org.eclipse.ui.texteditor.IDocumentProvider;
187 import org.eclipse.ui.texteditor.IEditorStatusLine;
188 import org.eclipse.ui.texteditor.ITextEditorActionConstants;
189 import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds;
190 import org.eclipse.ui.texteditor.IUpdate;
191 import org.eclipse.ui.texteditor.MarkerAnnotation;
192 import org.eclipse.ui.texteditor.SourceViewerDecorationSupport;
193 import org.eclipse.ui.texteditor.TextEditorAction;
194 import org.eclipse.ui.texteditor.TextNavigationAction;
195 import org.eclipse.ui.texteditor.TextOperationAction;
196 import org.eclipse.ui.views.contentoutline.ContentOutline;
197 import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
198 import org.eclipse.ui.views.tasklist.TaskList;
201 * PHP specific text editor.
203 public abstract class PHPEditor extends AbstractDecoratedTextEditor implements
204 IViewPartInputProvider, IShowInTargetList, IShowInSource {
205 // extends StatusTextEditor implements IViewPartInputProvider { // extends
209 * Internal implementation class for a change listener.
213 protected abstract class AbstractSelectionChangedListener implements
214 ISelectionChangedListener {
217 * Installs this selection changed listener with the given selection
218 * provider. If the selection provider is a post selection provider,
219 * post selection changed events are the preferred choice, otherwise
220 * normal 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
262 private class EditorSelectionChangedListener extends
263 AbstractSelectionChangedListener {
266 * @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent)
268 public void selectionChanged(SelectionChangedEvent event) {
269 // XXX: see https://bugs.eclipse.org/bugs/show_bug.cgi?id=56161
270 PHPEditor.this.selectionChanged();
275 * "Smart" runnable for updating the outline page's selection.
277 // class OutlinePageSelectionUpdater implements Runnable {
279 // /** Has the runnable already been posted? */
280 // private boolean fPosted = false;
282 // public OutlinePageSelectionUpdater() {
286 // * @see Runnable#run()
288 // public void run() {
289 // synchronizeOutlinePageSelection();
294 // * Posts this runnable into the event queue.
296 // public void post() {
300 // Shell shell = getSite().getShell();
301 // if (shell != null & !shell.isDisposed()) {
303 // shell.getDisplay().asyncExec(this);
307 class SelectionChangedListener implements ISelectionChangedListener {
308 public void selectionChanged(SelectionChangedEvent event) {
309 doSelectionChanged(event);
314 * Adapts an options {@link java.util.Map}to
315 * {@link org.eclipse.jface.preference.IPreferenceStore}.
317 * This preference store is read-only i.e. write access throws an
318 * {@link java.lang.UnsupportedOperationException}.
323 private static class OptionsAdapter implements IPreferenceStore {
326 * A property change event filter.
328 public interface IPropertyChangeEventFilter {
331 * Should the given event be filtered?
334 * The property change event.
335 * @return <code>true</code> iff the given event should be
338 public boolean isFiltered(PropertyChangeEvent event);
343 * Property change listener. Listens for events in the options Map and
344 * fires a {@link org.eclipse.jface.util.PropertyChangeEvent}on this
345 * adapter with arguments from the received event.
347 private class PropertyChangeListener implements IPropertyChangeListener {
352 public void propertyChange(PropertyChangeEvent event) {
353 if (getFilter().isFiltered(event))
356 if (event.getNewValue() == null)
357 fOptions.remove(event.getProperty());
359 fOptions.put(event.getProperty(), event.getNewValue());
361 firePropertyChangeEvent(event.getProperty(), event
362 .getOldValue(), event.getNewValue());
366 /** Listeners on this adapter */
367 private ListenerList fListeners = new ListenerList();
369 /** Listener on the adapted options Map */
370 private IPropertyChangeListener fListener = new PropertyChangeListener();
372 /** Adapted options Map */
373 private Map fOptions;
375 /** Preference store through which events are received. */
376 private IPreferenceStore fMockupPreferenceStore;
378 /** Property event filter. */
379 private IPropertyChangeEventFilter fFilter;
382 * Initialize with the given options.
385 * The options to wrap
386 * @param mockupPreferenceStore
387 * the mock-up preference store
389 * the property change filter
391 public OptionsAdapter(Map options,
392 IPreferenceStore mockupPreferenceStore,
393 IPropertyChangeEventFilter filter) {
394 fMockupPreferenceStore = mockupPreferenceStore;
402 public void addPropertyChangeListener(IPropertyChangeListener listener) {
403 if (fListeners.size() == 0)
404 fMockupPreferenceStore.addPropertyChangeListener(fListener);
405 fListeners.add(listener);
411 public void removePropertyChangeListener(
412 IPropertyChangeListener listener) {
413 fListeners.remove(listener);
414 if (fListeners.size() == 0)
415 fMockupPreferenceStore.removePropertyChangeListener(fListener);
421 public boolean contains(String name) {
422 return fOptions.containsKey(name);
428 public void firePropertyChangeEvent(String name, Object oldValue,
430 PropertyChangeEvent event = new PropertyChangeEvent(this, name,
432 Object[] listeners = fListeners.getListeners();
433 for (int i = 0; i < listeners.length; i++)
434 ((IPropertyChangeListener) listeners[i]).propertyChange(event);
440 public boolean getBoolean(String name) {
441 boolean value = BOOLEAN_DEFAULT_DEFAULT;
442 String s = (String) fOptions.get(name);
444 value = s.equals(TRUE);
451 public boolean getDefaultBoolean(String name) {
452 return BOOLEAN_DEFAULT_DEFAULT;
458 public double getDefaultDouble(String name) {
459 return DOUBLE_DEFAULT_DEFAULT;
465 public float getDefaultFloat(String name) {
466 return FLOAT_DEFAULT_DEFAULT;
472 public int getDefaultInt(String name) {
473 return INT_DEFAULT_DEFAULT;
479 public long getDefaultLong(String name) {
480 return LONG_DEFAULT_DEFAULT;
486 public String getDefaultString(String name) {
487 return STRING_DEFAULT_DEFAULT;
493 public double getDouble(String name) {
494 double value = DOUBLE_DEFAULT_DEFAULT;
495 String s = (String) fOptions.get(name);
498 value = new Double(s).doubleValue();
499 } catch (NumberFormatException e) {
508 public float getFloat(String name) {
509 float value = FLOAT_DEFAULT_DEFAULT;
510 String s = (String) fOptions.get(name);
513 value = new Float(s).floatValue();
514 } catch (NumberFormatException e) {
523 public int getInt(String name) {
524 int value = INT_DEFAULT_DEFAULT;
525 String s = (String) fOptions.get(name);
528 value = new Integer(s).intValue();
529 } catch (NumberFormatException e) {
538 public long getLong(String name) {
539 long value = LONG_DEFAULT_DEFAULT;
540 String s = (String) fOptions.get(name);
543 value = new Long(s).longValue();
544 } catch (NumberFormatException e) {
553 public String getString(String name) {
554 String value = (String) fOptions.get(name);
556 value = STRING_DEFAULT_DEFAULT;
563 public boolean isDefault(String name) {
570 public boolean needsSaving() {
571 return !fOptions.isEmpty();
577 public void putValue(String name, String value) {
578 throw new UnsupportedOperationException();
584 public void setDefault(String name, double value) {
585 throw new UnsupportedOperationException();
591 public void setDefault(String name, float value) {
592 throw new UnsupportedOperationException();
598 public void setDefault(String name, int value) {
599 throw new UnsupportedOperationException();
605 public void setDefault(String name, long value) {
606 throw new UnsupportedOperationException();
612 public void setDefault(String name, String defaultObject) {
613 throw new UnsupportedOperationException();
619 public void setDefault(String name, boolean value) {
620 throw new UnsupportedOperationException();
626 public void setToDefault(String name) {
627 throw new UnsupportedOperationException();
633 public void setValue(String name, double value) {
634 throw new UnsupportedOperationException();
640 public void setValue(String name, float value) {
641 throw new UnsupportedOperationException();
647 public void setValue(String name, int value) {
648 throw new UnsupportedOperationException();
654 public void setValue(String name, long value) {
655 throw new UnsupportedOperationException();
661 public void setValue(String name, String value) {
662 throw new UnsupportedOperationException();
668 public void setValue(String name, boolean value) {
669 throw new UnsupportedOperationException();
673 * Returns the adapted options Map.
675 * @return Returns the adapted options Map.
677 public Map getOptions() {
682 * Returns the mock-up preference store, events are received through
683 * this preference store.
685 * @return Returns the mock-up preference store.
687 public IPreferenceStore getMockupPreferenceStore() {
688 return fMockupPreferenceStore;
692 * Set the event filter to the given filter.
697 public void setFilter(IPropertyChangeEventFilter filter) {
702 * Returns the event filter.
704 * @return The event filter.
706 public IPropertyChangeEventFilter getFilter() {
714 // class MouseClickListener implements KeyListener, MouseListener,
715 // MouseMoveListener, FocusListener, PaintListener,
716 // IPropertyChangeListener, IDocumentListener, ITextInputListener {
718 // /** The session is active. */
719 // private boolean fActive;
721 // /** The currently active style range. */
722 // private IRegion fActiveRegion;
724 // /** The currently active style range as position. */
725 // private Position fRememberedPosition;
727 // /** The hand cursor. */
728 // private Cursor fCursor;
730 // /** The link color. */
731 // private Color fColor;
733 // /** The key modifier mask. */
734 // private int fKeyModifierMask;
736 // public void deactivate() {
737 // deactivate(false);
740 // public void deactivate(boolean redrawAll) {
744 // repairRepresentation(redrawAll);
748 // public void install() {
750 // ISourceViewer sourceViewer = getSourceViewer();
751 // if (sourceViewer == null)
754 // StyledText text = sourceViewer.getTextWidget();
755 // if (text == null || text.isDisposed())
758 // updateColor(sourceViewer);
760 // sourceViewer.addTextInputListener(this);
762 // IDocument document = sourceViewer.getDocument();
763 // if (document != null)
764 // document.addDocumentListener(this);
766 // text.addKeyListener(this);
767 // text.addMouseListener(this);
768 // text.addMouseMoveListener(this);
769 // text.addFocusListener(this);
770 // text.addPaintListener(this);
772 // updateKeyModifierMask();
774 // IPreferenceStore preferenceStore = getPreferenceStore();
775 // preferenceStore.addPropertyChangeListener(this);
778 // private void updateKeyModifierMask() {
779 // String modifiers =
780 // getPreferenceStore().getString(BROWSER_LIKE_LINKS_KEY_MODIFIER);
781 // fKeyModifierMask = computeStateMask(modifiers);
782 // if (fKeyModifierMask == -1) {
783 // // Fallback to stored state mask
784 // fKeyModifierMask =
785 // getPreferenceStore().getInt(BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK);
790 // private int computeStateMask(String modifiers) {
791 // if (modifiers == null)
794 // if (modifiers.length() == 0)
797 // int stateMask = 0;
798 // StringTokenizer modifierTokenizer = new StringTokenizer(modifiers,
801 // while (modifierTokenizer.hasMoreTokens()) {
803 // EditorUtility.findLocalizedModifier(modifierTokenizer.nextToken());
804 // if (modifier == 0 || (stateMask & modifier) == modifier)
806 // stateMask = stateMask | modifier;
811 // public void uninstall() {
813 // if (fColor != null) {
818 // if (fCursor != null) {
819 // fCursor.dispose();
823 // ISourceViewer sourceViewer = getSourceViewer();
824 // if (sourceViewer == null)
827 // sourceViewer.removeTextInputListener(this);
829 // IDocument document = sourceViewer.getDocument();
830 // if (document != null)
831 // document.removeDocumentListener(this);
833 // IPreferenceStore preferenceStore = getPreferenceStore();
834 // if (preferenceStore != null)
835 // preferenceStore.removePropertyChangeListener(this);
837 // StyledText text = sourceViewer.getTextWidget();
838 // if (text == null || text.isDisposed())
841 // text.removeKeyListener(this);
842 // text.removeMouseListener(this);
843 // text.removeMouseMoveListener(this);
844 // text.removeFocusListener(this);
845 // text.removePaintListener(this);
849 // * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
851 // public void propertyChange(PropertyChangeEvent event) {
852 // if (event.getProperty().equals(PHPEditor.LINK_COLOR)) {
853 // ISourceViewer viewer = getSourceViewer();
854 // if (viewer != null)
855 // updateColor(viewer);
856 // } else if (event.getProperty().equals(BROWSER_LIKE_LINKS_KEY_MODIFIER)) {
857 // updateKeyModifierMask();
861 // private void updateColor(ISourceViewer viewer) {
862 // if (fColor != null)
865 // StyledText text = viewer.getTextWidget();
866 // if (text == null || text.isDisposed())
869 // Display display = text.getDisplay();
870 // fColor = createColor(getPreferenceStore(), PHPEditor.LINK_COLOR,
875 // * Creates a color from the information stored in the given preference
876 // store. Returns <code>null</code> if there is no such
877 // * information available.
879 // private Color createColor(IPreferenceStore store, String key, Display
884 // if (store.contains(key)) {
886 // if (store.isDefault(key))
887 // rgb = PreferenceConverter.getDefaultColor(store, key);
889 // rgb = PreferenceConverter.getColor(store, key);
892 // return new Color(display, rgb);
898 // private void repairRepresentation() {
899 // repairRepresentation(false);
902 // private void repairRepresentation(boolean redrawAll) {
904 // if (fActiveRegion == null)
907 // ISourceViewer viewer = getSourceViewer();
908 // if (viewer != null) {
909 // resetCursor(viewer);
911 // int offset = fActiveRegion.getOffset();
912 // int length = fActiveRegion.getLength();
915 // if (!redrawAll && viewer instanceof ITextViewerExtension2)
916 // ((ITextViewerExtension2) viewer).invalidateTextPresentation(offset,
919 // viewer.invalidateTextPresentation();
921 // // remove underline
922 // if (viewer instanceof ITextViewerExtension3) {
923 // ITextViewerExtension3 extension = (ITextViewerExtension3) viewer;
924 // offset = extension.modelOffset2WidgetOffset(offset);
926 // offset -= viewer.getVisibleRegion().getOffset();
929 // StyledText text = viewer.getTextWidget();
931 // text.redrawRange(offset, length, true);
932 // } catch (IllegalArgumentException x) {
933 // PHPeclipsePlugin.log(x);
937 // fActiveRegion = null;
940 // // will eventually be replaced by a method provided by jdt.core
941 // private IRegion selectWord(IDocument document, int anchor) {
944 // int offset = anchor;
947 // while (offset >= 0) {
948 // c = document.getChar(offset);
949 // if (!Scanner.isPHPIdentifierPart(c))
954 // int start = offset;
957 // int length = document.getLength();
959 // while (offset < length) {
960 // c = document.getChar(offset);
961 // if (!Scanner.isPHPIdentifierPart(c))
969 // return new Region(start, 0);
971 // return new Region(start + 1, end - start - 1);
973 // } catch (BadLocationException x) {
978 // IRegion getCurrentTextRegion(ISourceViewer viewer) {
980 // int offset = getCurrentTextOffset(viewer);
985 // // IJavaElement input= SelectionConverter.getInput(PHPEditor.this);
986 // // if (input == null)
991 // // IJavaElement[] elements= null;
992 // // synchronized (input) {
993 // // elements= ((ICodeAssist) input).codeSelect(offset, 0);
996 // // if (elements == null || elements.length == 0)
999 // // return selectWord(viewer.getDocument(), offset);
1001 // // } catch (JavaModelException e) {
1006 // private int getCurrentTextOffset(ISourceViewer viewer) {
1009 // StyledText text = viewer.getTextWidget();
1010 // if (text == null || text.isDisposed())
1013 // Display display = text.getDisplay();
1014 // Point absolutePosition = display.getCursorLocation();
1015 // Point relativePosition = text.toControl(absolutePosition);
1017 // int widgetOffset = text.getOffsetAtLocation(relativePosition);
1018 // if (viewer instanceof ITextViewerExtension3) {
1019 // ITextViewerExtension3 extension = (ITextViewerExtension3) viewer;
1020 // return extension.widgetOffset2ModelOffset(widgetOffset);
1022 // return widgetOffset + viewer.getVisibleRegion().getOffset();
1025 // } catch (IllegalArgumentException e) {
1030 // private void highlightRegion(ISourceViewer viewer, IRegion region) {
1032 // if (region.equals(fActiveRegion))
1035 // repairRepresentation();
1037 // StyledText text = viewer.getTextWidget();
1038 // if (text == null || text.isDisposed())
1041 // // highlight region
1045 // if (viewer instanceof ITextViewerExtension3) {
1046 // ITextViewerExtension3 extension = (ITextViewerExtension3) viewer;
1047 // IRegion widgetRange = extension.modelRange2WidgetRange(region);
1048 // if (widgetRange == null)
1051 // offset = widgetRange.getOffset();
1052 // length = widgetRange.getLength();
1055 // offset = region.getOffset() - viewer.getVisibleRegion().getOffset();
1056 // length = region.getLength();
1059 // StyleRange oldStyleRange = text.getStyleRangeAtOffset(offset);
1060 // Color foregroundColor = fColor;
1061 // Color backgroundColor = oldStyleRange == null ? text.getBackground() :
1062 // oldStyleRange.background;
1063 // StyleRange styleRange = new StyleRange(offset, length, foregroundColor,
1064 // backgroundColor);
1065 // text.setStyleRange(styleRange);
1068 // text.redrawRange(offset, length, true);
1070 // fActiveRegion = region;
1073 // private void activateCursor(ISourceViewer viewer) {
1074 // StyledText text = viewer.getTextWidget();
1075 // if (text == null || text.isDisposed())
1077 // Display display = text.getDisplay();
1078 // if (fCursor == null)
1079 // fCursor = new Cursor(display, SWT.CURSOR_HAND);
1080 // text.setCursor(fCursor);
1083 // private void resetCursor(ISourceViewer viewer) {
1084 // StyledText text = viewer.getTextWidget();
1085 // if (text != null && !text.isDisposed())
1086 // text.setCursor(null);
1088 // if (fCursor != null) {
1089 // fCursor.dispose();
1096 // org.eclipse.swt.events.KeyListener#keyPressed(org.eclipse.swt.events.KeyEvent)
1098 // public void keyPressed(KeyEvent event) {
1105 // if (event.keyCode != fKeyModifierMask) {
1112 // // removed for #25871
1114 // // ISourceViewer viewer= getSourceViewer();
1115 // // if (viewer == null)
1118 // // IRegion region= getCurrentTextRegion(viewer);
1119 // // if (region == null)
1122 // // highlightRegion(viewer, region);
1123 // // activateCursor(viewer);
1128 // org.eclipse.swt.events.KeyListener#keyReleased(org.eclipse.swt.events.KeyEvent)
1130 // public void keyReleased(KeyEvent event) {
1140 // org.eclipse.swt.events.MouseListener#mouseDoubleClick(org.eclipse.swt.events.MouseEvent)
1142 // public void mouseDoubleClick(MouseEvent e) {
1147 // org.eclipse.swt.events.MouseListener#mouseDown(org.eclipse.swt.events.MouseEvent)
1149 // public void mouseDown(MouseEvent event) {
1154 // if (event.stateMask != fKeyModifierMask) {
1159 // if (event.button != 1) {
1167 // org.eclipse.swt.events.MouseListener#mouseUp(org.eclipse.swt.events.MouseEvent)
1169 // public void mouseUp(MouseEvent e) {
1174 // if (e.button != 1) {
1179 // boolean wasActive = fCursor != null;
1184 // IAction action = getAction("OpenEditor"); //$NON-NLS-1$
1185 // if (action != null)
1192 // org.eclipse.swt.events.MouseMoveListener#mouseMove(org.eclipse.swt.events.MouseEvent)
1194 // public void mouseMove(MouseEvent event) {
1196 // if (event.widget instanceof Control && !((Control)
1197 // event.widget).isFocusControl()) {
1203 // if (event.stateMask != fKeyModifierMask)
1205 // // modifier was already pressed
1209 // ISourceViewer viewer = getSourceViewer();
1210 // if (viewer == null) {
1215 // StyledText text = viewer.getTextWidget();
1216 // if (text == null || text.isDisposed()) {
1221 // if ((event.stateMask & SWT.BUTTON1) != 0 && text.getSelectionCount() !=
1228 // IRegion region = getCurrentTextRegion(viewer);
1229 // if (region == null || region.getLength() == 0) {
1230 // repairRepresentation();
1234 // highlightRegion(viewer, region);
1235 // activateCursor(viewer);
1240 // org.eclipse.swt.events.FocusListener#focusGained(org.eclipse.swt.events.FocusEvent)
1242 // public void focusGained(FocusEvent e) {
1247 // org.eclipse.swt.events.FocusListener#focusLost(org.eclipse.swt.events.FocusEvent)
1249 // public void focusLost(FocusEvent event) {
1255 // org.eclipse.jface.text.IDocumentListener#documentAboutToBeChanged(org.eclipse.jface.text.DocumentEvent)
1257 // public void documentAboutToBeChanged(DocumentEvent event) {
1258 // if (fActive && fActiveRegion != null) {
1259 // fRememberedPosition = new Position(fActiveRegion.getOffset(),
1260 // fActiveRegion.getLength());
1262 // event.getDocument().addPosition(fRememberedPosition);
1263 // } catch (BadLocationException x) {
1264 // fRememberedPosition = null;
1271 // org.eclipse.jface.text.IDocumentListener#documentChanged(org.eclipse.jface.text.DocumentEvent)
1273 // public void documentChanged(DocumentEvent event) {
1274 // if (fRememberedPosition != null && !fRememberedPosition.isDeleted()) {
1275 // event.getDocument().removePosition(fRememberedPosition);
1276 // fActiveRegion = new Region(fRememberedPosition.getOffset(),
1277 // fRememberedPosition.getLength());
1279 // fRememberedPosition = null;
1281 // ISourceViewer viewer = getSourceViewer();
1282 // if (viewer != null) {
1283 // StyledText widget = viewer.getTextWidget();
1284 // if (widget != null && !widget.isDisposed()) {
1285 // widget.getDisplay().asyncExec(new Runnable() {
1286 // public void run() {
1296 // org.eclipse.jface.text.ITextInputListener#inputDocumentAboutToBeChanged(org.eclipse.jface.text.IDocument,
1297 // * org.eclipse.jface.text.IDocument)
1299 // public void inputDocumentAboutToBeChanged(IDocument oldInput, IDocument
1301 // if (oldInput == null)
1304 // oldInput.removeDocumentListener(this);
1309 // org.eclipse.jface.text.ITextInputListener#inputDocumentChanged(org.eclipse.jface.text.IDocument,
1310 // * org.eclipse.jface.text.IDocument)
1312 // public void inputDocumentChanged(IDocument oldInput, IDocument newInput)
1314 // if (newInput == null)
1316 // newInput.addDocumentListener(this);
1320 // * @see PaintListener#paintControl(PaintEvent)
1322 // public void paintControl(PaintEvent event) {
1323 // if (fActiveRegion == null)
1326 // ISourceViewer viewer = getSourceViewer();
1327 // if (viewer == null)
1330 // StyledText text = viewer.getTextWidget();
1331 // if (text == null || text.isDisposed())
1337 // if (viewer instanceof ITextViewerExtension3) {
1339 // ITextViewerExtension3 extension = (ITextViewerExtension3) viewer;
1340 // IRegion widgetRange = extension.modelRange2WidgetRange(new Region(offset,
1342 // if (widgetRange == null)
1345 // offset = widgetRange.getOffset();
1346 // length = widgetRange.getLength();
1350 // IRegion region = viewer.getVisibleRegion();
1351 // if (!includes(region, fActiveRegion))
1354 // offset = fActiveRegion.getOffset() - region.getOffset();
1355 // length = fActiveRegion.getLength();
1358 // // support for bidi
1359 // Point minLocation = getMinimumLocation(text, offset, length);
1360 // Point maxLocation = getMaximumLocation(text, offset, length);
1362 // int x1 = minLocation.x;
1363 // int x2 = minLocation.x + maxLocation.x - minLocation.x - 1;
1364 // int y = minLocation.y + text.getLineHeight() - 1;
1366 // GC gc = event.gc;
1367 // if (fColor != null && !fColor.isDisposed())
1368 // gc.setForeground(fColor);
1369 // gc.drawLine(x1, y, x2, y);
1372 // private boolean includes(IRegion region, IRegion position) {
1373 // return position.getOffset() >= region.getOffset()
1374 // && position.getOffset() + position.getLength() <= region.getOffset() +
1375 // region.getLength();
1378 // private Point getMinimumLocation(StyledText text, int offset, int length)
1380 // Point minLocation = new Point(Integer.MAX_VALUE, Integer.MAX_VALUE);
1382 // for (int i = 0; i <= length; i++) {
1383 // Point location = text.getLocationAtOffset(offset + i);
1385 // if (location.x < minLocation.x)
1386 // minLocation.x = location.x;
1387 // if (location.y < minLocation.y)
1388 // minLocation.y = location.y;
1391 // return minLocation;
1394 // private Point getMaximumLocation(StyledText text, int offset, int length)
1396 // Point maxLocation = new Point(Integer.MIN_VALUE, Integer.MIN_VALUE);
1398 // for (int i = 0; i <= length; i++) {
1399 // Point location = text.getLocationAtOffset(offset + i);
1401 // if (location.x > maxLocation.x)
1402 // maxLocation.x = location.x;
1403 // if (location.y > maxLocation.y)
1404 // maxLocation.y = location.y;
1407 // return maxLocation;
1413 class MouseClickListener implements KeyListener, MouseListener,
1414 MouseMoveListener, FocusListener, PaintListener,
1415 IPropertyChangeListener, IDocumentListener, ITextInputListener,
1416 ITextPresentationListener {
1418 /** The session is active. */
1419 private boolean fActive;
1421 /** The currently active style range. */
1422 private IRegion fActiveRegion;
1424 /** The currently active style range as position. */
1425 private Position fRememberedPosition;
1427 /** The hand cursor. */
1428 private Cursor fCursor;
1430 /** The link color. */
1431 private Color fColor;
1433 /** The key modifier mask. */
1434 private int fKeyModifierMask;
1436 public void deactivate() {
1440 public void deactivate(boolean redrawAll) {
1444 repairRepresentation(redrawAll);
1448 public void install() {
1449 ISourceViewer sourceViewer = getSourceViewer();
1450 if (sourceViewer == null)
1453 StyledText text = sourceViewer.getTextWidget();
1454 if (text == null || text.isDisposed())
1457 updateColor(sourceViewer);
1459 sourceViewer.addTextInputListener(this);
1461 IDocument document = sourceViewer.getDocument();
1462 if (document != null)
1463 document.addDocumentListener(this);
1465 text.addKeyListener(this);
1466 text.addMouseListener(this);
1467 text.addMouseMoveListener(this);
1468 text.addFocusListener(this);
1469 text.addPaintListener(this);
1471 ((ITextViewerExtension4) sourceViewer)
1472 .addTextPresentationListener(this);
1474 updateKeyModifierMask();
1476 IPreferenceStore preferenceStore = getPreferenceStore();
1477 preferenceStore.addPropertyChangeListener(this);
1480 private void updateKeyModifierMask() {
1481 String modifiers = getPreferenceStore().getString(
1482 BROWSER_LIKE_LINKS_KEY_MODIFIER);
1483 fKeyModifierMask = computeStateMask(modifiers);
1484 if (fKeyModifierMask == -1) {
1485 // Fall back to stored state mask
1486 fKeyModifierMask = getPreferenceStore().getInt(
1487 BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK);
1491 private int computeStateMask(String modifiers) {
1492 if (modifiers == null)
1495 if (modifiers.length() == 0)
1499 StringTokenizer modifierTokenizer = new StringTokenizer(modifiers,
1500 ",;.:+-* "); //$NON-NLS-1$
1501 while (modifierTokenizer.hasMoreTokens()) {
1502 int modifier = EditorUtility
1503 .findLocalizedModifier(modifierTokenizer.nextToken());
1504 if (modifier == 0 || (stateMask & modifier) == modifier)
1506 stateMask = stateMask | modifier;
1511 public void uninstall() {
1513 if (fColor != null) {
1518 if (fCursor != null) {
1523 ISourceViewer sourceViewer = getSourceViewer();
1524 if (sourceViewer != null)
1525 sourceViewer.removeTextInputListener(this);
1527 IDocumentProvider documentProvider = getDocumentProvider();
1528 if (documentProvider != null) {
1529 IDocument document = documentProvider
1530 .getDocument(getEditorInput());
1531 if (document != null)
1532 document.removeDocumentListener(this);
1535 IPreferenceStore preferenceStore = getPreferenceStore();
1536 if (preferenceStore != null)
1537 preferenceStore.removePropertyChangeListener(this);
1539 if (sourceViewer == null)
1542 StyledText text = sourceViewer.getTextWidget();
1543 if (text == null || text.isDisposed())
1546 text.removeKeyListener(this);
1547 text.removeMouseListener(this);
1548 text.removeMouseMoveListener(this);
1549 text.removeFocusListener(this);
1550 text.removePaintListener(this);
1552 ((ITextViewerExtension4) sourceViewer)
1553 .removeTextPresentationListener(this);
1557 * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
1559 public void propertyChange(PropertyChangeEvent event) {
1560 if (event.getProperty().equals(PHPEditor.LINK_COLOR)) {
1561 ISourceViewer viewer = getSourceViewer();
1563 updateColor(viewer);
1564 } else if (event.getProperty().equals(
1565 BROWSER_LIKE_LINKS_KEY_MODIFIER)) {
1566 updateKeyModifierMask();
1570 private void updateColor(ISourceViewer viewer) {
1574 StyledText text = viewer.getTextWidget();
1575 if (text == null || text.isDisposed())
1578 Display display = text.getDisplay();
1579 fColor = createColor(getPreferenceStore(), PHPEditor.LINK_COLOR,
1584 * Creates a color from the information stored in the given preference
1588 * the preference store
1593 * @return the color or <code>null</code> if there is no such
1594 * information available
1596 private Color createColor(IPreferenceStore store, String key,
1601 if (store.contains(key)) {
1603 if (store.isDefault(key))
1604 rgb = PreferenceConverter.getDefaultColor(store, key);
1606 rgb = PreferenceConverter.getColor(store, key);
1609 return new Color(display, rgb);
1615 private void repairRepresentation() {
1616 repairRepresentation(false);
1619 private void repairRepresentation(boolean redrawAll) {
1621 if (fActiveRegion == null)
1624 int offset = fActiveRegion.getOffset();
1625 int length = fActiveRegion.getLength();
1626 fActiveRegion = null;
1628 ISourceViewer viewer = getSourceViewer();
1629 if (viewer != null) {
1631 resetCursor(viewer);
1633 // Invalidate ==> remove applied text presentation
1634 if (!redrawAll && viewer instanceof ITextViewerExtension2)
1635 ((ITextViewerExtension2) viewer)
1636 .invalidateTextPresentation(offset, length);
1638 viewer.invalidateTextPresentation();
1641 if (viewer instanceof ITextViewerExtension5) {
1642 ITextViewerExtension5 extension = (ITextViewerExtension5) viewer;
1643 offset = extension.modelOffset2WidgetOffset(offset);
1645 offset -= viewer.getVisibleRegion().getOffset();
1648 StyledText text = viewer.getTextWidget();
1650 text.redrawRange(offset, length, false);
1651 } catch (IllegalArgumentException x) {
1652 // JavaPlugin.log(x);
1657 // will eventually be replaced by a method provided by jdt.core
1658 private IRegion selectWord(IDocument document, int anchor) {
1661 int offset = anchor;
1664 while (offset >= 0) {
1665 c = document.getChar(offset);
1666 if (!Scanner.isPHPIdentifierPart(c) && c != '$')
1674 int length = document.getLength();
1676 while (offset < length) {
1677 c = document.getChar(offset);
1678 if (!Scanner.isPHPIdentifierPart(c) && c != '$')
1686 return new Region(start, 0);
1688 return new Region(start + 1, end - start - 1);
1690 } catch (BadLocationException x) {
1695 IRegion getCurrentTextRegion(ISourceViewer viewer) {
1697 int offset = getCurrentTextOffset(viewer);
1701 IJavaElement input = SelectionConverter.getInput(PHPEditor.this);
1707 // IJavaElement[] elements= null;
1708 // synchronized (input) {
1709 // elements= ((ICodeAssist) input).codeSelect(offset, 0);
1712 // if (elements == null || elements.length == 0)
1715 return selectWord(viewer.getDocument(), offset);
1717 // } catch (JavaModelException e) {
1722 private int getCurrentTextOffset(ISourceViewer viewer) {
1725 StyledText text = viewer.getTextWidget();
1726 if (text == null || text.isDisposed())
1729 Display display = text.getDisplay();
1730 Point absolutePosition = display.getCursorLocation();
1731 Point relativePosition = text.toControl(absolutePosition);
1733 int widgetOffset = text.getOffsetAtLocation(relativePosition);
1734 if (viewer instanceof ITextViewerExtension5) {
1735 ITextViewerExtension5 extension = (ITextViewerExtension5) viewer;
1736 return extension.widgetOffset2ModelOffset(widgetOffset);
1738 return widgetOffset + viewer.getVisibleRegion().getOffset();
1741 } catch (IllegalArgumentException e) {
1746 public void applyTextPresentation(TextPresentation textPresentation) {
1747 if (fActiveRegion == null)
1749 IRegion region = textPresentation.getExtent();
1750 if (fActiveRegion.getOffset() + fActiveRegion.getLength() >= region
1752 && region.getOffset() + region.getLength() > fActiveRegion
1754 textPresentation.mergeStyleRange(new StyleRange(fActiveRegion
1755 .getOffset(), fActiveRegion.getLength(), fColor, null));
1758 private void highlightRegion(ISourceViewer viewer, IRegion region) {
1760 if (region.equals(fActiveRegion))
1763 repairRepresentation();
1765 StyledText text = viewer.getTextWidget();
1766 if (text == null || text.isDisposed())
1772 if (viewer instanceof ITextViewerExtension5) {
1773 ITextViewerExtension5 extension = (ITextViewerExtension5) viewer;
1774 IRegion widgetRange = extension.modelRange2WidgetRange(region);
1775 if (widgetRange == null)
1778 offset = widgetRange.getOffset();
1779 length = widgetRange.getLength();
1782 offset = region.getOffset()
1783 - viewer.getVisibleRegion().getOffset();
1784 length = region.getLength();
1786 text.redrawRange(offset, length, false);
1788 // Invalidate region ==> apply text presentation
1789 fActiveRegion = region;
1790 if (viewer instanceof ITextViewerExtension2)
1791 ((ITextViewerExtension2) viewer).invalidateTextPresentation(
1792 region.getOffset(), region.getLength());
1794 viewer.invalidateTextPresentation();
1797 private void activateCursor(ISourceViewer viewer) {
1798 StyledText text = viewer.getTextWidget();
1799 if (text == null || text.isDisposed())
1801 Display display = text.getDisplay();
1802 if (fCursor == null)
1803 fCursor = new Cursor(display, SWT.CURSOR_HAND);
1804 text.setCursor(fCursor);
1807 private void resetCursor(ISourceViewer viewer) {
1808 StyledText text = viewer.getTextWidget();
1809 if (text != null && !text.isDisposed())
1810 text.setCursor(null);
1812 if (fCursor != null) {
1819 * @see org.eclipse.swt.events.KeyListener#keyPressed(org.eclipse.swt.events.KeyEvent)
1821 public void keyPressed(KeyEvent event) {
1828 if (event.keyCode != fKeyModifierMask) {
1835 // removed for #25871
1837 // ISourceViewer viewer= getSourceViewer();
1838 // if (viewer == null)
1841 // IRegion region= getCurrentTextRegion(viewer);
1842 // if (region == null)
1845 // highlightRegion(viewer, region);
1846 // activateCursor(viewer);
1850 * @see org.eclipse.swt.events.KeyListener#keyReleased(org.eclipse.swt.events.KeyEvent)
1852 public void keyReleased(KeyEvent event) {
1861 * @see org.eclipse.swt.events.MouseListener#mouseDoubleClick(org.eclipse.swt.events.MouseEvent)
1863 public void mouseDoubleClick(MouseEvent e) {
1867 * @see org.eclipse.swt.events.MouseListener#mouseDown(org.eclipse.swt.events.MouseEvent)
1869 public void mouseDown(MouseEvent event) {
1874 if (event.stateMask != fKeyModifierMask) {
1879 if (event.button != 1) {
1886 * @see org.eclipse.swt.events.MouseListener#mouseUp(org.eclipse.swt.events.MouseEvent)
1888 public void mouseUp(MouseEvent e) {
1893 if (e.button != 1) {
1898 boolean wasActive = fCursor != null;
1903 IAction action = getAction("OpenEditor"); //$NON-NLS-1$
1910 * @see org.eclipse.swt.events.MouseMoveListener#mouseMove(org.eclipse.swt.events.MouseEvent)
1912 public void mouseMove(MouseEvent event) {
1914 if (event.widget instanceof Control
1915 && !((Control) event.widget).isFocusControl()) {
1921 if (event.stateMask != fKeyModifierMask)
1923 // modifier was already pressed
1927 ISourceViewer viewer = getSourceViewer();
1928 if (viewer == null) {
1933 StyledText text = viewer.getTextWidget();
1934 if (text == null || text.isDisposed()) {
1939 if ((event.stateMask & SWT.BUTTON1) != 0
1940 && text.getSelectionCount() != 0) {
1945 IRegion region = getCurrentTextRegion(viewer);
1946 if (region == null || region.getLength() == 0) {
1947 repairRepresentation();
1951 highlightRegion(viewer, region);
1952 activateCursor(viewer);
1956 * @see org.eclipse.swt.events.FocusListener#focusGained(org.eclipse.swt.events.FocusEvent)
1958 public void focusGained(FocusEvent e) {
1962 * @see org.eclipse.swt.events.FocusListener#focusLost(org.eclipse.swt.events.FocusEvent)
1964 public void focusLost(FocusEvent event) {
1969 * @see org.eclipse.jface.text.IDocumentListener#documentAboutToBeChanged(org.eclipse.jface.text.DocumentEvent)
1971 public void documentAboutToBeChanged(DocumentEvent event) {
1972 if (fActive && fActiveRegion != null) {
1973 fRememberedPosition = new Position(fActiveRegion.getOffset(),
1974 fActiveRegion.getLength());
1976 event.getDocument().addPosition(fRememberedPosition);
1977 } catch (BadLocationException x) {
1978 fRememberedPosition = null;
1984 * @see org.eclipse.jface.text.IDocumentListener#documentChanged(org.eclipse.jface.text.DocumentEvent)
1986 public void documentChanged(DocumentEvent event) {
1987 if (fRememberedPosition != null) {
1988 if (!fRememberedPosition.isDeleted()) {
1990 event.getDocument().removePosition(fRememberedPosition);
1991 fActiveRegion = new Region(fRememberedPosition.getOffset(),
1992 fRememberedPosition.getLength());
1993 fRememberedPosition = null;
1995 ISourceViewer viewer = getSourceViewer();
1996 if (viewer != null) {
1997 StyledText widget = viewer.getTextWidget();
1998 if (widget != null && !widget.isDisposed()) {
1999 widget.getDisplay().asyncExec(new Runnable() {
2008 fActiveRegion = null;
2009 fRememberedPosition = null;
2016 * @see org.eclipse.jface.text.ITextInputListener#inputDocumentAboutToBeChanged(org.eclipse.jface.text.IDocument,
2017 * org.eclipse.jface.text.IDocument)
2019 public void inputDocumentAboutToBeChanged(IDocument oldInput,
2020 IDocument newInput) {
2021 if (oldInput == null)
2024 oldInput.removeDocumentListener(this);
2028 * @see org.eclipse.jface.text.ITextInputListener#inputDocumentChanged(org.eclipse.jface.text.IDocument,
2029 * org.eclipse.jface.text.IDocument)
2031 public void inputDocumentChanged(IDocument oldInput, IDocument newInput) {
2032 if (newInput == null)
2034 newInput.addDocumentListener(this);
2038 * @see PaintListener#paintControl(PaintEvent)
2040 public void paintControl(PaintEvent event) {
2041 if (fActiveRegion == null)
2044 ISourceViewer viewer = getSourceViewer();
2048 StyledText text = viewer.getTextWidget();
2049 if (text == null || text.isDisposed())
2055 if (viewer instanceof ITextViewerExtension5) {
2057 ITextViewerExtension5 extension = (ITextViewerExtension5) viewer;
2058 IRegion widgetRange = extension
2059 .modelRange2WidgetRange(fActiveRegion);
2060 if (widgetRange == null)
2063 offset = widgetRange.getOffset();
2064 length = widgetRange.getLength();
2068 IRegion region = viewer.getVisibleRegion();
2069 if (!includes(region, fActiveRegion))
2072 offset = fActiveRegion.getOffset() - region.getOffset();
2073 length = fActiveRegion.getLength();
2077 Point minLocation = getMinimumLocation(text, offset, length);
2078 Point maxLocation = getMaximumLocation(text, offset, length);
2080 int x1 = minLocation.x;
2081 int x2 = minLocation.x + maxLocation.x - minLocation.x - 1;
2082 int y = minLocation.y + text.getLineHeight() - 1;
2085 if (fColor != null && !fColor.isDisposed())
2086 gc.setForeground(fColor);
2087 gc.drawLine(x1, y, x2, y);
2090 private boolean includes(IRegion region, IRegion position) {
2091 return position.getOffset() >= region.getOffset()
2092 && position.getOffset() + position.getLength() <= region
2094 + region.getLength();
2097 private Point getMinimumLocation(StyledText text, int offset, int length) {
2098 Point minLocation = new Point(Integer.MAX_VALUE, Integer.MAX_VALUE);
2100 for (int i = 0; i <= length; i++) {
2101 Point location = text.getLocationAtOffset(offset + i);
2103 if (location.x < minLocation.x)
2104 minLocation.x = location.x;
2105 if (location.y < minLocation.y)
2106 minLocation.y = location.y;
2112 private Point getMaximumLocation(StyledText text, int offset, int length) {
2113 Point maxLocation = new Point(Integer.MIN_VALUE, Integer.MIN_VALUE);
2115 for (int i = 0; i <= length; i++) {
2116 Point location = text.getLocationAtOffset(offset + i);
2118 if (location.x > maxLocation.x)
2119 maxLocation.x = location.x;
2120 if (location.y > maxLocation.y)
2121 maxLocation.y = location.y;
2129 * This action dispatches into two behaviours: If there is no current text
2130 * hover, the javadoc is displayed using information presenter. If there is
2131 * a current text hover, it is converted into a information presenter in
2132 * order to make it sticky.
2134 class InformationDispatchAction extends TextEditorAction {
2136 /** The wrapped text operation action. */
2137 private final TextOperationAction fTextOperationAction;
2140 * Creates a dispatch action.
2142 public InformationDispatchAction(ResourceBundle resourceBundle,
2143 String prefix, final TextOperationAction textOperationAction) {
2144 super(resourceBundle, prefix, PHPEditor.this);
2145 if (textOperationAction == null)
2146 throw new IllegalArgumentException();
2147 fTextOperationAction = textOperationAction;
2151 * @see org.eclipse.jface.action.IAction#run()
2155 ISourceViewer sourceViewer = getSourceViewer();
2156 if (sourceViewer == null) {
2157 fTextOperationAction.run();
2161 if (!(sourceViewer instanceof ITextViewerExtension2)) {
2162 fTextOperationAction.run();
2166 ITextViewerExtension2 textViewerExtension2 = (ITextViewerExtension2) sourceViewer;
2168 // does a text hover exist?
2169 ITextHover textHover = textViewerExtension2.getCurrentTextHover();
2170 if (textHover == null) {
2171 fTextOperationAction.run();
2175 Point hoverEventLocation = textViewerExtension2
2176 .getHoverEventLocation();
2177 int offset = computeOffsetAtLocation(sourceViewer,
2178 hoverEventLocation.x, hoverEventLocation.y);
2180 fTextOperationAction.run();
2185 // get the text hover content
2186 IDocument document = sourceViewer.getDocument();
2187 String contentType = document.getContentType(offset);
2189 final IRegion hoverRegion = textHover.getHoverRegion(
2190 sourceViewer, offset);
2191 if (hoverRegion == null)
2194 final String hoverInfo = textHover.getHoverInfo(sourceViewer,
2197 // with information provider
2198 IInformationProvider informationProvider = new IInformationProvider() {
2200 * @see org.eclipse.jface.text.information.IInformationProvider#getSubject(org.eclipse.jface.text.ITextViewer,
2203 public IRegion getSubject(ITextViewer textViewer, int offset) {
2208 * @see org.eclipse.jface.text.information.IInformationProvider#getInformation(org.eclipse.jface.text.ITextViewer,
2209 * org.eclipse.jface.text.IRegion)
2211 public String getInformation(ITextViewer textViewer,
2217 fInformationPresenter.setOffset(offset);
2218 fInformationPresenter.setInformationProvider(
2219 informationProvider, contentType);
2220 fInformationPresenter.showInformation();
2222 } catch (BadLocationException e) {
2226 // modified version from TextViewer
2227 private int computeOffsetAtLocation(ITextViewer textViewer, int x, int y) {
2229 StyledText styledText = textViewer.getTextWidget();
2230 IDocument document = textViewer.getDocument();
2232 if (document == null)
2236 int widgetLocation = styledText.getOffsetAtLocation(new Point(
2238 if (textViewer instanceof ITextViewerExtension5) {
2239 ITextViewerExtension5 extension = (ITextViewerExtension5) textViewer;
2240 return extension.widgetOffset2ModelOffset(widgetLocation);
2242 IRegion visibleRegion = textViewer.getVisibleRegion();
2243 return widgetLocation + visibleRegion.getOffset();
2245 } catch (IllegalArgumentException e) {
2253 * This action implements smart home.
2255 * Instead of going to the start of a line it does the following: - if smart
2256 * home/end is enabled and the caret is after the line's first
2257 * non-whitespace then the caret is moved directly before it, taking JavaDoc
2258 * and multi-line comments into account. - if the caret is before the line's
2259 * first non-whitespace the caret is moved to the beginning of the line - if
2260 * the caret is at the beginning of the line see first case.
2264 protected class SmartLineStartAction extends LineStartAction {
2267 * Creates a new smart line start action
2270 * the styled text widget
2272 * a boolean flag which tells if the text up to the beginning
2273 * of the line should be selected
2275 public SmartLineStartAction(final StyledText textWidget,
2276 final boolean doSelect) {
2277 super(textWidget, doSelect);
2281 * @see org.eclipse.ui.texteditor.AbstractTextEditor.LineStartAction#getLineStartPosition(java.lang.String,
2282 * int, java.lang.String)
2284 protected int getLineStartPosition(final IDocument document,
2285 final String line, final int length, final int offset) {
2287 String type = IDocument.DEFAULT_CONTENT_TYPE;
2289 type = TextUtilities.getContentType(document,
2290 IPHPPartitions.PHP_PARTITIONING, offset, true);
2291 } catch (BadLocationException exception) {
2292 // Should not happen
2295 int index = super.getLineStartPosition(document, line, length,
2297 if (type.equals(IPHPPartitions.PHP_PHPDOC_COMMENT)
2298 || type.equals(IPHPPartitions.PHP_MULTILINE_COMMENT)) {
2299 if (index < length - 1 && line.charAt(index) == '*'
2300 && line.charAt(index + 1) != '/') {
2303 } while (index < length
2304 && Character.isWhitespace(line.charAt(index)));
2307 if (index < length - 1 && line.charAt(index) == '/'
2308 && line.charAt(index + 1) == '/') {
2312 } while (index < length
2313 && Character.isWhitespace(line.charAt(index)));
2321 * Text navigation action to navigate to the next sub-word.
2325 protected abstract class NextSubWordAction extends TextNavigationAction {
2327 protected JavaWordIterator fIterator = new JavaWordIterator();
2330 * Creates a new next sub-word action.
2333 * Action code for the default operation. Must be an action
2335 * @see org.eclipse.swt.custom.ST.
2337 protected NextSubWordAction(int code) {
2338 super(getSourceViewer().getTextWidget(), code);
2342 * @see org.eclipse.jface.action.IAction#run()
2345 // Check whether we are in a java code partition and the preference
2348 final IPreferenceStore store = getPreferenceStore();
2350 .getBoolean(PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION)) {
2355 final ISourceViewer viewer = getSourceViewer();
2356 final IDocument document = viewer.getDocument();
2358 .setText((CharacterIterator) new DocumentCharacterIterator(
2360 int position = widgetOffset2ModelOffset(viewer, viewer
2361 .getTextWidget().getCaretOffset());
2365 int next = findNextPosition(position);
2366 if (next != BreakIterator.DONE) {
2367 setCaretPosition(next);
2368 getTextWidget().showSelection();
2369 fireSelectionChanged();
2375 * Finds the next position after the given position.
2378 * the current position
2379 * @return the next position
2381 protected int findNextPosition(int position) {
2382 ISourceViewer viewer = getSourceViewer();
2384 while (position != BreakIterator.DONE && widget == -1) { // TODO:
2386 position = fIterator.following(position);
2387 if (position != BreakIterator.DONE)
2388 widget = modelOffset2WidgetOffset(viewer, position);
2394 * Sets the caret position to the sub-word boundary given with
2395 * <code>position</code>.
2398 * Position where the action should move the caret
2400 protected abstract void setCaretPosition(int position);
2404 * Text navigation action to navigate to the next sub-word.
2408 protected class NavigateNextSubWordAction extends NextSubWordAction {
2411 * Creates a new navigate next sub-word action.
2413 public NavigateNextSubWordAction() {
2414 super(ST.WORD_NEXT);
2418 * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor.NextSubWordAction#setCaretPosition(int)
2420 protected void setCaretPosition(final int position) {
2421 getTextWidget().setCaretOffset(
2422 modelOffset2WidgetOffset(getSourceViewer(), position));
2427 * Text operation action to delete the next sub-word.
2431 protected class DeleteNextSubWordAction extends NextSubWordAction implements
2435 * Creates a new delete next sub-word action.
2437 public DeleteNextSubWordAction() {
2438 super(ST.DELETE_WORD_NEXT);
2442 * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor.NextSubWordAction#setCaretPosition(int)
2444 protected void setCaretPosition(final int position) {
2445 if (!validateEditorInputState())
2448 final ISourceViewer viewer = getSourceViewer();
2449 final int caret = widgetOffset2ModelOffset(viewer, viewer
2450 .getTextWidget().getCaretOffset());
2453 viewer.getDocument().replace(caret, position - caret, ""); //$NON-NLS-1$
2454 } catch (BadLocationException exception) {
2455 // Should not happen
2460 * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor.NextSubWordAction#findNextPosition(int)
2462 protected int findNextPosition(int position) {
2463 return fIterator.following(position);
2467 * @see org.eclipse.ui.texteditor.IUpdate#update()
2469 public void update() {
2470 setEnabled(isEditorInputModifiable());
2475 * Text operation action to select the next sub-word.
2479 protected class SelectNextSubWordAction extends NextSubWordAction {
2482 * Creates a new select next sub-word action.
2484 public SelectNextSubWordAction() {
2485 super(ST.SELECT_WORD_NEXT);
2489 * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor.NextSubWordAction#setCaretPosition(int)
2491 protected void setCaretPosition(final int position) {
2492 final ISourceViewer viewer = getSourceViewer();
2494 final StyledText text = viewer.getTextWidget();
2495 if (text != null && !text.isDisposed()) {
2497 final Point selection = text.getSelection();
2498 final int caret = text.getCaretOffset();
2499 final int offset = modelOffset2WidgetOffset(viewer, position);
2501 if (caret == selection.x)
2502 text.setSelectionRange(selection.y, offset - selection.y);
2504 text.setSelectionRange(selection.x, offset - selection.x);
2510 * Text navigation action to navigate to the previous sub-word.
2514 protected abstract class PreviousSubWordAction extends TextNavigationAction {
2516 protected JavaWordIterator fIterator = new JavaWordIterator();
2519 * Creates a new previous sub-word action.
2522 * Action code for the default operation. Must be an action
2524 * @see org.eclipse.swt.custom.ST.
2526 protected PreviousSubWordAction(final int code) {
2527 super(getSourceViewer().getTextWidget(), code);
2531 * @see org.eclipse.jface.action.IAction#run()
2534 // Check whether we are in a java code partition and the preference
2537 final IPreferenceStore store = getPreferenceStore();
2539 .getBoolean(PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION)) {
2544 final ISourceViewer viewer = getSourceViewer();
2545 final IDocument document = viewer.getDocument();
2547 .setText((CharacterIterator) new DocumentCharacterIterator(
2549 int position = widgetOffset2ModelOffset(viewer, viewer
2550 .getTextWidget().getCaretOffset());
2554 int previous = findPreviousPosition(position);
2555 if (previous != BreakIterator.DONE) {
2556 setCaretPosition(previous);
2557 getTextWidget().showSelection();
2558 fireSelectionChanged();
2564 * Finds the previous position before the given position.
2567 * the current position
2568 * @return the previous position
2570 protected int findPreviousPosition(int position) {
2571 ISourceViewer viewer = getSourceViewer();
2573 while (position != BreakIterator.DONE && widget == -1) { // TODO:
2575 position = fIterator.preceding(position);
2576 if (position != BreakIterator.DONE)
2577 widget = modelOffset2WidgetOffset(viewer, position);
2583 * Sets the caret position to the sub-word boundary given with
2584 * <code>position</code>.
2587 * Position where the action should move the caret
2589 protected abstract void setCaretPosition(int position);
2593 * Text navigation action to navigate to the previous sub-word.
2597 protected class NavigatePreviousSubWordAction extends PreviousSubWordAction {
2600 * Creates a new navigate previous sub-word action.
2602 public NavigatePreviousSubWordAction() {
2603 super(ST.WORD_PREVIOUS);
2607 * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#setCaretPosition(int)
2609 protected void setCaretPosition(final int position) {
2610 getTextWidget().setCaretOffset(
2611 modelOffset2WidgetOffset(getSourceViewer(), position));
2616 * Text operation action to delete the previous sub-word.
2620 protected class DeletePreviousSubWordAction extends PreviousSubWordAction
2621 implements IUpdate {
2624 * Creates a new delete previous sub-word action.
2626 public DeletePreviousSubWordAction() {
2627 super(ST.DELETE_WORD_PREVIOUS);
2631 * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#setCaretPosition(int)
2633 protected void setCaretPosition(final int position) {
2634 if (!validateEditorInputState())
2637 final ISourceViewer viewer = getSourceViewer();
2638 final int caret = widgetOffset2ModelOffset(viewer, viewer
2639 .getTextWidget().getCaretOffset());
2642 viewer.getDocument().replace(position, caret - position, ""); //$NON-NLS-1$
2643 } catch (BadLocationException exception) {
2644 // Should not happen
2649 * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#findPreviousPosition(int)
2651 protected int findPreviousPosition(int position) {
2652 return fIterator.preceding(position);
2656 * @see org.eclipse.ui.texteditor.IUpdate#update()
2658 public void update() {
2659 setEnabled(isEditorInputModifiable());
2664 * Text operation action to select the previous sub-word.
2668 protected class SelectPreviousSubWordAction extends PreviousSubWordAction {
2671 * Creates a new select previous sub-word action.
2673 public SelectPreviousSubWordAction() {
2674 super(ST.SELECT_WORD_PREVIOUS);
2678 * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#setCaretPosition(int)
2680 protected void setCaretPosition(final int position) {
2681 final ISourceViewer viewer = getSourceViewer();
2683 final StyledText text = viewer.getTextWidget();
2684 if (text != null && !text.isDisposed()) {
2686 final Point selection = text.getSelection();
2687 final int caret = text.getCaretOffset();
2688 final int offset = modelOffset2WidgetOffset(viewer, position);
2690 if (caret == selection.x)
2691 text.setSelectionRange(selection.y, offset - selection.y);
2693 text.setSelectionRange(selection.x, offset - selection.x);
2698 // static protected class AnnotationAccess implements IAnnotationAccess {
2701 // org.eclipse.jface.text.source.IAnnotationAccess#getType(org.eclipse.jface.text.source.Annotation)
2703 // public Object getType(Annotation annotation) {
2704 // if (annotation instanceof IJavaAnnotation) {
2705 // IJavaAnnotation javaAnnotation = (IJavaAnnotation) annotation;
2706 // // if (javaAnnotation.isRelevant())
2707 // // return javaAnnotation.getAnnotationType();
2714 // org.eclipse.jface.text.source.IAnnotationAccess#isMultiLine(org.eclipse.jface.text.source.Annotation)
2716 // public boolean isMultiLine(Annotation annotation) {
2722 // org.eclipse.jface.text.source.IAnnotationAccess#isTemporary(org.eclipse.jface.text.source.Annotation)
2724 // public boolean isTemporary(Annotation annotation) {
2725 // if (annotation instanceof IJavaAnnotation) {
2726 // IJavaAnnotation javaAnnotation = (IJavaAnnotation) annotation;
2727 // if (javaAnnotation.isRelevant())
2728 // return javaAnnotation.isTemporary();
2734 private class PropertyChangeListener implements
2735 org.eclipse.core.runtime.Preferences.IPropertyChangeListener {
2737 * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
2739 public void propertyChange(
2740 org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) {
2741 handlePreferencePropertyChanged(event);
2746 * Finds and marks occurrence annotations.
2750 class OccurrencesFinderJob extends Job {
2752 private IDocument fDocument;
2754 private ISelection fSelection;
2756 private ISelectionValidator fPostSelectionValidator;
2758 private boolean fCanceled = false;
2760 private IProgressMonitor fProgressMonitor;
2762 private Position[] fPositions;
2764 public OccurrencesFinderJob(IDocument document, Position[] positions,
2765 ISelection selection) {
2766 super(PHPEditorMessages.JavaEditor_markOccurrences_job_name);
2767 fDocument = document;
2768 fSelection = selection;
2769 fPositions = positions;
2771 if (getSelectionProvider() instanceof ISelectionValidator)
2772 fPostSelectionValidator = (ISelectionValidator) getSelectionProvider();
2775 // cannot use cancel() because it is declared final
2781 private boolean isCanceled() {
2783 || fProgressMonitor.isCanceled()
2784 || fPostSelectionValidator != null
2785 && !(fPostSelectionValidator.isValid(fSelection) || fForcedMarkOccurrencesSelection == fSelection)
2786 || LinkedModeModel.hasInstalledModel(fDocument);
2790 * @see Job#run(org.eclipse.core.runtime.IProgressMonitor)
2792 public IStatus run(IProgressMonitor progressMonitor) {
2794 fProgressMonitor = progressMonitor;
2797 return Status.CANCEL_STATUS;
2799 ITextViewer textViewer = getViewer();
2800 if (textViewer == null)
2801 return Status.CANCEL_STATUS;
2803 IDocument document = textViewer.getDocument();
2804 if (document == null)
2805 return Status.CANCEL_STATUS;
2807 IDocumentProvider documentProvider = getDocumentProvider();
2808 if (documentProvider == null)
2809 return Status.CANCEL_STATUS;
2811 IAnnotationModel annotationModel = documentProvider
2812 .getAnnotationModel(getEditorInput());
2813 if (annotationModel == null)
2814 return Status.CANCEL_STATUS;
2816 // Add occurrence annotations
2817 int length = fPositions.length;
2818 Map annotationMap = new HashMap(length);
2819 for (int i = 0; i < length; i++) {
2822 return Status.CANCEL_STATUS;
2825 Position position = fPositions[i];
2827 // Create & add annotation
2829 message = document.get(position.offset, position.length);
2830 } catch (BadLocationException ex) {
2837 "net.sourceforge.phpdt.ui.occurrences", false, message), //$NON-NLS-1$
2842 return Status.CANCEL_STATUS;
2844 synchronized (getLockObject(annotationModel)) {
2845 if (annotationModel instanceof IAnnotationModelExtension) {
2846 ((IAnnotationModelExtension) annotationModel)
2847 .replaceAnnotations(fOccurrenceAnnotations,
2850 removeOccurrenceAnnotations();
2851 Iterator iter = annotationMap.entrySet().iterator();
2852 while (iter.hasNext()) {
2853 Map.Entry mapEntry = (Map.Entry) iter.next();
2854 annotationModel.addAnnotation((Annotation) mapEntry
2855 .getKey(), (Position) mapEntry.getValue());
2858 fOccurrenceAnnotations = (Annotation[]) annotationMap.keySet()
2859 .toArray(new Annotation[annotationMap.keySet().size()]);
2862 return Status.OK_STATUS;
2867 * Cancels the occurrences finder job upon document changes.
2871 class OccurrencesFinderJobCanceler implements IDocumentListener,
2872 ITextInputListener {
2874 public void install() {
2875 ISourceViewer sourceViewer = getSourceViewer();
2876 if (sourceViewer == null)
2879 StyledText text = sourceViewer.getTextWidget();
2880 if (text == null || text.isDisposed())
2883 sourceViewer.addTextInputListener(this);
2885 IDocument document = sourceViewer.getDocument();
2886 if (document != null)
2887 document.addDocumentListener(this);
2890 public void uninstall() {
2891 ISourceViewer sourceViewer = getSourceViewer();
2892 if (sourceViewer != null)
2893 sourceViewer.removeTextInputListener(this);
2895 IDocumentProvider documentProvider = getDocumentProvider();
2896 if (documentProvider != null) {
2897 IDocument document = documentProvider
2898 .getDocument(getEditorInput());
2899 if (document != null)
2900 document.removeDocumentListener(this);
2905 * @see org.eclipse.jface.text.IDocumentListener#documentAboutToBeChanged(org.eclipse.jface.text.DocumentEvent)
2907 public void documentAboutToBeChanged(DocumentEvent event) {
2908 if (fOccurrencesFinderJob != null)
2909 fOccurrencesFinderJob.doCancel();
2913 * @see org.eclipse.jface.text.IDocumentListener#documentChanged(org.eclipse.jface.text.DocumentEvent)
2915 public void documentChanged(DocumentEvent event) {
2919 * @see org.eclipse.jface.text.ITextInputListener#inputDocumentAboutToBeChanged(org.eclipse.jface.text.IDocument,
2920 * org.eclipse.jface.text.IDocument)
2922 public void inputDocumentAboutToBeChanged(IDocument oldInput,
2923 IDocument newInput) {
2924 if (oldInput == null)
2927 oldInput.removeDocumentListener(this);
2931 * @see org.eclipse.jface.text.ITextInputListener#inputDocumentChanged(org.eclipse.jface.text.IDocument,
2932 * org.eclipse.jface.text.IDocument)
2934 public void inputDocumentChanged(IDocument oldInput, IDocument newInput) {
2935 if (newInput == null)
2937 newInput.addDocumentListener(this);
2942 * Internal activation listener.
2946 private class ActivationListener implements IWindowListener {
2949 * @see org.eclipse.ui.IWindowListener#windowActivated(org.eclipse.ui.IWorkbenchWindow)
2952 public void windowActivated(IWorkbenchWindow window) {
2953 if (window == getEditorSite().getWorkbenchWindow()
2954 && fMarkOccurrenceAnnotations && isActivePart()) {
2955 fForcedMarkOccurrencesSelection = getSelectionProvider()
2957 SelectionListenerWithASTManager
2959 .forceSelectionChange(
2961 (ITextSelection) fForcedMarkOccurrencesSelection);
2966 * @see org.eclipse.ui.IWindowListener#windowDeactivated(org.eclipse.ui.IWorkbenchWindow)
2969 public void windowDeactivated(IWorkbenchWindow window) {
2970 if (window == getEditorSite().getWorkbenchWindow()
2971 && fMarkOccurrenceAnnotations && isActivePart())
2972 removeOccurrenceAnnotations();
2976 * @see org.eclipse.ui.IWindowListener#windowClosed(org.eclipse.ui.IWorkbenchWindow)
2979 public void windowClosed(IWorkbenchWindow window) {
2983 * @see org.eclipse.ui.IWindowListener#windowOpened(org.eclipse.ui.IWorkbenchWindow)
2986 public void windowOpened(IWorkbenchWindow window) {
2991 * Updates the selection in the editor's widget with the selection of the
2994 class OutlineSelectionChangedListener extends
2995 AbstractSelectionChangedListener {
2996 public void selectionChanged(SelectionChangedEvent event) {
2997 doSelectionChanged(event);
3002 * The internal shell activation listener for updating occurrences.
3006 private ActivationListener fActivationListener = new ActivationListener();
3008 private ISelectionListenerWithAST fPostSelectionListenerWithAST;
3010 private OccurrencesFinderJob fOccurrencesFinderJob;
3012 /** The occurrences finder job canceler */
3013 private OccurrencesFinderJobCanceler fOccurrencesFinderJobCanceler;
3016 * Holds the current occurrence annotations.
3020 private Annotation[] fOccurrenceAnnotations = null;
3023 * Tells whether all occurrences of the element at the current caret
3024 * location are automatically marked in this editor.
3028 private boolean fMarkOccurrenceAnnotations;
3031 * The selection used when forcing occurrence marking through code.
3035 private ISelection fForcedMarkOccurrencesSelection;
3038 * The document modification stamp at the time when the last occurrence
3039 * marking took place.
3043 private long fMarkOccurrenceModificationStamp = IDocumentExtension4.UNKNOWN_MODIFICATION_STAMP;
3046 * The region of the word under the caret used to when computing the current
3047 * occurrence markings.
3051 private IRegion fMarkOccurrenceTargetRegion;
3054 * Tells whether the occurrence annotations are sticky i.e. whether they
3055 * stay even if there's no valid Java element at the current caret position.
3056 * Only valid if {@link #fMarkOccurrenceAnnotations} is <code>true</code>.
3060 private boolean fStickyOccurrenceAnnotations;
3062 /** Preference key for showing the line number ruler */
3063 // private final static String LINE_NUMBER_RULER =
3064 // PreferenceConstants.EDITOR_LINE_NUMBER_RULER;
3065 /** Preference key for the foreground color of the line numbers */
3066 // private final static String LINE_NUMBER_COLOR =
3067 // PreferenceConstants.EDITOR_LINE_NUMBER_RULER_COLOR;
3068 /** Preference key for the link color */
3069 private final static String LINK_COLOR = PreferenceConstants.EDITOR_LINK_COLOR;
3071 /** Preference key for compiler task tags */
3072 private final static String COMPILER_TASK_TAGS = JavaCore.COMPILER_TASK_TAGS;
3074 // protected PHPActionGroup fActionGroups;
3075 // /** The outline page */
3076 // private AbstractContentOutlinePage fOutlinePage;
3077 /** The outline page */
3078 protected JavaOutlinePage fOutlinePage;
3080 /** Outliner context menu Id */
3081 protected String fOutlinerContextMenuId;
3084 * Indicates whether this editor should react on outline page selection
3087 private int fIgnoreOutlinePageSelection;
3089 /** The outline page selection updater */
3090 // private OutlinePageSelectionUpdater fUpdater;
3091 // protected PHPSyntaxParserThread fValidationThread = null;
3092 // private IPreferenceStore fPHPPrefStore;
3093 /** The selection changed listener */
3094 // protected ISelectionChangedListener fSelectionChangedListener = new
3095 // SelectionChangedListener();
3097 * The editor selection changed listener.
3101 private EditorSelectionChangedListener fEditorSelectionChangedListener;
3103 /** The selection changed listener */
3104 protected AbstractSelectionChangedListener fOutlineSelectionChangedListener = new OutlineSelectionChangedListener();
3106 /** The editor's bracket matcher */
3107 private PHPPairMatcher fBracketMatcher = new PHPPairMatcher(BRACKETS);
3109 /** The line number ruler column */
3110 // private LineNumberRulerColumn fLineNumberRulerColumn;
3111 /** This editor's encoding support */
3112 private DefaultEncodingSupport fEncodingSupport;
3114 /** The mouse listener */
3115 private MouseClickListener fMouseListener;
3118 * Indicates whether this editor is about to update any annotation views.
3122 private boolean fIsUpdatingAnnotationViews = false;
3125 * The marker that served as last target for a goto marker request.
3129 private IMarker fLastMarkerTarget = null;
3131 protected CompositeActionGroup fActionGroups;
3133 protected CompositeActionGroup fContextMenuGroup;
3136 * This editor's projection support
3140 private ProjectionSupport fProjectionSupport;
3143 * This editor's projection model updater
3147 private IJavaFoldingStructureProvider fProjectionModelUpdater;
3150 * The override and implements indicator manager for this editor.
3154 // protected OverrideIndicatorManager fOverrideIndicatorManager;
3156 * The action group for folding.
3160 private FoldingActionGroup fFoldingGroup;
3162 /** The information presenter. */
3163 private InformationPresenter fInformationPresenter;
3165 /** The annotation access */
3166 // protected IAnnotationAccess fAnnotationAccess = new AnnotationAccess();
3167 /** The overview ruler */
3168 protected OverviewRuler isOverviewRulerVisible;
3170 /** The source viewer decoration support */
3171 // protected SourceViewerDecorationSupport fSourceViewerDecorationSupport;
3172 /** The overview ruler */
3173 // protected OverviewRuler fOverviewRuler;
3174 /** The preference property change listener for java core. */
3175 private org.eclipse.core.runtime.Preferences.IPropertyChangeListener fPropertyChangeListener = new PropertyChangeListener();
3178 * Returns the most narrow java element including the given offset
3181 * the offset inside of the requested element
3183 abstract protected IJavaElement getElementAt(int offset);
3186 * Returns the java element of this editor's input corresponding to the
3187 * given IJavaElement
3189 abstract protected IJavaElement getCorrespondingElement(IJavaElement element);
3192 * Sets the input of the editor's outline page.
3194 abstract protected void setOutlinePageInput(JavaOutlinePage page,
3195 IEditorInput input);
3198 * Default constructor.
3200 public PHPEditor() {
3205 * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#initializeKeyBindingScopes()
3207 protected void initializeKeyBindingScopes() {
3208 setKeyBindingScopes(new String[] { "net.sourceforge.phpdt.ui.phpEditorScope" }); //$NON-NLS-1$
3212 * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#initializeEditor()
3214 protected void initializeEditor() {
3216 // JavaTextTools textTools =
3217 // PHPeclipsePlugin.getDefault().getJavaTextTools();
3218 // setSourceViewerConfiguration(new
3219 // PHPSourceViewerConfiguration(textTools,
3220 // this, IPHPPartitions.PHP_PARTITIONING)); //,
3221 // IJavaPartitions.JAVA_PARTITIONING));
3222 IPreferenceStore store = createCombinedPreferenceStore(null);
3223 setPreferenceStore(store);
3224 JavaTextTools textTools = PHPeclipsePlugin.getDefault()
3225 .getJavaTextTools();
3226 setSourceViewerConfiguration(new PHPSourceViewerConfiguration(textTools
3227 .getColorManager(), store, this,
3228 IPHPPartitions.PHP_PARTITIONING));
3230 // TODO changed in 3.x ?
3231 // setRangeIndicator(new DefaultRangeIndicator());
3233 // (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE))
3234 // fUpdater = new OutlinePageSelectionUpdater();
3237 // IPreferenceStore store= createCombinedPreferenceStore(null);
3238 // setPreferenceStore(store);
3239 // JavaTextTools textTools=
3240 // PHPeclipsePlugin.getDefault().getJavaTextTools();
3241 // setSourceViewerConfiguration(new
3242 // JavaSourceViewerConfiguration(textTools.getColorManager(), store,
3243 // this, IJavaPartitions.JAVA_PARTITIONING));
3244 fMarkOccurrenceAnnotations = store
3245 .getBoolean(PreferenceConstants.EDITOR_MARK_OCCURRENCES);
3246 fStickyOccurrenceAnnotations = store
3247 .getBoolean(PreferenceConstants.EDITOR_STICKY_OCCURRENCES);
3248 // fMarkTypeOccurrences=
3249 // store.getBoolean(PreferenceConstants.EDITOR_MARK_TYPE_OCCURRENCES);
3250 // fMarkMethodOccurrences=
3251 // store.getBoolean(PreferenceConstants.EDITOR_MARK_METHOD_OCCURRENCES);
3252 // fMarkConstantOccurrences=
3253 // store.getBoolean(PreferenceConstants.EDITOR_MARK_CONSTANT_OCCURRENCES);
3254 // fMarkFieldOccurrences=
3255 // store.getBoolean(PreferenceConstants.EDITOR_MARK_FIELD_OCCURRENCES);
3256 // fMarkLocalVariableypeOccurrences=
3257 // store.getBoolean(PreferenceConstants.EDITOR_MARK_LOCAL_VARIABLE_OCCURRENCES);
3259 // store.getBoolean(PreferenceConstants.EDITOR_MARK_EXCEPTION_OCCURRENCES);
3260 // fMarkImplementors=
3261 // store.getBoolean(PreferenceConstants.EDITOR_MARK_IMPLEMENTORS);
3262 // fMarkMethodExitPoints=
3263 // store.getBoolean(PreferenceConstants.EDITOR_MARK_METHOD_EXIT_POINTS);
3268 * @see org.eclipse.ui.texteditor.AbstractTextEditor#updatePropertyDependentActions()
3270 protected void updatePropertyDependentActions() {
3271 super.updatePropertyDependentActions();
3272 if (fEncodingSupport != null)
3273 fEncodingSupport.reset();
3277 * Update the hovering behavior depending on the preferences.
3279 private void updateHoverBehavior() {
3280 SourceViewerConfiguration configuration = getSourceViewerConfiguration();
3281 String[] types = configuration
3282 .getConfiguredContentTypes(getSourceViewer());
3284 for (int i = 0; i < types.length; i++) {
3286 String t = types[i];
3288 int[] stateMasks = configuration.getConfiguredTextHoverStateMasks(
3289 getSourceViewer(), t);
3291 ISourceViewer sourceViewer = getSourceViewer();
3292 if (sourceViewer instanceof ITextViewerExtension2) {
3293 if (stateMasks != null) {
3294 for (int j = 0; j < stateMasks.length; j++) {
3295 int stateMask = stateMasks[j];
3296 ITextHover textHover = configuration.getTextHover(
3297 sourceViewer, t, stateMask);
3298 ((ITextViewerExtension2) sourceViewer).setTextHover(
3299 textHover, t, stateMask);
3302 ITextHover textHover = configuration.getTextHover(
3304 ((ITextViewerExtension2) sourceViewer).setTextHover(
3306 ITextViewerExtension2.DEFAULT_HOVER_STATE_MASK);
3309 sourceViewer.setTextHover(configuration.getTextHover(
3310 sourceViewer, t), t);
3314 public void updatedTitleImage(Image image) {
3315 setTitleImage(image);
3319 * @see net.sourceforge.phpdt.internal.ui.viewsupport.IViewPartInputProvider#getViewPartInput()
3321 public Object getViewPartInput() {
3322 return getEditorInput().getAdapter(IResource.class);
3326 * @see org.eclipse.ui.texteditor.AbstractTextEditor#doSetSelection(ISelection)
3328 protected void doSetSelection(ISelection selection) {
3329 super.doSetSelection(selection);
3330 synchronizeOutlinePageSelection();
3333 boolean isFoldingEnabled() {
3334 return PHPeclipsePlugin.getDefault().getPreferenceStore().getBoolean(
3335 PreferenceConstants.EDITOR_FOLDING_ENABLED);
3339 * @see org.eclipse.ui.IWorkbenchPart#createPartControl(org.eclipse.swt.
3340 * widgets.Composite)
3342 public void createPartControl(Composite parent) {
3343 super.createPartControl(parent);
3345 // fSourceViewerDecorationSupport.install(getPreferenceStore());
3347 ProjectionViewer projectionViewer = (ProjectionViewer) getSourceViewer();
3349 fProjectionSupport = new ProjectionSupport(projectionViewer,
3350 getAnnotationAccess(), getSharedColors());
3352 .addSummarizableAnnotationType("org.eclipse.ui.workbench.texteditor.error"); //$NON-NLS-1$
3354 .addSummarizableAnnotationType("org.eclipse.ui.workbench.texteditor.warning"); //$NON-NLS-1$
3356 .setHoverControlCreator(new IInformationControlCreator() {
3357 public IInformationControl createInformationControl(
3359 return new CustomSourceInformationControl(shell,
3360 IDocument.DEFAULT_CONTENT_TYPE);
3363 fProjectionSupport.install();
3365 fProjectionModelUpdater = PHPeclipsePlugin.getDefault()
3366 .getFoldingStructureProviderRegistry()
3367 .getCurrentFoldingProvider();
3368 if (fProjectionModelUpdater != null)
3369 fProjectionModelUpdater.install(this, projectionViewer);
3371 if (isFoldingEnabled())
3372 projectionViewer.doOperation(ProjectionViewer.TOGGLE);
3373 Preferences preferences = PHPeclipsePlugin.getDefault()
3374 .getPluginPreferences();
3375 preferences.addPropertyChangeListener(fPropertyChangeListener);
3377 IInformationControlCreator informationControlCreator = new IInformationControlCreator() {
3378 public IInformationControl createInformationControl(Shell parent) {
3379 boolean cutDown = false;
3380 int style = cutDown ? SWT.NONE : (SWT.V_SCROLL | SWT.H_SCROLL);
3381 return new DefaultInformationControl(parent, SWT.RESIZE, style,
3382 new HTMLTextPresenter(cutDown));
3386 fInformationPresenter = new InformationPresenter(
3387 informationControlCreator);
3388 fInformationPresenter.setSizeConstraints(60, 10, true, true);
3389 fInformationPresenter.install(getSourceViewer());
3391 fEditorSelectionChangedListener = new EditorSelectionChangedListener();
3392 fEditorSelectionChangedListener.install(getSelectionProvider());
3394 if (isBrowserLikeLinks())
3395 enableBrowserLikeLinks();
3397 if (PreferenceConstants.getPreferenceStore().getBoolean(
3398 PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE))
3399 enableOverwriteMode(false);
3401 if (fMarkOccurrenceAnnotations)
3402 installOccurrencesFinder();
3404 PlatformUI.getWorkbench().addWindowListener(fActivationListener);
3409 private void setWordWrap() {
3410 if (getSourceViewer() != null) {
3411 getSourceViewer().getTextWidget().setWordWrap(
3412 PHPeclipsePlugin.getDefault().getPreferenceStore()
3413 .getBoolean(PreferenceConstants.EDITOR_WRAP_WORDS));
3417 protected void configureSourceViewerDecorationSupport(
3418 SourceViewerDecorationSupport support) {
3420 support.setCharacterPairMatcher(fBracketMatcher);
3421 support.setMatchingCharacterPainterPreferenceKeys(MATCHING_BRACKETS,
3422 MATCHING_BRACKETS_COLOR);
3424 super.configureSourceViewerDecorationSupport(support);
3428 * @see org.eclipse.ui.texteditor.AbstractTextEditor#gotoMarker(org.eclipse.core.resources.IMarker)
3430 public void gotoMarker(IMarker marker) {
3431 fLastMarkerTarget = marker;
3432 if (!fIsUpdatingAnnotationViews) {
3433 super.gotoMarker(marker);
3438 * Jumps to the next enabled annotation according to the given direction. An
3439 * annotation type is enabled if it is configured to be in the Next/Previous
3440 * tool bar drop down menu and if it is checked.
3443 * <code>true</code> if search direction is forward,
3444 * <code>false</code> if backward
3446 public Annotation gotoAnnotation(boolean forward) {
3447 ITextSelection selection = (ITextSelection) getSelectionProvider()
3449 Position position = new Position(0, 0);
3450 Annotation annotation = null;
3451 if (false /* delayed - see bug 18316 */) {
3452 annotation = getNextAnnotation(selection.getOffset(), selection
3453 .getLength(), forward, position);
3454 selectAndReveal(position.getOffset(), position.getLength());
3455 } else /* no delay - see bug 18316 */{
3456 annotation = getNextAnnotation(selection.getOffset(), selection
3457 .getLength(), forward, position);
3458 setStatusLineErrorMessage(null);
3459 setStatusLineMessage(null);
3460 if (annotation != null) {
3461 updateAnnotationViews(annotation);
3462 selectAndReveal(position.getOffset(), position.getLength());
3463 setStatusLineMessage(annotation.getText());
3470 * Returns the lock object for the given annotation model.
3472 * @param annotationModel
3473 * the annotation model
3474 * @return the annotation model's lock object
3477 private Object getLockObject(IAnnotationModel annotationModel) {
3478 if (annotationModel instanceof ISynchronizable)
3479 return ((ISynchronizable) annotationModel).getLockObject();
3481 return annotationModel;
3485 * Updates the annotation views that show the given annotation.
3490 private void updateAnnotationViews(Annotation annotation) {
3491 IMarker marker = null;
3492 if (annotation instanceof MarkerAnnotation)
3493 marker = ((MarkerAnnotation) annotation).getMarker();
3494 else if (annotation instanceof IJavaAnnotation) {
3495 Iterator e = ((IJavaAnnotation) annotation).getOverlaidIterator();
3497 while (e.hasNext()) {
3498 Object o = e.next();
3499 if (o instanceof MarkerAnnotation) {
3500 marker = ((MarkerAnnotation) o).getMarker();
3507 if (marker != null && !marker.equals(fLastMarkerTarget)) {
3509 boolean isProblem = marker.isSubtypeOf(IMarker.PROBLEM);
3510 IWorkbenchPage page = getSite().getPage();
3511 IViewPart view = page
3512 .findView(isProblem ? IPageLayout.ID_PROBLEM_VIEW
3513 : IPageLayout.ID_TASK_LIST); //$NON-NLS-1$ //$NON-NLS-2$
3515 Method method = view
3518 "setSelection", new Class[] { IStructuredSelection.class, boolean.class }); //$NON-NLS-1$
3519 method.invoke(view, new Object[] {
3520 new StructuredSelection(marker), Boolean.TRUE });
3522 } catch (CoreException x) {
3523 } catch (NoSuchMethodException x) {
3524 } catch (IllegalAccessException x) {
3525 } catch (InvocationTargetException x) {
3527 // ignore exceptions, don't update any of the lists, just set status
3533 * Returns this document's complete text.
3535 * @return the document's complete text
3537 public String get() {
3538 IDocument doc = this.getDocumentProvider().getDocument(
3539 this.getEditorInput());
3544 * Sets the outliner's context menu ID.
3546 protected void setOutlinerContextMenuId(String menuId) {
3547 fOutlinerContextMenuId = menuId;
3551 * Returns the standard action group of this editor.
3553 protected ActionGroup getActionGroup() {
3554 return fActionGroups;
3557 // public JavaOutlinePage getfOutlinePage() {
3558 // return fOutlinePage;
3562 * The <code>PHPEditor</code> implementation of this
3563 * <code>AbstractTextEditor</code> method extend the actions to add those
3564 * specific to the receiver
3566 protected void createActions() {
3567 super.createActions();
3569 ActionGroup oeg, ovg, jsg, sg;
3570 fActionGroups = new CompositeActionGroup(
3571 new ActionGroup[] { oeg = new OpenEditorActionGroup(this),
3572 // sg= new ShowActionGroup(this),
3573 // ovg= new OpenViewActionGroup(this),
3574 // jsg= new JavaSearchActionGroup(this)
3576 fContextMenuGroup = new CompositeActionGroup(new ActionGroup[] { oeg });
3577 // , ovg, sg, jsg});
3579 fFoldingGroup = new FoldingActionGroup(this, getViewer());
3581 // ResourceAction resAction = new
3582 // TextOperationAction(PHPEditorMessages.getResourceBundle(),
3583 // "ShowJavaDoc.", this, ISourceViewer.INFORMATION, true); //$NON-NLS-1$
3585 // InformationDispatchAction(PHPEditorMessages.getResourceBundle(),
3586 // "ShowJavaDoc.", (TextOperationAction) resAction); //$NON-NLS-1$
3587 // resAction.setActionDefinitionId(net.sourceforge.phpdt.ui.actions.PHPEditorActionDefinitionIds.SHOW_JAVADOC);
3588 // setAction("ShowJavaDoc", resAction); //$NON-NLS-1$
3590 // WorkbenchHelp.setHelp(resAction,
3591 // IJavaHelpContextIds.SHOW_JAVADOC_ACTION);
3593 Action action = new GotoMatchingBracketAction(this);
3595 .setActionDefinitionId(PHPEditorActionDefinitionIds.GOTO_MATCHING_BRACKET);
3596 setAction(GotoMatchingBracketAction.GOTO_MATCHING_BRACKET, action);
3599 // TextOperationAction(PHPEditorMessages.getResourceBundle(),"ShowOutline.",
3600 // this, JavaSourceViewer.SHOW_OUTLINE, true); //$NON-NLS-1$
3601 // action.setActionDefinitionId(PHPEditorActionDefinitionIds.SHOW_OUTLINE);
3602 // setAction(PHPEditorActionDefinitionIds.SHOW_OUTLINE, action);
3603 // // WorkbenchHelp.setHelp(action,
3604 // IJavaHelpContextIds.SHOW_OUTLINE_ACTION);
3607 // TextOperationAction(PHPEditorMessages.getResourceBundle(),"OpenStructure.",
3608 // this, JavaSourceViewer.OPEN_STRUCTURE, true); //$NON-NLS-1$
3609 // action.setActionDefinitionId(PHPEditorActionDefinitionIds.SHOW_OUTLINE.OPEN_STRUCTURE);
3610 // setAction(PHPEditorActionDefinitionIds.SHOW_OUTLINE.OPEN_STRUCTURE,
3612 // // WorkbenchHelp.setHelp(action,
3613 // IJavaHelpContextIds.OPEN_STRUCTURE_ACTION);
3616 // TextOperationAction(PHPEditorMessages.getResourceBundle(),"OpenHierarchy.",
3617 // this, JavaSourceViewer.SHOW_HIERARCHY, true); //$NON-NLS-1$
3618 // action.setActionDefinitionId(PHPEditorActionDefinitionIds.SHOW_OUTLINE.OPEN_HIERARCHY);
3619 // setAction(PHPEditorActionDefinitionIds.SHOW_OUTLINE.OPEN_HIERARCHY,
3621 // // WorkbenchHelp.setHelp(action,
3622 // IJavaHelpContextIds.OPEN_HIERARCHY_ACTION);
3624 fEncodingSupport = new DefaultEncodingSupport();
3625 fEncodingSupport.initialize(this);
3627 // fSelectionHistory= new SelectionHistory(this);
3629 // action= new StructureSelectEnclosingAction(this, fSelectionHistory);
3630 // action.setActionDefinitionId(PHPEditorActionDefinitionIds.SELECT_ENCLOSING);
3631 // setAction(StructureSelectionAction.ENCLOSING, action);
3633 // action= new StructureSelectNextAction(this, fSelectionHistory);
3634 // action.setActionDefinitionId(PHPEditorActionDefinitionIds.SELECT_NEXT);
3635 // setAction(StructureSelectionAction.NEXT, action);
3637 // action= new StructureSelectPreviousAction(this, fSelectionHistory);
3638 // action.setActionDefinitionId(PHPEditorActionDefinitionIds.SELECT_PREVIOUS);
3639 // setAction(StructureSelectionAction.PREVIOUS, action);
3641 // StructureSelectHistoryAction historyAction= new
3642 // StructureSelectHistoryAction(this, fSelectionHistory);
3643 // historyAction.setActionDefinitionId(PHPEditorActionDefinitionIds.SELECT_LAST);
3644 // setAction(StructureSelectionAction.HISTORY, historyAction);
3645 // fSelectionHistory.setHistoryAction(historyAction);
3647 // action= GoToNextPreviousMemberAction.newGoToNextMemberAction(this);
3648 // action.setActionDefinitionId(PHPEditorActionDefinitionIds.GOTO_NEXT_MEMBER);
3649 // setAction(GoToNextPreviousMemberAction.NEXT_MEMBER, action);
3652 // GoToNextPreviousMemberAction.newGoToPreviousMemberAction(this);
3653 // action.setActionDefinitionId(PHPEditorActionDefinitionIds.GOTO_PREVIOUS_MEMBER);
3654 // setAction(GoToNextPreviousMemberAction.PREVIOUS_MEMBER, action);
3656 // action= new QuickFormatAction();
3657 // action.setActionDefinitionId(PHPEditorActionDefinitionIds.QUICK_FORMAT);
3658 // setAction(IJavaEditorActionDefinitionIds.QUICK_FORMAT, action);
3660 // action= new RemoveOccurrenceAnnotations(this);
3661 // action.setActionDefinitionId(PHPEditorActionDefinitionIds.REMOVE_OCCURRENCE_ANNOTATIONS);
3662 // setAction("RemoveOccurrenceAnnotations", action); //$NON-NLS-1$
3664 // add annotation actions
3665 action = new JavaSelectMarkerRulerAction2(PHPEditorMessages
3666 .getResourceBundle(), "Editor.RulerAnnotationSelection.", this); //$NON-NLS-1$
3667 setAction("AnnotationAction", action); //$NON-NLS-1$
3670 private void internalDoSetInput(IEditorInput input) throws CoreException {
3671 super.doSetInput(input);
3673 if (getSourceViewer() instanceof JavaSourceViewer) {
3674 JavaSourceViewer viewer = (JavaSourceViewer) getSourceViewer();
3675 if (viewer.getReconciler() == null) {
3676 IReconciler reconciler = getSourceViewerConfiguration()
3677 .getReconciler(viewer);
3678 if (reconciler != null) {
3679 reconciler.install(viewer);
3680 viewer.setReconciler(reconciler);
3685 if (fEncodingSupport != null)
3686 fEncodingSupport.reset();
3688 setOutlinePageInput(fOutlinePage, input);
3690 if (fProjectionModelUpdater != null)
3691 fProjectionModelUpdater.initialize();
3693 // if (isShowingOverrideIndicators())
3694 // installOverrideIndicator(false);
3698 * @see org.eclipse.ui.texteditor.AbstractTextEditor#setPreferenceStore(org.eclipse.jface.preference.IPreferenceStore)
3701 protected void setPreferenceStore(IPreferenceStore store) {
3702 super.setPreferenceStore(store);
3703 if (getSourceViewerConfiguration() instanceof PHPSourceViewerConfiguration) {
3704 JavaTextTools textTools = PHPeclipsePlugin.getDefault()
3705 .getJavaTextTools();
3706 setSourceViewerConfiguration(new PHPSourceViewerConfiguration(
3707 textTools.getColorManager(), store, this,
3708 IPHPPartitions.PHP_PARTITIONING));
3710 if (getSourceViewer() instanceof JavaSourceViewer)
3711 ((JavaSourceViewer) getSourceViewer()).setPreferenceStore(store);
3715 * The <code>PHPEditor</code> implementation of this
3716 * <code>AbstractTextEditor</code> method performs any extra disposal
3717 * actions required by the php editor.
3719 public void dispose() {
3720 if (fProjectionModelUpdater != null) {
3721 fProjectionModelUpdater.uninstall();
3722 fProjectionModelUpdater = null;
3725 if (fProjectionSupport != null) {
3726 fProjectionSupport.dispose();
3727 fProjectionSupport = null;
3729 // PHPEditorEnvironment.disconnect(this);
3730 if (fOutlinePage != null)
3731 fOutlinePage.setInput(null);
3733 if (fActionGroups != null)
3734 fActionGroups.dispose();
3736 if (isBrowserLikeLinks())
3737 disableBrowserLikeLinks();
3739 // cancel possible running computation
3740 fMarkOccurrenceAnnotations = false;
3741 uninstallOccurrencesFinder();
3743 uninstallOverrideIndicator();
3745 if (fActivationListener != null) {
3746 PlatformUI.getWorkbench().removeWindowListener(fActivationListener);
3747 fActivationListener = null;
3750 if (fEncodingSupport != null) {
3751 fEncodingSupport.dispose();
3752 fEncodingSupport = null;
3755 if (fPropertyChangeListener != null) {
3756 Preferences preferences = PHPeclipsePlugin.getDefault()
3757 .getPluginPreferences();
3758 preferences.removePropertyChangeListener(fPropertyChangeListener);
3759 fPropertyChangeListener = null;
3762 // if (fSourceViewerDecorationSupport != null) {
3763 // fSourceViewerDecorationSupport.dispose();
3764 // fSourceViewerDecorationSupport = null;
3767 if (fBracketMatcher != null) {
3768 fBracketMatcher.dispose();
3769 fBracketMatcher = null;
3772 if (fEditorSelectionChangedListener != null) {
3773 fEditorSelectionChangedListener.uninstall(getSelectionProvider());
3774 fEditorSelectionChangedListener = null;
3781 * The <code>PHPEditor</code> implementation of this
3782 * <code>AbstractTextEditor</code> method performs any extra revert
3783 * behavior required by the php editor.
3785 // public void doRevertToSaved() {
3786 // super.doRevertToSaved();
3787 // if (fOutlinePage != null)
3788 // fOutlinePage.update();
3791 * The <code>PHPEditor</code> implementation of this
3792 * <code>AbstractTextEditor</code> method performs any extra save behavior
3793 * required by the php editor.
3795 // public void doSave(IProgressMonitor monitor) {
3796 // super.doSave(monitor);
3797 // compile or not, according to the user preferences
3798 // IPreferenceStore store = getPreferenceStore();
3799 // the parse on save was changed to the eclipse "builders" concept
3800 // if (store.getBoolean(PHPeclipsePlugin.PHP_PARSE_ON_SAVE)) {
3801 // IAction a = PHPParserAction.getInstance();
3805 // if (SWT.getPlatform().equals("win32")) {
3806 // IAction a = ShowExternalPreviewAction.getInstance();
3810 // if (fOutlinePage != null)
3811 // fOutlinePage.update();
3814 * The <code>PHPEditor</code> implementation of this
3815 * <code>AbstractTextEditor</code> method performs any extra save as
3816 * behavior required by the php editor.
3818 // public void doSaveAs() {
3819 // super.doSaveAs();
3820 // if (fOutlinePage != null)
3821 // fOutlinePage.update();
3824 * @see StatusTextEditor#getStatusHeader(IStatus)
3826 protected String getStatusHeader(IStatus status) {
3827 if (fEncodingSupport != null) {
3828 String message = fEncodingSupport.getStatusHeader(status);
3829 if (message != null)
3832 return super.getStatusHeader(status);
3836 * @see StatusTextEditor#getStatusBanner(IStatus)
3838 protected String getStatusBanner(IStatus status) {
3839 if (fEncodingSupport != null) {
3840 String message = fEncodingSupport.getStatusBanner(status);
3841 if (message != null)
3844 return super.getStatusBanner(status);
3848 * @see StatusTextEditor#getStatusMessage(IStatus)
3850 protected String getStatusMessage(IStatus status) {
3851 if (fEncodingSupport != null) {
3852 String message = fEncodingSupport.getStatusMessage(status);
3853 if (message != null)
3856 return super.getStatusMessage(status);
3860 * The <code>PHPEditor</code> implementation of this
3861 * <code>AbstractTextEditor</code> method performs sets the input of the
3862 * outline page after AbstractTextEditor has set input.
3864 // protected void doSetInput(IEditorInput input) throws CoreException {
3865 // super.doSetInput(input);
3866 // if (fEncodingSupport != null)
3867 // fEncodingSupport.reset();
3868 // setOutlinePageInput(fOutlinePage, input);
3871 * @see AbstractTextEditor#doSetInput
3873 protected void doSetInput(IEditorInput input) throws CoreException {
3874 ISourceViewer sourceViewer = getSourceViewer();
3875 if (!(sourceViewer instanceof ISourceViewerExtension2)) {
3876 setPreferenceStore(createCombinedPreferenceStore(input));
3877 internalDoSetInput(input);
3881 // uninstall & unregister preference store listener
3882 if (isBrowserLikeLinks())
3883 disableBrowserLikeLinks();
3884 getSourceViewerDecorationSupport(sourceViewer).uninstall();
3885 ((ISourceViewerExtension2) sourceViewer).unconfigure();
3887 setPreferenceStore(createCombinedPreferenceStore(input));
3889 // install & register preference store listener
3890 sourceViewer.configure(getSourceViewerConfiguration());
3891 getSourceViewerDecorationSupport(sourceViewer).install(
3892 getPreferenceStore());
3893 if (isBrowserLikeLinks())
3894 enableBrowserLikeLinks();
3896 internalDoSetInput(input);
3900 * @see org.phpeclipse.phpdt.internal.ui.viewsupport.IViewPartInputProvider#getViewPartInput()
3902 // public Object getViewPartInput() {
3903 // return getEditorInput().getAdapter(IFile.class);
3906 * The <code>PHPEditor</code> implementation of this
3907 * <code>AbstractTextEditor</code> method adds any PHPEditor specific
3910 public void editorContextMenuAboutToShow(MenuManager menu) {
3911 super.editorContextMenuAboutToShow(menu);
3912 menu.appendToGroup(ITextEditorActionConstants.GROUP_UNDO,
3913 new Separator(IContextMenuConstants.GROUP_OPEN));
3914 menu.insertAfter(IContextMenuConstants.GROUP_OPEN, new GroupMarker(
3915 IContextMenuConstants.GROUP_SHOW));
3917 ActionContext context = new ActionContext(getSelectionProvider()
3919 fContextMenuGroup.setContext(context);
3920 fContextMenuGroup.fillContextMenu(menu);
3921 fContextMenuGroup.setContext(null);
3922 // addAction(menu, ITextEditorActionConstants.GROUP_EDIT, "Format");
3925 // ActionContext context =
3926 // new ActionContext(getSelectionProvider().getSelection());
3927 // fContextMenuGroup.setContext(context);
3928 // fContextMenuGroup.fillContextMenu(menu);
3929 // fContextMenuGroup.setContext(null);
3933 * Creates the outline page used with this editor.
3935 protected JavaOutlinePage createOutlinePage() {
3936 JavaOutlinePage page = new JavaOutlinePage(fOutlinerContextMenuId, this);
3937 fOutlineSelectionChangedListener.install(page);
3938 setOutlinePageInput(page, getEditorInput());
3943 * Informs the editor that its outliner has been closed.
3945 public void outlinePageClosed() {
3946 if (fOutlinePage != null) {
3947 fOutlineSelectionChangedListener.uninstall(fOutlinePage);
3948 fOutlinePage = null;
3949 resetHighlightRange();
3954 * Synchronizes the outliner selection with the given element position in
3958 * the java element to select
3960 protected void synchronizeOutlinePage(ISourceReference element) {
3961 synchronizeOutlinePage(element, true);
3965 * Synchronizes the outliner selection with the given element position in
3969 * the java element to select
3970 * @param checkIfOutlinePageActive
3971 * <code>true</code> if check for active outline page needs to
3974 protected void synchronizeOutlinePage(ISourceReference element,
3975 boolean checkIfOutlinePageActive) {
3976 if (fOutlinePage != null && element != null
3977 && !(checkIfOutlinePageActive && isJavaOutlinePageActive())) {
3978 fOutlineSelectionChangedListener.uninstall(fOutlinePage);
3979 fOutlinePage.select(element);
3980 fOutlineSelectionChangedListener.install(fOutlinePage);
3985 * Synchronizes the outliner selection with the actual cursor position in
3988 public void synchronizeOutlinePageSelection() {
3989 synchronizeOutlinePage(computeHighlightRangeSourceReference());
3991 // ISourceViewer sourceViewer = getSourceViewer();
3992 // if (sourceViewer == null || fOutlinePage == null)
3995 // StyledText styledText = sourceViewer.getTextWidget();
3996 // if (styledText == null)
4000 // if (sourceViewer instanceof ITextViewerExtension3) {
4001 // ITextViewerExtension3 extension = (ITextViewerExtension3)
4004 // extension.widgetOffset2ModelOffset(styledText.getCaretOffset());
4006 // int offset = sourceViewer.getVisibleRegion().getOffset();
4007 // caret = offset + styledText.getCaretOffset();
4010 // IJavaElement element = getElementAt(caret);
4011 // if (element instanceof ISourceReference) {
4012 // fOutlinePage.removeSelectionChangedListener(fSelectionChangedListener);
4013 // fOutlinePage.select((ISourceReference) element);
4014 // fOutlinePage.addSelectionChangedListener(fSelectionChangedListener);
4018 protected void setSelection(ISourceReference reference, boolean moveCursor) {
4020 ISelection selection = getSelectionProvider().getSelection();
4021 if (selection instanceof TextSelection) {
4022 TextSelection textSelection = (TextSelection) selection;
4023 if (textSelection.getOffset() != 0
4024 || textSelection.getLength() != 0)
4025 markInNavigationHistory();
4028 if (reference != null) {
4030 StyledText textWidget = null;
4032 ISourceViewer sourceViewer = getSourceViewer();
4033 if (sourceViewer != null)
4034 textWidget = sourceViewer.getTextWidget();
4036 if (textWidget == null)
4041 ISourceRange range = reference.getSourceRange();
4045 int offset = range.getOffset();
4046 int length = range.getLength();
4048 if (offset < 0 || length < 0)
4051 textWidget.setRedraw(false);
4053 setHighlightRange(offset, length, moveCursor);
4061 if (reference instanceof IMember) {
4062 range = ((IMember) reference).getNameRange();
4063 if (range != null) {
4064 offset = range.getOffset();
4065 length = range.getLength();
4068 // else if (reference instanceof IImportDeclaration) {
4069 // String name= ((IImportDeclaration)
4070 // reference).getElementName();
4071 // if (name != null && name.length() > 0) {
4072 // String content= reference.getSource();
4073 // if (content != null) {
4074 // offset= range.getOffset() + content.indexOf(name);
4075 // length= name.length();
4078 // } else if (reference instanceof IPackageDeclaration) {
4079 // String name= ((IPackageDeclaration)
4080 // reference).getElementName();
4081 // if (name != null && name.length() > 0) {
4082 // String content= reference.getSource();
4083 // if (content != null) {
4084 // offset= range.getOffset() + content.indexOf(name);
4085 // length= name.length();
4090 if (offset > -1 && length > 0) {
4091 sourceViewer.revealRange(offset, length);
4092 sourceViewer.setSelectedRange(offset, length);
4095 } catch (JavaModelException x) {
4096 } catch (IllegalArgumentException x) {
4098 if (textWidget != null)
4099 textWidget.setRedraw(true);
4102 } else if (moveCursor) {
4103 resetHighlightRange();
4106 markInNavigationHistory();
4109 public void setSelection(IJavaElement element) {
4110 if (element == null || element instanceof ICompilationUnit) { // ||
4116 * If the element is an ICompilationUnit this unit is either the
4117 * input of this editor or not being displayed. In both cases,
4118 * nothing should happened.
4119 * (http://dev.eclipse.org/bugs/show_bug.cgi?id=5128)
4124 IJavaElement corresponding = getCorrespondingElement(element);
4125 if (corresponding instanceof ISourceReference) {
4126 ISourceReference reference = (ISourceReference) corresponding;
4127 // set highlight range
4128 setSelection(reference, true);
4129 // set outliner selection
4130 if (fOutlinePage != null) {
4131 fOutlineSelectionChangedListener.uninstall(fOutlinePage);
4132 fOutlinePage.select(reference);
4133 fOutlineSelectionChangedListener.install(fOutlinePage);
4138 public synchronized void editingScriptStarted() {
4139 ++fIgnoreOutlinePageSelection;
4142 public synchronized void editingScriptEnded() {
4143 --fIgnoreOutlinePageSelection;
4146 public synchronized boolean isEditingScriptRunning() {
4147 return (fIgnoreOutlinePageSelection > 0);
4151 * The <code>PHPEditor</code> implementation of this
4152 * <code>AbstractTextEditor</code> method performs gets the java content
4153 * outline page if request is for a an outline page.
4155 public Object getAdapter(Class required) {
4157 if (IContentOutlinePage.class.equals(required)) {
4158 if (fOutlinePage == null)
4159 fOutlinePage = createOutlinePage();
4160 return fOutlinePage;
4163 if (IEncodingSupport.class.equals(required))
4164 return fEncodingSupport;
4166 if (required == IShowInTargetList.class) {
4167 return new IShowInTargetList() {
4168 public String[] getShowInTargetIds() {
4169 return new String[] { JavaUI.ID_PACKAGES,
4170 IPageLayout.ID_OUTLINE, IPageLayout.ID_RES_NAV };
4175 if (fProjectionSupport != null) {
4176 Object adapter = fProjectionSupport.getAdapter(getSourceViewer(),
4178 if (adapter != null)
4182 return super.getAdapter(required);
4185 // public Object getAdapter(Class required) {
4186 // if (IContentOutlinePage.class.equals(required)) {
4187 // if (fOutlinePage == null) {
4188 // fOutlinePage = new PHPContentOutlinePage(getDocumentProvider(), this);
4189 // if (getEditorInput() != null)
4190 // fOutlinePage.setInput(getEditorInput());
4192 // return fOutlinePage;
4195 // if (IEncodingSupport.class.equals(required))
4196 // return fEncodingSupport;
4198 // return super.getAdapter(required);
4201 protected void doSelectionChanged(SelectionChangedEvent event) {
4202 ISourceReference reference = null;
4204 ISelection selection = event.getSelection();
4205 Iterator iter = ((IStructuredSelection) selection).iterator();
4206 while (iter.hasNext()) {
4207 Object o = iter.next();
4208 if (o instanceof ISourceReference) {
4209 reference = (ISourceReference) o;
4214 if (!isActivePart() && PHPeclipsePlugin.getActivePage() != null)
4215 PHPeclipsePlugin.getActivePage().bringToTop(this);
4218 editingScriptStarted();
4219 setSelection(reference, !isActivePart());
4221 editingScriptEnded();
4226 * @see AbstractTextEditor#adjustHighlightRange(int, int)
4228 protected void adjustHighlightRange(int offset, int length) {
4232 IJavaElement element = getElementAt(offset);
4233 while (element instanceof ISourceReference) {
4234 ISourceRange range = ((ISourceReference) element)
4236 if (offset < range.getOffset() + range.getLength()
4237 && range.getOffset() < offset + length) {
4239 ISourceViewer viewer = getSourceViewer();
4240 if (viewer instanceof ITextViewerExtension5) {
4241 ITextViewerExtension5 extension = (ITextViewerExtension5) viewer;
4242 extension.exposeModelRange(new Region(
4243 range.getOffset(), range.getLength()));
4246 setHighlightRange(range.getOffset(), range.getLength(),
4248 if (fOutlinePage != null) {
4249 fOutlineSelectionChangedListener
4250 .uninstall(fOutlinePage);
4251 fOutlinePage.select((ISourceReference) element);
4252 fOutlineSelectionChangedListener.install(fOutlinePage);
4257 element = element.getParent();
4260 } catch (JavaModelException x) {
4261 PHPeclipsePlugin.log(x.getStatus());
4264 ISourceViewer viewer = getSourceViewer();
4265 if (viewer instanceof ITextViewerExtension5) {
4266 ITextViewerExtension5 extension = (ITextViewerExtension5) viewer;
4267 extension.exposeModelRange(new Region(offset, length));
4269 resetHighlightRange();
4274 protected boolean isActivePart() {
4275 IWorkbenchWindow window = getSite().getWorkbenchWindow();
4276 IPartService service = window.getPartService();
4277 IWorkbenchPart part = service.getActivePart();
4278 return part != null && part.equals(this);
4281 // public void openContextHelp() {
4283 // this.getDocumentProvider().getDocument(this.getEditorInput());
4284 // ITextSelection selection = (ITextSelection)
4285 // this.getSelectionProvider().getSelection();
4286 // int pos = selection.getOffset();
4287 // String word = getFunctionName(doc, pos);
4288 // openContextHelp(word);
4291 // private void openContextHelp(String word) {
4295 // public static void open(String word) {
4296 // IHelp help = WorkbenchHelp.getHelpSupport();
4297 // if (help != null) {
4298 // IHelpResource helpResource = new PHPFunctionHelpResource(word);
4299 // WorkbenchHelp.getHelpSupport().displayHelpResource(helpResource);
4301 // // showMessage(shell, dialogTitle, ActionMessages.getString("Open help
4302 // not available"), false); //$NON-NLS-1$
4306 // private String getFunctionName(IDocument doc, int pos) {
4307 // Point word = PHPWordExtractor.findWord(doc, pos);
4308 // if (word != null) {
4310 // return doc.get(word.x, word.y).replace('_', '-');
4311 // } catch (BadLocationException e) {
4318 * @see AbstractTextEditor#handlePreferenceStoreChanged(PropertyChangeEvent)
4320 protected void handlePreferenceStoreChanged(PropertyChangeEvent event) {
4324 ISourceViewer sourceViewer = getSourceViewer();
4325 if (sourceViewer == null)
4328 String property = event.getProperty();
4330 if (PreferenceConstants.EDITOR_TAB_WIDTH.equals(property)) {
4331 Object value = event.getNewValue();
4332 if (value instanceof Integer) {
4333 sourceViewer.getTextWidget().setTabs(
4334 ((Integer) value).intValue());
4335 } else if (value instanceof String) {
4337 sourceViewer.getTextWidget().setTabs(
4338 Integer.parseInt((String) value));
4339 } catch (NumberFormatException e) {
4340 // bug #1038071 - set default tab:
4341 sourceViewer.getTextWidget().setTabs(80);
4347 // if (OVERVIEW_RULER.equals(property)) {
4348 // if (isOverviewRulerVisible())
4349 // showOverviewRuler();
4351 // hideOverviewRuler();
4355 // if (LINE_NUMBER_RULER.equals(property)) {
4356 // if (isLineNumberRulerVisible())
4357 // showLineNumberRuler();
4359 // hideLineNumberRuler();
4363 // if (fLineNumberRulerColumn != null
4364 // && (LINE_NUMBER_COLOR.equals(property) ||
4365 // PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT.equals(property) ||
4366 // PREFERENCE_COLOR_BACKGROUND.equals(property))) {
4368 // initializeLineNumberRulerColumn(fLineNumberRulerColumn);
4371 if (isJavaEditorHoverProperty(property))
4372 updateHoverBehavior();
4374 if (BROWSER_LIKE_LINKS.equals(property)) {
4375 if (isBrowserLikeLinks())
4376 enableBrowserLikeLinks();
4378 disableBrowserLikeLinks();
4382 if (PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE
4383 .equals(property)) {
4384 if (event.getNewValue() instanceof Boolean) {
4385 Boolean disable = (Boolean) event.getNewValue();
4386 enableOverwriteMode(!disable.booleanValue());
4391 boolean newBooleanValue = false;
4392 Object newValue = event.getNewValue();
4393 if (newValue != null)
4394 newBooleanValue = Boolean.valueOf(newValue.toString())
4397 if (PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE
4398 .equals(property)) {
4399 if (newBooleanValue)
4404 if (PreferenceConstants.EDITOR_MARK_OCCURRENCES.equals(property)) {
4405 if (newBooleanValue != fMarkOccurrenceAnnotations) {
4406 fMarkOccurrenceAnnotations = newBooleanValue;
4407 if (!fMarkOccurrenceAnnotations)
4408 uninstallOccurrencesFinder();
4410 installOccurrencesFinder();
4415 if (PreferenceConstants.EDITOR_STICKY_OCCURRENCES.equals(property)) {
4416 fStickyOccurrenceAnnotations = newBooleanValue;
4422 // (PreferenceConstants.EDITOR_STICKY_OCCURRENCES.equals(property))
4424 // if (event.getNewValue() instanceof Boolean) {
4425 // boolean stickyOccurrenceAnnotations=
4426 // ((Boolean)event.getNewValue()).booleanValue();
4427 // if (stickyOccurrenceAnnotations != fStickyOccurrenceAnnotations)
4430 ((PHPSourceViewerConfiguration) getSourceViewerConfiguration())
4431 .handlePropertyChangeEvent(event);
4433 // if (affectsOverrideIndicatorAnnotations(event)) {
4434 // if (isShowingOverrideIndicators()) {
4435 // if (fOverrideIndicatorManager == null)
4436 // installOverrideIndicator(true);
4438 // if (fOverrideIndicatorManager != null)
4439 // uninstallOverrideIndicator();
4444 if (PreferenceConstants.EDITOR_FOLDING_PROVIDER.equals(property)) {
4445 if (sourceViewer instanceof ProjectionViewer) {
4446 ProjectionViewer projectionViewer = (ProjectionViewer) sourceViewer;
4447 if (fProjectionModelUpdater != null)
4448 fProjectionModelUpdater.uninstall();
4449 // either freshly enabled or provider changed
4450 fProjectionModelUpdater = PHPeclipsePlugin.getDefault()
4451 .getFoldingStructureProviderRegistry()
4452 .getCurrentFoldingProvider();
4453 if (fProjectionModelUpdater != null) {
4454 fProjectionModelUpdater.install(this, projectionViewer);
4460 super.handlePreferenceStoreChanged(event);
4466 // AbstractTextEditor#handlePreferenceStoreChanged(PropertyChangeEvent)
4468 // protected void handlePreferenceStoreChanged(PropertyChangeEvent event) {
4472 // ISourceViewer sourceViewer = getSourceViewer();
4473 // if (sourceViewer == null)
4476 // String property = event.getProperty();
4479 // (JavaSourceViewerConfiguration.PREFERENCE_TAB_WIDTH.equals(property)) {
4480 // // Object value= event.getNewValue();
4481 // // if (value instanceof Integer) {
4482 // // sourceViewer.getTextWidget().setTabs(((Integer) value).intValue());
4483 // // } else if (value instanceof String) {
4484 // // sourceViewer.getTextWidget().setTabs(Integer.parseInt((String)
4490 // if (IPreferenceConstants.LINE_NUMBER_RULER.equals(property)) {
4491 // if (isLineNumberRulerVisible())
4492 // showLineNumberRuler();
4494 // hideLineNumberRuler();
4498 // if (fLineNumberRulerColumn != null
4499 // && (IPreferenceConstants.LINE_NUMBER_COLOR.equals(property)
4500 // || PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT.equals(property)
4501 // || PREFERENCE_COLOR_BACKGROUND.equals(property))) {
4503 // initializeLineNumberRulerColumn(fLineNumberRulerColumn);
4507 // super.handlePreferenceStoreChanged(event);
4511 // private boolean isJavaEditorHoverProperty(String property) {
4512 // return PreferenceConstants.EDITOR_DEFAULT_HOVER.equals(property)
4513 // || PreferenceConstants.EDITOR_NONE_HOVER.equals(property)
4514 // || PreferenceConstants.EDITOR_CTRL_HOVER.equals(property)
4515 // || PreferenceConstants.EDITOR_SHIFT_HOVER.equals(property)
4516 // || PreferenceConstants.EDITOR_CTRL_ALT_HOVER.equals(property)
4517 // || PreferenceConstants.EDITOR_CTRL_SHIFT_HOVER.equals(property)
4518 // || PreferenceConstants.EDITOR_CTRL_ALT_SHIFT_HOVER.equals(property)
4519 // || PreferenceConstants.EDITOR_ALT_SHIFT_HOVER.equals(property);
4523 * Shows the line number ruler column.
4525 // private void showLineNumberRuler() {
4526 // IVerticalRuler v = getVerticalRuler();
4527 // if (v instanceof CompositeRuler) {
4528 // CompositeRuler c = (CompositeRuler) v;
4529 // c.addDecorator(1, createLineNumberRulerColumn());
4532 private boolean isJavaEditorHoverProperty(String property) {
4533 return PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS.equals(property);
4537 * Return whether the browser like links should be enabled according to the
4538 * preference store settings.
4540 * @return <code>true</code> if the browser like links should be enabled
4542 private boolean isBrowserLikeLinks() {
4543 IPreferenceStore store = getPreferenceStore();
4544 return store.getBoolean(BROWSER_LIKE_LINKS);
4548 * Enables browser like links.
4550 private void enableBrowserLikeLinks() {
4551 if (fMouseListener == null) {
4552 fMouseListener = new MouseClickListener();
4553 fMouseListener.install();
4558 * Disables browser like links.
4560 private void disableBrowserLikeLinks() {
4561 if (fMouseListener != null) {
4562 fMouseListener.uninstall();
4563 fMouseListener = null;
4568 * Handles a property change event describing a change of the java core's
4569 * preferences and updates the preference related editor properties.
4572 * the property change event
4574 protected void handlePreferencePropertyChanged(
4575 org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) {
4576 if (COMPILER_TASK_TAGS.equals(event.getProperty())) {
4577 ISourceViewer sourceViewer = getSourceViewer();
4578 if (sourceViewer != null
4579 && affectsTextPresentation(new PropertyChangeEvent(event
4580 .getSource(), event.getProperty(), event
4581 .getOldValue(), event.getNewValue())))
4582 sourceViewer.invalidateTextPresentation();
4584 if (PreferenceConstants.EDITOR_WRAP_WORDS.equals(event.getProperty())) {
4590 * Return whether the line number ruler column should be visible according
4591 * to the preference store settings.
4593 * @return <code>true</code> if the line numbers should be visible
4595 // protected boolean isLineNumberRulerVisible() {
4596 // IPreferenceStore store = getPreferenceStore();
4597 // return store.getBoolean(LINE_NUMBER_RULER);
4600 * Hides the line number ruler column.
4602 // private void hideLineNumberRuler() {
4603 // IVerticalRuler v = getVerticalRuler();
4604 // if (v instanceof CompositeRuler) {
4605 // CompositeRuler c = (CompositeRuler) v;
4607 // c.removeDecorator(1);
4608 // } catch (Throwable e) {
4613 * @see AbstractTextEditor#handleCursorPositionChanged()
4615 // protected void handleCursorPositionChanged() {
4616 // super.handleCursorPositionChanged();
4617 // if (!isEditingScriptRunning() && fUpdater != null)
4621 * @see org.eclipse.ui.texteditor.AbstractTextEditor#handleElementContentReplaced()
4623 protected void handleElementContentReplaced() {
4624 super.handleElementContentReplaced();
4625 if (fProjectionModelUpdater != null)
4626 fProjectionModelUpdater.initialize();
4630 * Initializes the given line number ruler column from the preference store.
4632 * @param rulerColumn
4633 * the ruler column to be initialized
4635 // protected void initializeLineNumberRulerColumn(LineNumberRulerColumn
4637 // JavaTextTools textTools =
4638 // PHPeclipsePlugin.getDefault().getJavaTextTools();
4639 // IColorManager manager = textTools.getColorManager();
4641 // IPreferenceStore store = getPreferenceStore();
4642 // if (store != null) {
4645 // // foreground color
4646 // if (store.contains(LINE_NUMBER_COLOR)) {
4647 // if (store.isDefault(LINE_NUMBER_COLOR))
4648 // rgb = PreferenceConverter.getDefaultColor(store, LINE_NUMBER_COLOR);
4650 // rgb = PreferenceConverter.getColor(store, LINE_NUMBER_COLOR);
4652 // rulerColumn.setForeground(manager.getColor(rgb));
4655 // // background color
4656 // if (!store.getBoolean(PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT)) {
4657 // if (store.contains(PREFERENCE_COLOR_BACKGROUND)) {
4658 // if (store.isDefault(PREFERENCE_COLOR_BACKGROUND))
4659 // rgb = PreferenceConverter.getDefaultColor(store,
4660 // PREFERENCE_COLOR_BACKGROUND);
4662 // rgb = PreferenceConverter.getColor(store, PREFERENCE_COLOR_BACKGROUND);
4665 // rulerColumn.setBackground(manager.getColor(rgb));
4669 * Creates a new line number ruler column that is appropriately initialized.
4671 // protected IVerticalRulerColumn createLineNumberRulerColumn() {
4672 // fLineNumberRulerColumn = new LineNumberRulerColumn();
4673 // initializeLineNumberRulerColumn(fLineNumberRulerColumn);
4674 // return fLineNumberRulerColumn;
4677 * @see AbstractTextEditor#createVerticalRuler()
4679 // protected IVerticalRuler createVerticalRuler() {
4680 // CompositeRuler ruler = new CompositeRuler();
4681 // ruler.addDecorator(0, new AnnotationRulerColumn(VERTICAL_RULER_WIDTH));
4682 // if (isLineNumberRulerVisible())
4683 // ruler.addDecorator(1, createLineNumberRulerColumn());
4686 // private static IRegion getSignedSelection(ITextViewer viewer) {
4688 // StyledText text = viewer.getTextWidget();
4689 // int caretOffset = text.getCaretOffset();
4690 // Point selection = text.getSelection();
4693 // int offset, length;
4694 // if (caretOffset == selection.x) {
4695 // offset = selection.y;
4696 // length = selection.x - selection.y;
4700 // offset = selection.x;
4701 // length = selection.y - selection.x;
4704 // return new Region(offset, length);
4706 protected IRegion getSignedSelection(ISourceViewer sourceViewer) {
4707 StyledText text = sourceViewer.getTextWidget();
4708 Point selection = text.getSelectionRange();
4710 if (text.getCaretOffset() == selection.x) {
4711 selection.x = selection.x + selection.y;
4712 selection.y = -selection.y;
4715 selection.x = widgetOffset2ModelOffset(sourceViewer, selection.x);
4717 return new Region(selection.x, selection.y);
4720 /** Preference key for matching brackets */
4721 protected final static String MATCHING_BRACKETS = PreferenceConstants.EDITOR_MATCHING_BRACKETS;
4723 /** Preference key for matching brackets color */
4724 protected final static String MATCHING_BRACKETS_COLOR = PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR;
4726 /** Preference key for highlighting current line */
4727 // protected final static String CURRENT_LINE =
4728 // PreferenceConstants.EDITOR_CURRENT_LINE;
4729 /** Preference key for highlight color of current line */
4730 // protected final static String CURRENT_LINE_COLOR =
4731 // PreferenceConstants.EDITOR_CURRENT_LINE_COLOR;
4732 /** Preference key for showing print marging ruler */
4733 // protected final static String PRINT_MARGIN =
4734 // PreferenceConstants.EDITOR_PRINT_MARGIN;
4735 /** Preference key for print margin ruler color */
4736 // protected final static String PRINT_MARGIN_COLOR =
4737 // PreferenceConstants.EDITOR_PRINT_MARGIN_COLOR;
4738 /** Preference key for print margin ruler column */
4739 // protected final static String PRINT_MARGIN_COLUMN =
4740 // PreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN;
4741 /** Preference key for error indication */
4742 // protected final static String ERROR_INDICATION =
4743 // PreferenceConstants.EDITOR_PROBLEM_INDICATION;
4744 /** Preference key for error color */
4745 // protected final static String ERROR_INDICATION_COLOR =
4746 // PreferenceConstants.EDITOR_PROBLEM_INDICATION_COLOR;
4747 /** Preference key for warning indication */
4748 // protected final static String WARNING_INDICATION =
4749 // PreferenceConstants.EDITOR_WARNING_INDICATION;
4750 /** Preference key for warning color */
4751 // protected final static String WARNING_INDICATION_COLOR =
4752 // PreferenceConstants.EDITOR_WARNING_INDICATION_COLOR;
4753 /** Preference key for task indication */
4754 protected final static String TASK_INDICATION = PreferenceConstants.EDITOR_TASK_INDICATION;
4756 /** Preference key for task color */
4757 protected final static String TASK_INDICATION_COLOR = PreferenceConstants.EDITOR_TASK_INDICATION_COLOR;
4759 /** Preference key for bookmark indication */
4760 protected final static String BOOKMARK_INDICATION = PreferenceConstants.EDITOR_BOOKMARK_INDICATION;
4762 /** Preference key for bookmark color */
4763 protected final static String BOOKMARK_INDICATION_COLOR = PreferenceConstants.EDITOR_BOOKMARK_INDICATION_COLOR;
4765 /** Preference key for search result indication */
4766 protected final static String SEARCH_RESULT_INDICATION = PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION;
4768 /** Preference key for search result color */
4769 protected final static String SEARCH_RESULT_INDICATION_COLOR = PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_COLOR;
4771 /** Preference key for unknown annotation indication */
4772 protected final static String UNKNOWN_INDICATION = PreferenceConstants.EDITOR_UNKNOWN_INDICATION;
4774 /** Preference key for unknown annotation color */
4775 protected final static String UNKNOWN_INDICATION_COLOR = PreferenceConstants.EDITOR_UNKNOWN_INDICATION_COLOR;
4777 /** Preference key for shwoing the overview ruler */
4778 protected final static String OVERVIEW_RULER = PreferenceConstants.EDITOR_OVERVIEW_RULER;
4780 /** Preference key for error indication in overview ruler */
4781 protected final static String ERROR_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_ERROR_INDICATION_IN_OVERVIEW_RULER;
4783 /** Preference key for warning indication in overview ruler */
4784 protected final static String WARNING_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_WARNING_INDICATION_IN_OVERVIEW_RULER;
4786 /** Preference key for task indication in overview ruler */
4787 protected final static String TASK_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_TASK_INDICATION_IN_OVERVIEW_RULER;
4789 /** Preference key for bookmark indication in overview ruler */
4790 protected final static String BOOKMARK_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_BOOKMARK_INDICATION_IN_OVERVIEW_RULER;
4792 /** Preference key for search result indication in overview ruler */
4793 protected final static String SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER;
4795 /** Preference key for unknown annotation indication in overview ruler */
4796 protected final static String UNKNOWN_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_UNKNOWN_INDICATION_IN_OVERVIEW_RULER;
4798 // /** Preference key for compiler task tags */
4799 // private final static String COMPILER_TASK_TAGS=
4800 // JavaCore.COMPILER_TASK_TAGS;
4801 /** Preference key for browser like links */
4802 private final static String BROWSER_LIKE_LINKS = PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS;
4804 /** Preference key for key modifier of browser like links */
4805 private final static String BROWSER_LIKE_LINKS_KEY_MODIFIER = PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER;
4808 * Preference key for key modifier mask of browser like links. The value is
4809 * only used if the value of <code>EDITOR_BROWSER_LIKE_LINKS</code> cannot
4810 * be resolved to valid SWT modifier bits.
4814 private final static String BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK = PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK;
4816 private final static char[] BRACKETS = { '{', '}', '(', ')', '[', ']' };
4818 private static boolean isBracket(char character) {
4819 for (int i = 0; i != BRACKETS.length; ++i)
4820 if (character == BRACKETS[i])
4825 private static boolean isSurroundedByBrackets(IDocument document, int offset) {
4826 if (offset == 0 || offset == document.getLength())
4830 return isBracket(document.getChar(offset - 1))
4831 && isBracket(document.getChar(offset));
4833 } catch (BadLocationException e) {
4838 // protected void configureSourceViewerDecorationSupport() {
4840 // fSourceViewerDecorationSupport.setCharacterPairMatcher(fBracketMatcher);
4842 // fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(
4843 // AnnotationType.UNKNOWN,
4844 // UNKNOWN_INDICATION_COLOR,
4845 // UNKNOWN_INDICATION,
4846 // UNKNOWN_INDICATION_IN_OVERVIEW_RULER,
4848 // fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(
4849 // AnnotationType.BOOKMARK,
4850 // BOOKMARK_INDICATION_COLOR,
4851 // BOOKMARK_INDICATION,
4852 // BOOKMARK_INDICATION_IN_OVERVIEW_RULER,
4854 // fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(
4855 // AnnotationType.TASK,
4856 // TASK_INDICATION_COLOR,
4858 // TASK_INDICATION_IN_OVERVIEW_RULER,
4860 // fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(
4861 // AnnotationType.SEARCH,
4862 // SEARCH_RESULT_INDICATION_COLOR,
4863 // SEARCH_RESULT_INDICATION,
4864 // SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER,
4866 // fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(
4867 // AnnotationType.WARNING,
4868 // WARNING_INDICATION_COLOR,
4869 // WARNING_INDICATION,
4870 // WARNING_INDICATION_IN_OVERVIEW_RULER,
4872 // fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(
4873 // AnnotationType.ERROR,
4874 // ERROR_INDICATION_COLOR,
4875 // ERROR_INDICATION,
4876 // ERROR_INDICATION_IN_OVERVIEW_RULER,
4879 // fSourceViewerDecorationSupport.setCursorLinePainterPreferenceKeys(CURRENT_LINE,
4880 // CURRENT_LINE_COLOR);
4881 // fSourceViewerDecorationSupport.setMarginPainterPreferenceKeys(PRINT_MARGIN,
4882 // PRINT_MARGIN_COLOR, PRINT_MARGIN_COLUMN);
4883 // fSourceViewerDecorationSupport.setMatchingCharacterPainterPreferenceKeys(MATCHING_BRACKETS,
4884 // MATCHING_BRACKETS_COLOR);
4886 // fSourceViewerDecorationSupport.setSymbolicFontName(getFontPropertyPreferenceKey());
4890 * Returns the Java element wrapped by this editors input.
4892 * @return the Java element wrapped by this editors input.
4895 abstract protected IJavaElement getInputJavaElement();
4897 protected void updateStatusLine() {
4898 ITextSelection selection = (ITextSelection) getSelectionProvider()
4900 Annotation annotation = getAnnotation(selection.getOffset(), selection
4902 setStatusLineErrorMessage(null);
4903 setStatusLineMessage(null);
4904 if (annotation != null) {
4906 fIsUpdatingAnnotationViews = true;
4907 updateAnnotationViews(annotation);
4909 fIsUpdatingAnnotationViews = false;
4911 if (annotation instanceof IJavaAnnotation
4912 && ((IJavaAnnotation) annotation).isProblem())
4913 setStatusLineMessage(annotation.getText());
4918 * Jumps to the matching bracket.
4920 public void gotoMatchingBracket() {
4922 ISourceViewer sourceViewer = getSourceViewer();
4923 IDocument document = sourceViewer.getDocument();
4924 if (document == null)
4927 IRegion selection = getSignedSelection(sourceViewer);
4929 int selectionLength = Math.abs(selection.getLength());
4930 if (selectionLength > 1) {
4931 setStatusLineErrorMessage(PHPEditorMessages
4932 .getString("GotoMatchingBracket.error.invalidSelection")); //$NON-NLS-1$
4933 sourceViewer.getTextWidget().getDisplay().beep();
4938 int sourceCaretOffset = selection.getOffset() + selection.getLength();
4939 if (isSurroundedByBrackets(document, sourceCaretOffset))
4940 sourceCaretOffset -= selection.getLength();
4942 IRegion region = fBracketMatcher.match(document, sourceCaretOffset);
4943 if (region == null) {
4944 setStatusLineErrorMessage(PHPEditorMessages
4945 .getString("GotoMatchingBracket.error.noMatchingBracket")); //$NON-NLS-1$
4946 sourceViewer.getTextWidget().getDisplay().beep();
4950 int offset = region.getOffset();
4951 int length = region.getLength();
4956 int anchor = fBracketMatcher.getAnchor();
4957 int targetOffset = (PHPPairMatcher.RIGHT == anchor) ? offset : offset
4960 boolean visible = false;
4961 if (sourceViewer instanceof ITextViewerExtension5) {
4962 ITextViewerExtension5 extension = (ITextViewerExtension5) sourceViewer;
4963 visible = (extension.modelOffset2WidgetOffset(targetOffset) > -1);
4965 IRegion visibleRegion = sourceViewer.getVisibleRegion();
4966 visible = (targetOffset >= visibleRegion.getOffset() && targetOffset < visibleRegion
4968 + visibleRegion.getLength());
4972 setStatusLineErrorMessage(PHPEditorMessages
4973 .getString("GotoMatchingBracket.error.bracketOutsideSelectedElement")); //$NON-NLS-1$
4974 sourceViewer.getTextWidget().getDisplay().beep();
4978 if (selection.getLength() < 0)
4979 targetOffset -= selection.getLength();
4981 sourceViewer.setSelectedRange(targetOffset, selection.getLength());
4982 sourceViewer.revealRange(targetOffset, selection.getLength());
4986 * Ses the given message as error message to this editor's status line.
4991 protected void setStatusLineErrorMessage(String msg) {
4992 IEditorStatusLine statusLine = (IEditorStatusLine) getAdapter(IEditorStatusLine.class);
4993 if (statusLine != null)
4994 statusLine.setMessage(true, msg, null);
4998 * Sets the given message as message to this editor's status line.
5004 protected void setStatusLineMessage(String msg) {
5005 IEditorStatusLine statusLine = (IEditorStatusLine) getAdapter(IEditorStatusLine.class);
5006 if (statusLine != null)
5007 statusLine.setMessage(false, msg, null);
5011 * Returns the annotation closest to the given range respecting the given
5012 * direction. If an annotation is found, the annotations current position is
5013 * copied into the provided annotation position.
5020 * <code>true</code> for forwards, <code>false</code> for
5022 * @param annotationPosition
5023 * the position of the found annotation
5024 * @return the found annotation
5026 private Annotation getNextAnnotation(final int offset, final int length,
5027 boolean forward, Position annotationPosition) {
5029 Annotation nextAnnotation = null;
5030 Position nextAnnotationPosition = null;
5031 Annotation containingAnnotation = null;
5032 Position containingAnnotationPosition = null;
5033 boolean currentAnnotation = false;
5035 IDocument document = getDocumentProvider()
5036 .getDocument(getEditorInput());
5037 int endOfDocument = document.getLength();
5038 int distance = Integer.MAX_VALUE;
5040 IAnnotationModel model = getDocumentProvider().getAnnotationModel(
5042 Iterator e = new JavaAnnotationIterator(model, true, true);
5043 while (e.hasNext()) {
5044 Annotation a = (Annotation) e.next();
5045 if ((a instanceof IJavaAnnotation)
5046 && ((IJavaAnnotation) a).hasOverlay()
5047 || !isNavigationTarget(a))
5050 Position p = model.getPosition(a);
5054 if (forward && p.offset == offset || !forward
5055 && p.offset + p.getLength() == offset + length) {// ||
5056 // p.includes(offset))
5058 if (containingAnnotation == null
5060 && p.length >= containingAnnotationPosition.length || !forward
5061 && p.length >= containingAnnotationPosition.length)) {
5062 containingAnnotation = a;
5063 containingAnnotationPosition = p;
5064 currentAnnotation = p.length == length;
5067 int currentDistance = 0;
5070 currentDistance = p.getOffset() - offset;
5071 if (currentDistance < 0)
5072 currentDistance = endOfDocument + currentDistance;
5074 if (currentDistance < distance
5075 || currentDistance == distance
5076 && p.length < nextAnnotationPosition.length) {
5077 distance = currentDistance;
5079 nextAnnotationPosition = p;
5082 currentDistance = offset + length
5083 - (p.getOffset() + p.length);
5084 if (currentDistance < 0)
5085 currentDistance = endOfDocument + currentDistance;
5087 if (currentDistance < distance
5088 || currentDistance == distance
5089 && p.length < nextAnnotationPosition.length) {
5090 distance = currentDistance;
5092 nextAnnotationPosition = p;
5097 if (containingAnnotationPosition != null
5098 && (!currentAnnotation || nextAnnotation == null)) {
5099 annotationPosition.setOffset(containingAnnotationPosition
5101 annotationPosition.setLength(containingAnnotationPosition
5103 return containingAnnotation;
5105 if (nextAnnotationPosition != null) {
5106 annotationPosition.setOffset(nextAnnotationPosition.getOffset());
5107 annotationPosition.setLength(nextAnnotationPosition.getLength());
5110 return nextAnnotation;
5114 * Returns the annotation overlapping with the given range or
5115 * <code>null</code>.
5121 * @return the found annotation or <code>null</code>
5124 private Annotation getAnnotation(int offset, int length) {
5125 IAnnotationModel model = getDocumentProvider().getAnnotationModel(
5127 Iterator e = new JavaAnnotationIterator(model, true, true);
5128 while (e.hasNext()) {
5129 Annotation a = (Annotation) e.next();
5130 if (!isNavigationTarget(a))
5133 Position p = model.getPosition(a);
5134 if (p != null && p.overlapsWith(offset, length))
5142 * Returns whether the given annotation is configured as a target for the
5143 * "Go to Next/Previous Annotation" actions
5147 * @return <code>true</code> if this is a target, <code>false</code>
5151 protected boolean isNavigationTarget(Annotation annotation) {
5152 Preferences preferences = EditorsUI.getPluginPreferences();
5153 AnnotationPreference preference = getAnnotationPreferenceLookup()
5154 .getAnnotationPreference(annotation);
5156 // String key= forward ? preference.getIsGoToNextNavigationTargetKey() :
5157 // preference.getIsGoToPreviousNavigationTargetKey();
5158 String key = preference == null ? null : preference
5159 .getIsGoToNextNavigationTargetKey();
5160 return (key != null && preferences.getBoolean(key));
5164 * Returns a segmentation of the line of the given document appropriate for
5165 * bidi rendering. The default implementation returns only the string
5166 * literals of a php code line as segments.
5171 * the offset of the line
5172 * @return the line's bidi segmentation
5173 * @throws BadLocationException
5174 * in case lineOffset is not valid in document
5176 public static int[] getBidiLineSegments(IDocument document, int lineOffset)
5177 throws BadLocationException {
5179 IRegion line = document.getLineInformationOfOffset(lineOffset);
5180 ITypedRegion[] linePartitioning = document.computePartitioning(
5181 lineOffset, line.getLength());
5183 List segmentation = new ArrayList();
5184 for (int i = 0; i < linePartitioning.length; i++) {
5185 if (IPHPPartitions.PHP_STRING_DQ.equals(linePartitioning[i]
5187 segmentation.add(linePartitioning[i]);
5188 } else if (IPHPPartitions.PHP_STRING_HEREDOC
5189 .equals(linePartitioning[i].getType())) {
5190 segmentation.add(linePartitioning[i]);
5194 if (segmentation.size() == 0)
5197 int size = segmentation.size();
5198 int[] segments = new int[size * 2 + 1];
5201 for (int i = 0; i < size; i++) {
5202 ITypedRegion segment = (ITypedRegion) segmentation.get(i);
5207 int offset = segment.getOffset() - lineOffset;
5208 if (offset > segments[j - 1])
5209 segments[j++] = offset;
5211 if (offset + segment.getLength() >= line.getLength())
5214 segments[j++] = offset + segment.getLength();
5217 if (j < segments.length) {
5218 int[] result = new int[j];
5219 System.arraycopy(segments, 0, result, 0, j);
5227 * Returns a segmentation of the given line appropriate for bidi rendering.
5228 * The default implementation returns only the string literals of a php code
5232 * the offset of the line
5234 * the content of the line
5235 * @return the line's bidi segmentation
5237 protected int[] getBidiLineSegments(int lineOffset, String line) {
5238 IDocumentProvider provider = getDocumentProvider();
5239 if (provider != null && line != null && line.length() > 0) {
5240 IDocument document = provider.getDocument(getEditorInput());
5241 if (document != null)
5243 return getBidiLineSegments(document, lineOffset);
5244 } catch (BadLocationException x) {
5252 * @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler,
5255 // protected final ISourceViewer createSourceViewer(
5256 // Composite parent,
5257 // IVerticalRuler ruler,
5259 // ISourceViewer viewer = createJavaSourceViewer(parent, ruler, styles);
5260 // StyledText text = viewer.getTextWidget();
5261 // text.addBidiSegmentListener(new BidiSegmentListener() {
5262 // public void lineGetSegments(BidiSegmentEvent event) {
5263 // event.segments = getBidiLineSegments(event.lineOffset, event.lineText);
5266 // // JavaUIHelp.setHelp(this, text, IJavaHelpContextIds.JAVA_EDITOR);
5269 public final ISourceViewer getViewer() {
5270 return getSourceViewer();
5273 // protected void showOverviewRuler() {
5274 // if (fOverviewRuler != null) {
5275 // if (getSourceViewer() instanceof ISourceViewerExtension) {
5276 // ((ISourceViewerExtension)
5277 // getSourceViewer()).showAnnotationsOverview(true);
5278 // fSourceViewerDecorationSupport.updateOverviewDecorations();
5283 // protected void hideOverviewRuler() {
5284 // if (getSourceViewer() instanceof ISourceViewerExtension) {
5285 // fSourceViewerDecorationSupport.hideAnnotationOverview();
5286 // ((ISourceViewerExtension)
5287 // getSourceViewer()).showAnnotationsOverview(false);
5291 // protected boolean isOverviewRulerVisible() {
5292 // IPreferenceStore store = getPreferenceStore();
5293 // return store.getBoolean(OVERVIEW_RULER);
5296 * @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler,
5299 // protected ISourceViewer createJavaSourceViewer(
5300 // Composite parent,
5301 // IVerticalRuler ruler,
5302 // IOverviewRuler overviewRuler,
5303 // boolean isOverviewRulerVisible,
5305 // return new SourceViewer(parent, ruler, overviewRuler,
5306 // isOverviewRulerVisible(), styles);
5309 * @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler,
5312 protected ISourceViewer createJavaSourceViewer(Composite parent,
5313 IVerticalRuler verticalRuler, IOverviewRuler overviewRuler,
5314 boolean isOverviewRulerVisible, int styles, IPreferenceStore store) {
5315 return new JavaSourceViewer(parent, verticalRuler, getOverviewRuler(),
5316 isOverviewRulerVisible(), styles, store);
5320 * @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler,
5323 protected final ISourceViewer createSourceViewer(Composite parent,
5324 IVerticalRuler verticalRuler, int styles) {
5326 ISourceViewer viewer = createJavaSourceViewer(parent, verticalRuler,
5327 getOverviewRuler(), isOverviewRulerVisible(), styles,
5328 getPreferenceStore());
5330 StyledText text = viewer.getTextWidget();
5331 text.addBidiSegmentListener(new BidiSegmentListener() {
5332 public void lineGetSegments(BidiSegmentEvent event) {
5333 event.segments = getBidiLineSegments(event.lineOffset,
5338 // JavaUIHelp.setHelp(this, text, IJavaHelpContextIds.JAVA_EDITOR);
5340 // ensure source viewer decoration support has been created and
5342 getSourceViewerDecorationSupport(viewer);
5348 * @see AbstractTextEditor#affectsTextPresentation(PropertyChangeEvent)
5350 protected boolean affectsTextPresentation(PropertyChangeEvent event) {
5351 return ((PHPSourceViewerConfiguration) getSourceViewerConfiguration())
5352 .affectsTextPresentation(event)
5353 || super.affectsTextPresentation(event);
5357 // protected boolean affectsTextPresentation(PropertyChangeEvent event) {
5358 // JavaTextTools textTools =
5359 // PHPeclipsePlugin.getDefault().getJavaTextTools();
5360 // return textTools.affectsBehavior(event);
5363 * Creates and returns the preference store for this Java editor with the
5367 * The editor input for which to create the preference store
5368 * @return the preference store for this editor
5372 private IPreferenceStore createCombinedPreferenceStore(IEditorInput input) {
5373 List stores = new ArrayList(3);
5375 IJavaProject project = EditorUtility.getJavaProject(input);
5376 if (project != null)
5377 stores.add(new OptionsAdapter(project.getOptions(false),
5378 PHPeclipsePlugin.getDefault().getMockupPreferenceStore(),
5379 new OptionsAdapter.IPropertyChangeEventFilter() {
5381 public boolean isFiltered(PropertyChangeEvent event) {
5382 IJavaElement inputJavaElement = getInputJavaElement();
5383 IJavaProject javaProject = inputJavaElement != null ? inputJavaElement
5386 if (javaProject == null)
5389 return !javaProject.getProject().equals(
5395 stores.add(PHPeclipsePlugin.getDefault().getPreferenceStore());
5396 stores.add(new PreferencesAdapter(JavaCore.getPlugin()
5397 .getPluginPreferences()));
5398 stores.add(EditorsUI.getPreferenceStore());
5400 return new ChainedPreferenceStore((IPreferenceStore[]) stores
5401 .toArray(new IPreferenceStore[stores.size()]));
5405 * Jumps to the error next according to the given direction.
5407 public void gotoError(boolean forward) {
5409 ISelectionProvider provider = getSelectionProvider();
5411 ITextSelection s = (ITextSelection) provider.getSelection();
5412 Position errorPosition = new Position(0, 0);
5413 IJavaAnnotation nextError = getNextError(s.getOffset(), forward,
5416 if (nextError != null) {
5418 IMarker marker = null;
5419 if (nextError instanceof MarkerAnnotation)
5420 marker = ((MarkerAnnotation) nextError).getMarker();
5422 Iterator e = nextError.getOverlaidIterator();
5424 while (e.hasNext()) {
5425 Object o = e.next();
5426 if (o instanceof MarkerAnnotation) {
5427 marker = ((MarkerAnnotation) o).getMarker();
5434 if (marker != null) {
5435 IWorkbenchPage page = getSite().getPage();
5436 IViewPart view = view = page
5437 .findView("org.eclipse.ui.views.TaskList"); //$NON-NLS-1$
5438 if (view instanceof TaskList) {
5439 StructuredSelection ss = new StructuredSelection(marker);
5440 ((TaskList) view).setSelection(ss, true);
5444 selectAndReveal(errorPosition.getOffset(), errorPosition
5446 // setStatusLineErrorMessage(nextError.getMessage());
5450 setStatusLineErrorMessage(null);
5455 private IJavaAnnotation getNextError(int offset, boolean forward,
5456 Position errorPosition) {
5458 IJavaAnnotation nextError = null;
5459 Position nextErrorPosition = null;
5461 IDocument document = getDocumentProvider()
5462 .getDocument(getEditorInput());
5463 int endOfDocument = document.getLength();
5466 IAnnotationModel model = getDocumentProvider().getAnnotationModel(
5468 Iterator e = new JavaAnnotationIterator(model, false);
5469 while (e.hasNext()) {
5471 IJavaAnnotation a = (IJavaAnnotation) e.next();
5472 if (a.hasOverlay() || !a.isProblem())
5475 Position p = model.getPosition((Annotation) a);
5476 if (!p.includes(offset)) {
5478 int currentDistance = 0;
5481 currentDistance = p.getOffset() - offset;
5482 if (currentDistance < 0)
5483 currentDistance = endOfDocument - offset
5486 currentDistance = offset - p.getOffset();
5487 if (currentDistance < 0)
5488 currentDistance = offset + endOfDocument
5492 if (nextError == null || currentDistance < distance) {
5493 distance = currentDistance;
5495 nextErrorPosition = p;
5500 if (nextErrorPosition != null) {
5501 errorPosition.setOffset(nextErrorPosition.getOffset());
5502 errorPosition.setLength(nextErrorPosition.getLength());
5508 protected void uninstallOverrideIndicator() {
5509 // if (fOverrideIndicatorManager != null) {
5510 // fOverrideIndicatorManager.removeAnnotations();
5511 // fOverrideIndicatorManager= null;
5515 protected void installOverrideIndicator(boolean waitForReconcilation) {
5516 uninstallOverrideIndicator();
5517 IAnnotationModel model = getDocumentProvider().getAnnotationModel(
5519 final IJavaElement inputElement = getInputJavaElement();
5521 if (model == null || inputElement == null)
5524 // fOverrideIndicatorManager= new OverrideIndicatorManager(model,
5525 // inputElement, null);
5527 // if (provideAST) {
5529 // Job(JavaEditorMessages.getString("OverrideIndicatorManager.intallJob"))
5534 // org.eclipse.core.runtime.jobs.Job#run(org.eclipse.core.runtime.IProgressMonitor)
5537 // protected IStatus run(IProgressMonitor monitor) {
5538 // CompilationUnit ast=
5539 // JavaPlugin.getDefault().getASTProvider().getAST(inputElement, true,
5541 // if (fOverrideIndicatorManager != null) // editor might have been
5544 // fOverrideIndicatorManager.reconciled(ast, true, monitor);
5545 // return Status.OK_STATUS;
5548 // job.setPriority(Job.DECORATE);
5549 // job.setSystem(true);
5555 * Tells whether override indicators are shown.
5557 * @return <code>true</code> if the override indicators are shown
5560 // protected boolean isShowingOverrideIndicators() {
5561 // AnnotationPreference preference=
5562 // getAnnotationPreferenceLookup().getAnnotationPreference(OverrideIndicatorManager.ANNOTATION_TYPE);
5563 // IPreferenceStore store= getPreferenceStore();
5564 // return getBoolean(store, preference.getHighlightPreferenceKey())
5565 // || getBoolean(store, preference.getVerticalRulerPreferenceKey())
5566 // || getBoolean(store, preference.getOverviewRulerPreferenceKey())
5567 // || getBoolean(store, preference.getTextPreferenceKey());
5570 * Returns the boolean preference for the given key.
5573 * the preference store
5575 * the preference key
5576 * @return <code>true</code> if the key exists in the store and its value
5577 * is <code>true</code>
5580 private boolean getBoolean(IPreferenceStore store, String key) {
5581 return key != null && store.getBoolean(key);
5584 protected boolean isPrefQuickDiffAlwaysOn() {
5585 return false; // never show change ruler for the non-editable java
5587 // Overridden in subclasses like PHPUnitEditor
5591 * @see org.eclipse.ui.texteditor.AbstractTextEditor#createNavigationActions()
5593 protected void createNavigationActions() {
5594 super.createNavigationActions();
5596 final StyledText textWidget = getSourceViewer().getTextWidget();
5598 IAction action = new SmartLineStartAction(textWidget, false);
5599 action.setActionDefinitionId(ITextEditorActionDefinitionIds.LINE_START);
5600 setAction(ITextEditorActionDefinitionIds.LINE_START, action);
5602 action = new SmartLineStartAction(textWidget, true);
5604 .setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_LINE_START);
5605 setAction(ITextEditorActionDefinitionIds.SELECT_LINE_START, action);
5607 action = new NavigatePreviousSubWordAction();
5609 .setActionDefinitionId(ITextEditorActionDefinitionIds.WORD_PREVIOUS);
5610 setAction(ITextEditorActionDefinitionIds.WORD_PREVIOUS, action);
5611 textWidget.setKeyBinding(SWT.CTRL | SWT.ARROW_LEFT, SWT.NULL);
5613 action = new NavigateNextSubWordAction();
5614 action.setActionDefinitionId(ITextEditorActionDefinitionIds.WORD_NEXT);
5615 setAction(ITextEditorActionDefinitionIds.WORD_NEXT, action);
5616 textWidget.setKeyBinding(SWT.CTRL | SWT.ARROW_RIGHT, SWT.NULL);
5618 action = new SelectPreviousSubWordAction();
5620 .setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_WORD_PREVIOUS);
5621 setAction(ITextEditorActionDefinitionIds.SELECT_WORD_PREVIOUS, action);
5622 textWidget.setKeyBinding(SWT.CTRL | SWT.SHIFT | SWT.ARROW_LEFT,
5625 action = new SelectNextSubWordAction();
5627 .setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_WORD_NEXT);
5628 setAction(ITextEditorActionDefinitionIds.SELECT_WORD_NEXT, action);
5629 textWidget.setKeyBinding(SWT.CTRL | SWT.SHIFT | SWT.ARROW_RIGHT,
5634 * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#createCompositeRuler()
5636 // protected CompositeRuler createCompositeRuler() {
5638 // (!getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_ANNOTATION_ROLL_OVER))
5639 // return super.createCompositeRuler();
5641 // CompositeRuler ruler = new CompositeRuler();
5642 // AnnotationRulerColumn column = new
5643 // AnnotationRulerColumn(VERTICAL_RULER_WIDTH, getAnnotationAccess());
5644 // column.setHover(new JavaExpandHover(ruler, getAnnotationAccess(), new
5645 // IDoubleClickListener() {
5647 // public void doubleClick(DoubleClickEvent event) {
5648 // // for now: just invoke ruler double click action
5649 // triggerAction(ITextEditorActionConstants.RULER_DOUBLE_CLICK);
5652 // private void triggerAction(String actionID) {
5653 // IAction action = getAction(actionID);
5654 // if (action != null) {
5655 // if (action instanceof IUpdate)
5656 // ((IUpdate) action).update();
5657 // // hack to propagate line change
5658 // if (action instanceof ISelectionListener) {
5659 // ((ISelectionListener) action).selectionChanged(null, null);
5661 // if (action.isEnabled())
5667 // ruler.addDecorator(0, column);
5669 // if (isLineNumberRulerVisible())
5670 // ruler.addDecorator(1, createLineNumberRulerColumn());
5671 // else if (isPrefQuickDiffAlwaysOn())
5672 // ruler.addDecorator(1, createChangeRulerColumn());
5677 * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#createAnnotationRulerColumn(org.eclipse.jface.text.source.CompositeRuler)
5680 protected IVerticalRulerColumn createAnnotationRulerColumn(
5681 CompositeRuler ruler) {
5682 if (!getPreferenceStore().getBoolean(
5683 PreferenceConstants.EDITOR_ANNOTATION_ROLL_OVER))
5684 return super.createAnnotationRulerColumn(ruler);
5686 AnnotationRulerColumn column = new AnnotationRulerColumn(
5687 VERTICAL_RULER_WIDTH, getAnnotationAccess());
5688 column.setHover(new JavaExpandHover(ruler, getAnnotationAccess(),
5689 new IDoubleClickListener() {
5691 public void doubleClick(DoubleClickEvent event) {
5692 // for now: just invoke ruler double click action
5693 triggerAction(ITextEditorActionConstants.RULER_DOUBLE_CLICK);
5696 private void triggerAction(String actionID) {
5697 IAction action = getAction(actionID);
5698 if (action != null) {
5699 if (action instanceof IUpdate)
5700 ((IUpdate) action).update();
5701 // hack to propagate line change
5702 if (action instanceof ISelectionListener) {
5703 ((ISelectionListener) action).selectionChanged(
5706 if (action.isEnabled())
5717 * Returns the folding action group, or <code>null</code> if there is
5720 * @return the folding action group, or <code>null</code> if there is none
5723 protected FoldingActionGroup getFoldingActionGroup() {
5724 return fFoldingGroup;
5728 * @see org.eclipse.ui.texteditor.AbstractTextEditor#performRevert()
5730 protected void performRevert() {
5731 ProjectionViewer projectionViewer = (ProjectionViewer) getSourceViewer();
5732 projectionViewer.setRedraw(false);
5735 boolean projectionMode = projectionViewer.isProjectionMode();
5736 if (projectionMode) {
5737 projectionViewer.disableProjection();
5738 if (fProjectionModelUpdater != null)
5739 fProjectionModelUpdater.uninstall();
5742 super.performRevert();
5744 if (projectionMode) {
5745 if (fProjectionModelUpdater != null)
5746 fProjectionModelUpdater.install(this, projectionViewer);
5747 projectionViewer.enableProjection();
5751 projectionViewer.setRedraw(true);
5756 * React to changed selection.
5760 protected void selectionChanged() {
5761 if (getSelectionProvider() == null)
5763 ISourceReference element = computeHighlightRangeSourceReference();
5764 if (getPreferenceStore().getBoolean(
5765 PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE))
5766 synchronizeOutlinePage(element);
5767 setSelection(element, false);
5771 private boolean isJavaOutlinePageActive() {
5772 IWorkbenchPart part = getActivePart();
5773 return part instanceof ContentOutline
5774 && ((ContentOutline) part).getCurrentPage() == fOutlinePage;
5777 private IWorkbenchPart getActivePart() {
5778 IWorkbenchWindow window = getSite().getWorkbenchWindow();
5779 IPartService service = window.getPartService();
5780 IWorkbenchPart part = service.getActivePart();
5785 * Computes and returns the source reference that includes the caret and
5786 * serves as provider for the outline page selection and the editor range
5789 * @return the computed source reference
5792 protected ISourceReference computeHighlightRangeSourceReference() {
5793 ISourceViewer sourceViewer = getSourceViewer();
5794 if (sourceViewer == null)
5797 StyledText styledText = sourceViewer.getTextWidget();
5798 if (styledText == null)
5802 if (sourceViewer instanceof ITextViewerExtension5) {
5803 ITextViewerExtension5 extension = (ITextViewerExtension5) sourceViewer;
5804 caret = extension.widgetOffset2ModelOffset(styledText
5807 int offset = sourceViewer.getVisibleRegion().getOffset();
5808 caret = offset + styledText.getCaretOffset();
5811 IJavaElement element = getElementAt(caret, false);
5813 if (!(element instanceof ISourceReference))
5816 if (element.getElementType() == IJavaElement.IMPORT_DECLARATION) {
5818 IImportDeclaration declaration = (IImportDeclaration) element;
5819 IImportContainer container = (IImportContainer) declaration
5821 ISourceRange srcRange = null;
5824 srcRange = container.getSourceRange();
5825 } catch (JavaModelException e) {
5828 if (srcRange != null && srcRange.getOffset() == caret)
5832 return (ISourceReference) element;
5836 * Returns the most narrow java element including the given offset.
5839 * the offset inside of the requested element
5841 * <code>true</code> if editor input should be reconciled in
5843 * @return the most narrow java element
5846 protected IJavaElement getElementAt(int offset, boolean reconcile) {
5847 return getElementAt(offset);
5850 public ShowInContext getShowInContext() {
5851 FileEditorInput fei = (FileEditorInput) getEditorInput();
5852 ShowInContext context = BrowserUtil.getShowInContext(fei.getFile(),
5854 if (context != null) {
5857 return new ShowInContext(fei.getFile(), null);
5860 public String[] getShowInTargetIds() {
5861 return new String[] { BrowserView.ID_BROWSER };
5865 * Updates the occurrences annotations based on the current selection.
5868 * the text selection
5870 * the compilation unit AST
5873 protected void updateOccurrenceAnnotations(ITextSelection selection) {// ,
5878 if (fOccurrencesFinderJob != null)
5879 fOccurrencesFinderJob.cancel();
5881 if (!fMarkOccurrenceAnnotations)
5884 // if (astRoot == null || selection == null)
5885 if (selection == null)
5888 IDocument document = getSourceViewer().getDocument();
5889 if (document == null)
5892 fMarkOccurrenceTargetRegion = null;
5893 if (document instanceof IDocumentExtension4) {
5894 int offset = selection.getOffset();
5895 long currentModificationStamp = ((IDocumentExtension4) document)
5896 .getModificationStamp();
5897 if (fMarkOccurrenceTargetRegion != null
5898 && currentModificationStamp == fMarkOccurrenceModificationStamp) {
5899 if (fMarkOccurrenceTargetRegion.getOffset() <= offset
5900 && offset <= fMarkOccurrenceTargetRegion.getOffset()
5901 + fMarkOccurrenceTargetRegion.getLength())
5904 fMarkOccurrenceTargetRegion = JavaWordFinder.findWord(document,
5906 fMarkOccurrenceModificationStamp = currentModificationStamp;
5909 if (fMarkOccurrenceTargetRegion == null
5910 || fMarkOccurrenceTargetRegion.getLength() == 0) {
5914 List matches = null;
5916 if (matches == null) {
5918 matches = new ArrayList();
5920 Scanner fScanner = new Scanner();
5921 fScanner.setSource(document.get().toCharArray());
5922 fScanner.setPHPMode(false);
5926 wordStr = document.get(fMarkOccurrenceTargetRegion.getOffset(),
5927 fMarkOccurrenceTargetRegion.getLength());
5928 if (wordStr != null) {
5929 word = wordStr.toCharArray();
5930 int fToken = ITerminalSymbols.TokenNameEOF;
5932 fToken = fScanner.getNextToken();
5933 while (fToken != ITerminalSymbols.TokenNameEOF) { // &&
5936 // TokenNameERROR) {
5937 if (fToken == ITerminalSymbols.TokenNameVariable
5938 || fToken == ITerminalSymbols.TokenNameIdentifier) {
5940 if (fScanner.equalsCurrentTokenSource(word)) {
5944 .getCurrentTokenStartPosition(),
5946 .getCurrentTokenEndPosition()
5948 .getCurrentTokenStartPosition()
5952 fToken = fScanner.getNextToken();
5954 } catch (InvalidInputException e) {
5956 } catch (SyntaxError e) {
5960 } catch (BadLocationException e1) {
5962 } catch (Exception e) {
5963 e.printStackTrace();
5969 if (matches == null || matches.size() == 0) {
5970 if (!fStickyOccurrenceAnnotations)
5971 removeOccurrenceAnnotations();
5975 Position[] positions = new Position[matches.size()];
5977 for (Iterator each = matches.iterator(); each.hasNext();) {
5978 IRegion currentNode = (IRegion) each.next();
5979 positions[i++] = new Position(currentNode.getOffset(), currentNode
5983 fOccurrencesFinderJob = new OccurrencesFinderJob(document, positions,
5985 // fOccurrencesFinderJob.setPriority(Job.DECORATE);
5986 // fOccurrencesFinderJob.setSystem(true);
5987 // fOccurrencesFinderJob.schedule();
5988 fOccurrencesFinderJob.run(new NullProgressMonitor());
5991 protected void installOccurrencesFinder() {
5992 fMarkOccurrenceAnnotations = true;
5994 fPostSelectionListenerWithAST = new ISelectionListenerWithAST() {
5995 public void selectionChanged(IEditorPart part,
5996 ITextSelection selection) { // ,
6000 updateOccurrenceAnnotations(selection);// , astRoot);
6003 SelectionListenerWithASTManager.getDefault().addListener(this,
6004 fPostSelectionListenerWithAST);
6005 if (getSelectionProvider() != null) {
6006 fForcedMarkOccurrencesSelection = getSelectionProvider()
6008 SelectionListenerWithASTManager.getDefault().forceSelectionChange(
6009 this, (ITextSelection) fForcedMarkOccurrencesSelection);
6012 if (fOccurrencesFinderJobCanceler == null) {
6013 fOccurrencesFinderJobCanceler = new OccurrencesFinderJobCanceler();
6014 fOccurrencesFinderJobCanceler.install();
6018 protected void uninstallOccurrencesFinder() {
6019 fMarkOccurrenceAnnotations = false;
6021 if (fOccurrencesFinderJob != null) {
6022 fOccurrencesFinderJob.cancel();
6023 fOccurrencesFinderJob = null;
6026 if (fOccurrencesFinderJobCanceler != null) {
6027 fOccurrencesFinderJobCanceler.uninstall();
6028 fOccurrencesFinderJobCanceler = null;
6031 if (fPostSelectionListenerWithAST != null) {
6032 SelectionListenerWithASTManager.getDefault().removeListener(this,
6033 fPostSelectionListenerWithAST);
6034 fPostSelectionListenerWithAST = null;
6037 removeOccurrenceAnnotations();
6040 protected boolean isMarkingOccurrences() {
6041 return fMarkOccurrenceAnnotations;
6044 void removeOccurrenceAnnotations() {
6045 fMarkOccurrenceModificationStamp = IDocumentExtension4.UNKNOWN_MODIFICATION_STAMP;
6046 fMarkOccurrenceTargetRegion = null;
6048 IDocumentProvider documentProvider = getDocumentProvider();
6049 if (documentProvider == null)
6052 IAnnotationModel annotationModel = documentProvider
6053 .getAnnotationModel(getEditorInput());
6054 if (annotationModel == null || fOccurrenceAnnotations == null)
6057 synchronized (getLockObject(annotationModel)) {
6058 if (annotationModel instanceof IAnnotationModelExtension) {
6059 ((IAnnotationModelExtension) annotationModel)
6060 .replaceAnnotations(fOccurrenceAnnotations, null);
6062 for (int i = 0, length = fOccurrenceAnnotations.length; i < length; i++)
6063 annotationModel.removeAnnotation(fOccurrenceAnnotations[i]);
6065 fOccurrenceAnnotations = null;