repaired missing icon
[phpeclipse.git] / net.sourceforge.phpeclipse / src / net / sourceforge / phpeclipse / phpeditor / PHPEditor.java
1 package net.sourceforge.phpeclipse.phpeditor;
2
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
9
10  Contributors:
11  IBM Corporation - Initial implementation
12  www.phpeclipse.de
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;
22 import java.util.Map;
23 import java.util.ResourceBundle;
24 import java.util.StringTokenizer;
25
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;
66
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;
199
200 /**
201  * PHP specific text editor.
202  */
203 public abstract class PHPEditor extends AbstractDecoratedTextEditor implements
204                 IViewPartInputProvider, IShowInTargetList, IShowInSource {
205         // extends StatusTextEditor implements IViewPartInputProvider { // extends
206         // TextEditor {
207
208         /**
209          * Internal implementation class for a change listener.
210          * 
211          * @since 3.0
212          */
213         protected abstract class AbstractSelectionChangedListener implements
214                         ISelectionChangedListener {
215
216                 /**
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.
221                  * 
222                  * @param selectionProvider
223                  */
224                 public void install(ISelectionProvider selectionProvider) {
225                         if (selectionProvider == null)
226                                 return;
227
228                         if (selectionProvider instanceof IPostSelectionProvider) {
229                                 IPostSelectionProvider provider = (IPostSelectionProvider) selectionProvider;
230                                 provider.addPostSelectionChangedListener(this);
231                         } else {
232                                 selectionProvider.addSelectionChangedListener(this);
233                         }
234                 }
235
236                 /**
237                  * Removes this selection changed listener from the given selection
238                  * provider.
239                  * 
240                  * @param selectionProvider
241                  *            the selection provider
242                  */
243                 public void uninstall(ISelectionProvider selectionProvider) {
244                         if (selectionProvider == null)
245                                 return;
246
247                         if (selectionProvider instanceof IPostSelectionProvider) {
248                                 IPostSelectionProvider provider = (IPostSelectionProvider) selectionProvider;
249                                 provider.removePostSelectionChangedListener(this);
250                         } else {
251                                 selectionProvider.removeSelectionChangedListener(this);
252                         }
253                 }
254         }
255
256         /**
257          * Updates the Java outline page selection and this editor's range
258          * indicator.
259          * 
260          * @since 3.0
261          */
262         private class EditorSelectionChangedListener extends
263                         AbstractSelectionChangedListener {
264
265                 /*
266                  * @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent)
267                  */
268                 public void selectionChanged(SelectionChangedEvent event) {
269                         // XXX: see https://bugs.eclipse.org/bugs/show_bug.cgi?id=56161
270                         PHPEditor.this.selectionChanged();
271                 }
272         }
273
274         /**
275          * "Smart" runnable for updating the outline page's selection.
276          */
277         // class OutlinePageSelectionUpdater implements Runnable {
278         //
279         // /** Has the runnable already been posted? */
280         // private boolean fPosted = false;
281         //
282         // public OutlinePageSelectionUpdater() {
283         // }
284         //
285         // /*
286         // * @see Runnable#run()
287         // */
288         // public void run() {
289         // synchronizeOutlinePageSelection();
290         // fPosted = false;
291         // }
292         //
293         // /**
294         // * Posts this runnable into the event queue.
295         // */
296         // public void post() {
297         // if (fPosted)
298         // return;
299         //
300         // Shell shell = getSite().getShell();
301         // if (shell != null & !shell.isDisposed()) {
302         // fPosted = true;
303         // shell.getDisplay().asyncExec(this);
304         // }
305         // }
306         // };
307         class SelectionChangedListener implements ISelectionChangedListener {
308                 public void selectionChanged(SelectionChangedEvent event) {
309                         doSelectionChanged(event);
310                 }
311         };
312
313         /**
314          * Adapts an options {@link java.util.Map}to
315          * {@link org.eclipse.jface.preference.IPreferenceStore}.
316          * <p>
317          * This preference store is read-only i.e. write access throws an
318          * {@link java.lang.UnsupportedOperationException}.
319          * </p>
320          * 
321          * @since 3.0
322          */
323         private static class OptionsAdapter implements IPreferenceStore {
324
325                 /**
326                  * A property change event filter.
327                  */
328                 public interface IPropertyChangeEventFilter {
329
330                         /**
331                          * Should the given event be filtered?
332                          * 
333                          * @param event
334                          *            The property change event.
335                          * @return <code>true</code> iff the given event should be
336                          *         filtered.
337                          */
338                         public boolean isFiltered(PropertyChangeEvent event);
339
340                 }
341
342                 /**
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.
346                  */
347                 private class PropertyChangeListener implements IPropertyChangeListener {
348
349                         /**
350                          * {@inheritDoc}
351                          */
352                         public void propertyChange(PropertyChangeEvent event) {
353                                 if (getFilter().isFiltered(event))
354                                         return;
355
356                                 if (event.getNewValue() == null)
357                                         fOptions.remove(event.getProperty());
358                                 else
359                                         fOptions.put(event.getProperty(), event.getNewValue());
360
361                                 firePropertyChangeEvent(event.getProperty(), event
362                                                 .getOldValue(), event.getNewValue());
363                         }
364                 }
365
366                 /** Listeners on this adapter */
367                 private ListenerList fListeners = new ListenerList();
368
369                 /** Listener on the adapted options Map */
370                 private IPropertyChangeListener fListener = new PropertyChangeListener();
371
372                 /** Adapted options Map */
373                 private Map fOptions;
374
375                 /** Preference store through which events are received. */
376                 private IPreferenceStore fMockupPreferenceStore;
377
378                 /** Property event filter. */
379                 private IPropertyChangeEventFilter fFilter;
380
381                 /**
382                  * Initialize with the given options.
383                  * 
384                  * @param options
385                  *            The options to wrap
386                  * @param mockupPreferenceStore
387                  *            the mock-up preference store
388                  * @param filter
389                  *            the property change filter
390                  */
391                 public OptionsAdapter(Map options,
392                                 IPreferenceStore mockupPreferenceStore,
393                                 IPropertyChangeEventFilter filter) {
394                         fMockupPreferenceStore = mockupPreferenceStore;
395                         fOptions = options;
396                         setFilter(filter);
397                 }
398
399                 /**
400                  * {@inheritDoc}
401                  */
402                 public void addPropertyChangeListener(IPropertyChangeListener listener) {
403                         if (fListeners.size() == 0)
404                                 fMockupPreferenceStore.addPropertyChangeListener(fListener);
405                         fListeners.add(listener);
406                 }
407
408                 /**
409                  * {@inheritDoc}
410                  */
411                 public void removePropertyChangeListener(
412                                 IPropertyChangeListener listener) {
413                         fListeners.remove(listener);
414                         if (fListeners.size() == 0)
415                                 fMockupPreferenceStore.removePropertyChangeListener(fListener);
416                 }
417
418                 /**
419                  * {@inheritDoc}
420                  */
421                 public boolean contains(String name) {
422                         return fOptions.containsKey(name);
423                 }
424
425                 /**
426                  * {@inheritDoc}
427                  */
428                 public void firePropertyChangeEvent(String name, Object oldValue,
429                                 Object newValue) {
430                         PropertyChangeEvent event = new PropertyChangeEvent(this, name,
431                                         oldValue, newValue);
432                         Object[] listeners = fListeners.getListeners();
433                         for (int i = 0; i < listeners.length; i++)
434                                 ((IPropertyChangeListener) listeners[i]).propertyChange(event);
435                 }
436
437                 /**
438                  * {@inheritDoc}
439                  */
440                 public boolean getBoolean(String name) {
441                         boolean value = BOOLEAN_DEFAULT_DEFAULT;
442                         String s = (String) fOptions.get(name);
443                         if (s != null)
444                                 value = s.equals(TRUE);
445                         return value;
446                 }
447
448                 /**
449                  * {@inheritDoc}
450                  */
451                 public boolean getDefaultBoolean(String name) {
452                         return BOOLEAN_DEFAULT_DEFAULT;
453                 }
454
455                 /**
456                  * {@inheritDoc}
457                  */
458                 public double getDefaultDouble(String name) {
459                         return DOUBLE_DEFAULT_DEFAULT;
460                 }
461
462                 /**
463                  * {@inheritDoc}
464                  */
465                 public float getDefaultFloat(String name) {
466                         return FLOAT_DEFAULT_DEFAULT;
467                 }
468
469                 /**
470                  * {@inheritDoc}
471                  */
472                 public int getDefaultInt(String name) {
473                         return INT_DEFAULT_DEFAULT;
474                 }
475
476                 /**
477                  * {@inheritDoc}
478                  */
479                 public long getDefaultLong(String name) {
480                         return LONG_DEFAULT_DEFAULT;
481                 }
482
483                 /**
484                  * {@inheritDoc}
485                  */
486                 public String getDefaultString(String name) {
487                         return STRING_DEFAULT_DEFAULT;
488                 }
489
490                 /**
491                  * {@inheritDoc}
492                  */
493                 public double getDouble(String name) {
494                         double value = DOUBLE_DEFAULT_DEFAULT;
495                         String s = (String) fOptions.get(name);
496                         if (s != null) {
497                                 try {
498                                         value = new Double(s).doubleValue();
499                                 } catch (NumberFormatException e) {
500                                 }
501                         }
502                         return value;
503                 }
504
505                 /**
506                  * {@inheritDoc}
507                  */
508                 public float getFloat(String name) {
509                         float value = FLOAT_DEFAULT_DEFAULT;
510                         String s = (String) fOptions.get(name);
511                         if (s != null) {
512                                 try {
513                                         value = new Float(s).floatValue();
514                                 } catch (NumberFormatException e) {
515                                 }
516                         }
517                         return value;
518                 }
519
520                 /**
521                  * {@inheritDoc}
522                  */
523                 public int getInt(String name) {
524                         int value = INT_DEFAULT_DEFAULT;
525                         String s = (String) fOptions.get(name);
526                         if (s != null) {
527                                 try {
528                                         value = new Integer(s).intValue();
529                                 } catch (NumberFormatException e) {
530                                 }
531                         }
532                         return value;
533                 }
534
535                 /**
536                  * {@inheritDoc}
537                  */
538                 public long getLong(String name) {
539                         long value = LONG_DEFAULT_DEFAULT;
540                         String s = (String) fOptions.get(name);
541                         if (s != null) {
542                                 try {
543                                         value = new Long(s).longValue();
544                                 } catch (NumberFormatException e) {
545                                 }
546                         }
547                         return value;
548                 }
549
550                 /**
551                  * {@inheritDoc}
552                  */
553                 public String getString(String name) {
554                         String value = (String) fOptions.get(name);
555                         if (value == null)
556                                 value = STRING_DEFAULT_DEFAULT;
557                         return value;
558                 }
559
560                 /**
561                  * {@inheritDoc}
562                  */
563                 public boolean isDefault(String name) {
564                         return false;
565                 }
566
567                 /**
568                  * {@inheritDoc}
569                  */
570                 public boolean needsSaving() {
571                         return !fOptions.isEmpty();
572                 }
573
574                 /**
575                  * {@inheritDoc}
576                  */
577                 public void putValue(String name, String value) {
578                         throw new UnsupportedOperationException();
579                 }
580
581                 /**
582                  * {@inheritDoc}
583                  */
584                 public void setDefault(String name, double value) {
585                         throw new UnsupportedOperationException();
586                 }
587
588                 /**
589                  * {@inheritDoc}
590                  */
591                 public void setDefault(String name, float value) {
592                         throw new UnsupportedOperationException();
593                 }
594
595                 /**
596                  * {@inheritDoc}
597                  */
598                 public void setDefault(String name, int value) {
599                         throw new UnsupportedOperationException();
600                 }
601
602                 /**
603                  * {@inheritDoc}
604                  */
605                 public void setDefault(String name, long value) {
606                         throw new UnsupportedOperationException();
607                 }
608
609                 /**
610                  * {@inheritDoc}
611                  */
612                 public void setDefault(String name, String defaultObject) {
613                         throw new UnsupportedOperationException();
614                 }
615
616                 /**
617                  * {@inheritDoc}
618                  */
619                 public void setDefault(String name, boolean value) {
620                         throw new UnsupportedOperationException();
621                 }
622
623                 /**
624                  * {@inheritDoc}
625                  */
626                 public void setToDefault(String name) {
627                         throw new UnsupportedOperationException();
628                 }
629
630                 /**
631                  * {@inheritDoc}
632                  */
633                 public void setValue(String name, double value) {
634                         throw new UnsupportedOperationException();
635                 }
636
637                 /**
638                  * {@inheritDoc}
639                  */
640                 public void setValue(String name, float value) {
641                         throw new UnsupportedOperationException();
642                 }
643
644                 /**
645                  * {@inheritDoc}
646                  */
647                 public void setValue(String name, int value) {
648                         throw new UnsupportedOperationException();
649                 }
650
651                 /**
652                  * {@inheritDoc}
653                  */
654                 public void setValue(String name, long value) {
655                         throw new UnsupportedOperationException();
656                 }
657
658                 /**
659                  * {@inheritDoc}
660                  */
661                 public void setValue(String name, String value) {
662                         throw new UnsupportedOperationException();
663                 }
664
665                 /**
666                  * {@inheritDoc}
667                  */
668                 public void setValue(String name, boolean value) {
669                         throw new UnsupportedOperationException();
670                 }
671
672                 /**
673                  * Returns the adapted options Map.
674                  * 
675                  * @return Returns the adapted options Map.
676                  */
677                 public Map getOptions() {
678                         return fOptions;
679                 }
680
681                 /**
682                  * Returns the mock-up preference store, events are received through
683                  * this preference store.
684                  * 
685                  * @return Returns the mock-up preference store.
686                  */
687                 public IPreferenceStore getMockupPreferenceStore() {
688                         return fMockupPreferenceStore;
689                 }
690
691                 /**
692                  * Set the event filter to the given filter.
693                  * 
694                  * @param filter
695                  *            The new filter.
696                  */
697                 public void setFilter(IPropertyChangeEventFilter filter) {
698                         fFilter = filter;
699                 }
700
701                 /**
702                  * Returns the event filter.
703                  * 
704                  * @return The event filter.
705                  */
706                 public IPropertyChangeEventFilter getFilter() {
707                         return fFilter;
708                 }
709         }
710
711         /*
712          * Link mode.
713          */
714         // class MouseClickListener implements KeyListener, MouseListener,
715         // MouseMoveListener, FocusListener, PaintListener,
716         // IPropertyChangeListener, IDocumentListener, ITextInputListener {
717         //
718         // /** The session is active. */
719         // private boolean fActive;
720         //
721         // /** The currently active style range. */
722         // private IRegion fActiveRegion;
723         //
724         // /** The currently active style range as position. */
725         // private Position fRememberedPosition;
726         //
727         // /** The hand cursor. */
728         // private Cursor fCursor;
729         //
730         // /** The link color. */
731         // private Color fColor;
732         //
733         // /** The key modifier mask. */
734         // private int fKeyModifierMask;
735         //
736         // public void deactivate() {
737         // deactivate(false);
738         // }
739         //
740         // public void deactivate(boolean redrawAll) {
741         // if (!fActive)
742         // return;
743         //
744         // repairRepresentation(redrawAll);
745         // fActive = false;
746         // }
747         //
748         // public void install() {
749         //
750         // ISourceViewer sourceViewer = getSourceViewer();
751         // if (sourceViewer == null)
752         // return;
753         //
754         // StyledText text = sourceViewer.getTextWidget();
755         // if (text == null || text.isDisposed())
756         // return;
757         //
758         // updateColor(sourceViewer);
759         //
760         // sourceViewer.addTextInputListener(this);
761         //
762         // IDocument document = sourceViewer.getDocument();
763         // if (document != null)
764         // document.addDocumentListener(this);
765         //
766         // text.addKeyListener(this);
767         // text.addMouseListener(this);
768         // text.addMouseMoveListener(this);
769         // text.addFocusListener(this);
770         // text.addPaintListener(this);
771         //
772         // updateKeyModifierMask();
773         //
774         // IPreferenceStore preferenceStore = getPreferenceStore();
775         // preferenceStore.addPropertyChangeListener(this);
776         // }
777         //
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);
786         // }
787         // ;
788         // }
789         //
790         // private int computeStateMask(String modifiers) {
791         // if (modifiers == null)
792         // return -1;
793         //
794         // if (modifiers.length() == 0)
795         // return SWT.NONE;
796         //
797         // int stateMask = 0;
798         // StringTokenizer modifierTokenizer = new StringTokenizer(modifiers,
799         // ",;.:+-*
800         // "); //$NON-NLS-1$
801         // while (modifierTokenizer.hasMoreTokens()) {
802         // int modifier =
803         // EditorUtility.findLocalizedModifier(modifierTokenizer.nextToken());
804         // if (modifier == 0 || (stateMask & modifier) == modifier)
805         // return -1;
806         // stateMask = stateMask | modifier;
807         // }
808         // return stateMask;
809         // }
810         //
811         // public void uninstall() {
812         //
813         // if (fColor != null) {
814         // fColor.dispose();
815         // fColor = null;
816         // }
817         //
818         // if (fCursor != null) {
819         // fCursor.dispose();
820         // fCursor = null;
821         // }
822         //
823         // ISourceViewer sourceViewer = getSourceViewer();
824         // if (sourceViewer == null)
825         // return;
826         //
827         // sourceViewer.removeTextInputListener(this);
828         //
829         // IDocument document = sourceViewer.getDocument();
830         // if (document != null)
831         // document.removeDocumentListener(this);
832         //
833         // IPreferenceStore preferenceStore = getPreferenceStore();
834         // if (preferenceStore != null)
835         // preferenceStore.removePropertyChangeListener(this);
836         //
837         // StyledText text = sourceViewer.getTextWidget();
838         // if (text == null || text.isDisposed())
839         // return;
840         //
841         // text.removeKeyListener(this);
842         // text.removeMouseListener(this);
843         // text.removeMouseMoveListener(this);
844         // text.removeFocusListener(this);
845         // text.removePaintListener(this);
846         // }
847         //
848         // /*
849         // * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
850         // */
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();
858         // }
859         // }
860         //
861         // private void updateColor(ISourceViewer viewer) {
862         // if (fColor != null)
863         // fColor.dispose();
864         //
865         // StyledText text = viewer.getTextWidget();
866         // if (text == null || text.isDisposed())
867         // return;
868         //
869         // Display display = text.getDisplay();
870         // fColor = createColor(getPreferenceStore(), PHPEditor.LINK_COLOR,
871         // display);
872         // }
873         //
874         // /**
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.
878         // */
879         // private Color createColor(IPreferenceStore store, String key, Display
880         // display) {
881         //
882         // RGB rgb = null;
883         //
884         // if (store.contains(key)) {
885         //
886         // if (store.isDefault(key))
887         // rgb = PreferenceConverter.getDefaultColor(store, key);
888         // else
889         // rgb = PreferenceConverter.getColor(store, key);
890         //
891         // if (rgb != null)
892         // return new Color(display, rgb);
893         // }
894         //
895         // return null;
896         // }
897         //
898         // private void repairRepresentation() {
899         // repairRepresentation(false);
900         // }
901         //
902         // private void repairRepresentation(boolean redrawAll) {
903         //
904         // if (fActiveRegion == null)
905         // return;
906         //
907         // ISourceViewer viewer = getSourceViewer();
908         // if (viewer != null) {
909         // resetCursor(viewer);
910         //
911         // int offset = fActiveRegion.getOffset();
912         // int length = fActiveRegion.getLength();
913         //
914         // // remove style
915         // if (!redrawAll && viewer instanceof ITextViewerExtension2)
916         // ((ITextViewerExtension2) viewer).invalidateTextPresentation(offset,
917         // length);
918         // else
919         // viewer.invalidateTextPresentation();
920         //
921         // // remove underline
922         // if (viewer instanceof ITextViewerExtension3) {
923         // ITextViewerExtension3 extension = (ITextViewerExtension3) viewer;
924         // offset = extension.modelOffset2WidgetOffset(offset);
925         // } else {
926         // offset -= viewer.getVisibleRegion().getOffset();
927         // }
928         //
929         // StyledText text = viewer.getTextWidget();
930         // try {
931         // text.redrawRange(offset, length, true);
932         // } catch (IllegalArgumentException x) {
933         // PHPeclipsePlugin.log(x);
934         // }
935         // }
936         //
937         // fActiveRegion = null;
938         // }
939         //
940         // // will eventually be replaced by a method provided by jdt.core
941         // private IRegion selectWord(IDocument document, int anchor) {
942         //
943         // try {
944         // int offset = anchor;
945         // char c;
946         //
947         // while (offset >= 0) {
948         // c = document.getChar(offset);
949         // if (!Scanner.isPHPIdentifierPart(c))
950         // break;
951         // --offset;
952         // }
953         //
954         // int start = offset;
955         //
956         // offset = anchor;
957         // int length = document.getLength();
958         //
959         // while (offset < length) {
960         // c = document.getChar(offset);
961         // if (!Scanner.isPHPIdentifierPart(c))
962         // break;
963         // ++offset;
964         // }
965         //
966         // int end = offset;
967         //
968         // if (start == end)
969         // return new Region(start, 0);
970         // else
971         // return new Region(start + 1, end - start - 1);
972         //
973         // } catch (BadLocationException x) {
974         // return null;
975         // }
976         // }
977         //
978         // IRegion getCurrentTextRegion(ISourceViewer viewer) {
979         //
980         // int offset = getCurrentTextOffset(viewer);
981         // if (offset == -1)
982         // return null;
983         //
984         // return null;
985         // // IJavaElement input= SelectionConverter.getInput(PHPEditor.this);
986         // // if (input == null)
987         // // return null;
988         // //
989         // // try {
990         // //
991         // // IJavaElement[] elements= null;
992         // // synchronized (input) {
993         // // elements= ((ICodeAssist) input).codeSelect(offset, 0);
994         // // }
995         // //
996         // // if (elements == null || elements.length == 0)
997         // // return null;
998         // //
999         // // return selectWord(viewer.getDocument(), offset);
1000         // //
1001         // // } catch (JavaModelException e) {
1002         // // return null;
1003         // // }
1004         // }
1005         //
1006         // private int getCurrentTextOffset(ISourceViewer viewer) {
1007         //
1008         // try {
1009         // StyledText text = viewer.getTextWidget();
1010         // if (text == null || text.isDisposed())
1011         // return -1;
1012         //
1013         // Display display = text.getDisplay();
1014         // Point absolutePosition = display.getCursorLocation();
1015         // Point relativePosition = text.toControl(absolutePosition);
1016         //
1017         // int widgetOffset = text.getOffsetAtLocation(relativePosition);
1018         // if (viewer instanceof ITextViewerExtension3) {
1019         // ITextViewerExtension3 extension = (ITextViewerExtension3) viewer;
1020         // return extension.widgetOffset2ModelOffset(widgetOffset);
1021         // } else {
1022         // return widgetOffset + viewer.getVisibleRegion().getOffset();
1023         // }
1024         //
1025         // } catch (IllegalArgumentException e) {
1026         // return -1;
1027         // }
1028         // }
1029         //
1030         // private void highlightRegion(ISourceViewer viewer, IRegion region) {
1031         //
1032         // if (region.equals(fActiveRegion))
1033         // return;
1034         //
1035         // repairRepresentation();
1036         //
1037         // StyledText text = viewer.getTextWidget();
1038         // if (text == null || text.isDisposed())
1039         // return;
1040         //
1041         // // highlight region
1042         // int offset = 0;
1043         // int length = 0;
1044         //
1045         // if (viewer instanceof ITextViewerExtension3) {
1046         // ITextViewerExtension3 extension = (ITextViewerExtension3) viewer;
1047         // IRegion widgetRange = extension.modelRange2WidgetRange(region);
1048         // if (widgetRange == null)
1049         // return;
1050         //
1051         // offset = widgetRange.getOffset();
1052         // length = widgetRange.getLength();
1053         //
1054         // } else {
1055         // offset = region.getOffset() - viewer.getVisibleRegion().getOffset();
1056         // length = region.getLength();
1057         // }
1058         //
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);
1066         //
1067         // // underline
1068         // text.redrawRange(offset, length, true);
1069         //
1070         // fActiveRegion = region;
1071         // }
1072         //
1073         // private void activateCursor(ISourceViewer viewer) {
1074         // StyledText text = viewer.getTextWidget();
1075         // if (text == null || text.isDisposed())
1076         // return;
1077         // Display display = text.getDisplay();
1078         // if (fCursor == null)
1079         // fCursor = new Cursor(display, SWT.CURSOR_HAND);
1080         // text.setCursor(fCursor);
1081         // }
1082         //
1083         // private void resetCursor(ISourceViewer viewer) {
1084         // StyledText text = viewer.getTextWidget();
1085         // if (text != null && !text.isDisposed())
1086         // text.setCursor(null);
1087         //
1088         // if (fCursor != null) {
1089         // fCursor.dispose();
1090         // fCursor = null;
1091         // }
1092         // }
1093         //
1094         // /*
1095         // * @see
1096         // org.eclipse.swt.events.KeyListener#keyPressed(org.eclipse.swt.events.KeyEvent)
1097         // */
1098         // public void keyPressed(KeyEvent event) {
1099         //
1100         // if (fActive) {
1101         // deactivate();
1102         // return;
1103         // }
1104         //
1105         // if (event.keyCode != fKeyModifierMask) {
1106         // deactivate();
1107         // return;
1108         // }
1109         //
1110         // fActive = true;
1111         //
1112         // // removed for #25871
1113         // //
1114         // // ISourceViewer viewer= getSourceViewer();
1115         // // if (viewer == null)
1116         // // return;
1117         // //
1118         // // IRegion region= getCurrentTextRegion(viewer);
1119         // // if (region == null)
1120         // // return;
1121         // //
1122         // // highlightRegion(viewer, region);
1123         // // activateCursor(viewer);
1124         // }
1125         //
1126         // /*
1127         // * @see
1128         // org.eclipse.swt.events.KeyListener#keyReleased(org.eclipse.swt.events.KeyEvent)
1129         // */
1130         // public void keyReleased(KeyEvent event) {
1131         //
1132         // if (!fActive)
1133         // return;
1134         //
1135         // deactivate();
1136         // }
1137         //
1138         // /*
1139         // * @see
1140         // org.eclipse.swt.events.MouseListener#mouseDoubleClick(org.eclipse.swt.events.MouseEvent)
1141         // */
1142         // public void mouseDoubleClick(MouseEvent e) {
1143         // }
1144         //
1145         // /*
1146         // * @see
1147         // org.eclipse.swt.events.MouseListener#mouseDown(org.eclipse.swt.events.MouseEvent)
1148         // */
1149         // public void mouseDown(MouseEvent event) {
1150         //
1151         // if (!fActive)
1152         // return;
1153         //
1154         // if (event.stateMask != fKeyModifierMask) {
1155         // deactivate();
1156         // return;
1157         // }
1158         //
1159         // if (event.button != 1) {
1160         // deactivate();
1161         // return;
1162         // }
1163         // }
1164         //
1165         // /*
1166         // * @see
1167         // org.eclipse.swt.events.MouseListener#mouseUp(org.eclipse.swt.events.MouseEvent)
1168         // */
1169         // public void mouseUp(MouseEvent e) {
1170         //
1171         // if (!fActive)
1172         // return;
1173         //
1174         // if (e.button != 1) {
1175         // deactivate();
1176         // return;
1177         // }
1178         //
1179         // boolean wasActive = fCursor != null;
1180         //
1181         // deactivate();
1182         //
1183         // if (wasActive) {
1184         // IAction action = getAction("OpenEditor"); //$NON-NLS-1$
1185         // if (action != null)
1186         // action.run();
1187         // }
1188         // }
1189         //
1190         // /*
1191         // * @see
1192         // org.eclipse.swt.events.MouseMoveListener#mouseMove(org.eclipse.swt.events.MouseEvent)
1193         // */
1194         // public void mouseMove(MouseEvent event) {
1195         //
1196         // if (event.widget instanceof Control && !((Control)
1197         // event.widget).isFocusControl()) {
1198         // deactivate();
1199         // return;
1200         // }
1201         //
1202         // if (!fActive) {
1203         // if (event.stateMask != fKeyModifierMask)
1204         // return;
1205         // // modifier was already pressed
1206         // fActive = true;
1207         // }
1208         //
1209         // ISourceViewer viewer = getSourceViewer();
1210         // if (viewer == null) {
1211         // deactivate();
1212         // return;
1213         // }
1214         //
1215         // StyledText text = viewer.getTextWidget();
1216         // if (text == null || text.isDisposed()) {
1217         // deactivate();
1218         // return;
1219         // }
1220         //
1221         // if ((event.stateMask & SWT.BUTTON1) != 0 && text.getSelectionCount() !=
1222         // 0)
1223         // {
1224         // deactivate();
1225         // return;
1226         // }
1227         //
1228         // IRegion region = getCurrentTextRegion(viewer);
1229         // if (region == null || region.getLength() == 0) {
1230         // repairRepresentation();
1231         // return;
1232         // }
1233         //
1234         // highlightRegion(viewer, region);
1235         // activateCursor(viewer);
1236         // }
1237         //
1238         // /*
1239         // * @see
1240         // org.eclipse.swt.events.FocusListener#focusGained(org.eclipse.swt.events.FocusEvent)
1241         // */
1242         // public void focusGained(FocusEvent e) {
1243         // }
1244         //
1245         // /*
1246         // * @see
1247         // org.eclipse.swt.events.FocusListener#focusLost(org.eclipse.swt.events.FocusEvent)
1248         // */
1249         // public void focusLost(FocusEvent event) {
1250         // deactivate();
1251         // }
1252         //
1253         // /*
1254         // * @see
1255         // org.eclipse.jface.text.IDocumentListener#documentAboutToBeChanged(org.eclipse.jface.text.DocumentEvent)
1256         // */
1257         // public void documentAboutToBeChanged(DocumentEvent event) {
1258         // if (fActive && fActiveRegion != null) {
1259         // fRememberedPosition = new Position(fActiveRegion.getOffset(),
1260         // fActiveRegion.getLength());
1261         // try {
1262         // event.getDocument().addPosition(fRememberedPosition);
1263         // } catch (BadLocationException x) {
1264         // fRememberedPosition = null;
1265         // }
1266         // }
1267         // }
1268         //
1269         // /*
1270         // * @see
1271         // org.eclipse.jface.text.IDocumentListener#documentChanged(org.eclipse.jface.text.DocumentEvent)
1272         // */
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());
1278         // }
1279         // fRememberedPosition = null;
1280         //
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() {
1287         // deactivate();
1288         // }
1289         // });
1290         // }
1291         // }
1292         // }
1293         //
1294         // /*
1295         // * @see
1296         // org.eclipse.jface.text.ITextInputListener#inputDocumentAboutToBeChanged(org.eclipse.jface.text.IDocument,
1297         // * org.eclipse.jface.text.IDocument)
1298         // */
1299         // public void inputDocumentAboutToBeChanged(IDocument oldInput, IDocument
1300         // newInput) {
1301         // if (oldInput == null)
1302         // return;
1303         // deactivate();
1304         // oldInput.removeDocumentListener(this);
1305         // }
1306         //
1307         // /*
1308         // * @see
1309         // org.eclipse.jface.text.ITextInputListener#inputDocumentChanged(org.eclipse.jface.text.IDocument,
1310         // * org.eclipse.jface.text.IDocument)
1311         // */
1312         // public void inputDocumentChanged(IDocument oldInput, IDocument newInput)
1313         // {
1314         // if (newInput == null)
1315         // return;
1316         // newInput.addDocumentListener(this);
1317         // }
1318         //
1319         // /*
1320         // * @see PaintListener#paintControl(PaintEvent)
1321         // */
1322         // public void paintControl(PaintEvent event) {
1323         // if (fActiveRegion == null)
1324         // return;
1325         //
1326         // ISourceViewer viewer = getSourceViewer();
1327         // if (viewer == null)
1328         // return;
1329         //
1330         // StyledText text = viewer.getTextWidget();
1331         // if (text == null || text.isDisposed())
1332         // return;
1333         //
1334         // int offset = 0;
1335         // int length = 0;
1336         //
1337         // if (viewer instanceof ITextViewerExtension3) {
1338         //
1339         // ITextViewerExtension3 extension = (ITextViewerExtension3) viewer;
1340         // IRegion widgetRange = extension.modelRange2WidgetRange(new Region(offset,
1341         // length));
1342         // if (widgetRange == null)
1343         // return;
1344         //
1345         // offset = widgetRange.getOffset();
1346         // length = widgetRange.getLength();
1347         //
1348         // } else {
1349         //
1350         // IRegion region = viewer.getVisibleRegion();
1351         // if (!includes(region, fActiveRegion))
1352         // return;
1353         //
1354         // offset = fActiveRegion.getOffset() - region.getOffset();
1355         // length = fActiveRegion.getLength();
1356         // }
1357         //
1358         // // support for bidi
1359         // Point minLocation = getMinimumLocation(text, offset, length);
1360         // Point maxLocation = getMaximumLocation(text, offset, length);
1361         //
1362         // int x1 = minLocation.x;
1363         // int x2 = minLocation.x + maxLocation.x - minLocation.x - 1;
1364         // int y = minLocation.y + text.getLineHeight() - 1;
1365         //
1366         // GC gc = event.gc;
1367         // if (fColor != null && !fColor.isDisposed())
1368         // gc.setForeground(fColor);
1369         // gc.drawLine(x1, y, x2, y);
1370         // }
1371         //
1372         // private boolean includes(IRegion region, IRegion position) {
1373         // return position.getOffset() >= region.getOffset()
1374         // && position.getOffset() + position.getLength() <= region.getOffset() +
1375         // region.getLength();
1376         // }
1377         //
1378         // private Point getMinimumLocation(StyledText text, int offset, int length)
1379         // {
1380         // Point minLocation = new Point(Integer.MAX_VALUE, Integer.MAX_VALUE);
1381         //
1382         // for (int i = 0; i <= length; i++) {
1383         // Point location = text.getLocationAtOffset(offset + i);
1384         //
1385         // if (location.x < minLocation.x)
1386         // minLocation.x = location.x;
1387         // if (location.y < minLocation.y)
1388         // minLocation.y = location.y;
1389         // }
1390         //
1391         // return minLocation;
1392         // }
1393         //
1394         // private Point getMaximumLocation(StyledText text, int offset, int length)
1395         // {
1396         // Point maxLocation = new Point(Integer.MIN_VALUE, Integer.MIN_VALUE);
1397         //
1398         // for (int i = 0; i <= length; i++) {
1399         // Point location = text.getLocationAtOffset(offset + i);
1400         //
1401         // if (location.x > maxLocation.x)
1402         // maxLocation.x = location.x;
1403         // if (location.y > maxLocation.y)
1404         // maxLocation.y = location.y;
1405         // }
1406         //
1407         // return maxLocation;
1408         // }
1409         // };
1410         /*
1411          * Link mode.
1412          */
1413         class MouseClickListener implements KeyListener, MouseListener,
1414                         MouseMoveListener, FocusListener, PaintListener,
1415                         IPropertyChangeListener, IDocumentListener, ITextInputListener,
1416                         ITextPresentationListener {
1417
1418                 /** The session is active. */
1419                 private boolean fActive;
1420
1421                 /** The currently active style range. */
1422                 private IRegion fActiveRegion;
1423
1424                 /** The currently active style range as position. */
1425                 private Position fRememberedPosition;
1426
1427                 /** The hand cursor. */
1428                 private Cursor fCursor;
1429
1430                 /** The link color. */
1431                 private Color fColor;
1432
1433                 /** The key modifier mask. */
1434                 private int fKeyModifierMask;
1435
1436                 public void deactivate() {
1437                         deactivate(false);
1438                 }
1439
1440                 public void deactivate(boolean redrawAll) {
1441                         if (!fActive)
1442                                 return;
1443
1444                         repairRepresentation(redrawAll);
1445                         fActive = false;
1446                 }
1447
1448                 public void install() {
1449                         ISourceViewer sourceViewer = getSourceViewer();
1450                         if (sourceViewer == null)
1451                                 return;
1452
1453                         StyledText text = sourceViewer.getTextWidget();
1454                         if (text == null || text.isDisposed())
1455                                 return;
1456
1457                         updateColor(sourceViewer);
1458
1459                         sourceViewer.addTextInputListener(this);
1460
1461                         IDocument document = sourceViewer.getDocument();
1462                         if (document != null)
1463                                 document.addDocumentListener(this);
1464
1465                         text.addKeyListener(this);
1466                         text.addMouseListener(this);
1467                         text.addMouseMoveListener(this);
1468                         text.addFocusListener(this);
1469                         text.addPaintListener(this);
1470
1471                         ((ITextViewerExtension4) sourceViewer)
1472                                         .addTextPresentationListener(this);
1473
1474                         updateKeyModifierMask();
1475
1476                         IPreferenceStore preferenceStore = getPreferenceStore();
1477                         preferenceStore.addPropertyChangeListener(this);
1478                 }
1479
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);
1488                         }
1489                 }
1490
1491                 private int computeStateMask(String modifiers) {
1492                         if (modifiers == null)
1493                                 return -1;
1494
1495                         if (modifiers.length() == 0)
1496                                 return SWT.NONE;
1497
1498                         int stateMask = 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)
1505                                         return -1;
1506                                 stateMask = stateMask | modifier;
1507                         }
1508                         return stateMask;
1509                 }
1510
1511                 public void uninstall() {
1512
1513                         if (fColor != null) {
1514                                 fColor.dispose();
1515                                 fColor = null;
1516                         }
1517
1518                         if (fCursor != null) {
1519                                 fCursor.dispose();
1520                                 fCursor = null;
1521                         }
1522
1523                         ISourceViewer sourceViewer = getSourceViewer();
1524                         if (sourceViewer != null)
1525                                 sourceViewer.removeTextInputListener(this);
1526
1527                         IDocumentProvider documentProvider = getDocumentProvider();
1528                         if (documentProvider != null) {
1529                                 IDocument document = documentProvider
1530                                                 .getDocument(getEditorInput());
1531                                 if (document != null)
1532                                         document.removeDocumentListener(this);
1533                         }
1534
1535                         IPreferenceStore preferenceStore = getPreferenceStore();
1536                         if (preferenceStore != null)
1537                                 preferenceStore.removePropertyChangeListener(this);
1538
1539                         if (sourceViewer == null)
1540                                 return;
1541
1542                         StyledText text = sourceViewer.getTextWidget();
1543                         if (text == null || text.isDisposed())
1544                                 return;
1545
1546                         text.removeKeyListener(this);
1547                         text.removeMouseListener(this);
1548                         text.removeMouseMoveListener(this);
1549                         text.removeFocusListener(this);
1550                         text.removePaintListener(this);
1551
1552                         ((ITextViewerExtension4) sourceViewer)
1553                                         .removeTextPresentationListener(this);
1554                 }
1555
1556                 /*
1557                  * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
1558                  */
1559                 public void propertyChange(PropertyChangeEvent event) {
1560                         if (event.getProperty().equals(PHPEditor.LINK_COLOR)) {
1561                                 ISourceViewer viewer = getSourceViewer();
1562                                 if (viewer != null)
1563                                         updateColor(viewer);
1564                         } else if (event.getProperty().equals(
1565                                         BROWSER_LIKE_LINKS_KEY_MODIFIER)) {
1566                                 updateKeyModifierMask();
1567                         }
1568                 }
1569
1570                 private void updateColor(ISourceViewer viewer) {
1571                         if (fColor != null)
1572                                 fColor.dispose();
1573
1574                         StyledText text = viewer.getTextWidget();
1575                         if (text == null || text.isDisposed())
1576                                 return;
1577
1578                         Display display = text.getDisplay();
1579                         fColor = createColor(getPreferenceStore(), PHPEditor.LINK_COLOR,
1580                                         display);
1581                 }
1582
1583                 /**
1584                  * Creates a color from the information stored in the given preference
1585                  * store.
1586                  * 
1587                  * @param store
1588                  *            the preference store
1589                  * @param key
1590                  *            the key
1591                  * @param display
1592                  *            the display
1593                  * @return the color or <code>null</code> if there is no such
1594                  *         information available
1595                  */
1596                 private Color createColor(IPreferenceStore store, String key,
1597                                 Display display) {
1598
1599                         RGB rgb = null;
1600
1601                         if (store.contains(key)) {
1602
1603                                 if (store.isDefault(key))
1604                                         rgb = PreferenceConverter.getDefaultColor(store, key);
1605                                 else
1606                                         rgb = PreferenceConverter.getColor(store, key);
1607
1608                                 if (rgb != null)
1609                                         return new Color(display, rgb);
1610                         }
1611
1612                         return null;
1613                 }
1614
1615                 private void repairRepresentation() {
1616                         repairRepresentation(false);
1617                 }
1618
1619                 private void repairRepresentation(boolean redrawAll) {
1620
1621                         if (fActiveRegion == null)
1622                                 return;
1623
1624                         int offset = fActiveRegion.getOffset();
1625                         int length = fActiveRegion.getLength();
1626                         fActiveRegion = null;
1627
1628                         ISourceViewer viewer = getSourceViewer();
1629                         if (viewer != null) {
1630
1631                                 resetCursor(viewer);
1632
1633                                 // Invalidate ==> remove applied text presentation
1634                                 if (!redrawAll && viewer instanceof ITextViewerExtension2)
1635                                         ((ITextViewerExtension2) viewer)
1636                                                         .invalidateTextPresentation(offset, length);
1637                                 else
1638                                         viewer.invalidateTextPresentation();
1639
1640                                 // Remove underline
1641                                 if (viewer instanceof ITextViewerExtension5) {
1642                                         ITextViewerExtension5 extension = (ITextViewerExtension5) viewer;
1643                                         offset = extension.modelOffset2WidgetOffset(offset);
1644                                 } else {
1645                                         offset -= viewer.getVisibleRegion().getOffset();
1646                                 }
1647                                 try {
1648                                         StyledText text = viewer.getTextWidget();
1649
1650                                         text.redrawRange(offset, length, false);
1651                                 } catch (IllegalArgumentException x) {
1652                                         // JavaPlugin.log(x);
1653                                 }
1654                         }
1655                 }
1656
1657                 // will eventually be replaced by a method provided by jdt.core
1658                 private IRegion selectWord(IDocument document, int anchor) {
1659
1660                         try {
1661                                 int offset = anchor;
1662                                 char c;
1663
1664                                 while (offset >= 0) {
1665                                         c = document.getChar(offset);
1666                                         if (!Scanner.isPHPIdentifierPart(c) && c != '$')
1667                                                 break;
1668                                         --offset;
1669                                 }
1670
1671                                 int start = offset;
1672
1673                                 offset = anchor;
1674                                 int length = document.getLength();
1675
1676                                 while (offset < length) {
1677                                         c = document.getChar(offset);
1678                                         if (!Scanner.isPHPIdentifierPart(c) && c != '$')
1679                                                 break;
1680                                         ++offset;
1681                                 }
1682
1683                                 int end = offset;
1684
1685                                 if (start == end)
1686                                         return new Region(start, 0);
1687                                 else
1688                                         return new Region(start + 1, end - start - 1);
1689
1690                         } catch (BadLocationException x) {
1691                                 return null;
1692                         }
1693                 }
1694
1695                 IRegion getCurrentTextRegion(ISourceViewer viewer) {
1696
1697                         int offset = getCurrentTextOffset(viewer);
1698                         if (offset == -1)
1699                                 return null;
1700
1701                         IJavaElement input = SelectionConverter.getInput(PHPEditor.this);
1702                         if (input == null)
1703                                 return null;
1704
1705                         // try {
1706
1707                         // IJavaElement[] elements= null;
1708                         // synchronized (input) {
1709                         // elements= ((ICodeAssist) input).codeSelect(offset, 0);
1710                         // }
1711                         //
1712                         // if (elements == null || elements.length == 0)
1713                         // return null;
1714
1715                         return selectWord(viewer.getDocument(), offset);
1716
1717                         // } catch (JavaModelException e) {
1718                         // return null;
1719                         // }
1720                 }
1721
1722                 private int getCurrentTextOffset(ISourceViewer viewer) {
1723
1724                         try {
1725                                 StyledText text = viewer.getTextWidget();
1726                                 if (text == null || text.isDisposed())
1727                                         return -1;
1728
1729                                 Display display = text.getDisplay();
1730                                 Point absolutePosition = display.getCursorLocation();
1731                                 Point relativePosition = text.toControl(absolutePosition);
1732
1733                                 int widgetOffset = text.getOffsetAtLocation(relativePosition);
1734                                 if (viewer instanceof ITextViewerExtension5) {
1735                                         ITextViewerExtension5 extension = (ITextViewerExtension5) viewer;
1736                                         return extension.widgetOffset2ModelOffset(widgetOffset);
1737                                 } else {
1738                                         return widgetOffset + viewer.getVisibleRegion().getOffset();
1739                                 }
1740
1741                         } catch (IllegalArgumentException e) {
1742                                 return -1;
1743                         }
1744                 }
1745
1746                 public void applyTextPresentation(TextPresentation textPresentation) {
1747                         if (fActiveRegion == null)
1748                                 return;
1749                         IRegion region = textPresentation.getExtent();
1750                         if (fActiveRegion.getOffset() + fActiveRegion.getLength() >= region
1751                                         .getOffset()
1752                                         && region.getOffset() + region.getLength() > fActiveRegion
1753                                                         .getOffset())
1754                                 textPresentation.mergeStyleRange(new StyleRange(fActiveRegion
1755                                                 .getOffset(), fActiveRegion.getLength(), fColor, null));
1756                 }
1757
1758                 private void highlightRegion(ISourceViewer viewer, IRegion region) {
1759
1760                         if (region.equals(fActiveRegion))
1761                                 return;
1762
1763                         repairRepresentation();
1764
1765                         StyledText text = viewer.getTextWidget();
1766                         if (text == null || text.isDisposed())
1767                                 return;
1768
1769                         // Underline
1770                         int offset = 0;
1771                         int length = 0;
1772                         if (viewer instanceof ITextViewerExtension5) {
1773                                 ITextViewerExtension5 extension = (ITextViewerExtension5) viewer;
1774                                 IRegion widgetRange = extension.modelRange2WidgetRange(region);
1775                                 if (widgetRange == null)
1776                                         return;
1777
1778                                 offset = widgetRange.getOffset();
1779                                 length = widgetRange.getLength();
1780
1781                         } else {
1782                                 offset = region.getOffset()
1783                                                 - viewer.getVisibleRegion().getOffset();
1784                                 length = region.getLength();
1785                         }
1786                         text.redrawRange(offset, length, false);
1787
1788                         // Invalidate region ==> apply text presentation
1789                         fActiveRegion = region;
1790                         if (viewer instanceof ITextViewerExtension2)
1791                                 ((ITextViewerExtension2) viewer).invalidateTextPresentation(
1792                                                 region.getOffset(), region.getLength());
1793                         else
1794                                 viewer.invalidateTextPresentation();
1795                 }
1796
1797                 private void activateCursor(ISourceViewer viewer) {
1798                         StyledText text = viewer.getTextWidget();
1799                         if (text == null || text.isDisposed())
1800                                 return;
1801                         Display display = text.getDisplay();
1802                         if (fCursor == null)
1803                                 fCursor = new Cursor(display, SWT.CURSOR_HAND);
1804                         text.setCursor(fCursor);
1805                 }
1806
1807                 private void resetCursor(ISourceViewer viewer) {
1808                         StyledText text = viewer.getTextWidget();
1809                         if (text != null && !text.isDisposed())
1810                                 text.setCursor(null);
1811
1812                         if (fCursor != null) {
1813                                 fCursor.dispose();
1814                                 fCursor = null;
1815                         }
1816                 }
1817
1818                 /*
1819                  * @see org.eclipse.swt.events.KeyListener#keyPressed(org.eclipse.swt.events.KeyEvent)
1820                  */
1821                 public void keyPressed(KeyEvent event) {
1822
1823                         if (fActive) {
1824                                 deactivate();
1825                                 return;
1826                         }
1827
1828                         if (event.keyCode != fKeyModifierMask) {
1829                                 deactivate();
1830                                 return;
1831                         }
1832
1833                         fActive = true;
1834
1835                         // removed for #25871
1836                         //
1837                         // ISourceViewer viewer= getSourceViewer();
1838                         // if (viewer == null)
1839                         // return;
1840                         //
1841                         // IRegion region= getCurrentTextRegion(viewer);
1842                         // if (region == null)
1843                         // return;
1844                         //
1845                         // highlightRegion(viewer, region);
1846                         // activateCursor(viewer);
1847                 }
1848
1849                 /*
1850                  * @see org.eclipse.swt.events.KeyListener#keyReleased(org.eclipse.swt.events.KeyEvent)
1851                  */
1852                 public void keyReleased(KeyEvent event) {
1853
1854                         if (!fActive)
1855                                 return;
1856
1857                         deactivate();
1858                 }
1859
1860                 /*
1861                  * @see org.eclipse.swt.events.MouseListener#mouseDoubleClick(org.eclipse.swt.events.MouseEvent)
1862                  */
1863                 public void mouseDoubleClick(MouseEvent e) {
1864                 }
1865
1866                 /*
1867                  * @see org.eclipse.swt.events.MouseListener#mouseDown(org.eclipse.swt.events.MouseEvent)
1868                  */
1869                 public void mouseDown(MouseEvent event) {
1870
1871                         if (!fActive)
1872                                 return;
1873
1874                         if (event.stateMask != fKeyModifierMask) {
1875                                 deactivate();
1876                                 return;
1877                         }
1878
1879                         if (event.button != 1) {
1880                                 deactivate();
1881                                 return;
1882                         }
1883                 }
1884
1885                 /*
1886                  * @see org.eclipse.swt.events.MouseListener#mouseUp(org.eclipse.swt.events.MouseEvent)
1887                  */
1888                 public void mouseUp(MouseEvent e) {
1889
1890                         if (!fActive)
1891                                 return;
1892
1893                         if (e.button != 1) {
1894                                 deactivate();
1895                                 return;
1896                         }
1897
1898                         boolean wasActive = fCursor != null;
1899
1900                         deactivate();
1901
1902                         if (wasActive) {
1903                                 IAction action = getAction("OpenEditor"); //$NON-NLS-1$
1904                                 if (action != null)
1905                                         action.run();
1906                         }
1907                 }
1908
1909                 /*
1910                  * @see org.eclipse.swt.events.MouseMoveListener#mouseMove(org.eclipse.swt.events.MouseEvent)
1911                  */
1912                 public void mouseMove(MouseEvent event) {
1913
1914                         if (event.widget instanceof Control
1915                                         && !((Control) event.widget).isFocusControl()) {
1916                                 deactivate();
1917                                 return;
1918                         }
1919
1920                         if (!fActive) {
1921                                 if (event.stateMask != fKeyModifierMask)
1922                                         return;
1923                                 // modifier was already pressed
1924                                 fActive = true;
1925                         }
1926
1927                         ISourceViewer viewer = getSourceViewer();
1928                         if (viewer == null) {
1929                                 deactivate();
1930                                 return;
1931                         }
1932
1933                         StyledText text = viewer.getTextWidget();
1934                         if (text == null || text.isDisposed()) {
1935                                 deactivate();
1936                                 return;
1937                         }
1938
1939                         if ((event.stateMask & SWT.BUTTON1) != 0
1940                                         && text.getSelectionCount() != 0) {
1941                                 deactivate();
1942                                 return;
1943                         }
1944
1945                         IRegion region = getCurrentTextRegion(viewer);
1946                         if (region == null || region.getLength() == 0) {
1947                                 repairRepresentation();
1948                                 return;
1949                         }
1950
1951                         highlightRegion(viewer, region);
1952                         activateCursor(viewer);
1953                 }
1954
1955                 /*
1956                  * @see org.eclipse.swt.events.FocusListener#focusGained(org.eclipse.swt.events.FocusEvent)
1957                  */
1958                 public void focusGained(FocusEvent e) {
1959                 }
1960
1961                 /*
1962                  * @see org.eclipse.swt.events.FocusListener#focusLost(org.eclipse.swt.events.FocusEvent)
1963                  */
1964                 public void focusLost(FocusEvent event) {
1965                         deactivate();
1966                 }
1967
1968                 /*
1969                  * @see org.eclipse.jface.text.IDocumentListener#documentAboutToBeChanged(org.eclipse.jface.text.DocumentEvent)
1970                  */
1971                 public void documentAboutToBeChanged(DocumentEvent event) {
1972                         if (fActive && fActiveRegion != null) {
1973                                 fRememberedPosition = new Position(fActiveRegion.getOffset(),
1974                                                 fActiveRegion.getLength());
1975                                 try {
1976                                         event.getDocument().addPosition(fRememberedPosition);
1977                                 } catch (BadLocationException x) {
1978                                         fRememberedPosition = null;
1979                                 }
1980                         }
1981                 }
1982
1983                 /*
1984                  * @see org.eclipse.jface.text.IDocumentListener#documentChanged(org.eclipse.jface.text.DocumentEvent)
1985                  */
1986                 public void documentChanged(DocumentEvent event) {
1987                         if (fRememberedPosition != null) {
1988                                 if (!fRememberedPosition.isDeleted()) {
1989
1990                                         event.getDocument().removePosition(fRememberedPosition);
1991                                         fActiveRegion = new Region(fRememberedPosition.getOffset(),
1992                                                         fRememberedPosition.getLength());
1993                                         fRememberedPosition = null;
1994
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() {
2000                                                                 public void run() {
2001                                                                         deactivate();
2002                                                                 }
2003                                                         });
2004                                                 }
2005                                         }
2006
2007                                 } else {
2008                                         fActiveRegion = null;
2009                                         fRememberedPosition = null;
2010                                         deactivate();
2011                                 }
2012                         }
2013                 }
2014
2015                 /*
2016                  * @see org.eclipse.jface.text.ITextInputListener#inputDocumentAboutToBeChanged(org.eclipse.jface.text.IDocument,
2017                  *      org.eclipse.jface.text.IDocument)
2018                  */
2019                 public void inputDocumentAboutToBeChanged(IDocument oldInput,
2020                                 IDocument newInput) {
2021                         if (oldInput == null)
2022                                 return;
2023                         deactivate();
2024                         oldInput.removeDocumentListener(this);
2025                 }
2026
2027                 /*
2028                  * @see org.eclipse.jface.text.ITextInputListener#inputDocumentChanged(org.eclipse.jface.text.IDocument,
2029                  *      org.eclipse.jface.text.IDocument)
2030                  */
2031                 public void inputDocumentChanged(IDocument oldInput, IDocument newInput) {
2032                         if (newInput == null)
2033                                 return;
2034                         newInput.addDocumentListener(this);
2035                 }
2036
2037                 /*
2038                  * @see PaintListener#paintControl(PaintEvent)
2039                  */
2040                 public void paintControl(PaintEvent event) {
2041                         if (fActiveRegion == null)
2042                                 return;
2043
2044                         ISourceViewer viewer = getSourceViewer();
2045                         if (viewer == null)
2046                                 return;
2047
2048                         StyledText text = viewer.getTextWidget();
2049                         if (text == null || text.isDisposed())
2050                                 return;
2051
2052                         int offset = 0;
2053                         int length = 0;
2054
2055                         if (viewer instanceof ITextViewerExtension5) {
2056
2057                                 ITextViewerExtension5 extension = (ITextViewerExtension5) viewer;
2058                                 IRegion widgetRange = extension
2059                                                 .modelRange2WidgetRange(fActiveRegion);
2060                                 if (widgetRange == null)
2061                                         return;
2062
2063                                 offset = widgetRange.getOffset();
2064                                 length = widgetRange.getLength();
2065
2066                         } else {
2067
2068                                 IRegion region = viewer.getVisibleRegion();
2069                                 if (!includes(region, fActiveRegion))
2070                                         return;
2071
2072                                 offset = fActiveRegion.getOffset() - region.getOffset();
2073                                 length = fActiveRegion.getLength();
2074                         }
2075
2076                         // support for bidi
2077                         Point minLocation = getMinimumLocation(text, offset, length);
2078                         Point maxLocation = getMaximumLocation(text, offset, length);
2079
2080                         int x1 = minLocation.x;
2081                         int x2 = minLocation.x + maxLocation.x - minLocation.x - 1;
2082                         int y = minLocation.y + text.getLineHeight() - 1;
2083
2084                         GC gc = event.gc;
2085                         if (fColor != null && !fColor.isDisposed())
2086                                 gc.setForeground(fColor);
2087                         gc.drawLine(x1, y, x2, y);
2088                 }
2089
2090                 private boolean includes(IRegion region, IRegion position) {
2091                         return position.getOffset() >= region.getOffset()
2092                                         && position.getOffset() + position.getLength() <= region
2093                                                         .getOffset()
2094                                                         + region.getLength();
2095                 }
2096
2097                 private Point getMinimumLocation(StyledText text, int offset, int length) {
2098                         Point minLocation = new Point(Integer.MAX_VALUE, Integer.MAX_VALUE);
2099
2100                         for (int i = 0; i <= length; i++) {
2101                                 Point location = text.getLocationAtOffset(offset + i);
2102
2103                                 if (location.x < minLocation.x)
2104                                         minLocation.x = location.x;
2105                                 if (location.y < minLocation.y)
2106                                         minLocation.y = location.y;
2107                         }
2108
2109                         return minLocation;
2110                 }
2111
2112                 private Point getMaximumLocation(StyledText text, int offset, int length) {
2113                         Point maxLocation = new Point(Integer.MIN_VALUE, Integer.MIN_VALUE);
2114
2115                         for (int i = 0; i <= length; i++) {
2116                                 Point location = text.getLocationAtOffset(offset + i);
2117
2118                                 if (location.x > maxLocation.x)
2119                                         maxLocation.x = location.x;
2120                                 if (location.y > maxLocation.y)
2121                                         maxLocation.y = location.y;
2122                         }
2123
2124                         return maxLocation;
2125                 }
2126         }
2127
2128         /**
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.
2133          */
2134         class InformationDispatchAction extends TextEditorAction {
2135
2136                 /** The wrapped text operation action. */
2137                 private final TextOperationAction fTextOperationAction;
2138
2139                 /**
2140                  * Creates a dispatch action.
2141                  */
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;
2148                 }
2149
2150                 /*
2151                  * @see org.eclipse.jface.action.IAction#run()
2152                  */
2153                 public void run() {
2154
2155                         ISourceViewer sourceViewer = getSourceViewer();
2156                         if (sourceViewer == null) {
2157                                 fTextOperationAction.run();
2158                                 return;
2159                         }
2160
2161                         if (!(sourceViewer instanceof ITextViewerExtension2)) {
2162                                 fTextOperationAction.run();
2163                                 return;
2164                         }
2165
2166                         ITextViewerExtension2 textViewerExtension2 = (ITextViewerExtension2) sourceViewer;
2167
2168                         // does a text hover exist?
2169                         ITextHover textHover = textViewerExtension2.getCurrentTextHover();
2170                         if (textHover == null) {
2171                                 fTextOperationAction.run();
2172                                 return;
2173                         }
2174
2175                         Point hoverEventLocation = textViewerExtension2
2176                                         .getHoverEventLocation();
2177                         int offset = computeOffsetAtLocation(sourceViewer,
2178                                         hoverEventLocation.x, hoverEventLocation.y);
2179                         if (offset == -1) {
2180                                 fTextOperationAction.run();
2181                                 return;
2182                         }
2183
2184                         try {
2185                                 // get the text hover content
2186                                 IDocument document = sourceViewer.getDocument();
2187                                 String contentType = document.getContentType(offset);
2188
2189                                 final IRegion hoverRegion = textHover.getHoverRegion(
2190                                                 sourceViewer, offset);
2191                                 if (hoverRegion == null)
2192                                         return;
2193
2194                                 final String hoverInfo = textHover.getHoverInfo(sourceViewer,
2195                                                 hoverRegion);
2196
2197                                 // with information provider
2198                                 IInformationProvider informationProvider = new IInformationProvider() {
2199                                         /*
2200                                          * @see org.eclipse.jface.text.information.IInformationProvider#getSubject(org.eclipse.jface.text.ITextViewer,
2201                                          *      int)
2202                                          */
2203                                         public IRegion getSubject(ITextViewer textViewer, int offset) {
2204                                                 return hoverRegion;
2205                                         }
2206
2207                                         /*
2208                                          * @see org.eclipse.jface.text.information.IInformationProvider#getInformation(org.eclipse.jface.text.ITextViewer,
2209                                          *      org.eclipse.jface.text.IRegion)
2210                                          */
2211                                         public String getInformation(ITextViewer textViewer,
2212                                                         IRegion subject) {
2213                                                 return hoverInfo;
2214                                         }
2215                                 };
2216
2217                                 fInformationPresenter.setOffset(offset);
2218                                 fInformationPresenter.setInformationProvider(
2219                                                 informationProvider, contentType);
2220                                 fInformationPresenter.showInformation();
2221
2222                         } catch (BadLocationException e) {
2223                         }
2224                 }
2225
2226                 // modified version from TextViewer
2227                 private int computeOffsetAtLocation(ITextViewer textViewer, int x, int y) {
2228
2229                         StyledText styledText = textViewer.getTextWidget();
2230                         IDocument document = textViewer.getDocument();
2231
2232                         if (document == null)
2233                                 return -1;
2234
2235                         try {
2236                                 int widgetLocation = styledText.getOffsetAtLocation(new Point(
2237                                                 x, y));
2238                                 if (textViewer instanceof ITextViewerExtension5) {
2239                                         ITextViewerExtension5 extension = (ITextViewerExtension5) textViewer;
2240                                         return extension.widgetOffset2ModelOffset(widgetLocation);
2241                                 } else {
2242                                         IRegion visibleRegion = textViewer.getVisibleRegion();
2243                                         return widgetLocation + visibleRegion.getOffset();
2244                                 }
2245                         } catch (IllegalArgumentException e) {
2246                                 return -1;
2247                         }
2248
2249                 }
2250         };
2251
2252         /**
2253          * This action implements smart home.
2254          * 
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.
2261          * 
2262          * @since 3.0
2263          */
2264         protected class SmartLineStartAction extends LineStartAction {
2265
2266                 /**
2267                  * Creates a new smart line start action
2268                  * 
2269                  * @param textWidget
2270                  *            the styled text widget
2271                  * @param doSelect
2272                  *            a boolean flag which tells if the text up to the beginning
2273                  *            of the line should be selected
2274                  */
2275                 public SmartLineStartAction(final StyledText textWidget,
2276                                 final boolean doSelect) {
2277                         super(textWidget, doSelect);
2278                 }
2279
2280                 /*
2281                  * @see org.eclipse.ui.texteditor.AbstractTextEditor.LineStartAction#getLineStartPosition(java.lang.String,
2282                  *      int, java.lang.String)
2283                  */
2284                 protected int getLineStartPosition(final IDocument document,
2285                                 final String line, final int length, final int offset) {
2286
2287                         String type = IDocument.DEFAULT_CONTENT_TYPE;
2288                         try {
2289                                 type = TextUtilities.getContentType(document,
2290                                                 IPHPPartitions.PHP_PARTITIONING, offset, true);
2291                         } catch (BadLocationException exception) {
2292                                 // Should not happen
2293                         }
2294
2295                         int index = super.getLineStartPosition(document, line, length,
2296                                         offset);
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) != '/') {
2301                                         do {
2302                                                 ++index;
2303                                         } while (index < length
2304                                                         && Character.isWhitespace(line.charAt(index)));
2305                                 }
2306                         } else {
2307                                 if (index < length - 1 && line.charAt(index) == '/'
2308                                                 && line.charAt(index + 1) == '/') {
2309                                         index++;
2310                                         do {
2311                                                 ++index;
2312                                         } while (index < length
2313                                                         && Character.isWhitespace(line.charAt(index)));
2314                                 }
2315                         }
2316                         return index;
2317                 }
2318         }
2319
2320         /**
2321          * Text navigation action to navigate to the next sub-word.
2322          * 
2323          * @since 3.0
2324          */
2325         protected abstract class NextSubWordAction extends TextNavigationAction {
2326
2327                 protected JavaWordIterator fIterator = new JavaWordIterator();
2328
2329                 /**
2330                  * Creates a new next sub-word action.
2331                  * 
2332                  * @param code
2333                  *            Action code for the default operation. Must be an action
2334                  *            code from
2335                  * @see org.eclipse.swt.custom.ST.
2336                  */
2337                 protected NextSubWordAction(int code) {
2338                         super(getSourceViewer().getTextWidget(), code);
2339                 }
2340
2341                 /*
2342                  * @see org.eclipse.jface.action.IAction#run()
2343                  */
2344                 public void run() {
2345                         // Check whether we are in a java code partition and the preference
2346                         // is
2347                         // enabled
2348                         final IPreferenceStore store = getPreferenceStore();
2349                         if (!store
2350                                         .getBoolean(PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION)) {
2351                                 super.run();
2352                                 return;
2353                         }
2354
2355                         final ISourceViewer viewer = getSourceViewer();
2356                         final IDocument document = viewer.getDocument();
2357                         fIterator
2358                                         .setText((CharacterIterator) new DocumentCharacterIterator(
2359                                                         document));
2360                         int position = widgetOffset2ModelOffset(viewer, viewer
2361                                         .getTextWidget().getCaretOffset());
2362                         if (position == -1)
2363                                 return;
2364
2365                         int next = findNextPosition(position);
2366                         if (next != BreakIterator.DONE) {
2367                                 setCaretPosition(next);
2368                                 getTextWidget().showSelection();
2369                                 fireSelectionChanged();
2370                         }
2371
2372                 }
2373
2374                 /**
2375                  * Finds the next position after the given position.
2376                  * 
2377                  * @param position
2378                  *            the current position
2379                  * @return the next position
2380                  */
2381                 protected int findNextPosition(int position) {
2382                         ISourceViewer viewer = getSourceViewer();
2383                         int widget = -1;
2384                         while (position != BreakIterator.DONE && widget == -1) { // TODO:
2385                                 // optimize
2386                                 position = fIterator.following(position);
2387                                 if (position != BreakIterator.DONE)
2388                                         widget = modelOffset2WidgetOffset(viewer, position);
2389                         }
2390                         return position;
2391                 }
2392
2393                 /**
2394                  * Sets the caret position to the sub-word boundary given with
2395                  * <code>position</code>.
2396                  * 
2397                  * @param position
2398                  *            Position where the action should move the caret
2399                  */
2400                 protected abstract void setCaretPosition(int position);
2401         }
2402
2403         /**
2404          * Text navigation action to navigate to the next sub-word.
2405          * 
2406          * @since 3.0
2407          */
2408         protected class NavigateNextSubWordAction extends NextSubWordAction {
2409
2410                 /**
2411                  * Creates a new navigate next sub-word action.
2412                  */
2413                 public NavigateNextSubWordAction() {
2414                         super(ST.WORD_NEXT);
2415                 }
2416
2417                 /*
2418                  * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor.NextSubWordAction#setCaretPosition(int)
2419                  */
2420                 protected void setCaretPosition(final int position) {
2421                         getTextWidget().setCaretOffset(
2422                                         modelOffset2WidgetOffset(getSourceViewer(), position));
2423                 }
2424         }
2425
2426         /**
2427          * Text operation action to delete the next sub-word.
2428          * 
2429          * @since 3.0
2430          */
2431         protected class DeleteNextSubWordAction extends NextSubWordAction implements
2432                         IUpdate {
2433
2434                 /**
2435                  * Creates a new delete next sub-word action.
2436                  */
2437                 public DeleteNextSubWordAction() {
2438                         super(ST.DELETE_WORD_NEXT);
2439                 }
2440
2441                 /*
2442                  * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor.NextSubWordAction#setCaretPosition(int)
2443                  */
2444                 protected void setCaretPosition(final int position) {
2445                         if (!validateEditorInputState())
2446                                 return;
2447
2448                         final ISourceViewer viewer = getSourceViewer();
2449                         final int caret = widgetOffset2ModelOffset(viewer, viewer
2450                                         .getTextWidget().getCaretOffset());
2451
2452                         try {
2453                                 viewer.getDocument().replace(caret, position - caret, ""); //$NON-NLS-1$
2454                         } catch (BadLocationException exception) {
2455                                 // Should not happen
2456                         }
2457                 }
2458
2459                 /*
2460                  * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor.NextSubWordAction#findNextPosition(int)
2461                  */
2462                 protected int findNextPosition(int position) {
2463                         return fIterator.following(position);
2464                 }
2465
2466                 /*
2467                  * @see org.eclipse.ui.texteditor.IUpdate#update()
2468                  */
2469                 public void update() {
2470                         setEnabled(isEditorInputModifiable());
2471                 }
2472         }
2473
2474         /**
2475          * Text operation action to select the next sub-word.
2476          * 
2477          * @since 3.0
2478          */
2479         protected class SelectNextSubWordAction extends NextSubWordAction {
2480
2481                 /**
2482                  * Creates a new select next sub-word action.
2483                  */
2484                 public SelectNextSubWordAction() {
2485                         super(ST.SELECT_WORD_NEXT);
2486                 }
2487
2488                 /*
2489                  * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor.NextSubWordAction#setCaretPosition(int)
2490                  */
2491                 protected void setCaretPosition(final int position) {
2492                         final ISourceViewer viewer = getSourceViewer();
2493
2494                         final StyledText text = viewer.getTextWidget();
2495                         if (text != null && !text.isDisposed()) {
2496
2497                                 final Point selection = text.getSelection();
2498                                 final int caret = text.getCaretOffset();
2499                                 final int offset = modelOffset2WidgetOffset(viewer, position);
2500
2501                                 if (caret == selection.x)
2502                                         text.setSelectionRange(selection.y, offset - selection.y);
2503                                 else
2504                                         text.setSelectionRange(selection.x, offset - selection.x);
2505                         }
2506                 }
2507         }
2508
2509         /**
2510          * Text navigation action to navigate to the previous sub-word.
2511          * 
2512          * @since 3.0
2513          */
2514         protected abstract class PreviousSubWordAction extends TextNavigationAction {
2515
2516                 protected JavaWordIterator fIterator = new JavaWordIterator();
2517
2518                 /**
2519                  * Creates a new previous sub-word action.
2520                  * 
2521                  * @param code
2522                  *            Action code for the default operation. Must be an action
2523                  *            code from
2524                  * @see org.eclipse.swt.custom.ST.
2525                  */
2526                 protected PreviousSubWordAction(final int code) {
2527                         super(getSourceViewer().getTextWidget(), code);
2528                 }
2529
2530                 /*
2531                  * @see org.eclipse.jface.action.IAction#run()
2532                  */
2533                 public void run() {
2534                         // Check whether we are in a java code partition and the preference
2535                         // is
2536                         // enabled
2537                         final IPreferenceStore store = getPreferenceStore();
2538                         if (!store
2539                                         .getBoolean(PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION)) {
2540                                 super.run();
2541                                 return;
2542                         }
2543
2544                         final ISourceViewer viewer = getSourceViewer();
2545                         final IDocument document = viewer.getDocument();
2546                         fIterator
2547                                         .setText((CharacterIterator) new DocumentCharacterIterator(
2548                                                         document));
2549                         int position = widgetOffset2ModelOffset(viewer, viewer
2550                                         .getTextWidget().getCaretOffset());
2551                         if (position == -1)
2552                                 return;
2553
2554                         int previous = findPreviousPosition(position);
2555                         if (previous != BreakIterator.DONE) {
2556                                 setCaretPosition(previous);
2557                                 getTextWidget().showSelection();
2558                                 fireSelectionChanged();
2559                         }
2560
2561                 }
2562
2563                 /**
2564                  * Finds the previous position before the given position.
2565                  * 
2566                  * @param position
2567                  *            the current position
2568                  * @return the previous position
2569                  */
2570                 protected int findPreviousPosition(int position) {
2571                         ISourceViewer viewer = getSourceViewer();
2572                         int widget = -1;
2573                         while (position != BreakIterator.DONE && widget == -1) { // TODO:
2574                                 // optimize
2575                                 position = fIterator.preceding(position);
2576                                 if (position != BreakIterator.DONE)
2577                                         widget = modelOffset2WidgetOffset(viewer, position);
2578                         }
2579                         return position;
2580                 }
2581
2582                 /**
2583                  * Sets the caret position to the sub-word boundary given with
2584                  * <code>position</code>.
2585                  * 
2586                  * @param position
2587                  *            Position where the action should move the caret
2588                  */
2589                 protected abstract void setCaretPosition(int position);
2590         }
2591
2592         /**
2593          * Text navigation action to navigate to the previous sub-word.
2594          * 
2595          * @since 3.0
2596          */
2597         protected class NavigatePreviousSubWordAction extends PreviousSubWordAction {
2598
2599                 /**
2600                  * Creates a new navigate previous sub-word action.
2601                  */
2602                 public NavigatePreviousSubWordAction() {
2603                         super(ST.WORD_PREVIOUS);
2604                 }
2605
2606                 /*
2607                  * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#setCaretPosition(int)
2608                  */
2609                 protected void setCaretPosition(final int position) {
2610                         getTextWidget().setCaretOffset(
2611                                         modelOffset2WidgetOffset(getSourceViewer(), position));
2612                 }
2613         }
2614
2615         /**
2616          * Text operation action to delete the previous sub-word.
2617          * 
2618          * @since 3.0
2619          */
2620         protected class DeletePreviousSubWordAction extends PreviousSubWordAction
2621                         implements IUpdate {
2622
2623                 /**
2624                  * Creates a new delete previous sub-word action.
2625                  */
2626                 public DeletePreviousSubWordAction() {
2627                         super(ST.DELETE_WORD_PREVIOUS);
2628                 }
2629
2630                 /*
2631                  * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#setCaretPosition(int)
2632                  */
2633                 protected void setCaretPosition(final int position) {
2634                         if (!validateEditorInputState())
2635                                 return;
2636
2637                         final ISourceViewer viewer = getSourceViewer();
2638                         final int caret = widgetOffset2ModelOffset(viewer, viewer
2639                                         .getTextWidget().getCaretOffset());
2640
2641                         try {
2642                                 viewer.getDocument().replace(position, caret - position, ""); //$NON-NLS-1$
2643                         } catch (BadLocationException exception) {
2644                                 // Should not happen
2645                         }
2646                 }
2647
2648                 /*
2649                  * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#findPreviousPosition(int)
2650                  */
2651                 protected int findPreviousPosition(int position) {
2652                         return fIterator.preceding(position);
2653                 }
2654
2655                 /*
2656                  * @see org.eclipse.ui.texteditor.IUpdate#update()
2657                  */
2658                 public void update() {
2659                         setEnabled(isEditorInputModifiable());
2660                 }
2661         }
2662
2663         /**
2664          * Text operation action to select the previous sub-word.
2665          * 
2666          * @since 3.0
2667          */
2668         protected class SelectPreviousSubWordAction extends PreviousSubWordAction {
2669
2670                 /**
2671                  * Creates a new select previous sub-word action.
2672                  */
2673                 public SelectPreviousSubWordAction() {
2674                         super(ST.SELECT_WORD_PREVIOUS);
2675                 }
2676
2677                 /*
2678                  * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#setCaretPosition(int)
2679                  */
2680                 protected void setCaretPosition(final int position) {
2681                         final ISourceViewer viewer = getSourceViewer();
2682
2683                         final StyledText text = viewer.getTextWidget();
2684                         if (text != null && !text.isDisposed()) {
2685
2686                                 final Point selection = text.getSelection();
2687                                 final int caret = text.getCaretOffset();
2688                                 final int offset = modelOffset2WidgetOffset(viewer, position);
2689
2690                                 if (caret == selection.x)
2691                                         text.setSelectionRange(selection.y, offset - selection.y);
2692                                 else
2693                                         text.setSelectionRange(selection.x, offset - selection.x);
2694                         }
2695                 }
2696         }
2697
2698         // static protected class AnnotationAccess implements IAnnotationAccess {
2699         // /*
2700         // * @see
2701         // org.eclipse.jface.text.source.IAnnotationAccess#getType(org.eclipse.jface.text.source.Annotation)
2702         // */
2703         // public Object getType(Annotation annotation) {
2704         // if (annotation instanceof IJavaAnnotation) {
2705         // IJavaAnnotation javaAnnotation = (IJavaAnnotation) annotation;
2706         // // if (javaAnnotation.isRelevant())
2707         // // return javaAnnotation.getAnnotationType();
2708         // }
2709         // return null;
2710         // }
2711         //
2712         // /*
2713         // * @see
2714         // org.eclipse.jface.text.source.IAnnotationAccess#isMultiLine(org.eclipse.jface.text.source.Annotation)
2715         // */
2716         // public boolean isMultiLine(Annotation annotation) {
2717         // return true;
2718         // }
2719         //
2720         // /*
2721         // * @see
2722         // org.eclipse.jface.text.source.IAnnotationAccess#isTemporary(org.eclipse.jface.text.source.Annotation)
2723         // */
2724         // public boolean isTemporary(Annotation annotation) {
2725         // if (annotation instanceof IJavaAnnotation) {
2726         // IJavaAnnotation javaAnnotation = (IJavaAnnotation) annotation;
2727         // if (javaAnnotation.isRelevant())
2728         // return javaAnnotation.isTemporary();
2729         // }
2730         // return false;
2731         // }
2732         // };
2733
2734         private class PropertyChangeListener implements
2735                         org.eclipse.core.runtime.Preferences.IPropertyChangeListener {
2736                 /*
2737                  * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
2738                  */
2739                 public void propertyChange(
2740                                 org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) {
2741                         handlePreferencePropertyChanged(event);
2742                 }
2743         };
2744
2745         /**
2746          * Finds and marks occurrence annotations.
2747          * 
2748          * @since 3.0
2749          */
2750         class OccurrencesFinderJob extends Job {
2751
2752                 private IDocument fDocument;
2753
2754                 private ISelection fSelection;
2755
2756                 private ISelectionValidator fPostSelectionValidator;
2757
2758                 private boolean fCanceled = false;
2759
2760                 private IProgressMonitor fProgressMonitor;
2761
2762                 private Position[] fPositions;
2763
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;
2770
2771                         if (getSelectionProvider() instanceof ISelectionValidator)
2772                                 fPostSelectionValidator = (ISelectionValidator) getSelectionProvider();
2773                 }
2774
2775                 // cannot use cancel() because it is declared final
2776                 void doCancel() {
2777                         fCanceled = true;
2778                         cancel();
2779                 }
2780
2781                 private boolean isCanceled() {
2782                         return fCanceled
2783                                         || fProgressMonitor.isCanceled()
2784                                         || fPostSelectionValidator != null
2785                                         && !(fPostSelectionValidator.isValid(fSelection) || fForcedMarkOccurrencesSelection == fSelection)
2786                                         || LinkedModeModel.hasInstalledModel(fDocument);
2787                 }
2788
2789                 /*
2790                  * @see Job#run(org.eclipse.core.runtime.IProgressMonitor)
2791                  */
2792                 public IStatus run(IProgressMonitor progressMonitor) {
2793
2794                         fProgressMonitor = progressMonitor;
2795
2796                         if (isCanceled())
2797                                 return Status.CANCEL_STATUS;
2798
2799                         ITextViewer textViewer = getViewer();
2800                         if (textViewer == null)
2801                                 return Status.CANCEL_STATUS;
2802
2803                         IDocument document = textViewer.getDocument();
2804                         if (document == null)
2805                                 return Status.CANCEL_STATUS;
2806
2807                         IDocumentProvider documentProvider = getDocumentProvider();
2808                         if (documentProvider == null)
2809                                 return Status.CANCEL_STATUS;
2810
2811                         IAnnotationModel annotationModel = documentProvider
2812                                         .getAnnotationModel(getEditorInput());
2813                         if (annotationModel == null)
2814                                 return Status.CANCEL_STATUS;
2815
2816                         // Add occurrence annotations
2817                         int length = fPositions.length;
2818                         Map annotationMap = new HashMap(length);
2819                         for (int i = 0; i < length; i++) {
2820
2821                                 if (isCanceled())
2822                                         return Status.CANCEL_STATUS;
2823
2824                                 String message;
2825                                 Position position = fPositions[i];
2826
2827                                 // Create & add annotation
2828                                 try {
2829                                         message = document.get(position.offset, position.length);
2830                                 } catch (BadLocationException ex) {
2831                                         // Skip this match
2832                                         continue;
2833                                 }
2834                                 annotationMap
2835                                                 .put(
2836                                                                 new Annotation(
2837                                                                                 "net.sourceforge.phpdt.ui.occurrences", false, message), //$NON-NLS-1$
2838                                                                 position);
2839                         }
2840
2841                         if (isCanceled())
2842                                 return Status.CANCEL_STATUS;
2843
2844                         synchronized (getLockObject(annotationModel)) {
2845                                 if (annotationModel instanceof IAnnotationModelExtension) {
2846                                         ((IAnnotationModelExtension) annotationModel)
2847                                                         .replaceAnnotations(fOccurrenceAnnotations,
2848                                                                         annotationMap);
2849                                 } else {
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());
2856                                         }
2857                                 }
2858                                 fOccurrenceAnnotations = (Annotation[]) annotationMap.keySet()
2859                                                 .toArray(new Annotation[annotationMap.keySet().size()]);
2860                         }
2861
2862                         return Status.OK_STATUS;
2863                 }
2864         }
2865
2866         /**
2867          * Cancels the occurrences finder job upon document changes.
2868          * 
2869          * @since 3.0
2870          */
2871         class OccurrencesFinderJobCanceler implements IDocumentListener,
2872                         ITextInputListener {
2873
2874                 public void install() {
2875                         ISourceViewer sourceViewer = getSourceViewer();
2876                         if (sourceViewer == null)
2877                                 return;
2878
2879                         StyledText text = sourceViewer.getTextWidget();
2880                         if (text == null || text.isDisposed())
2881                                 return;
2882
2883                         sourceViewer.addTextInputListener(this);
2884
2885                         IDocument document = sourceViewer.getDocument();
2886                         if (document != null)
2887                                 document.addDocumentListener(this);
2888                 }
2889
2890                 public void uninstall() {
2891                         ISourceViewer sourceViewer = getSourceViewer();
2892                         if (sourceViewer != null)
2893                                 sourceViewer.removeTextInputListener(this);
2894
2895                         IDocumentProvider documentProvider = getDocumentProvider();
2896                         if (documentProvider != null) {
2897                                 IDocument document = documentProvider
2898                                                 .getDocument(getEditorInput());
2899                                 if (document != null)
2900                                         document.removeDocumentListener(this);
2901                         }
2902                 }
2903
2904                 /*
2905                  * @see org.eclipse.jface.text.IDocumentListener#documentAboutToBeChanged(org.eclipse.jface.text.DocumentEvent)
2906                  */
2907                 public void documentAboutToBeChanged(DocumentEvent event) {
2908                         if (fOccurrencesFinderJob != null)
2909                                 fOccurrencesFinderJob.doCancel();
2910                 }
2911
2912                 /*
2913                  * @see org.eclipse.jface.text.IDocumentListener#documentChanged(org.eclipse.jface.text.DocumentEvent)
2914                  */
2915                 public void documentChanged(DocumentEvent event) {
2916                 }
2917
2918                 /*
2919                  * @see org.eclipse.jface.text.ITextInputListener#inputDocumentAboutToBeChanged(org.eclipse.jface.text.IDocument,
2920                  *      org.eclipse.jface.text.IDocument)
2921                  */
2922                 public void inputDocumentAboutToBeChanged(IDocument oldInput,
2923                                 IDocument newInput) {
2924                         if (oldInput == null)
2925                                 return;
2926
2927                         oldInput.removeDocumentListener(this);
2928                 }
2929
2930                 /*
2931                  * @see org.eclipse.jface.text.ITextInputListener#inputDocumentChanged(org.eclipse.jface.text.IDocument,
2932                  *      org.eclipse.jface.text.IDocument)
2933                  */
2934                 public void inputDocumentChanged(IDocument oldInput, IDocument newInput) {
2935                         if (newInput == null)
2936                                 return;
2937                         newInput.addDocumentListener(this);
2938                 }
2939         }
2940
2941         /**
2942          * Internal activation listener.
2943          * 
2944          * @since 3.0
2945          */
2946         private class ActivationListener implements IWindowListener {
2947
2948                 /*
2949                  * @see org.eclipse.ui.IWindowListener#windowActivated(org.eclipse.ui.IWorkbenchWindow)
2950                  * @since 3.1
2951                  */
2952                 public void windowActivated(IWorkbenchWindow window) {
2953                         if (window == getEditorSite().getWorkbenchWindow()
2954                                         && fMarkOccurrenceAnnotations && isActivePart()) {
2955                                 fForcedMarkOccurrencesSelection = getSelectionProvider()
2956                                                 .getSelection();
2957                                 SelectionListenerWithASTManager
2958                                                 .getDefault()
2959                                                 .forceSelectionChange(
2960                                                                 PHPEditor.this,
2961                                                                 (ITextSelection) fForcedMarkOccurrencesSelection);
2962                         }
2963                 }
2964
2965                 /*
2966                  * @see org.eclipse.ui.IWindowListener#windowDeactivated(org.eclipse.ui.IWorkbenchWindow)
2967                  * @since 3.1
2968                  */
2969                 public void windowDeactivated(IWorkbenchWindow window) {
2970                         if (window == getEditorSite().getWorkbenchWindow()
2971                                         && fMarkOccurrenceAnnotations && isActivePart())
2972                                 removeOccurrenceAnnotations();
2973                 }
2974
2975                 /*
2976                  * @see org.eclipse.ui.IWindowListener#windowClosed(org.eclipse.ui.IWorkbenchWindow)
2977                  * @since 3.1
2978                  */
2979                 public void windowClosed(IWorkbenchWindow window) {
2980                 }
2981
2982                 /*
2983                  * @see org.eclipse.ui.IWindowListener#windowOpened(org.eclipse.ui.IWorkbenchWindow)
2984                  * @since 3.1
2985                  */
2986                 public void windowOpened(IWorkbenchWindow window) {
2987                 }
2988         }
2989
2990         /**
2991          * Updates the selection in the editor's widget with the selection of the
2992          * outline page.
2993          */
2994         class OutlineSelectionChangedListener extends
2995                         AbstractSelectionChangedListener {
2996                 public void selectionChanged(SelectionChangedEvent event) {
2997                         doSelectionChanged(event);
2998                 }
2999         }
3000
3001         /**
3002          * The internal shell activation listener for updating occurrences.
3003          * 
3004          * @since 3.0
3005          */
3006         private ActivationListener fActivationListener = new ActivationListener();
3007
3008         private ISelectionListenerWithAST fPostSelectionListenerWithAST;
3009
3010         private OccurrencesFinderJob fOccurrencesFinderJob;
3011
3012         /** The occurrences finder job canceler */
3013         private OccurrencesFinderJobCanceler fOccurrencesFinderJobCanceler;
3014
3015         /**
3016          * Holds the current occurrence annotations.
3017          * 
3018          * @since 3.0
3019          */
3020         private Annotation[] fOccurrenceAnnotations = null;
3021
3022         /**
3023          * Tells whether all occurrences of the element at the current caret
3024          * location are automatically marked in this editor.
3025          * 
3026          * @since 3.0
3027          */
3028         private boolean fMarkOccurrenceAnnotations;
3029
3030         /**
3031          * The selection used when forcing occurrence marking through code.
3032          * 
3033          * @since 3.0
3034          */
3035         private ISelection fForcedMarkOccurrencesSelection;
3036
3037         /**
3038          * The document modification stamp at the time when the last occurrence
3039          * marking took place.
3040          * 
3041          * @since 3.1
3042          */
3043         private long fMarkOccurrenceModificationStamp = IDocumentExtension4.UNKNOWN_MODIFICATION_STAMP;
3044
3045         /**
3046          * The region of the word under the caret used to when computing the current
3047          * occurrence markings.
3048          * 
3049          * @since 3.1
3050          */
3051         private IRegion fMarkOccurrenceTargetRegion;
3052
3053         /**
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>.
3057          * 
3058          * @since 3.0
3059          */
3060         private boolean fStickyOccurrenceAnnotations;
3061
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;
3070
3071         /** Preference key for compiler task tags */
3072         private final static String COMPILER_TASK_TAGS = JavaCore.COMPILER_TASK_TAGS;
3073
3074         // protected PHPActionGroup fActionGroups;
3075         // /** The outline page */
3076         // private AbstractContentOutlinePage fOutlinePage;
3077         /** The outline page */
3078         protected JavaOutlinePage fOutlinePage;
3079
3080         /** Outliner context menu Id */
3081         protected String fOutlinerContextMenuId;
3082
3083         /**
3084          * Indicates whether this editor should react on outline page selection
3085          * changes
3086          */
3087         private int fIgnoreOutlinePageSelection;
3088
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();
3096         /**
3097          * The editor selection changed listener.
3098          * 
3099          * @since 3.0
3100          */
3101         private EditorSelectionChangedListener fEditorSelectionChangedListener;
3102
3103         /** The selection changed listener */
3104         protected AbstractSelectionChangedListener fOutlineSelectionChangedListener = new OutlineSelectionChangedListener();
3105
3106         /** The editor's bracket matcher */
3107         private PHPPairMatcher fBracketMatcher = new PHPPairMatcher(BRACKETS);
3108
3109         /** The line number ruler column */
3110         // private LineNumberRulerColumn fLineNumberRulerColumn;
3111         /** This editor's encoding support */
3112         private DefaultEncodingSupport fEncodingSupport;
3113
3114         /** The mouse listener */
3115         private MouseClickListener fMouseListener;
3116
3117         /**
3118          * Indicates whether this editor is about to update any annotation views.
3119          * 
3120          * @since 3.0
3121          */
3122         private boolean fIsUpdatingAnnotationViews = false;
3123
3124         /**
3125          * The marker that served as last target for a goto marker request.
3126          * 
3127          * @since 3.0
3128          */
3129         private IMarker fLastMarkerTarget = null;
3130
3131         protected CompositeActionGroup fActionGroups;
3132
3133         protected CompositeActionGroup fContextMenuGroup;
3134
3135         /**
3136          * This editor's projection support
3137          * 
3138          * @since 3.0
3139          */
3140         private ProjectionSupport fProjectionSupport;
3141
3142         /**
3143          * This editor's projection model updater
3144          * 
3145          * @since 3.0
3146          */
3147         private IJavaFoldingStructureProvider fProjectionModelUpdater;
3148
3149         /**
3150          * The override and implements indicator manager for this editor.
3151          * 
3152          * @since 3.0
3153          */
3154         // protected OverrideIndicatorManager fOverrideIndicatorManager;
3155         /**
3156          * The action group for folding.
3157          * 
3158          * @since 3.0
3159          */
3160         private FoldingActionGroup fFoldingGroup;
3161
3162         /** The information presenter. */
3163         private InformationPresenter fInformationPresenter;
3164
3165         /** The annotation access */
3166         // protected IAnnotationAccess fAnnotationAccess = new AnnotationAccess();
3167         /** The overview ruler */
3168         protected OverviewRuler isOverviewRulerVisible;
3169
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();
3176
3177         /**
3178          * Returns the most narrow java element including the given offset
3179          * 
3180          * @param offset
3181          *            the offset inside of the requested element
3182          */
3183         abstract protected IJavaElement getElementAt(int offset);
3184
3185         /**
3186          * Returns the java element of this editor's input corresponding to the
3187          * given IJavaElement
3188          */
3189         abstract protected IJavaElement getCorrespondingElement(IJavaElement element);
3190
3191         /**
3192          * Sets the input of the editor's outline page.
3193          */
3194         abstract protected void setOutlinePageInput(JavaOutlinePage page,
3195                         IEditorInput input);
3196
3197         /**
3198          * Default constructor.
3199          */
3200         public PHPEditor() {
3201                 super();
3202         }
3203
3204         /*
3205          * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#initializeKeyBindingScopes()
3206          */
3207         protected void initializeKeyBindingScopes() {
3208                 setKeyBindingScopes(new String[] { "net.sourceforge.phpdt.ui.phpEditorScope" }); //$NON-NLS-1$
3209         }
3210
3211         /*
3212          * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#initializeEditor()
3213          */
3214         protected void initializeEditor() {
3215                 // jsurfer old code
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));
3229
3230                 // TODO changed in 3.x ?
3231                 // setRangeIndicator(new DefaultRangeIndicator());
3232                 // if
3233                 // (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE))
3234                 // fUpdater = new OutlinePageSelectionUpdater();
3235                 // jsurfer end
3236
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);
3258                 // fMarkExceptions=
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);
3264
3265         }
3266
3267         /*
3268          * @see org.eclipse.ui.texteditor.AbstractTextEditor#updatePropertyDependentActions()
3269          */
3270         protected void updatePropertyDependentActions() {
3271                 super.updatePropertyDependentActions();
3272                 if (fEncodingSupport != null)
3273                         fEncodingSupport.reset();
3274         }
3275
3276         /*
3277          * Update the hovering behavior depending on the preferences.
3278          */
3279         private void updateHoverBehavior() {
3280                 SourceViewerConfiguration configuration = getSourceViewerConfiguration();
3281                 String[] types = configuration
3282                                 .getConfiguredContentTypes(getSourceViewer());
3283
3284                 for (int i = 0; i < types.length; i++) {
3285
3286                         String t = types[i];
3287
3288                         int[] stateMasks = configuration.getConfiguredTextHoverStateMasks(
3289                                         getSourceViewer(), t);
3290
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);
3300                                         }
3301                                 } else {
3302                                         ITextHover textHover = configuration.getTextHover(
3303                                                         sourceViewer, t);
3304                                         ((ITextViewerExtension2) sourceViewer).setTextHover(
3305                                                         textHover, t,
3306                                                         ITextViewerExtension2.DEFAULT_HOVER_STATE_MASK);
3307                                 }
3308                         } else
3309                                 sourceViewer.setTextHover(configuration.getTextHover(
3310                                                 sourceViewer, t), t);
3311                 }
3312         }
3313
3314         public void updatedTitleImage(Image image) {
3315                 setTitleImage(image);
3316         }
3317
3318         /*
3319          * @see net.sourceforge.phpdt.internal.ui.viewsupport.IViewPartInputProvider#getViewPartInput()
3320          */
3321         public Object getViewPartInput() {
3322                 return getEditorInput().getAdapter(IResource.class);
3323         }
3324
3325         /*
3326          * @see org.eclipse.ui.texteditor.AbstractTextEditor#doSetSelection(ISelection)
3327          */
3328         protected void doSetSelection(ISelection selection) {
3329                 super.doSetSelection(selection);
3330                 synchronizeOutlinePageSelection();
3331         }
3332
3333         boolean isFoldingEnabled() {
3334                 return PHPeclipsePlugin.getDefault().getPreferenceStore().getBoolean(
3335                                 PreferenceConstants.EDITOR_FOLDING_ENABLED);
3336         }
3337
3338         /*
3339          * @see org.eclipse.ui.IWorkbenchPart#createPartControl(org.eclipse.swt.
3340          *      widgets.Composite)
3341          */
3342         public void createPartControl(Composite parent) {
3343                 super.createPartControl(parent);
3344
3345                 // fSourceViewerDecorationSupport.install(getPreferenceStore());
3346
3347                 ProjectionViewer projectionViewer = (ProjectionViewer) getSourceViewer();
3348
3349                 fProjectionSupport = new ProjectionSupport(projectionViewer,
3350                                 getAnnotationAccess(), getSharedColors());
3351                 fProjectionSupport
3352                                 .addSummarizableAnnotationType("org.eclipse.ui.workbench.texteditor.error"); //$NON-NLS-1$
3353                 fProjectionSupport
3354                                 .addSummarizableAnnotationType("org.eclipse.ui.workbench.texteditor.warning"); //$NON-NLS-1$
3355                 fProjectionSupport
3356                                 .setHoverControlCreator(new IInformationControlCreator() {
3357                                         public IInformationControl createInformationControl(
3358                                                         Shell shell) {
3359                                                 return new CustomSourceInformationControl(shell,
3360                                                                 IDocument.DEFAULT_CONTENT_TYPE);
3361                                         }
3362                                 });
3363                 fProjectionSupport.install();
3364
3365                 fProjectionModelUpdater = PHPeclipsePlugin.getDefault()
3366                                 .getFoldingStructureProviderRegistry()
3367                                 .getCurrentFoldingProvider();
3368                 if (fProjectionModelUpdater != null)
3369                         fProjectionModelUpdater.install(this, projectionViewer);
3370
3371                 if (isFoldingEnabled())
3372                         projectionViewer.doOperation(ProjectionViewer.TOGGLE);
3373                 Preferences preferences = PHPeclipsePlugin.getDefault()
3374                                 .getPluginPreferences();
3375                 preferences.addPropertyChangeListener(fPropertyChangeListener);
3376
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));
3383                         }
3384                 };
3385
3386                 fInformationPresenter = new InformationPresenter(
3387                                 informationControlCreator);
3388                 fInformationPresenter.setSizeConstraints(60, 10, true, true);
3389                 fInformationPresenter.install(getSourceViewer());
3390
3391                 fEditorSelectionChangedListener = new EditorSelectionChangedListener();
3392                 fEditorSelectionChangedListener.install(getSelectionProvider());
3393
3394                 if (isBrowserLikeLinks())
3395                         enableBrowserLikeLinks();
3396
3397                 if (PreferenceConstants.getPreferenceStore().getBoolean(
3398                                 PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE))
3399                         enableOverwriteMode(false);
3400
3401                 if (fMarkOccurrenceAnnotations)
3402                         installOccurrencesFinder();
3403
3404                 PlatformUI.getWorkbench().addWindowListener(fActivationListener);
3405
3406                 setWordWrap();
3407         }
3408
3409         private void setWordWrap() {
3410                 if (getSourceViewer() != null) {
3411                         getSourceViewer().getTextWidget().setWordWrap(
3412                                         PHPeclipsePlugin.getDefault().getPreferenceStore()
3413                                                         .getBoolean(PreferenceConstants.EDITOR_WRAP_WORDS));
3414                 }
3415         }
3416
3417         protected void configureSourceViewerDecorationSupport(
3418                         SourceViewerDecorationSupport support) {
3419
3420                 support.setCharacterPairMatcher(fBracketMatcher);
3421                 support.setMatchingCharacterPainterPreferenceKeys(MATCHING_BRACKETS,
3422                                 MATCHING_BRACKETS_COLOR);
3423
3424                 super.configureSourceViewerDecorationSupport(support);
3425         }
3426
3427         /*
3428          * @see org.eclipse.ui.texteditor.AbstractTextEditor#gotoMarker(org.eclipse.core.resources.IMarker)
3429          */
3430         public void gotoMarker(IMarker marker) {
3431                 fLastMarkerTarget = marker;
3432                 if (!fIsUpdatingAnnotationViews) {
3433                         super.gotoMarker(marker);
3434                 }
3435         }
3436
3437         /**
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.
3441          * 
3442          * @param forward
3443          *            <code>true</code> if search direction is forward,
3444          *            <code>false</code> if backward
3445          */
3446         public Annotation gotoAnnotation(boolean forward) {
3447                 ITextSelection selection = (ITextSelection) getSelectionProvider()
3448                                 .getSelection();
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());
3464                         }
3465                 }
3466                 return annotation;
3467         }
3468
3469         /**
3470          * Returns the lock object for the given annotation model.
3471          * 
3472          * @param annotationModel
3473          *            the annotation model
3474          * @return the annotation model's lock object
3475          * @since 3.0
3476          */
3477         private Object getLockObject(IAnnotationModel annotationModel) {
3478                 if (annotationModel instanceof ISynchronizable)
3479                         return ((ISynchronizable) annotationModel).getLockObject();
3480                 else
3481                         return annotationModel;
3482         }
3483
3484         /**
3485          * Updates the annotation views that show the given annotation.
3486          * 
3487          * @param annotation
3488          *            the annotation
3489          */
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();
3496                         if (e != null) {
3497                                 while (e.hasNext()) {
3498                                         Object o = e.next();
3499                                         if (o instanceof MarkerAnnotation) {
3500                                                 marker = ((MarkerAnnotation) o).getMarker();
3501                                                 break;
3502                                         }
3503                                 }
3504                         }
3505                 }
3506
3507                 if (marker != null && !marker.equals(fLastMarkerTarget)) {
3508                         try {
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$
3514                                 if (view != null) {
3515                                         Method method = view
3516                                                         .getClass()
3517                                                         .getMethod(
3518                                                                         "setSelection", new Class[] { IStructuredSelection.class, boolean.class }); //$NON-NLS-1$
3519                                         method.invoke(view, new Object[] {
3520                                                         new StructuredSelection(marker), Boolean.TRUE });
3521                                 }
3522                         } catch (CoreException x) {
3523                         } catch (NoSuchMethodException x) {
3524                         } catch (IllegalAccessException x) {
3525                         } catch (InvocationTargetException x) {
3526                         }
3527                         // ignore exceptions, don't update any of the lists, just set status
3528                         // line
3529                 }
3530         }
3531
3532         /**
3533          * Returns this document's complete text.
3534          * 
3535          * @return the document's complete text
3536          */
3537         public String get() {
3538                 IDocument doc = this.getDocumentProvider().getDocument(
3539                                 this.getEditorInput());
3540                 return doc.get();
3541         }
3542
3543         /**
3544          * Sets the outliner's context menu ID.
3545          */
3546         protected void setOutlinerContextMenuId(String menuId) {
3547                 fOutlinerContextMenuId = menuId;
3548         }
3549
3550         /**
3551          * Returns the standard action group of this editor.
3552          */
3553         protected ActionGroup getActionGroup() {
3554                 return fActionGroups;
3555         }
3556
3557         // public JavaOutlinePage getfOutlinePage() {
3558         // return fOutlinePage;
3559         // }
3560
3561         /**
3562          * The <code>PHPEditor</code> implementation of this
3563          * <code>AbstractTextEditor</code> method extend the actions to add those
3564          * specific to the receiver
3565          */
3566         protected void createActions() {
3567                 super.createActions();
3568
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)
3575                                 });
3576                 fContextMenuGroup = new CompositeActionGroup(new ActionGroup[] { oeg });
3577                 // , ovg, sg, jsg});
3578
3579                 fFoldingGroup = new FoldingActionGroup(this, getViewer());
3580
3581                 // ResourceAction resAction = new
3582                 // TextOperationAction(PHPEditorMessages.getResourceBundle(),
3583                 // "ShowJavaDoc.", this, ISourceViewer.INFORMATION, true); //$NON-NLS-1$
3584                 // resAction = new
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$
3589
3590                 // WorkbenchHelp.setHelp(resAction,
3591                 // IJavaHelpContextIds.SHOW_JAVADOC_ACTION);
3592
3593                 Action action = new GotoMatchingBracketAction(this);
3594                 action
3595                                 .setActionDefinitionId(PHPEditorActionDefinitionIds.GOTO_MATCHING_BRACKET);
3596                 setAction(GotoMatchingBracketAction.GOTO_MATCHING_BRACKET, action);
3597
3598                 // action= new
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);
3605                 //
3606                 // action= new
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,
3611                 // action);
3612                 // // WorkbenchHelp.setHelp(action,
3613                 // IJavaHelpContextIds.OPEN_STRUCTURE_ACTION);
3614                 //
3615                 // action= new
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,
3620                 // action);
3621                 // // WorkbenchHelp.setHelp(action,
3622                 // IJavaHelpContextIds.OPEN_HIERARCHY_ACTION);
3623
3624                 fEncodingSupport = new DefaultEncodingSupport();
3625                 fEncodingSupport.initialize(this);
3626
3627                 // fSelectionHistory= new SelectionHistory(this);
3628                 //
3629                 // action= new StructureSelectEnclosingAction(this, fSelectionHistory);
3630                 // action.setActionDefinitionId(PHPEditorActionDefinitionIds.SELECT_ENCLOSING);
3631                 // setAction(StructureSelectionAction.ENCLOSING, action);
3632                 //
3633                 // action= new StructureSelectNextAction(this, fSelectionHistory);
3634                 // action.setActionDefinitionId(PHPEditorActionDefinitionIds.SELECT_NEXT);
3635                 // setAction(StructureSelectionAction.NEXT, action);
3636                 //
3637                 // action= new StructureSelectPreviousAction(this, fSelectionHistory);
3638                 // action.setActionDefinitionId(PHPEditorActionDefinitionIds.SELECT_PREVIOUS);
3639                 // setAction(StructureSelectionAction.PREVIOUS, action);
3640                 //
3641                 // StructureSelectHistoryAction historyAction= new
3642                 // StructureSelectHistoryAction(this, fSelectionHistory);
3643                 // historyAction.setActionDefinitionId(PHPEditorActionDefinitionIds.SELECT_LAST);
3644                 // setAction(StructureSelectionAction.HISTORY, historyAction);
3645                 // fSelectionHistory.setHistoryAction(historyAction);
3646                 //
3647                 // action= GoToNextPreviousMemberAction.newGoToNextMemberAction(this);
3648                 // action.setActionDefinitionId(PHPEditorActionDefinitionIds.GOTO_NEXT_MEMBER);
3649                 // setAction(GoToNextPreviousMemberAction.NEXT_MEMBER, action);
3650                 //
3651                 // action=
3652                 // GoToNextPreviousMemberAction.newGoToPreviousMemberAction(this);
3653                 // action.setActionDefinitionId(PHPEditorActionDefinitionIds.GOTO_PREVIOUS_MEMBER);
3654                 // setAction(GoToNextPreviousMemberAction.PREVIOUS_MEMBER, action);
3655                 //
3656                 // action= new QuickFormatAction();
3657                 // action.setActionDefinitionId(PHPEditorActionDefinitionIds.QUICK_FORMAT);
3658                 // setAction(IJavaEditorActionDefinitionIds.QUICK_FORMAT, action);
3659                 //
3660                 // action= new RemoveOccurrenceAnnotations(this);
3661                 // action.setActionDefinitionId(PHPEditorActionDefinitionIds.REMOVE_OCCURRENCE_ANNOTATIONS);
3662                 // setAction("RemoveOccurrenceAnnotations", action); //$NON-NLS-1$
3663
3664                 // add annotation actions
3665                 action = new JavaSelectMarkerRulerAction2(PHPEditorMessages
3666                                 .getResourceBundle(), "Editor.RulerAnnotationSelection.", this); //$NON-NLS-1$
3667                 setAction("AnnotationAction", action); //$NON-NLS-1$
3668         }
3669
3670         private void internalDoSetInput(IEditorInput input) throws CoreException {
3671                 super.doSetInput(input);
3672
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);
3681                                 }
3682                         }
3683                 }
3684
3685                 if (fEncodingSupport != null)
3686                         fEncodingSupport.reset();
3687
3688                 setOutlinePageInput(fOutlinePage, input);
3689
3690                 if (fProjectionModelUpdater != null)
3691                         fProjectionModelUpdater.initialize();
3692
3693                 // if (isShowingOverrideIndicators())
3694                 // installOverrideIndicator(false);
3695         }
3696
3697         /*
3698          * @see org.eclipse.ui.texteditor.AbstractTextEditor#setPreferenceStore(org.eclipse.jface.preference.IPreferenceStore)
3699          * @since 3.0
3700          */
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));
3709                 }
3710                 if (getSourceViewer() instanceof JavaSourceViewer)
3711                         ((JavaSourceViewer) getSourceViewer()).setPreferenceStore(store);
3712         }
3713
3714         /**
3715          * The <code>PHPEditor</code> implementation of this
3716          * <code>AbstractTextEditor</code> method performs any extra disposal
3717          * actions required by the php editor.
3718          */
3719         public void dispose() {
3720                 if (fProjectionModelUpdater != null) {
3721                         fProjectionModelUpdater.uninstall();
3722                         fProjectionModelUpdater = null;
3723                 }
3724
3725                 if (fProjectionSupport != null) {
3726                         fProjectionSupport.dispose();
3727                         fProjectionSupport = null;
3728                 }
3729                 // PHPEditorEnvironment.disconnect(this);
3730                 if (fOutlinePage != null)
3731                         fOutlinePage.setInput(null);
3732
3733                 if (fActionGroups != null)
3734                         fActionGroups.dispose();
3735
3736                 if (isBrowserLikeLinks())
3737                         disableBrowserLikeLinks();
3738
3739                 // cancel possible running computation
3740                 fMarkOccurrenceAnnotations = false;
3741                 uninstallOccurrencesFinder();
3742
3743                 uninstallOverrideIndicator();
3744
3745                 if (fActivationListener != null) {
3746                         PlatformUI.getWorkbench().removeWindowListener(fActivationListener);
3747                         fActivationListener = null;
3748                 }
3749
3750                 if (fEncodingSupport != null) {
3751                         fEncodingSupport.dispose();
3752                         fEncodingSupport = null;
3753                 }
3754
3755                 if (fPropertyChangeListener != null) {
3756                         Preferences preferences = PHPeclipsePlugin.getDefault()
3757                                         .getPluginPreferences();
3758                         preferences.removePropertyChangeListener(fPropertyChangeListener);
3759                         fPropertyChangeListener = null;
3760                 }
3761
3762                 // if (fSourceViewerDecorationSupport != null) {
3763                 // fSourceViewerDecorationSupport.dispose();
3764                 // fSourceViewerDecorationSupport = null;
3765                 // }
3766
3767                 if (fBracketMatcher != null) {
3768                         fBracketMatcher.dispose();
3769                         fBracketMatcher = null;
3770                 }
3771
3772                 if (fEditorSelectionChangedListener != null) {
3773                         fEditorSelectionChangedListener.uninstall(getSelectionProvider());
3774                         fEditorSelectionChangedListener = null;
3775                 }
3776
3777                 super.dispose();
3778         }
3779
3780         /**
3781          * The <code>PHPEditor</code> implementation of this
3782          * <code>AbstractTextEditor</code> method performs any extra revert
3783          * behavior required by the php editor.
3784          */
3785         // public void doRevertToSaved() {
3786         // super.doRevertToSaved();
3787         // if (fOutlinePage != null)
3788         // fOutlinePage.update();
3789         // }
3790         /**
3791          * The <code>PHPEditor</code> implementation of this
3792          * <code>AbstractTextEditor</code> method performs any extra save behavior
3793          * required by the php editor.
3794          */
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();
3802         // if (a != null)
3803         // a.run();
3804         // }
3805         // if (SWT.getPlatform().equals("win32")) {
3806         // IAction a = ShowExternalPreviewAction.getInstance();
3807         // if (a != null)
3808         // a.run();
3809         // }
3810         // if (fOutlinePage != null)
3811         // fOutlinePage.update();
3812         // }
3813         /**
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.
3817          */
3818         // public void doSaveAs() {
3819         // super.doSaveAs();
3820         // if (fOutlinePage != null)
3821         // fOutlinePage.update();
3822         // }
3823         /*
3824          * @see StatusTextEditor#getStatusHeader(IStatus)
3825          */
3826         protected String getStatusHeader(IStatus status) {
3827                 if (fEncodingSupport != null) {
3828                         String message = fEncodingSupport.getStatusHeader(status);
3829                         if (message != null)
3830                                 return message;
3831                 }
3832                 return super.getStatusHeader(status);
3833         }
3834
3835         /*
3836          * @see StatusTextEditor#getStatusBanner(IStatus)
3837          */
3838         protected String getStatusBanner(IStatus status) {
3839                 if (fEncodingSupport != null) {
3840                         String message = fEncodingSupport.getStatusBanner(status);
3841                         if (message != null)
3842                                 return message;
3843                 }
3844                 return super.getStatusBanner(status);
3845         }
3846
3847         /*
3848          * @see StatusTextEditor#getStatusMessage(IStatus)
3849          */
3850         protected String getStatusMessage(IStatus status) {
3851                 if (fEncodingSupport != null) {
3852                         String message = fEncodingSupport.getStatusMessage(status);
3853                         if (message != null)
3854                                 return message;
3855                 }
3856                 return super.getStatusMessage(status);
3857         }
3858
3859         /**
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.
3863          */
3864         // protected void doSetInput(IEditorInput input) throws CoreException {
3865         // super.doSetInput(input);
3866         // if (fEncodingSupport != null)
3867         // fEncodingSupport.reset();
3868         // setOutlinePageInput(fOutlinePage, input);
3869         // }
3870         /*
3871          * @see AbstractTextEditor#doSetInput
3872          */
3873         protected void doSetInput(IEditorInput input) throws CoreException {
3874                 ISourceViewer sourceViewer = getSourceViewer();
3875                 if (!(sourceViewer instanceof ISourceViewerExtension2)) {
3876                         setPreferenceStore(createCombinedPreferenceStore(input));
3877                         internalDoSetInput(input);
3878                         return;
3879                 }
3880
3881                 // uninstall & unregister preference store listener
3882                 if (isBrowserLikeLinks())
3883                         disableBrowserLikeLinks();
3884                 getSourceViewerDecorationSupport(sourceViewer).uninstall();
3885                 ((ISourceViewerExtension2) sourceViewer).unconfigure();
3886
3887                 setPreferenceStore(createCombinedPreferenceStore(input));
3888
3889                 // install & register preference store listener
3890                 sourceViewer.configure(getSourceViewerConfiguration());
3891                 getSourceViewerDecorationSupport(sourceViewer).install(
3892                                 getPreferenceStore());
3893                 if (isBrowserLikeLinks())
3894                         enableBrowserLikeLinks();
3895
3896                 internalDoSetInput(input);
3897         }
3898
3899         /*
3900          * @see org.phpeclipse.phpdt.internal.ui.viewsupport.IViewPartInputProvider#getViewPartInput()
3901          */
3902         // public Object getViewPartInput() {
3903         // return getEditorInput().getAdapter(IFile.class);
3904         // }
3905         /**
3906          * The <code>PHPEditor</code> implementation of this
3907          * <code>AbstractTextEditor</code> method adds any PHPEditor specific
3908          * entries.
3909          */
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));
3916
3917                 ActionContext context = new ActionContext(getSelectionProvider()
3918                                 .getSelection());
3919                 fContextMenuGroup.setContext(context);
3920                 fContextMenuGroup.fillContextMenu(menu);
3921                 fContextMenuGroup.setContext(null);
3922                 // addAction(menu, ITextEditorActionConstants.GROUP_EDIT, "Format");
3923                 // //$NON-NLS-1$
3924                 //
3925                 // ActionContext context =
3926                 // new ActionContext(getSelectionProvider().getSelection());
3927                 // fContextMenuGroup.setContext(context);
3928                 // fContextMenuGroup.fillContextMenu(menu);
3929                 // fContextMenuGroup.setContext(null);
3930         }
3931
3932         /**
3933          * Creates the outline page used with this editor.
3934          */
3935         protected JavaOutlinePage createOutlinePage() {
3936                 JavaOutlinePage page = new JavaOutlinePage(fOutlinerContextMenuId, this);
3937                 fOutlineSelectionChangedListener.install(page);
3938                 setOutlinePageInput(page, getEditorInput());
3939                 return page;
3940         }
3941
3942         /**
3943          * Informs the editor that its outliner has been closed.
3944          */
3945         public void outlinePageClosed() {
3946                 if (fOutlinePage != null) {
3947                         fOutlineSelectionChangedListener.uninstall(fOutlinePage);
3948                         fOutlinePage = null;
3949                         resetHighlightRange();
3950                 }
3951         }
3952
3953         /**
3954          * Synchronizes the outliner selection with the given element position in
3955          * the editor.
3956          * 
3957          * @param element
3958          *            the java element to select
3959          */
3960         protected void synchronizeOutlinePage(ISourceReference element) {
3961                 synchronizeOutlinePage(element, true);
3962         }
3963
3964         /**
3965          * Synchronizes the outliner selection with the given element position in
3966          * the editor.
3967          * 
3968          * @param element
3969          *            the java element to select
3970          * @param checkIfOutlinePageActive
3971          *            <code>true</code> if check for active outline page needs to
3972          *            be done
3973          */
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);
3981                 }
3982         }
3983
3984         /**
3985          * Synchronizes the outliner selection with the actual cursor position in
3986          * the editor.
3987          */
3988         public void synchronizeOutlinePageSelection() {
3989                 synchronizeOutlinePage(computeHighlightRangeSourceReference());
3990
3991                 // ISourceViewer sourceViewer = getSourceViewer();
3992                 // if (sourceViewer == null || fOutlinePage == null)
3993                 // return;
3994                 //
3995                 // StyledText styledText = sourceViewer.getTextWidget();
3996                 // if (styledText == null)
3997                 // return;
3998                 //
3999                 // int caret = 0;
4000                 // if (sourceViewer instanceof ITextViewerExtension3) {
4001                 // ITextViewerExtension3 extension = (ITextViewerExtension3)
4002                 // sourceViewer;
4003                 // caret =
4004                 // extension.widgetOffset2ModelOffset(styledText.getCaretOffset());
4005                 // } else {
4006                 // int offset = sourceViewer.getVisibleRegion().getOffset();
4007                 // caret = offset + styledText.getCaretOffset();
4008                 // }
4009                 //
4010                 // IJavaElement element = getElementAt(caret);
4011                 // if (element instanceof ISourceReference) {
4012                 // fOutlinePage.removeSelectionChangedListener(fSelectionChangedListener);
4013                 // fOutlinePage.select((ISourceReference) element);
4014                 // fOutlinePage.addSelectionChangedListener(fSelectionChangedListener);
4015                 // }
4016         }
4017
4018         protected void setSelection(ISourceReference reference, boolean moveCursor) {
4019
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();
4026                 }
4027
4028                 if (reference != null) {
4029
4030                         StyledText textWidget = null;
4031
4032                         ISourceViewer sourceViewer = getSourceViewer();
4033                         if (sourceViewer != null)
4034                                 textWidget = sourceViewer.getTextWidget();
4035
4036                         if (textWidget == null)
4037                                 return;
4038
4039                         try {
4040
4041                                 ISourceRange range = reference.getSourceRange();
4042                                 if (range == null)
4043                                         return;
4044
4045                                 int offset = range.getOffset();
4046                                 int length = range.getLength();
4047
4048                                 if (offset < 0 || length < 0)
4049                                         return;
4050
4051                                 textWidget.setRedraw(false);
4052
4053                                 setHighlightRange(offset, length, moveCursor);
4054
4055                                 if (!moveCursor)
4056                                         return;
4057
4058                                 offset = -1;
4059                                 length = -1;
4060
4061                                 if (reference instanceof IMember) {
4062                                         range = ((IMember) reference).getNameRange();
4063                                         if (range != null) {
4064                                                 offset = range.getOffset();
4065                                                 length = range.getLength();
4066                                         }
4067                                 }
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();
4076                                 // }
4077                                 // }
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();
4086                                 // }
4087                                 // }
4088                                 // }
4089
4090                                 if (offset > -1 && length > 0) {
4091                                         sourceViewer.revealRange(offset, length);
4092                                         sourceViewer.setSelectedRange(offset, length);
4093                                 }
4094
4095                         } catch (JavaModelException x) {
4096                         } catch (IllegalArgumentException x) {
4097                         } finally {
4098                                 if (textWidget != null)
4099                                         textWidget.setRedraw(true);
4100                         }
4101
4102                 } else if (moveCursor) {
4103                         resetHighlightRange();
4104                 }
4105
4106                 markInNavigationHistory();
4107         }
4108
4109         public void setSelection(IJavaElement element) {
4110                 if (element == null || element instanceof ICompilationUnit) { // ||
4111                         // element
4112                         // instanceof
4113                         // IClassFile)
4114                         // {
4115                         /*
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)
4120                          */
4121                         return;
4122                 }
4123
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);
4134                         }
4135                 }
4136         }
4137
4138         public synchronized void editingScriptStarted() {
4139                 ++fIgnoreOutlinePageSelection;
4140         }
4141
4142         public synchronized void editingScriptEnded() {
4143                 --fIgnoreOutlinePageSelection;
4144         }
4145
4146         public synchronized boolean isEditingScriptRunning() {
4147                 return (fIgnoreOutlinePageSelection > 0);
4148         }
4149
4150         /**
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.
4154          */
4155         public Object getAdapter(Class required) {
4156
4157                 if (IContentOutlinePage.class.equals(required)) {
4158                         if (fOutlinePage == null)
4159                                 fOutlinePage = createOutlinePage();
4160                         return fOutlinePage;
4161                 }
4162
4163                 if (IEncodingSupport.class.equals(required))
4164                         return fEncodingSupport;
4165
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 };
4171                                 }
4172
4173                         };
4174                 }
4175                 if (fProjectionSupport != null) {
4176                         Object adapter = fProjectionSupport.getAdapter(getSourceViewer(),
4177                                         required);
4178                         if (adapter != null)
4179                                 return adapter;
4180                 }
4181
4182                 return super.getAdapter(required);
4183         }
4184
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());
4191         // }
4192         // return fOutlinePage;
4193         // }
4194         //
4195         // if (IEncodingSupport.class.equals(required))
4196         // return fEncodingSupport;
4197         //
4198         // return super.getAdapter(required);
4199         // }
4200
4201         protected void doSelectionChanged(SelectionChangedEvent event) {
4202                 ISourceReference reference = null;
4203
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;
4210                                 break;
4211                         }
4212                 }
4213
4214                 if (!isActivePart() && PHPeclipsePlugin.getActivePage() != null)
4215                         PHPeclipsePlugin.getActivePage().bringToTop(this);
4216
4217                 try {
4218                         editingScriptStarted();
4219                         setSelection(reference, !isActivePart());
4220                 } finally {
4221                         editingScriptEnded();
4222                 }
4223         }
4224
4225         /*
4226          * @see AbstractTextEditor#adjustHighlightRange(int, int)
4227          */
4228         protected void adjustHighlightRange(int offset, int length) {
4229
4230                 try {
4231
4232                         IJavaElement element = getElementAt(offset);
4233                         while (element instanceof ISourceReference) {
4234                                 ISourceRange range = ((ISourceReference) element)
4235                                                 .getSourceRange();
4236                                 if (offset < range.getOffset() + range.getLength()
4237                                                 && range.getOffset() < offset + length) {
4238
4239                                         ISourceViewer viewer = getSourceViewer();
4240                                         if (viewer instanceof ITextViewerExtension5) {
4241                                                 ITextViewerExtension5 extension = (ITextViewerExtension5) viewer;
4242                                                 extension.exposeModelRange(new Region(
4243                                                                 range.getOffset(), range.getLength()));
4244                                         }
4245
4246                                         setHighlightRange(range.getOffset(), range.getLength(),
4247                                                         true);
4248                                         if (fOutlinePage != null) {
4249                                                 fOutlineSelectionChangedListener
4250                                                                 .uninstall(fOutlinePage);
4251                                                 fOutlinePage.select((ISourceReference) element);
4252                                                 fOutlineSelectionChangedListener.install(fOutlinePage);
4253                                         }
4254
4255                                         return;
4256                                 }
4257                                 element = element.getParent();
4258                         }
4259
4260                 } catch (JavaModelException x) {
4261                         PHPeclipsePlugin.log(x.getStatus());
4262                 }
4263
4264                 ISourceViewer viewer = getSourceViewer();
4265                 if (viewer instanceof ITextViewerExtension5) {
4266                         ITextViewerExtension5 extension = (ITextViewerExtension5) viewer;
4267                         extension.exposeModelRange(new Region(offset, length));
4268                 } else {
4269                         resetHighlightRange();
4270                 }
4271
4272         }
4273
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);
4279         }
4280
4281         // public void openContextHelp() {
4282         // IDocument doc =
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);
4289         // }
4290         //
4291         // private void openContextHelp(String word) {
4292         // open(word);
4293         // }
4294         //
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);
4300         // } else {
4301         // // showMessage(shell, dialogTitle, ActionMessages.getString("Open help
4302         // not available"), false); //$NON-NLS-1$
4303         // }
4304         // }
4305
4306         // private String getFunctionName(IDocument doc, int pos) {
4307         // Point word = PHPWordExtractor.findWord(doc, pos);
4308         // if (word != null) {
4309         // try {
4310         // return doc.get(word.x, word.y).replace('_', '-');
4311         // } catch (BadLocationException e) {
4312         // }
4313         // }
4314         // return "";
4315         // }
4316
4317         /*
4318          * @see AbstractTextEditor#handlePreferenceStoreChanged(PropertyChangeEvent)
4319          */
4320         protected void handlePreferenceStoreChanged(PropertyChangeEvent event) {
4321
4322                 try {
4323
4324                         ISourceViewer sourceViewer = getSourceViewer();
4325                         if (sourceViewer == null)
4326                                 return;
4327
4328                         String property = event.getProperty();
4329
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) {
4336                                         try {
4337                                                 sourceViewer.getTextWidget().setTabs(
4338                                                                 Integer.parseInt((String) value));
4339                                         } catch (NumberFormatException e) {
4340                                                 // bug #1038071 - set default tab:
4341                                                 sourceViewer.getTextWidget().setTabs(80);
4342                                         }
4343                                 }
4344                                 return;
4345                         }
4346
4347                         // if (OVERVIEW_RULER.equals(property)) {
4348                         // if (isOverviewRulerVisible())
4349                         // showOverviewRuler();
4350                         // else
4351                         // hideOverviewRuler();
4352                         // return;
4353                         // }
4354
4355                         // if (LINE_NUMBER_RULER.equals(property)) {
4356                         // if (isLineNumberRulerVisible())
4357                         // showLineNumberRuler();
4358                         // else
4359                         // hideLineNumberRuler();
4360                         // return;
4361                         // }
4362
4363                         // if (fLineNumberRulerColumn != null
4364                         // && (LINE_NUMBER_COLOR.equals(property) ||
4365                         // PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT.equals(property) ||
4366                         // PREFERENCE_COLOR_BACKGROUND.equals(property))) {
4367                         //
4368                         // initializeLineNumberRulerColumn(fLineNumberRulerColumn);
4369                         // }
4370
4371                         if (isJavaEditorHoverProperty(property))
4372                                 updateHoverBehavior();
4373
4374                         if (BROWSER_LIKE_LINKS.equals(property)) {
4375                                 if (isBrowserLikeLinks())
4376                                         enableBrowserLikeLinks();
4377                                 else
4378                                         disableBrowserLikeLinks();
4379                                 return;
4380                         }
4381
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());
4387                                 }
4388                                 return;
4389                         }
4390
4391                         boolean newBooleanValue = false;
4392                         Object newValue = event.getNewValue();
4393                         if (newValue != null)
4394                                 newBooleanValue = Boolean.valueOf(newValue.toString())
4395                                                 .booleanValue();
4396
4397                         if (PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE
4398                                         .equals(property)) {
4399                                 if (newBooleanValue)
4400                                         selectionChanged();
4401                                 return;
4402                         }
4403
4404                         if (PreferenceConstants.EDITOR_MARK_OCCURRENCES.equals(property)) {
4405                                 if (newBooleanValue != fMarkOccurrenceAnnotations) {
4406                                         fMarkOccurrenceAnnotations = newBooleanValue;
4407                                         if (!fMarkOccurrenceAnnotations)
4408                                                 uninstallOccurrencesFinder();
4409                                         else
4410                                                 installOccurrencesFinder();
4411                                 }
4412                                 return;
4413                         }
4414
4415                         if (PreferenceConstants.EDITOR_STICKY_OCCURRENCES.equals(property)) {
4416                                 fStickyOccurrenceAnnotations = newBooleanValue;
4417                                 return;
4418                         }
4419                         // }
4420                         // }
4421                         // if
4422                         // (PreferenceConstants.EDITOR_STICKY_OCCURRENCES.equals(property))
4423                         // {
4424                         // if (event.getNewValue() instanceof Boolean) {
4425                         // boolean stickyOccurrenceAnnotations=
4426                         // ((Boolean)event.getNewValue()).booleanValue();
4427                         // if (stickyOccurrenceAnnotations != fStickyOccurrenceAnnotations)
4428                         // {
4429
4430                         ((PHPSourceViewerConfiguration) getSourceViewerConfiguration())
4431                                         .handlePropertyChangeEvent(event);
4432
4433                         // if (affectsOverrideIndicatorAnnotations(event)) {
4434                         // if (isShowingOverrideIndicators()) {
4435                         // if (fOverrideIndicatorManager == null)
4436                         // installOverrideIndicator(true);
4437                         // } else {
4438                         // if (fOverrideIndicatorManager != null)
4439                         // uninstallOverrideIndicator();
4440                         // }
4441                         // return;
4442                         // }
4443
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);
4455                                         }
4456                                 }
4457                                 return;
4458                         }
4459                 } finally {
4460                         super.handlePreferenceStoreChanged(event);
4461                 }
4462         }
4463
4464         // /*
4465         // * @see
4466         // AbstractTextEditor#handlePreferenceStoreChanged(PropertyChangeEvent)
4467         // */
4468         // protected void handlePreferenceStoreChanged(PropertyChangeEvent event) {
4469         //
4470         // try {
4471         //
4472         // ISourceViewer sourceViewer = getSourceViewer();
4473         // if (sourceViewer == null)
4474         // return;
4475         //
4476         // String property = event.getProperty();
4477         //
4478         // // if
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)
4485         // value));
4486         // // }
4487         // // return;
4488         // // }
4489         //
4490         // if (IPreferenceConstants.LINE_NUMBER_RULER.equals(property)) {
4491         // if (isLineNumberRulerVisible())
4492         // showLineNumberRuler();
4493         // else
4494         // hideLineNumberRuler();
4495         // return;
4496         // }
4497         //
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))) {
4502         //
4503         // initializeLineNumberRulerColumn(fLineNumberRulerColumn);
4504         // }
4505         //
4506         // } finally {
4507         // super.handlePreferenceStoreChanged(event);
4508         // }
4509         // }
4510
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);
4520         // }
4521
4522         /**
4523          * Shows the line number ruler column.
4524          */
4525         // private void showLineNumberRuler() {
4526         // IVerticalRuler v = getVerticalRuler();
4527         // if (v instanceof CompositeRuler) {
4528         // CompositeRuler c = (CompositeRuler) v;
4529         // c.addDecorator(1, createLineNumberRulerColumn());
4530         // }
4531         // }
4532         private boolean isJavaEditorHoverProperty(String property) {
4533                 return PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS.equals(property);
4534         }
4535
4536         /**
4537          * Return whether the browser like links should be enabled according to the
4538          * preference store settings.
4539          * 
4540          * @return <code>true</code> if the browser like links should be enabled
4541          */
4542         private boolean isBrowserLikeLinks() {
4543                 IPreferenceStore store = getPreferenceStore();
4544                 return store.getBoolean(BROWSER_LIKE_LINKS);
4545         }
4546
4547         /**
4548          * Enables browser like links.
4549          */
4550         private void enableBrowserLikeLinks() {
4551                 if (fMouseListener == null) {
4552                         fMouseListener = new MouseClickListener();
4553                         fMouseListener.install();
4554                 }
4555         }
4556
4557         /**
4558          * Disables browser like links.
4559          */
4560         private void disableBrowserLikeLinks() {
4561                 if (fMouseListener != null) {
4562                         fMouseListener.uninstall();
4563                         fMouseListener = null;
4564                 }
4565         }
4566
4567         /**
4568          * Handles a property change event describing a change of the java core's
4569          * preferences and updates the preference related editor properties.
4570          * 
4571          * @param event
4572          *            the property change event
4573          */
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();
4583                 }
4584                 if (PreferenceConstants.EDITOR_WRAP_WORDS.equals(event.getProperty())) {
4585                         setWordWrap();
4586                 }
4587         }
4588
4589         /**
4590          * Return whether the line number ruler column should be visible according
4591          * to the preference store settings.
4592          * 
4593          * @return <code>true</code> if the line numbers should be visible
4594          */
4595         // protected boolean isLineNumberRulerVisible() {
4596         // IPreferenceStore store = getPreferenceStore();
4597         // return store.getBoolean(LINE_NUMBER_RULER);
4598         // }
4599         /**
4600          * Hides the line number ruler column.
4601          */
4602         // private void hideLineNumberRuler() {
4603         // IVerticalRuler v = getVerticalRuler();
4604         // if (v instanceof CompositeRuler) {
4605         // CompositeRuler c = (CompositeRuler) v;
4606         // try {
4607         // c.removeDecorator(1);
4608         // } catch (Throwable e) {
4609         // }
4610         // }
4611         // }
4612         /*
4613          * @see AbstractTextEditor#handleCursorPositionChanged()
4614          */
4615         // protected void handleCursorPositionChanged() {
4616         // super.handleCursorPositionChanged();
4617         // if (!isEditingScriptRunning() && fUpdater != null)
4618         // fUpdater.post();
4619         // }
4620         /*
4621          * @see org.eclipse.ui.texteditor.AbstractTextEditor#handleElementContentReplaced()
4622          */
4623         protected void handleElementContentReplaced() {
4624                 super.handleElementContentReplaced();
4625                 if (fProjectionModelUpdater != null)
4626                         fProjectionModelUpdater.initialize();
4627         }
4628
4629         /**
4630          * Initializes the given line number ruler column from the preference store.
4631          * 
4632          * @param rulerColumn
4633          *            the ruler column to be initialized
4634          */
4635         // protected void initializeLineNumberRulerColumn(LineNumberRulerColumn
4636         // rulerColumn) {
4637         // JavaTextTools textTools =
4638         // PHPeclipsePlugin.getDefault().getJavaTextTools();
4639         // IColorManager manager = textTools.getColorManager();
4640         //
4641         // IPreferenceStore store = getPreferenceStore();
4642         // if (store != null) {
4643         //
4644         // RGB rgb = 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);
4649         // else
4650         // rgb = PreferenceConverter.getColor(store, LINE_NUMBER_COLOR);
4651         // }
4652         // rulerColumn.setForeground(manager.getColor(rgb));
4653         //
4654         // rgb = null;
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);
4661         // else
4662         // rgb = PreferenceConverter.getColor(store, PREFERENCE_COLOR_BACKGROUND);
4663         // }
4664         // }
4665         // rulerColumn.setBackground(manager.getColor(rgb));
4666         // }
4667         // }
4668         /**
4669          * Creates a new line number ruler column that is appropriately initialized.
4670          */
4671         // protected IVerticalRulerColumn createLineNumberRulerColumn() {
4672         // fLineNumberRulerColumn = new LineNumberRulerColumn();
4673         // initializeLineNumberRulerColumn(fLineNumberRulerColumn);
4674         // return fLineNumberRulerColumn;
4675         // }
4676         /*
4677          * @see AbstractTextEditor#createVerticalRuler()
4678          */
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());
4684         // return ruler;
4685         // }
4686         // private static IRegion getSignedSelection(ITextViewer viewer) {
4687         //
4688         // StyledText text = viewer.getTextWidget();
4689         // int caretOffset = text.getCaretOffset();
4690         // Point selection = text.getSelection();
4691         //
4692         // // caret left
4693         // int offset, length;
4694         // if (caretOffset == selection.x) {
4695         // offset = selection.y;
4696         // length = selection.x - selection.y;
4697         //
4698         // // caret right
4699         // } else {
4700         // offset = selection.x;
4701         // length = selection.y - selection.x;
4702         // }
4703         //
4704         // return new Region(offset, length);
4705         // }
4706         protected IRegion getSignedSelection(ISourceViewer sourceViewer) {
4707                 StyledText text = sourceViewer.getTextWidget();
4708                 Point selection = text.getSelectionRange();
4709
4710                 if (text.getCaretOffset() == selection.x) {
4711                         selection.x = selection.x + selection.y;
4712                         selection.y = -selection.y;
4713                 }
4714
4715                 selection.x = widgetOffset2ModelOffset(sourceViewer, selection.x);
4716
4717                 return new Region(selection.x, selection.y);
4718         }
4719
4720         /** Preference key for matching brackets */
4721         protected final static String MATCHING_BRACKETS = PreferenceConstants.EDITOR_MATCHING_BRACKETS;
4722
4723         /** Preference key for matching brackets color */
4724         protected final static String MATCHING_BRACKETS_COLOR = PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR;
4725
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;
4755
4756         /** Preference key for task color */
4757         protected final static String TASK_INDICATION_COLOR = PreferenceConstants.EDITOR_TASK_INDICATION_COLOR;
4758
4759         /** Preference key for bookmark indication */
4760         protected final static String BOOKMARK_INDICATION = PreferenceConstants.EDITOR_BOOKMARK_INDICATION;
4761
4762         /** Preference key for bookmark color */
4763         protected final static String BOOKMARK_INDICATION_COLOR = PreferenceConstants.EDITOR_BOOKMARK_INDICATION_COLOR;
4764
4765         /** Preference key for search result indication */
4766         protected final static String SEARCH_RESULT_INDICATION = PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION;
4767
4768         /** Preference key for search result color */
4769         protected final static String SEARCH_RESULT_INDICATION_COLOR = PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_COLOR;
4770
4771         /** Preference key for unknown annotation indication */
4772         protected final static String UNKNOWN_INDICATION = PreferenceConstants.EDITOR_UNKNOWN_INDICATION;
4773
4774         /** Preference key for unknown annotation color */
4775         protected final static String UNKNOWN_INDICATION_COLOR = PreferenceConstants.EDITOR_UNKNOWN_INDICATION_COLOR;
4776
4777         /** Preference key for shwoing the overview ruler */
4778         protected final static String OVERVIEW_RULER = PreferenceConstants.EDITOR_OVERVIEW_RULER;
4779
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;
4782
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;
4785
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;
4788
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;
4791
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;
4794
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;
4797
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;
4803
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;
4806
4807         /**
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.
4811          * 
4812          * @since 2.1.1
4813          */
4814         private final static String BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK = PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK;
4815
4816         private final static char[] BRACKETS = { '{', '}', '(', ')', '[', ']' };
4817
4818         private static boolean isBracket(char character) {
4819                 for (int i = 0; i != BRACKETS.length; ++i)
4820                         if (character == BRACKETS[i])
4821                                 return true;
4822                 return false;
4823         }
4824
4825         private static boolean isSurroundedByBrackets(IDocument document, int offset) {
4826                 if (offset == 0 || offset == document.getLength())
4827                         return false;
4828
4829                 try {
4830                         return isBracket(document.getChar(offset - 1))
4831                                         && isBracket(document.getChar(offset));
4832
4833                 } catch (BadLocationException e) {
4834                         return false;
4835                 }
4836         }
4837
4838         // protected void configureSourceViewerDecorationSupport() {
4839         //
4840         // fSourceViewerDecorationSupport.setCharacterPairMatcher(fBracketMatcher);
4841         //
4842         // fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(
4843         // AnnotationType.UNKNOWN,
4844         // UNKNOWN_INDICATION_COLOR,
4845         // UNKNOWN_INDICATION,
4846         // UNKNOWN_INDICATION_IN_OVERVIEW_RULER,
4847         // 0);
4848         // fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(
4849         // AnnotationType.BOOKMARK,
4850         // BOOKMARK_INDICATION_COLOR,
4851         // BOOKMARK_INDICATION,
4852         // BOOKMARK_INDICATION_IN_OVERVIEW_RULER,
4853         // 1);
4854         // fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(
4855         // AnnotationType.TASK,
4856         // TASK_INDICATION_COLOR,
4857         // TASK_INDICATION,
4858         // TASK_INDICATION_IN_OVERVIEW_RULER,
4859         // 2);
4860         // fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(
4861         // AnnotationType.SEARCH,
4862         // SEARCH_RESULT_INDICATION_COLOR,
4863         // SEARCH_RESULT_INDICATION,
4864         // SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER,
4865         // 3);
4866         // fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(
4867         // AnnotationType.WARNING,
4868         // WARNING_INDICATION_COLOR,
4869         // WARNING_INDICATION,
4870         // WARNING_INDICATION_IN_OVERVIEW_RULER,
4871         // 4);
4872         // fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(
4873         // AnnotationType.ERROR,
4874         // ERROR_INDICATION_COLOR,
4875         // ERROR_INDICATION,
4876         // ERROR_INDICATION_IN_OVERVIEW_RULER,
4877         // 5);
4878         //
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);
4885         //
4886         // fSourceViewerDecorationSupport.setSymbolicFontName(getFontPropertyPreferenceKey());
4887         //
4888         // }
4889         /**
4890          * Returns the Java element wrapped by this editors input.
4891          * 
4892          * @return the Java element wrapped by this editors input.
4893          * @since 3.0
4894          */
4895         abstract protected IJavaElement getInputJavaElement();
4896
4897         protected void updateStatusLine() {
4898                 ITextSelection selection = (ITextSelection) getSelectionProvider()
4899                                 .getSelection();
4900                 Annotation annotation = getAnnotation(selection.getOffset(), selection
4901                                 .getLength());
4902                 setStatusLineErrorMessage(null);
4903                 setStatusLineMessage(null);
4904                 if (annotation != null) {
4905                         try {
4906                                 fIsUpdatingAnnotationViews = true;
4907                                 updateAnnotationViews(annotation);
4908                         } finally {
4909                                 fIsUpdatingAnnotationViews = false;
4910                         }
4911                         if (annotation instanceof IJavaAnnotation
4912                                         && ((IJavaAnnotation) annotation).isProblem())
4913                                 setStatusLineMessage(annotation.getText());
4914                 }
4915         }
4916
4917         /**
4918          * Jumps to the matching bracket.
4919          */
4920         public void gotoMatchingBracket() {
4921
4922                 ISourceViewer sourceViewer = getSourceViewer();
4923                 IDocument document = sourceViewer.getDocument();
4924                 if (document == null)
4925                         return;
4926
4927                 IRegion selection = getSignedSelection(sourceViewer);
4928
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();
4934                         return;
4935                 }
4936
4937                 // #26314
4938                 int sourceCaretOffset = selection.getOffset() + selection.getLength();
4939                 if (isSurroundedByBrackets(document, sourceCaretOffset))
4940                         sourceCaretOffset -= selection.getLength();
4941
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();
4947                         return;
4948                 }
4949
4950                 int offset = region.getOffset();
4951                 int length = region.getLength();
4952
4953                 if (length < 1)
4954                         return;
4955
4956                 int anchor = fBracketMatcher.getAnchor();
4957                 int targetOffset = (PHPPairMatcher.RIGHT == anchor) ? offset : offset
4958                                 + length - 1;
4959
4960                 boolean visible = false;
4961                 if (sourceViewer instanceof ITextViewerExtension5) {
4962                         ITextViewerExtension5 extension = (ITextViewerExtension5) sourceViewer;
4963                         visible = (extension.modelOffset2WidgetOffset(targetOffset) > -1);
4964                 } else {
4965                         IRegion visibleRegion = sourceViewer.getVisibleRegion();
4966                         visible = (targetOffset >= visibleRegion.getOffset() && targetOffset < visibleRegion
4967                                         .getOffset()
4968                                         + visibleRegion.getLength());
4969                 }
4970
4971                 if (!visible) {
4972                         setStatusLineErrorMessage(PHPEditorMessages
4973                                         .getString("GotoMatchingBracket.error.bracketOutsideSelectedElement")); //$NON-NLS-1$
4974                         sourceViewer.getTextWidget().getDisplay().beep();
4975                         return;
4976                 }
4977
4978                 if (selection.getLength() < 0)
4979                         targetOffset -= selection.getLength();
4980
4981                 sourceViewer.setSelectedRange(targetOffset, selection.getLength());
4982                 sourceViewer.revealRange(targetOffset, selection.getLength());
4983         }
4984
4985         /**
4986          * Ses the given message as error message to this editor's status line.
4987          * 
4988          * @param msg
4989          *            message to be set
4990          */
4991         protected void setStatusLineErrorMessage(String msg) {
4992                 IEditorStatusLine statusLine = (IEditorStatusLine) getAdapter(IEditorStatusLine.class);
4993                 if (statusLine != null)
4994                         statusLine.setMessage(true, msg, null);
4995         }
4996
4997         /**
4998          * Sets the given message as message to this editor's status line.
4999          * 
5000          * @param msg
5001          *            message to be set
5002          * @since 3.0
5003          */
5004         protected void setStatusLineMessage(String msg) {
5005                 IEditorStatusLine statusLine = (IEditorStatusLine) getAdapter(IEditorStatusLine.class);
5006                 if (statusLine != null)
5007                         statusLine.setMessage(false, msg, null);
5008         }
5009
5010         /**
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.
5014          * 
5015          * @param offset
5016          *            the region offset
5017          * @param length
5018          *            the region length
5019          * @param forward
5020          *            <code>true</code> for forwards, <code>false</code> for
5021          *            backward
5022          * @param annotationPosition
5023          *            the position of the found annotation
5024          * @return the found annotation
5025          */
5026         private Annotation getNextAnnotation(final int offset, final int length,
5027                         boolean forward, Position annotationPosition) {
5028
5029                 Annotation nextAnnotation = null;
5030                 Position nextAnnotationPosition = null;
5031                 Annotation containingAnnotation = null;
5032                 Position containingAnnotationPosition = null;
5033                 boolean currentAnnotation = false;
5034
5035                 IDocument document = getDocumentProvider()
5036                                 .getDocument(getEditorInput());
5037                 int endOfDocument = document.getLength();
5038                 int distance = Integer.MAX_VALUE;
5039
5040                 IAnnotationModel model = getDocumentProvider().getAnnotationModel(
5041                                 getEditorInput());
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))
5048                                 continue;
5049
5050                         Position p = model.getPosition(a);
5051                         if (p == null)
5052                                 continue;
5053
5054                         if (forward && p.offset == offset || !forward
5055                                         && p.offset + p.getLength() == offset + length) {// ||
5056                                 // p.includes(offset))
5057                                 // {
5058                                 if (containingAnnotation == null
5059                                                 || (forward
5060                                                                 && p.length >= containingAnnotationPosition.length || !forward
5061                                                                 && p.length >= containingAnnotationPosition.length)) {
5062                                         containingAnnotation = a;
5063                                         containingAnnotationPosition = p;
5064                                         currentAnnotation = p.length == length;
5065                                 }
5066                         } else {
5067                                 int currentDistance = 0;
5068
5069                                 if (forward) {
5070                                         currentDistance = p.getOffset() - offset;
5071                                         if (currentDistance < 0)
5072                                                 currentDistance = endOfDocument + currentDistance;
5073
5074                                         if (currentDistance < distance
5075                                                         || currentDistance == distance
5076                                                         && p.length < nextAnnotationPosition.length) {
5077                                                 distance = currentDistance;
5078                                                 nextAnnotation = a;
5079                                                 nextAnnotationPosition = p;
5080                                         }
5081                                 } else {
5082                                         currentDistance = offset + length
5083                                                         - (p.getOffset() + p.length);
5084                                         if (currentDistance < 0)
5085                                                 currentDistance = endOfDocument + currentDistance;
5086
5087                                         if (currentDistance < distance
5088                                                         || currentDistance == distance
5089                                                         && p.length < nextAnnotationPosition.length) {
5090                                                 distance = currentDistance;
5091                                                 nextAnnotation = a;
5092                                                 nextAnnotationPosition = p;
5093                                         }
5094                                 }
5095                         }
5096                 }
5097                 if (containingAnnotationPosition != null
5098                                 && (!currentAnnotation || nextAnnotation == null)) {
5099                         annotationPosition.setOffset(containingAnnotationPosition
5100                                         .getOffset());
5101                         annotationPosition.setLength(containingAnnotationPosition
5102                                         .getLength());
5103                         return containingAnnotation;
5104                 }
5105                 if (nextAnnotationPosition != null) {
5106                         annotationPosition.setOffset(nextAnnotationPosition.getOffset());
5107                         annotationPosition.setLength(nextAnnotationPosition.getLength());
5108                 }
5109
5110                 return nextAnnotation;
5111         }
5112
5113         /**
5114          * Returns the annotation overlapping with the given range or
5115          * <code>null</code>.
5116          * 
5117          * @param offset
5118          *            the region offset
5119          * @param length
5120          *            the region length
5121          * @return the found annotation or <code>null</code>
5122          * @since 3.0
5123          */
5124         private Annotation getAnnotation(int offset, int length) {
5125                 IAnnotationModel model = getDocumentProvider().getAnnotationModel(
5126                                 getEditorInput());
5127                 Iterator e = new JavaAnnotationIterator(model, true, true);
5128                 while (e.hasNext()) {
5129                         Annotation a = (Annotation) e.next();
5130                         if (!isNavigationTarget(a))
5131                                 continue;
5132
5133                         Position p = model.getPosition(a);
5134                         if (p != null && p.overlapsWith(offset, length))
5135                                 return a;
5136                 }
5137
5138                 return null;
5139         }
5140
5141         /**
5142          * Returns whether the given annotation is configured as a target for the
5143          * "Go to Next/Previous Annotation" actions
5144          * 
5145          * @param annotation
5146          *            the annotation
5147          * @return <code>true</code> if this is a target, <code>false</code>
5148          *         otherwise
5149          * @since 3.0
5150          */
5151         protected boolean isNavigationTarget(Annotation annotation) {
5152                 Preferences preferences = EditorsUI.getPluginPreferences();
5153                 AnnotationPreference preference = getAnnotationPreferenceLookup()
5154                                 .getAnnotationPreference(annotation);
5155                 // See bug 41689
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));
5161         }
5162
5163         /**
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.
5167          * 
5168          * @param document
5169          *            the document
5170          * @param lineOffset
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
5175          */
5176         public static int[] getBidiLineSegments(IDocument document, int lineOffset)
5177                         throws BadLocationException {
5178
5179                 IRegion line = document.getLineInformationOfOffset(lineOffset);
5180                 ITypedRegion[] linePartitioning = document.computePartitioning(
5181                                 lineOffset, line.getLength());
5182
5183                 List segmentation = new ArrayList();
5184                 for (int i = 0; i < linePartitioning.length; i++) {
5185                         if (IPHPPartitions.PHP_STRING_DQ.equals(linePartitioning[i]
5186                                         .getType())) {
5187                                 segmentation.add(linePartitioning[i]);
5188                         } else if (IPHPPartitions.PHP_STRING_HEREDOC
5189                                         .equals(linePartitioning[i].getType())) {
5190                                 segmentation.add(linePartitioning[i]);
5191                         }
5192                 }
5193
5194                 if (segmentation.size() == 0)
5195                         return null;
5196
5197                 int size = segmentation.size();
5198                 int[] segments = new int[size * 2 + 1];
5199
5200                 int j = 0;
5201                 for (int i = 0; i < size; i++) {
5202                         ITypedRegion segment = (ITypedRegion) segmentation.get(i);
5203
5204                         if (i == 0)
5205                                 segments[j++] = 0;
5206
5207                         int offset = segment.getOffset() - lineOffset;
5208                         if (offset > segments[j - 1])
5209                                 segments[j++] = offset;
5210
5211                         if (offset + segment.getLength() >= line.getLength())
5212                                 break;
5213
5214                         segments[j++] = offset + segment.getLength();
5215                 }
5216
5217                 if (j < segments.length) {
5218                         int[] result = new int[j];
5219                         System.arraycopy(segments, 0, result, 0, j);
5220                         segments = result;
5221                 }
5222
5223                 return segments;
5224         }
5225
5226         /**
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
5229          * line as segments.
5230          * 
5231          * @param lineOffset
5232          *            the offset of the line
5233          * @param line
5234          *            the content of the line
5235          * @return the line's bidi segmentation
5236          */
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)
5242                                 try {
5243                                         return getBidiLineSegments(document, lineOffset);
5244                                 } catch (BadLocationException x) {
5245                                         // ignore
5246                                 }
5247                 }
5248                 return null;
5249         }
5250
5251         /*
5252          * @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler,
5253          *      int)
5254          */
5255         // protected final ISourceViewer createSourceViewer(
5256         // Composite parent,
5257         // IVerticalRuler ruler,
5258         // int styles) {
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);
5264         // }
5265         // });
5266         // // JavaUIHelp.setHelp(this, text, IJavaHelpContextIds.JAVA_EDITOR);
5267         // return viewer;
5268         // }
5269         public final ISourceViewer getViewer() {
5270                 return getSourceViewer();
5271         }
5272
5273         // protected void showOverviewRuler() {
5274         // if (fOverviewRuler != null) {
5275         // if (getSourceViewer() instanceof ISourceViewerExtension) {
5276         // ((ISourceViewerExtension)
5277         // getSourceViewer()).showAnnotationsOverview(true);
5278         // fSourceViewerDecorationSupport.updateOverviewDecorations();
5279         // }
5280         // }
5281         // }
5282         //
5283         // protected void hideOverviewRuler() {
5284         // if (getSourceViewer() instanceof ISourceViewerExtension) {
5285         // fSourceViewerDecorationSupport.hideAnnotationOverview();
5286         // ((ISourceViewerExtension)
5287         // getSourceViewer()).showAnnotationsOverview(false);
5288         // }
5289         // }
5290
5291         // protected boolean isOverviewRulerVisible() {
5292         // IPreferenceStore store = getPreferenceStore();
5293         // return store.getBoolean(OVERVIEW_RULER);
5294         // }
5295         /*
5296          * @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler,
5297          *      int)
5298          */
5299         // protected ISourceViewer createJavaSourceViewer(
5300         // Composite parent,
5301         // IVerticalRuler ruler,
5302         // IOverviewRuler overviewRuler,
5303         // boolean isOverviewRulerVisible,
5304         // int styles) {
5305         // return new SourceViewer(parent, ruler, overviewRuler,
5306         // isOverviewRulerVisible(), styles);
5307         // }
5308         /*
5309          * @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler,
5310          *      int)
5311          */
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);
5317         }
5318
5319         /*
5320          * @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler,
5321          *      int)
5322          */
5323         protected final ISourceViewer createSourceViewer(Composite parent,
5324                         IVerticalRuler verticalRuler, int styles) {
5325
5326                 ISourceViewer viewer = createJavaSourceViewer(parent, verticalRuler,
5327                                 getOverviewRuler(), isOverviewRulerVisible(), styles,
5328                                 getPreferenceStore());
5329
5330                 StyledText text = viewer.getTextWidget();
5331                 text.addBidiSegmentListener(new BidiSegmentListener() {
5332                         public void lineGetSegments(BidiSegmentEvent event) {
5333                                 event.segments = getBidiLineSegments(event.lineOffset,
5334                                                 event.lineText);
5335                         }
5336                 });
5337
5338                 // JavaUIHelp.setHelp(this, text, IJavaHelpContextIds.JAVA_EDITOR);
5339
5340                 // ensure source viewer decoration support has been created and
5341                 // configured
5342                 getSourceViewerDecorationSupport(viewer);
5343
5344                 return viewer;
5345         }
5346
5347         /*
5348          * @see AbstractTextEditor#affectsTextPresentation(PropertyChangeEvent)
5349          */
5350         protected boolean affectsTextPresentation(PropertyChangeEvent event) {
5351                 return ((PHPSourceViewerConfiguration) getSourceViewerConfiguration())
5352                                 .affectsTextPresentation(event)
5353                                 || super.affectsTextPresentation(event);
5354         }
5355
5356         //
5357         // protected boolean affectsTextPresentation(PropertyChangeEvent event) {
5358         // JavaTextTools textTools =
5359         // PHPeclipsePlugin.getDefault().getJavaTextTools();
5360         // return textTools.affectsBehavior(event);
5361         // }
5362         /**
5363          * Creates and returns the preference store for this Java editor with the
5364          * given input.
5365          * 
5366          * @param input
5367          *            The editor input for which to create the preference store
5368          * @return the preference store for this editor
5369          * 
5370          * @since 3.0
5371          */
5372         private IPreferenceStore createCombinedPreferenceStore(IEditorInput input) {
5373                 List stores = new ArrayList(3);
5374
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() {
5380
5381                                                 public boolean isFiltered(PropertyChangeEvent event) {
5382                                                         IJavaElement inputJavaElement = getInputJavaElement();
5383                                                         IJavaProject javaProject = inputJavaElement != null ? inputJavaElement
5384                                                                         .getJavaProject()
5385                                                                         : null;
5386                                                         if (javaProject == null)
5387                                                                 return true;
5388
5389                                                         return !javaProject.getProject().equals(
5390                                                                         event.getSource());
5391                                                 }
5392
5393                                         }));
5394
5395                 stores.add(PHPeclipsePlugin.getDefault().getPreferenceStore());
5396                 stores.add(new PreferencesAdapter(JavaCore.getPlugin()
5397                                 .getPluginPreferences()));
5398                 stores.add(EditorsUI.getPreferenceStore());
5399
5400                 return new ChainedPreferenceStore((IPreferenceStore[]) stores
5401                                 .toArray(new IPreferenceStore[stores.size()]));
5402         }
5403
5404         /**
5405          * Jumps to the error next according to the given direction.
5406          */
5407         public void gotoError(boolean forward) {
5408
5409                 ISelectionProvider provider = getSelectionProvider();
5410
5411                 ITextSelection s = (ITextSelection) provider.getSelection();
5412                 Position errorPosition = new Position(0, 0);
5413                 IJavaAnnotation nextError = getNextError(s.getOffset(), forward,
5414                                 errorPosition);
5415
5416                 if (nextError != null) {
5417
5418                         IMarker marker = null;
5419                         if (nextError instanceof MarkerAnnotation)
5420                                 marker = ((MarkerAnnotation) nextError).getMarker();
5421                         else {
5422                                 Iterator e = nextError.getOverlaidIterator();
5423                                 if (e != null) {
5424                                         while (e.hasNext()) {
5425                                                 Object o = e.next();
5426                                                 if (o instanceof MarkerAnnotation) {
5427                                                         marker = ((MarkerAnnotation) o).getMarker();
5428                                                         break;
5429                                                 }
5430                                         }
5431                                 }
5432                         }
5433
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);
5441                                 }
5442                         }
5443
5444                         selectAndReveal(errorPosition.getOffset(), errorPosition
5445                                         .getLength());
5446                         // setStatusLineErrorMessage(nextError.getMessage());
5447
5448                 } else {
5449
5450                         setStatusLineErrorMessage(null);
5451
5452                 }
5453         }
5454
5455         private IJavaAnnotation getNextError(int offset, boolean forward,
5456                         Position errorPosition) {
5457
5458                 IJavaAnnotation nextError = null;
5459                 Position nextErrorPosition = null;
5460
5461                 IDocument document = getDocumentProvider()
5462                                 .getDocument(getEditorInput());
5463                 int endOfDocument = document.getLength();
5464                 int distance = 0;
5465
5466                 IAnnotationModel model = getDocumentProvider().getAnnotationModel(
5467                                 getEditorInput());
5468                 Iterator e = new JavaAnnotationIterator(model, false);
5469                 while (e.hasNext()) {
5470
5471                         IJavaAnnotation a = (IJavaAnnotation) e.next();
5472                         if (a.hasOverlay() || !a.isProblem())
5473                                 continue;
5474
5475                         Position p = model.getPosition((Annotation) a);
5476                         if (!p.includes(offset)) {
5477
5478                                 int currentDistance = 0;
5479
5480                                 if (forward) {
5481                                         currentDistance = p.getOffset() - offset;
5482                                         if (currentDistance < 0)
5483                                                 currentDistance = endOfDocument - offset
5484                                                                 + p.getOffset();
5485                                 } else {
5486                                         currentDistance = offset - p.getOffset();
5487                                         if (currentDistance < 0)
5488                                                 currentDistance = offset + endOfDocument
5489                                                                 - p.getOffset();
5490                                 }
5491
5492                                 if (nextError == null || currentDistance < distance) {
5493                                         distance = currentDistance;
5494                                         nextError = a;
5495                                         nextErrorPosition = p;
5496                                 }
5497                         }
5498                 }
5499
5500                 if (nextErrorPosition != null) {
5501                         errorPosition.setOffset(nextErrorPosition.getOffset());
5502                         errorPosition.setLength(nextErrorPosition.getLength());
5503                 }
5504
5505                 return nextError;
5506         }
5507
5508         protected void uninstallOverrideIndicator() {
5509                 // if (fOverrideIndicatorManager != null) {
5510                 // fOverrideIndicatorManager.removeAnnotations();
5511                 // fOverrideIndicatorManager= null;
5512                 // }
5513         }
5514
5515         protected void installOverrideIndicator(boolean waitForReconcilation) {
5516                 uninstallOverrideIndicator();
5517                 IAnnotationModel model = getDocumentProvider().getAnnotationModel(
5518                                 getEditorInput());
5519                 final IJavaElement inputElement = getInputJavaElement();
5520
5521                 if (model == null || inputElement == null)
5522                         return;
5523
5524                 // fOverrideIndicatorManager= new OverrideIndicatorManager(model,
5525                 // inputElement, null);
5526                 //
5527                 // if (provideAST) {
5528                 // Job job= new
5529                 // Job(JavaEditorMessages.getString("OverrideIndicatorManager.intallJob"))
5530                 // {
5531                 // //$NON-NLS-1$
5532                 // /*
5533                 // * @see
5534                 // org.eclipse.core.runtime.jobs.Job#run(org.eclipse.core.runtime.IProgressMonitor)
5535                 // * @since 3.0
5536                 // */
5537                 // protected IStatus run(IProgressMonitor monitor) {
5538                 // CompilationUnit ast=
5539                 // JavaPlugin.getDefault().getASTProvider().getAST(inputElement, true,
5540                 // null);
5541                 // if (fOverrideIndicatorManager != null) // editor might have been
5542                 // closed
5543                 // in the meanwhile
5544                 // fOverrideIndicatorManager.reconciled(ast, true, monitor);
5545                 // return Status.OK_STATUS;
5546                 // }
5547                 // };
5548                 // job.setPriority(Job.DECORATE);
5549                 // job.setSystem(true);
5550                 // job.schedule();
5551                 // }
5552         }
5553
5554         /**
5555          * Tells whether override indicators are shown.
5556          * 
5557          * @return <code>true</code> if the override indicators are shown
5558          * @since 3.0
5559          */
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());
5568         // }
5569         /**
5570          * Returns the boolean preference for the given key.
5571          * 
5572          * @param store
5573          *            the preference store
5574          * @param key
5575          *            the preference key
5576          * @return <code>true</code> if the key exists in the store and its value
5577          *         is <code>true</code>
5578          * @since 3.0
5579          */
5580         private boolean getBoolean(IPreferenceStore store, String key) {
5581                 return key != null && store.getBoolean(key);
5582         }
5583
5584         protected boolean isPrefQuickDiffAlwaysOn() {
5585                 return false; // never show change ruler for the non-editable java
5586                                                 // editor.
5587                 // Overridden in subclasses like PHPUnitEditor
5588         }
5589
5590         /*
5591          * @see org.eclipse.ui.texteditor.AbstractTextEditor#createNavigationActions()
5592          */
5593         protected void createNavigationActions() {
5594                 super.createNavigationActions();
5595
5596                 final StyledText textWidget = getSourceViewer().getTextWidget();
5597
5598                 IAction action = new SmartLineStartAction(textWidget, false);
5599                 action.setActionDefinitionId(ITextEditorActionDefinitionIds.LINE_START);
5600                 setAction(ITextEditorActionDefinitionIds.LINE_START, action);
5601
5602                 action = new SmartLineStartAction(textWidget, true);
5603                 action
5604                                 .setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_LINE_START);
5605                 setAction(ITextEditorActionDefinitionIds.SELECT_LINE_START, action);
5606
5607                 action = new NavigatePreviousSubWordAction();
5608                 action
5609                                 .setActionDefinitionId(ITextEditorActionDefinitionIds.WORD_PREVIOUS);
5610                 setAction(ITextEditorActionDefinitionIds.WORD_PREVIOUS, action);
5611                 textWidget.setKeyBinding(SWT.CTRL | SWT.ARROW_LEFT, SWT.NULL);
5612
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);
5617
5618                 action = new SelectPreviousSubWordAction();
5619                 action
5620                                 .setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_WORD_PREVIOUS);
5621                 setAction(ITextEditorActionDefinitionIds.SELECT_WORD_PREVIOUS, action);
5622                 textWidget.setKeyBinding(SWT.CTRL | SWT.SHIFT | SWT.ARROW_LEFT,
5623                                 SWT.NULL);
5624
5625                 action = new SelectNextSubWordAction();
5626                 action
5627                                 .setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_WORD_NEXT);
5628                 setAction(ITextEditorActionDefinitionIds.SELECT_WORD_NEXT, action);
5629                 textWidget.setKeyBinding(SWT.CTRL | SWT.SHIFT | SWT.ARROW_RIGHT,
5630                                 SWT.NULL);
5631         }
5632
5633         /*
5634          * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#createCompositeRuler()
5635          */
5636         // protected CompositeRuler createCompositeRuler() {
5637         // if
5638         // (!getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_ANNOTATION_ROLL_OVER))
5639         // return super.createCompositeRuler();
5640         //
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() {
5646         //
5647         // public void doubleClick(DoubleClickEvent event) {
5648         // // for now: just invoke ruler double click action
5649         // triggerAction(ITextEditorActionConstants.RULER_DOUBLE_CLICK);
5650         // }
5651         //
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);
5660         // }
5661         // if (action.isEnabled())
5662         // action.run();
5663         // }
5664         // }
5665         //
5666         // }));
5667         // ruler.addDecorator(0, column);
5668         //
5669         // if (isLineNumberRulerVisible())
5670         // ruler.addDecorator(1, createLineNumberRulerColumn());
5671         // else if (isPrefQuickDiffAlwaysOn())
5672         // ruler.addDecorator(1, createChangeRulerColumn());
5673         //
5674         // return ruler;
5675         // }
5676         /*
5677          * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#createAnnotationRulerColumn(org.eclipse.jface.text.source.CompositeRuler)
5678          * @since 3.2
5679          */
5680         protected IVerticalRulerColumn createAnnotationRulerColumn(
5681                         CompositeRuler ruler) {
5682                 if (!getPreferenceStore().getBoolean(
5683                                 PreferenceConstants.EDITOR_ANNOTATION_ROLL_OVER))
5684                         return super.createAnnotationRulerColumn(ruler);
5685
5686                 AnnotationRulerColumn column = new AnnotationRulerColumn(
5687                                 VERTICAL_RULER_WIDTH, getAnnotationAccess());
5688                 column.setHover(new JavaExpandHover(ruler, getAnnotationAccess(),
5689                                 new IDoubleClickListener() {
5690
5691                                         public void doubleClick(DoubleClickEvent event) {
5692                                                 // for now: just invoke ruler double click action
5693                                                 triggerAction(ITextEditorActionConstants.RULER_DOUBLE_CLICK);
5694                                         }
5695
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(
5704                                                                                 null, null);
5705                                                         }
5706                                                         if (action.isEnabled())
5707                                                                 action.run();
5708                                                 }
5709                                         }
5710
5711                                 }));
5712
5713                 return column;
5714         }
5715
5716         /**
5717          * Returns the folding action group, or <code>null</code> if there is
5718          * none.
5719          * 
5720          * @return the folding action group, or <code>null</code> if there is none
5721          * @since 3.0
5722          */
5723         protected FoldingActionGroup getFoldingActionGroup() {
5724                 return fFoldingGroup;
5725         }
5726
5727         /*
5728          * @see org.eclipse.ui.texteditor.AbstractTextEditor#performRevert()
5729          */
5730         protected void performRevert() {
5731                 ProjectionViewer projectionViewer = (ProjectionViewer) getSourceViewer();
5732                 projectionViewer.setRedraw(false);
5733                 try {
5734
5735                         boolean projectionMode = projectionViewer.isProjectionMode();
5736                         if (projectionMode) {
5737                                 projectionViewer.disableProjection();
5738                                 if (fProjectionModelUpdater != null)
5739                                         fProjectionModelUpdater.uninstall();
5740                         }
5741
5742                         super.performRevert();
5743
5744                         if (projectionMode) {
5745                                 if (fProjectionModelUpdater != null)
5746                                         fProjectionModelUpdater.install(this, projectionViewer);
5747                                 projectionViewer.enableProjection();
5748                         }
5749
5750                 } finally {
5751                         projectionViewer.setRedraw(true);
5752                 }
5753         }
5754
5755         /**
5756          * React to changed selection.
5757          * 
5758          * @since 3.0
5759          */
5760         protected void selectionChanged() {
5761                 if (getSelectionProvider() == null)
5762                         return;
5763                 ISourceReference element = computeHighlightRangeSourceReference();
5764                 if (getPreferenceStore().getBoolean(
5765                                 PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE))
5766                         synchronizeOutlinePage(element);
5767                 setSelection(element, false);
5768                 updateStatusLine();
5769         }
5770
5771         private boolean isJavaOutlinePageActive() {
5772                 IWorkbenchPart part = getActivePart();
5773                 return part instanceof ContentOutline
5774                                 && ((ContentOutline) part).getCurrentPage() == fOutlinePage;
5775         }
5776
5777         private IWorkbenchPart getActivePart() {
5778                 IWorkbenchWindow window = getSite().getWorkbenchWindow();
5779                 IPartService service = window.getPartService();
5780                 IWorkbenchPart part = service.getActivePart();
5781                 return part;
5782         }
5783
5784         /**
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
5787          * indication.
5788          * 
5789          * @return the computed source reference
5790          * @since 3.0
5791          */
5792         protected ISourceReference computeHighlightRangeSourceReference() {
5793                 ISourceViewer sourceViewer = getSourceViewer();
5794                 if (sourceViewer == null)
5795                         return null;
5796
5797                 StyledText styledText = sourceViewer.getTextWidget();
5798                 if (styledText == null)
5799                         return null;
5800
5801                 int caret = 0;
5802                 if (sourceViewer instanceof ITextViewerExtension5) {
5803                         ITextViewerExtension5 extension = (ITextViewerExtension5) sourceViewer;
5804                         caret = extension.widgetOffset2ModelOffset(styledText
5805                                         .getCaretOffset());
5806                 } else {
5807                         int offset = sourceViewer.getVisibleRegion().getOffset();
5808                         caret = offset + styledText.getCaretOffset();
5809                 }
5810
5811                 IJavaElement element = getElementAt(caret, false);
5812
5813                 if (!(element instanceof ISourceReference))
5814                         return null;
5815
5816                 if (element.getElementType() == IJavaElement.IMPORT_DECLARATION) {
5817
5818                         IImportDeclaration declaration = (IImportDeclaration) element;
5819                         IImportContainer container = (IImportContainer) declaration
5820                                         .getParent();
5821                         ISourceRange srcRange = null;
5822
5823                         try {
5824                                 srcRange = container.getSourceRange();
5825                         } catch (JavaModelException e) {
5826                         }
5827
5828                         if (srcRange != null && srcRange.getOffset() == caret)
5829                                 return container;
5830                 }
5831
5832                 return (ISourceReference) element;
5833         }
5834
5835         /**
5836          * Returns the most narrow java element including the given offset.
5837          * 
5838          * @param offset
5839          *            the offset inside of the requested element
5840          * @param reconcile
5841          *            <code>true</code> if editor input should be reconciled in
5842          *            advance
5843          * @return the most narrow java element
5844          * @since 3.0
5845          */
5846         protected IJavaElement getElementAt(int offset, boolean reconcile) {
5847                 return getElementAt(offset);
5848         }
5849
5850         public ShowInContext getShowInContext() {
5851                 FileEditorInput fei = (FileEditorInput) getEditorInput();
5852                 ShowInContext context = BrowserUtil.getShowInContext(fei.getFile(),
5853                                 false, "");
5854                 if (context != null) {
5855                         return context;
5856                 }
5857                 return new ShowInContext(fei.getFile(), null);
5858         }
5859
5860         public String[] getShowInTargetIds() {
5861                 return new String[] { BrowserView.ID_BROWSER };
5862         }
5863
5864         /**
5865          * Updates the occurrences annotations based on the current selection.
5866          * 
5867          * @param selection
5868          *            the text selection
5869          * @param astRoot
5870          *            the compilation unit AST
5871          * @since 3.0
5872          */
5873         protected void updateOccurrenceAnnotations(ITextSelection selection) {// ,
5874                 // CompilationUnit
5875                 // astRoot)
5876                 // {
5877
5878                 if (fOccurrencesFinderJob != null)
5879                         fOccurrencesFinderJob.cancel();
5880
5881                 if (!fMarkOccurrenceAnnotations)
5882                         return;
5883
5884                 // if (astRoot == null || selection == null)
5885                 if (selection == null)
5886                         return;
5887
5888                 IDocument document = getSourceViewer().getDocument();
5889                 if (document == null)
5890                         return;
5891
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())
5902                                         return;
5903                         }
5904                         fMarkOccurrenceTargetRegion = JavaWordFinder.findWord(document,
5905                                         offset);
5906                         fMarkOccurrenceModificationStamp = currentModificationStamp;
5907                 }
5908
5909                 if (fMarkOccurrenceTargetRegion == null
5910                                 || fMarkOccurrenceTargetRegion.getLength() == 0) {
5911                         return;
5912                 }
5913
5914                 List matches = null;
5915
5916                 if (matches == null) {
5917                         try {
5918                                 matches = new ArrayList();
5919
5920                                 Scanner fScanner = new Scanner();
5921                                 fScanner.setSource(document.get().toCharArray());
5922                                 fScanner.setPHPMode(false);
5923                                 String wordStr;
5924                                 char[] word;
5925
5926                                 wordStr = document.get(fMarkOccurrenceTargetRegion.getOffset(),
5927                                                 fMarkOccurrenceTargetRegion.getLength());
5928                                 if (wordStr != null) {
5929                                         word = wordStr.toCharArray();
5930                                         int fToken = ITerminalSymbols.TokenNameEOF;
5931                                         try {
5932                                                 fToken = fScanner.getNextToken();
5933                                                 while (fToken != ITerminalSymbols.TokenNameEOF) { // &&
5934                                                                                                                                                         // fToken
5935                                                                                                                                                         // !=
5936                                                         // TokenNameERROR) {
5937                                                         if (fToken == ITerminalSymbols.TokenNameVariable
5938                                                                         || fToken == ITerminalSymbols.TokenNameIdentifier) {
5939                                                                 // global variable
5940                                                                 if (fScanner.equalsCurrentTokenSource(word)) {
5941                                                                         matches
5942                                                                                         .add(new Region(
5943                                                                                                         fScanner
5944                                                                                                                         .getCurrentTokenStartPosition(),
5945                                                                                                         fScanner
5946                                                                                                                         .getCurrentTokenEndPosition()
5947                                                                                                                         - fScanner
5948                                                                                                                                         .getCurrentTokenStartPosition()
5949                                                                                                                         + 1));
5950                                                                 }
5951                                                         }
5952                                                         fToken = fScanner.getNextToken();
5953                                                 }
5954                                         } catch (InvalidInputException e) {
5955                                                 // ignore errors
5956                                         } catch (SyntaxError e) {
5957                                                 // ignore errors
5958                                         }
5959                                 }
5960                         } catch (BadLocationException e1) {
5961                                 // ignore errors
5962                         } catch (Exception e) {
5963                                 e.printStackTrace();
5964                                 // ignore errors
5965                         }
5966
5967                 }
5968
5969                 if (matches == null || matches.size() == 0) {
5970                         if (!fStickyOccurrenceAnnotations)
5971                                 removeOccurrenceAnnotations();
5972                         return;
5973                 }
5974
5975                 Position[] positions = new Position[matches.size()];
5976                 int i = 0;
5977                 for (Iterator each = matches.iterator(); each.hasNext();) {
5978                         IRegion currentNode = (IRegion) each.next();
5979                         positions[i++] = new Position(currentNode.getOffset(), currentNode
5980                                         .getLength());
5981                 }
5982
5983                 fOccurrencesFinderJob = new OccurrencesFinderJob(document, positions,
5984                                 selection);
5985                 // fOccurrencesFinderJob.setPriority(Job.DECORATE);
5986                 // fOccurrencesFinderJob.setSystem(true);
5987                 // fOccurrencesFinderJob.schedule();
5988                 fOccurrencesFinderJob.run(new NullProgressMonitor());
5989         }
5990
5991         protected void installOccurrencesFinder() {
5992                 fMarkOccurrenceAnnotations = true;
5993
5994                 fPostSelectionListenerWithAST = new ISelectionListenerWithAST() {
5995                         public void selectionChanged(IEditorPart part,
5996                                         ITextSelection selection) { // ,
5997                                 // CompilationUnit
5998                                 // astRoot)
5999                                 // {
6000                                 updateOccurrenceAnnotations(selection);// , astRoot);
6001                         }
6002                 };
6003                 SelectionListenerWithASTManager.getDefault().addListener(this,
6004                                 fPostSelectionListenerWithAST);
6005                 if (getSelectionProvider() != null) {
6006                         fForcedMarkOccurrencesSelection = getSelectionProvider()
6007                                         .getSelection();
6008                         SelectionListenerWithASTManager.getDefault().forceSelectionChange(
6009                                         this, (ITextSelection) fForcedMarkOccurrencesSelection);
6010                 }
6011
6012                 if (fOccurrencesFinderJobCanceler == null) {
6013                         fOccurrencesFinderJobCanceler = new OccurrencesFinderJobCanceler();
6014                         fOccurrencesFinderJobCanceler.install();
6015                 }
6016         }
6017
6018         protected void uninstallOccurrencesFinder() {
6019                 fMarkOccurrenceAnnotations = false;
6020
6021                 if (fOccurrencesFinderJob != null) {
6022                         fOccurrencesFinderJob.cancel();
6023                         fOccurrencesFinderJob = null;
6024                 }
6025
6026                 if (fOccurrencesFinderJobCanceler != null) {
6027                         fOccurrencesFinderJobCanceler.uninstall();
6028                         fOccurrencesFinderJobCanceler = null;
6029                 }
6030
6031                 if (fPostSelectionListenerWithAST != null) {
6032                         SelectionListenerWithASTManager.getDefault().removeListener(this,
6033                                         fPostSelectionListenerWithAST);
6034                         fPostSelectionListenerWithAST = null;
6035                 }
6036
6037                 removeOccurrenceAnnotations();
6038         }
6039
6040         protected boolean isMarkingOccurrences() {
6041                 return fMarkOccurrenceAnnotations;
6042         }
6043
6044         void removeOccurrenceAnnotations() {
6045                 fMarkOccurrenceModificationStamp = IDocumentExtension4.UNKNOWN_MODIFICATION_STAMP;
6046                 fMarkOccurrenceTargetRegion = null;
6047
6048                 IDocumentProvider documentProvider = getDocumentProvider();
6049                 if (documentProvider == null)
6050                         return;
6051
6052                 IAnnotationModel annotationModel = documentProvider
6053                                 .getAnnotationModel(getEditorInput());
6054                 if (annotationModel == null || fOccurrenceAnnotations == null)
6055                         return;
6056
6057                 synchronized (getLockObject(annotationModel)) {
6058                         if (annotationModel instanceof IAnnotationModelExtension) {
6059                                 ((IAnnotationModelExtension) annotationModel)
6060                                                 .replaceAnnotations(fOccurrenceAnnotations, null);
6061                         } else {
6062                                 for (int i = 0, length = fOccurrenceAnnotations.length; i < length; i++)
6063                                         annotationModel.removeAnnotation(fOccurrenceAnnotations[i]);
6064                         }
6065                         fOccurrenceAnnotations = null;
6066                 }
6067         }
6068 }