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