75709ed4f368f9c69b3c026474192dd03f147d37
[phpeclipse.git] / net.sourceforge.phpeclipse / src / net / sourceforge / phpeclipse / PHPeclipsePlugin.java
1 /**********************************************************************
2  Copyright (c) 2000, 2002 IBM Corp. and others.
3  All rights reserved. This program and the accompanying materials
4  are made available under the terms of the Common Public License v1.0
5  which accompanies this distribution, and is available at
6  http://www.eclipse.org/legal/cpl-v10.html
7
8  Contributors:
9  IBM Corporation - Initial implementation
10  Klaus Hartlage - www.eclipseproject.de
11  **********************************************************************/
12 package net.sourceforge.phpeclipse;
13
14 import java.io.File;
15 import java.util.ArrayList;
16 import java.util.Collection;
17 import java.util.HashMap;
18 import java.util.HashSet;
19 import java.util.Iterator;
20 import java.util.List;
21 import java.util.Set;
22
23 import net.sourceforge.phpdt.core.IBuffer;
24 import net.sourceforge.phpdt.core.IBufferFactory;
25 import net.sourceforge.phpdt.core.ICompilationUnit;
26 import net.sourceforge.phpdt.core.IJavaElement;
27 import net.sourceforge.phpdt.core.JavaCore;
28 import net.sourceforge.phpdt.core.WorkingCopyOwner;
29 import net.sourceforge.phpdt.externaltools.internal.model.ColorManager;
30 import net.sourceforge.phpdt.externaltools.internal.model.ExternalToolsPlugin;
31 import net.sourceforge.phpdt.externaltools.internal.model.VariableContextManager;
32 import net.sourceforge.phpdt.internal.core.BatchOperation;
33 import net.sourceforge.phpdt.internal.core.JavaModelManager;
34 import net.sourceforge.phpdt.internal.core.util.Util;
35 import net.sourceforge.phpdt.internal.ui.IJavaStatusConstants;
36 import net.sourceforge.phpdt.internal.ui.JavaElementAdapterFactory;
37 import net.sourceforge.phpdt.internal.ui.ResourceAdapterFactory;
38 import net.sourceforge.phpdt.internal.ui.preferences.MembersOrderPreferenceCache;
39 import net.sourceforge.phpdt.internal.ui.preferences.MockupPreferenceStore;
40 import net.sourceforge.phpdt.internal.ui.preferences.TemplatePreferencePage;
41 import net.sourceforge.phpdt.internal.ui.text.PreferencesAdapter;
42 import net.sourceforge.phpdt.internal.ui.text.folding.JavaFoldingStructureProviderRegistry;
43 import net.sourceforge.phpdt.internal.ui.text.java.hover.JavaEditorTextHoverDescriptor;
44 import net.sourceforge.phpdt.internal.ui.viewsupport.ImageDescriptorRegistry;
45 import net.sourceforge.phpdt.internal.ui.viewsupport.ProblemMarkerManager;
46 import net.sourceforge.phpdt.ui.IContextMenuConstants;
47 import net.sourceforge.phpdt.ui.IWorkingCopyManager;
48 import net.sourceforge.phpdt.ui.PreferenceConstants;
49 import net.sourceforge.phpdt.ui.text.JavaTextTools;
50 import net.sourceforge.phpeclipse.builder.ExternalEditorInput;
51 import net.sourceforge.phpeclipse.builder.ExternalStorageDocumentProvider;
52 import net.sourceforge.phpeclipse.builder.FileStorage;
53 import net.sourceforge.phpeclipse.builder.IdentifierIndexManager;
54 import net.sourceforge.phpeclipse.phpeditor.CustomBufferFactory;
55 import net.sourceforge.phpeclipse.phpeditor.DocumentAdapter;
56 import net.sourceforge.phpeclipse.phpeditor.PHPDocumentProvider;
57 import net.sourceforge.phpeclipse.phpeditor.PHPSyntaxRdr;
58 import net.sourceforge.phpeclipse.phpeditor.WorkingCopyManager;
59 import net.sourceforge.phpeclipse.phpeditor.util.PHPColorProvider;
60
61 import org.eclipse.core.internal.runtime.InternalPlatform;
62 import org.eclipse.core.resources.IFile;
63 import org.eclipse.core.resources.IProject;
64 import org.eclipse.core.resources.IResource;
65 import org.eclipse.core.resources.IResourceChangeEvent;
66 import org.eclipse.core.resources.ISavedState;
67 import org.eclipse.core.resources.IWorkspace;
68 import org.eclipse.core.resources.IWorkspaceRunnable;
69 import org.eclipse.core.resources.ResourcesPlugin;
70 import org.eclipse.core.runtime.CoreException;
71 import org.eclipse.core.runtime.IAdapterManager;
72 import org.eclipse.core.runtime.IConfigurationElement;
73 import org.eclipse.core.runtime.IPath;
74 import org.eclipse.core.runtime.IPluginDescriptor;
75 import org.eclipse.core.runtime.IProgressMonitor;
76 import org.eclipse.core.runtime.IStatus;
77 import org.eclipse.core.runtime.Path;
78 import org.eclipse.core.runtime.Platform;
79 import org.eclipse.core.runtime.Status;
80 import org.eclipse.core.runtime.jobs.ISchedulingRule;
81 import org.eclipse.core.runtime.jobs.Job;
82 import org.eclipse.jface.action.GroupMarker;
83 import org.eclipse.jface.action.IMenuManager;
84 import org.eclipse.jface.action.Separator;
85 import org.eclipse.jface.preference.IPreferenceStore;
86 import org.eclipse.jface.preference.PreferenceConverter;
87 import org.eclipse.jface.resource.JFaceResources;
88 import org.eclipse.jface.text.BadLocationException;
89 import org.eclipse.jface.text.IDocument;
90 import org.eclipse.jface.util.IPropertyChangeListener;
91 import org.eclipse.jface.util.PropertyChangeEvent;
92 import org.eclipse.swt.graphics.RGB;
93 import org.eclipse.swt.widgets.Display;
94 import org.eclipse.swt.widgets.Shell;
95 import org.eclipse.ui.IEditorDescriptor;
96 import org.eclipse.ui.IEditorInput;
97 import org.eclipse.ui.IEditorPart;
98 import org.eclipse.ui.IEditorRegistry;
99 import org.eclipse.ui.IWorkbench;
100 import org.eclipse.ui.IWorkbenchPage;
101 import org.eclipse.ui.IWorkbenchWindow;
102 import org.eclipse.ui.PlatformUI;
103 import org.eclipse.ui.editors.text.EditorsUI;
104 import org.eclipse.ui.ide.IDE;
105 import org.eclipse.ui.plugin.AbstractUIPlugin;
106 import org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants;
107 import org.eclipse.ui.texteditor.ChainedPreferenceStore;
108 import org.eclipse.ui.texteditor.ConfigurationElementSorter;
109 import org.eclipse.ui.texteditor.IDocumentProvider;
110 import org.eclipse.ui.texteditor.ITextEditor;
111 import org.eclipse.ui.texteditor.MarkerAnnotationPreferences;
112 import org.osgi.framework.BundleContext;
113
114 /**
115  * The main plugin class to be used in the desktop.
116  */
117 public class PHPeclipsePlugin extends AbstractUIPlugin implements
118     IPreferenceConstants {
119   /**
120    * The id of the PHP plugin (value <code>"net.sourceforge.phpeclipse"</code>).
121    */
122   public static final String PLUGIN_ID = "net.sourceforge.phpeclipse"; //$NON-NLS-1$
123
124   /**
125    * id of builder - matches plugin.xml (concatenate pluginid.builderid)
126    */
127   public static final String BUILDER_PARSER_ID = PLUGIN_ID + ".parserbuilder";
128
129   //public static final String BUILDER_INDEX_ID = PLUGIN_ID + ".indexbuilder";
130   /** General debug flag */
131   public static final boolean DEBUG = false;
132
133   /**
134    * The maximum number of allowed proposals by category
135    */
136   public final static int MAX_PROPOSALS = 200;
137
138   private static ExternalToolsPlugin externalTools;
139
140   /**
141    * The Java virtual machine that we are running on.
142    */
143   private static int jvm;
144
145   /** MRJ 2.0 */
146   private static final int MRJ_2_0 = 0;
147
148   /** MRJ 2.1 or later */
149   private static final int MRJ_2_1 = 1;
150
151   /** Java on Mac OS X 10.0 (MRJ 3.0) */
152   private static final int MRJ_3_0 = 3;
153
154   /** MRJ 3.1 */
155   private static final int MRJ_3_1 = 4;
156
157   /** JVM constant for any other platform */
158   private static final int OTHER = -1;
159
160   // public static final String PHP_RESOURCES_VIEW_ID = PLUGIN_ID +
161   // ".resourcesview.ViewPHPResources"; //$NON-NLS-1$
162   public static final String PHP_CODING_ACTION_SET_ID = PLUGIN_ID
163       + ".ui.CodingActionSet"; //$NON-NLS-1$
164
165   public final static String PHP_NATURE_ID = PLUGIN_ID + ".phpnature";
166
167   public static final String PHPPARSER_ORIGINAL = "net.sourceforge.phpdt.internal.compiler.parser.Parser";
168
169   public static final String PHPPARSER_NEW = "test.PHPParser";
170
171   /** Change this if you want to switch PHP Parser. */
172   public static final String PHPPARSER = PHPPARSER_ORIGINAL;
173
174   //The shared instance.
175   private static PHPeclipsePlugin plugin;
176
177   /** Windows 9x */
178   private static final int WINDOWS_9x = 6;
179
180   /** Windows NT */
181   private static final int WINDOWS_NT = 5;
182
183   private ImageDescriptorRegistry fImageDescriptorRegistry;
184
185   private HashMap fIndexManagerMap = new HashMap();
186
187   private IWorkingCopyManager fWorkingCopyManager;
188
189   private IBufferFactory fBufferFactory;
190
191   private PHPDocumentProvider fCompilationUnitDocumentProvider;
192
193   private JavaTextTools fJavaTextTools;
194
195   private ProblemMarkerManager fProblemMarkerManager;
196
197   private MembersOrderPreferenceCache fMembersOrderPreferenceCache;
198
199   private IFile fLastEditorFile = null;
200
201   private JavaEditorTextHoverDescriptor[] fJavaEditorTextHoverDescriptors;
202
203   private JavaElementAdapterFactory fJavaElementAdapterFactory;
204
205   //    private MarkerAdapterFactory fMarkerAdapterFactory;
206   //    private EditorInputAdapterFactory fEditorInputAdapterFactory;
207   private ResourceAdapterFactory fResourceAdapterFactory;
208
209   //    private LogicalPackageAdapterFactory fLogicalPackageAdapterFactory;
210   private IPropertyChangeListener fFontPropertyChangeListener;
211
212   /**
213    * Property change listener on this plugin's preference store.
214    * 
215    * @since 3.0
216    */
217   private IPropertyChangeListener fPropertyChangeListener;
218
219   /**
220    * The combined preference store.
221    * 
222    * @since 3.0
223    */
224   private IPreferenceStore fCombinedPreferenceStore;
225
226   /**
227    * The extension point registry for the
228    * <code>org.eclipse.jdt.ui.javaFoldingStructureProvider</code> extension
229    * point.
230    * 
231    * @since 3.0
232    */
233   private JavaFoldingStructureProviderRegistry fFoldingStructureProviderRegistry;
234
235   /**
236    * Mockup preference store for firing events and registering listeners on
237    * project setting changes. FIXME: Temporary solution.
238    * 
239    * @since 3.0
240    */
241   private MockupPreferenceStore fMockupPreferenceStore;
242
243   /**
244    * The constructor.
245    */
246   public PHPeclipsePlugin(IPluginDescriptor descriptor) {
247     super(descriptor);
248     plugin = this;
249     setJVM();
250     externalTools = new ExternalToolsPlugin();
251     //    try {
252     //      resourceBundle =
253     // ResourceBundle.getBundle("net.sourceforge.PHPeclipsePluginResources");
254     //    } catch (MissingResourceException x) {
255     //      resourceBundle = null;
256     //    }
257   }
258
259   //  /**
260   //   * Returns all Java editor text hovers contributed to the workbench.
261   //   *
262   //   * @return an array of JavaEditorTextHoverDescriptor
263   //   * @since 2.1
264   //   */
265   //  public JavaEditorTextHoverDescriptor[] getJavaEditorTextHoverDescriptors()
266   // {
267   //    if (fJavaEditorTextHoverDescriptors == null)
268   //      fJavaEditorTextHoverDescriptors = JavaEditorTextHoverDescriptor
269   //          .getContributedHovers();
270   //    return fJavaEditorTextHoverDescriptors;
271   //  }
272   /**
273    * Returns all Java editor text hovers contributed to the workbench.
274    * 
275    * @return an array of JavaEditorTextHoverDescriptor
276    * @since 2.1
277    */
278   public JavaEditorTextHoverDescriptor[] getJavaEditorTextHoverDescriptors() {
279     if (fJavaEditorTextHoverDescriptors == null) {
280       fJavaEditorTextHoverDescriptors = JavaEditorTextHoverDescriptor
281           .getContributedHovers();
282       ConfigurationElementSorter sorter = new ConfigurationElementSorter() {
283         /*
284          * @see org.eclipse.ui.texteditor.ConfigurationElementSorter#getConfigurationElement(java.lang.Object)
285          */
286         public IConfigurationElement getConfigurationElement(Object object) {
287           return ((JavaEditorTextHoverDescriptor) object)
288               .getConfigurationElement();
289         }
290       };
291       sorter.sort(fJavaEditorTextHoverDescriptors);
292
293       // The Problem hover has to be the first and the Annotation hover has to
294       // be the last one in the JDT UI's hover list
295       int length = fJavaEditorTextHoverDescriptors.length;
296       int first = -1;
297       int last = length - 1;
298       int problemHoverIndex = -1;
299       int annotationHoverIndex = -1;
300       for (int i = 0; i < length; i++) {
301         if (!fJavaEditorTextHoverDescriptors[i].getId().startsWith(PLUGIN_ID)) {
302           if (problemHoverIndex == -1 || annotationHoverIndex == -1)
303             continue;
304           else {
305             last = i - 1;
306             break;
307           }
308         }
309         if (first == -1)
310           first = i;
311
312         if (fJavaEditorTextHoverDescriptors[i].getId().equals(
313             "net.sourceforge.phpdt.ui.AnnotationHover")) { //$NON-NLS-1$
314           annotationHoverIndex = i;
315           continue;
316         }
317         if (fJavaEditorTextHoverDescriptors[i].getId().equals(
318             "net.sourceforge.phpdt.ui.ProblemHover")) { //$NON-NLS-1$
319           problemHoverIndex = i;
320           continue;
321         }
322       }
323
324       JavaEditorTextHoverDescriptor hoverDescriptor = null;
325
326       if (first > -1 && problemHoverIndex > -1 && problemHoverIndex != first) {
327         // move problem hover to beginning
328         hoverDescriptor = fJavaEditorTextHoverDescriptors[first];
329         fJavaEditorTextHoverDescriptors[first] = fJavaEditorTextHoverDescriptors[problemHoverIndex];
330         fJavaEditorTextHoverDescriptors[problemHoverIndex] = hoverDescriptor;
331
332         // update annotation hover index if needed
333         if (annotationHoverIndex == first)
334           annotationHoverIndex = problemHoverIndex;
335       }
336
337       if (annotationHoverIndex > -1 && annotationHoverIndex != last) {
338         // move annotation hover to end
339         hoverDescriptor = fJavaEditorTextHoverDescriptors[last];
340         fJavaEditorTextHoverDescriptors[last] = fJavaEditorTextHoverDescriptors[annotationHoverIndex];
341         fJavaEditorTextHoverDescriptors[annotationHoverIndex] = hoverDescriptor;
342       }
343
344       // Move Best Match hover to front
345       for (int i = 0; i < fJavaEditorTextHoverDescriptors.length - 1; i++) {
346         if (PreferenceConstants.ID_BESTMATCH_HOVER
347             .equals(fJavaEditorTextHoverDescriptors[i].getId())) {
348           hoverDescriptor = fJavaEditorTextHoverDescriptors[i];
349           for (int j = i; j > 0; j--)
350             fJavaEditorTextHoverDescriptors[j] = fJavaEditorTextHoverDescriptors[j - 1];
351           fJavaEditorTextHoverDescriptors[0] = hoverDescriptor;
352           break;
353         }
354
355       }
356     }
357
358     return fJavaEditorTextHoverDescriptors;
359   }
360
361   /**
362    * Resets the Java editor text hovers contributed to the workbench.
363    * <p>
364    * This will force a rebuild of the descriptors the next time a client asks
365    * for them.
366    * </p>
367    * 
368    * @return an array of JavaEditorTextHoverDescriptor
369    * @since 2.1
370    */
371   public void resetJavaEditorTextHoverDescriptors() {
372     fJavaEditorTextHoverDescriptors = null;
373   }
374
375   /**
376    * Creates the PHP plugin standard groups in a context menu.
377    */
378   public static void createStandardGroups(IMenuManager menu) {
379     if (!menu.isEmpty())
380       return;
381     menu.add(new Separator(IContextMenuConstants.GROUP_NEW));
382     menu.add(new GroupMarker(IContextMenuConstants.GROUP_GOTO));
383     menu.add(new Separator(IContextMenuConstants.GROUP_OPEN));
384     menu.add(new GroupMarker(IContextMenuConstants.GROUP_SHOW));
385     menu.add(new Separator(IContextMenuConstants.GROUP_REORGANIZE));
386     menu.add(new Separator(IContextMenuConstants.GROUP_GENERATE));
387     menu.add(new Separator(IContextMenuConstants.GROUP_SEARCH));
388     menu.add(new Separator(IContextMenuConstants.GROUP_BUILD));
389     menu.add(new Separator(IContextMenuConstants.GROUP_ADDITIONS));
390     menu.add(new Separator(IContextMenuConstants.GROUP_VIEWER_SETUP));
391     menu.add(new Separator(IContextMenuConstants.GROUP_PROPERTIES));
392   }
393
394   public static IWorkbenchPage getActivePage() {
395     return getDefault().internalGetActivePage();
396   }
397
398   public static Shell getActiveWorkbenchShell() {
399     return getActiveWorkbenchWindow().getShell();
400   }
401
402   /**
403    * Returns an array of all editors that have an unsaved content. If the
404    * identical content is presented in more than one editor, only one of those
405    * editor parts is part of the result.
406    * 
407    * @return an array of all dirty editor parts.
408    */
409   public static IEditorPart[] getDirtyEditors() {
410     Set inputs = new HashSet();
411     List result = new ArrayList(0);
412     IWorkbench workbench = getDefault().getWorkbench();
413     IWorkbenchWindow[] windows = workbench.getWorkbenchWindows();
414     for (int i = 0; i < windows.length; i++) {
415       IWorkbenchPage[] pages = windows[i].getPages();
416       for (int x = 0; x < pages.length; x++) {
417         IEditorPart[] editors = pages[x].getDirtyEditors();
418         for (int z = 0; z < editors.length; z++) {
419           IEditorPart ep = editors[z];
420           IEditorInput input = ep.getEditorInput();
421           if (!inputs.contains(input)) {
422             inputs.add(input);
423             result.add(ep);
424           }
425         }
426       }
427     }
428     return (IEditorPart[]) result.toArray(new IEditorPart[result.size()]);
429   }
430
431   public static IWorkbenchWindow getActiveWorkbenchWindow() {
432     return getDefault().getWorkbench().getActiveWorkbenchWindow();
433   }
434
435   /**
436    * Returns the shared instance.
437    */
438   public static PHPeclipsePlugin getDefault() {
439     return plugin;
440   }
441
442   public static ImageDescriptorRegistry getImageDescriptorRegistry() {
443     return getDefault().internalGetImageDescriptorRegistry();
444   }
445
446   static IPath getInstallLocation() {
447     return new Path(getDefault().getDescriptor().getInstallURL().getFile());
448   }
449
450   public static int getJVM() {
451     return jvm;
452   }
453
454   public static String getPluginId() {
455     return getDefault().getDescriptor().getUniqueIdentifier();
456   }
457
458   /**
459    * Returns the standard display to be used. The method first checks, if the
460    * thread calling this method has an associated display. If so, this display
461    * is returned. Otherwise the method returns the default display.
462    */
463   public static Display getStandardDisplay() {
464     Display display = Display.getCurrent();
465     if (display == null) {
466       display = Display.getDefault();
467     }
468     return display;
469   }
470
471   //  public static ExternalToolsPlugin getExternalTools() {
472   //    return externalTools;
473   //  }
474   /**
475    * Returns the workspace instance.
476    */
477   public static IWorkspace getWorkspace() {
478     return ResourcesPlugin.getWorkspace();
479   }
480
481   public static boolean isDebug() {
482     return getDefault().isDebugging();
483   }
484
485   //  public static void logErrorMessage(String message) {
486   //    log(new Status(IStatus.ERROR, getPluginId(),
487   // JavaStatusConstants.INTERNAL_ERROR, message, null));
488   //  }
489   //
490   //  public static void logErrorStatus(String message, IStatus status) {
491   //    if (status == null) {
492   //      logErrorMessage(message);
493   //      return;
494   //    }
495   //    MultiStatus multi= new MultiStatus(getPluginId(),
496   // JavaStatusConstants.INTERNAL_ERROR, message, null);
497   //    multi.add(status);
498   //    log(multi);
499   //  }
500   //
501   //  public static void log(Throwable e) {
502   //    log(new Status(IStatus.ERROR, getPluginId(),
503   // JavaStatusConstants.INTERNAL_ERROR,
504   // JavaUIMessages.getString("JavaPlugin.internal_error"), e)); //$NON-NLS-1$
505   //  }
506   public static void log(int severity, String message) {
507     Status status = new Status(severity, PLUGIN_ID, IStatus.OK, message, null);
508     log(status);
509   }
510
511   public static void log(IStatus status) {
512     getDefault().getLog().log(status);
513   }
514
515   public static void log(Throwable e) {
516     log(new Status(IStatus.ERROR, PLUGIN_ID, IStatus.ERROR,
517         "PHPeclipsePlugin.internalErrorOccurred", e)); //$NON-NLS-1$
518   }
519
520   public static void logErrorMessage(String message) {
521     log(new Status(IStatus.ERROR, getPluginId(),
522         IJavaStatusConstants.INTERNAL_ERROR, message, null));
523   }
524
525   private static void setJVM() {
526     String osName = System.getProperty("os.name");
527     if (osName.startsWith("Mac OS")) {
528       String mrjVersion = System.getProperty("mrj.version");
529       String majorMRJVersion = mrjVersion.substring(0, 3);
530       jvm = OTHER;
531       try {
532         double version = Double.valueOf(majorMRJVersion).doubleValue();
533         if (version == 2) {
534           jvm = MRJ_2_0;
535         } else if (version >= 2.1 && version < 3) {
536           jvm = MRJ_2_1;
537         } else if (version == 3.0) {
538           jvm = MRJ_3_0;
539         } else if (version >= 3.1) {
540           jvm = MRJ_3_1;
541         }
542       } catch (NumberFormatException nfe) {
543       }
544     } else if (osName.startsWith("Windows")) {
545       if (osName.indexOf("9") != -1) {
546         jvm = WINDOWS_9x;
547       } else {
548         jvm = WINDOWS_NT;
549       }
550     }
551   }
552
553   // TODO: refactor this into a better method name !
554   public synchronized PHPDocumentProvider getCompilationUnitDocumentProvider() {
555     if (fCompilationUnitDocumentProvider == null)
556       fCompilationUnitDocumentProvider = new PHPDocumentProvider();
557     return fCompilationUnitDocumentProvider;
558   }
559
560   /**
561    * Get the identifier index manager for the given project
562    * 
563    * @param iProject
564    *          the current project
565    * @return
566    */
567   public IdentifierIndexManager getIndexManager(IProject iProject) {
568     String indexFilename = iProject.getLocation() + File.separator
569         + "project.index";
570     IdentifierIndexManager indexManager = (IdentifierIndexManager) fIndexManagerMap
571         .get(indexFilename);
572     if (indexManager == null) {
573       indexManager = new IdentifierIndexManager(indexFilename);
574       fIndexManagerMap.put(indexFilename, indexManager);
575     }
576     return indexManager;
577   }
578
579   public synchronized IWorkingCopyManager getWorkingCopyManager() {
580     if (fWorkingCopyManager == null) {
581       PHPDocumentProvider provider = getCompilationUnitDocumentProvider();
582       fWorkingCopyManager = new WorkingCopyManager(provider);
583     }
584     return fWorkingCopyManager;
585   }
586
587   public synchronized MembersOrderPreferenceCache getMemberOrderPreferenceCache() {
588     if (fMembersOrderPreferenceCache == null)
589       fMembersOrderPreferenceCache = new MembersOrderPreferenceCache();
590     return fMembersOrderPreferenceCache;
591   }
592
593   /**
594    * Returns the mockup preference store for firing events and registering
595    * listeners on project setting changes. Temporary solution.
596    */
597   public MockupPreferenceStore getMockupPreferenceStore() {
598     if (fMockupPreferenceStore == null)
599       fMockupPreferenceStore = new MockupPreferenceStore();
600
601     return fMockupPreferenceStore;
602   }
603
604   public synchronized ProblemMarkerManager getProblemMarkerManager() {
605     if (fProblemMarkerManager == null)
606       fProblemMarkerManager = new ProblemMarkerManager();
607     return fProblemMarkerManager;
608   }
609
610   //  public synchronized JavaTextTools getJavaTextTools() {
611   //    if (fJavaTextTools == null)
612   //      fJavaTextTools = new JavaTextTools(getPreferenceStore());
613   //    return fJavaTextTools;
614   //  }
615   public synchronized JavaTextTools getJavaTextTools() {
616     if (fJavaTextTools == null)
617       fJavaTextTools = new JavaTextTools(getPreferenceStore(), JavaCore
618           .getPlugin().getPluginPreferences());
619     return fJavaTextTools;
620   }
621
622   public IFile getLastEditorFile() {
623     return fLastEditorFile;
624   }
625
626   /**
627    * Returns the string from the plugin's resource bundle, or 'key' if not
628    * found.
629    */
630   //  public static String getResourceString(String key) {
631   //    ResourceBundle bundle = PHPeclipsePlugin.getDefault().getResourceBundle();
632   //    try {
633   //      return bundle.getString(key);
634   //    } catch (MissingResourceException e) {
635   //      return key;
636   //    }
637   //  }
638   /**
639    * Returns the plugin's resource bundle,
640    */
641   //  public ResourceBundle getResourceBundle() {
642   //    return resourceBundle;
643   //  }
644   protected void initializeDefaultPreferences(IPreferenceStore store) {
645     // windows preferences:
646     //    store.setDefault(LOCALHOST_PREF, "http://localhost");
647     //    store.setDefault(DOCUMENTROOT_PREF,
648     // getWorkspace().getRoot().getLocation().toString());
649 //    store.setDefault(PHP_LOCALHOST_PREF, "http://localhost");
650 //    store.setDefault(PHP_DOCUMENTROOT_PREF, getWorkspace().getRoot()
651 //        .getLocation().toString());
652
653     //    store.setDefault(SHOW_EXTERNAL_PREVIEW_PREF, "true");
654     store.setDefault(USE_EXTERNAL_BROWSER_PREF, "false");
655     store.setDefault(SHOW_OUTPUT_IN_CONSOLE, "true");
656     store.setDefault(PHP_OBFUSCATOR_DEFAULT, "c:\\temp");
657 //    store.setDefault(PHP_BOOKMARK_DEFAULT, "");
658 //
659 //    store.setDefault(PHP_AUTO_PREVIEW_DEFAULT, "true");
660 //    store.setDefault(PHP_BRING_TO_TOP_PREVIEW_DEFAULT, "true");
661 //    store.setDefault(PHP_SHOW_HTML_FILES_LOCAL, "true");
662
663     String windowsSystem = Platform.getWS();
664     if (jvm == WINDOWS_9x) {
665       store.setDefault(EXTERNAL_BROWSER_PREF,
666           "command.com /c start iexplore {0}");
667     } else if (windowsSystem.equals(Platform.WS_WIN32)) {
668       store.setDefault(EXTERNAL_BROWSER_PREF,
669           "rundll32 url.dll,FileProtocolHandler {0}");
670     } else if (windowsSystem.equals(Platform.WS_CARBON)) {
671       // TODO How do we start Safari on Mac OS X ?
672       store.setDefault(EXTERNAL_BROWSER_PREF, "netscape {0}");
673     } else {
674       store.setDefault(PHP_OBFUSCATOR_DEFAULT, "/tmp");
675       store.setDefault(EXTERNAL_BROWSER_PREF, "netscape {0}");
676     }
677     //  if ((jvm == WINDOWS_9x) || (jvm == WINDOWS_NT)) {
678     //  
679     if (windowsSystem.equals(Platform.WS_WIN32)) {
680       store.setDefault(PHP_RUN_PREF, "c:\\apache\\php\\php.exe");
681       store.setDefault(EXTERNAL_PARSER_PREF, "c:\\apache\\php\\php -l -f {0}");
682       store.setDefault(MYSQL_RUN_PREF, "c:\\apache\\mysql\\bin\\mysqld-nt.exe");
683       store.setDefault(APACHE_RUN_PREF, "c:\\apache\\apache.exe");
684     } else {
685       store.setDefault(PHP_RUN_PREF, "/apache/php/php");
686       store.setDefault(EXTERNAL_PARSER_PREF, "/apache/php/php -l -f {0}");
687       store.setDefault(MYSQL_RUN_PREF, "/apache/mysql/bin/mysqld");
688       store.setDefault(APACHE_RUN_PREF, "/apache/apache");
689     }
690     store.setDefault(MYSQL_PREF, "--standalone");
691     store.setDefault(APACHE_START_PREF, "-c \"DocumentRoot \"{0}\"\"");
692     store.setDefault(APACHE_STOP_PREF, "-k shutdown");
693     store.setDefault(APACHE_RESTART_PREF, "-k restart");
694     store.setDefault(MYSQL_START_BACKGROUND, "true");
695     store.setDefault(APACHE_START_BACKGROUND, "true");
696     store.setDefault(APACHE_STOP_BACKGROUND, "true");
697     store.setDefault(APACHE_RESTART_BACKGROUND, "true");
698     //    store.setDefault(PHP_PARSER_DEFAULT, PHP_EXTERNAL_PARSER);
699     //    store.setDefault(PHP_INTERNAL_PARSER, "false");
700     //    store.setDefault(PHP_EXTERNAL_PARSER, "true");
701     //    store.setDefault(PHP_PARSE_ON_SAVE, "true");
702     // show line numbers:
703     //   store.setDefault(LINE_NUMBER_RULER, "false");
704     //    store.setDefault(FORMATTER_TAB_SIZE, "4");
705     // php syntax highlighting
706     store.setDefault(PHP_USERDEF_XMLFILE, "");
707     //assume there is none chooA
708     PreferenceConverter.setDefault(store, PHP_MULTILINE_COMMENT,
709         PHPColorProvider.MULTI_LINE_COMMENT);
710     PreferenceConverter.setDefault(store, PHP_SINGLELINE_COMMENT,
711         PHPColorProvider.SINGLE_LINE_COMMENT);
712     PreferenceConverter.setDefault(store, PHP_TAG, PHPColorProvider.TAG);
713     PreferenceConverter
714         .setDefault(store, PHP_KEYWORD, PHPColorProvider.KEYWORD);
715     PreferenceConverter.setDefault(store, PHP_VARIABLE,
716         PHPColorProvider.VARIABLE);
717     PreferenceConverter.setDefault(store, PHP_FUNCTIONNAME,
718         PHPColorProvider.FUNCTION_NAME);
719     PreferenceConverter.setDefault(store, PHP_CONSTANT,
720         PHPColorProvider.CONSTANT);
721     PreferenceConverter.setDefault(store, PHP_TYPE, PHPColorProvider.TYPE);
722     PreferenceConverter.setDefault(store, PHP_STRING, PHPColorProvider.STRING);
723     PreferenceConverter
724         .setDefault(store, PHP_DEFAULT, PHPColorProvider.DEFAULT);
725     PreferenceConverter.setDefault(store, PHPDOC_KEYWORD,
726         PHPColorProvider.PHPDOC_KEYWORD);
727     PreferenceConverter.setDefault(store, PHPDOC_TAG,
728         PHPColorProvider.PHPDOC_TAG);
729     PreferenceConverter.setDefault(store, PHPDOC_LINK,
730         PHPColorProvider.PHPDOC_LINK);
731     PreferenceConverter.setDefault(store, PHPDOC_DEFAULT,
732         PHPColorProvider.PHPDOC_DEFAULT);
733
734     PreferenceConverter.setDefault(store, EDITOR_PHP_KEYWORD_RETURN_COLOR,
735         new RGB(127, 0, 85));
736     store.setDefault(EDITOR_PHP_KEYWORD_RETURN_BOLD, true);
737     store.setDefault(EDITOR_PHP_KEYWORD_RETURN_ITALIC, false);
738
739     PreferenceConverter.setDefault(store, EDITOR_PHP_OPERATOR_COLOR, new RGB(0,
740         0, 0));
741     store.setDefault(EDITOR_PHP_OPERATOR_BOLD, false);
742     store.setDefault(EDITOR_PHP_OPERATOR_ITALIC, false);
743
744     //    PreferenceConverter.setDefault(
745     //      store,
746     //      PHP_EDITOR_BACKGROUND,
747     //      PHPColorProvider.BACKGROUND);
748     //    PreferenceConverter.setDefault(
749     //      store,
750     //      LINKED_POSITION_COLOR,
751     //      PHPColorProvider.LINKED_POSITION_COLOR);
752     //    PreferenceConverter.setDefault(
753     //      store,
754     //      LINE_NUMBER_COLOR,
755     //      PHPColorProvider.LINE_NUMBER_COLOR);
756     //    // set default PHPDoc colors:
757     //    PreferenceConverter.setDefault(
758     //      store,
759     //      PHPDOC_KEYWORD,
760     //      PHPColorProvider.PHPDOC_KEYWORD);
761     //    PreferenceConverter.setDefault(
762     //      store,
763     //      PHPDOC_LINK,
764     //      PHPColorProvider.PHPDOC_LINK);
765     //    PreferenceConverter.setDefault(
766     //      store,
767     //      PHPDOC_DEFAULT,
768     //      PHPColorProvider.PHPDOC_DEFAULT);
769     //    PreferenceConverter.setDefault(
770     //      store,
771     //      PHPDOC_TAG,
772     //      PHPColorProvider.PHPDOC_TAG);
773     //    store.setDefault(PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT, "true");
774     //    PreferenceConverter.setDefault(
775     //      store,
776     //      PREFERENCE_COLOR_BACKGROUND,
777     //      PHPColorProvider.BACKGROUND_COLOR);
778     //language stuff
779     //    store.setDefault(RESOURCE_BUNDLE, LANGUAGE_DEFAULT);
780     //    store.setDefault(RESOURCE_BUNDLE_EN_GB, "true");
781     //    store.setDefault(RESOURCE_BUNDLE_DE, "false");
782     //    store.setDefault(RESOURCE_BUNDLE_FR, "false");
783     //    store.setDefault(RESOURCE_BUNDLE_ES, "false");
784     TemplatePreferencePage.initDefaults(store);
785     //this will initialize the static fields in the syntaxrdr class
786     new PHPSyntaxRdr();
787     JavaCore.initializeDefaultPluginPreferences();
788     PreferenceConstants.initializeDefaultValues(store);
789     externalTools.initializeDefaultPreferences(store);
790     MarkerAnnotationPreferences.initializeDefaultValues(store);
791   }
792
793   private IWorkbenchPage internalGetActivePage() {
794     IWorkbenchWindow window = getWorkbench().getActiveWorkbenchWindow();
795     if (window != null)
796       return window.getActivePage();
797     return null;
798   }
799
800   private ImageDescriptorRegistry internalGetImageDescriptorRegistry() {
801     if (fImageDescriptorRegistry == null)
802       fImageDescriptorRegistry = new ImageDescriptorRegistry();
803     return fImageDescriptorRegistry;
804   }
805
806   /**
807    * Open a file in the Workbench that may or may not exist in the workspace.
808    * Must be run on the UI thread.
809    * 
810    * @param filename
811    * @throws CoreException
812    */
813   public ITextEditor openFileInTextEditor(String filename) throws CoreException {
814     //  reject directories
815     if (new File(filename).isDirectory())
816       return null;
817     IWorkbench workbench = PlatformUI.getWorkbench();
818     IWorkbenchWindow window = workbench.getWorkbenchWindows()[0];
819     IWorkbenchPage page = window.getActivePage();
820     IPath path = new Path(filename);
821     // If the file exists in the workspace, open it
822     IFile file = getWorkspace().getRoot().getFileForLocation(path);
823     IEditorPart editor;
824     ITextEditor textEditor;
825     if (file != null && file.exists()) {
826       editor = IDE.openEditor(page, file, true);
827       textEditor = (ITextEditor) editor.getAdapter(ITextEditor.class);
828     } else {
829       // Otherwise open the stream directly
830       if (page == null)
831         return null;
832       FileStorage storage = new FileStorage(path);
833       IEditorRegistry registry = getWorkbench().getEditorRegistry();
834       IEditorDescriptor desc = registry.getDefaultEditor(filename);
835       if (desc == null) {
836         desc = registry.findEditor(IEditorRegistry.SYSTEM_EXTERNAL_EDITOR_ID);
837         //   desc = registry.getDefaultEditor();
838       }
839       IEditorInput input = new ExternalEditorInput(storage);
840       editor = page.openEditor(input, desc.getId());
841       textEditor = (ITextEditor) editor.getAdapter(ITextEditor.class);
842       // If the storage provider is not ours, we can't guarantee read/write.
843       if (textEditor != null) {
844         IDocumentProvider documentProvider = textEditor.getDocumentProvider();
845         if (!(documentProvider instanceof ExternalStorageDocumentProvider)) {
846           storage.setReadOnly();
847         }
848       }
849     }
850     return textEditor;
851   }
852
853   /**
854    * Open a file in the Workbench that may or may not exist in the workspace.
855    * Must be run on the UI thread.
856    * 
857    * @param filename
858    * @param line
859    * @throws CoreException
860    */
861   public void openFileAndGotoLine(String filename, int line)
862       throws CoreException {
863     ITextEditor textEditor = openFileInTextEditor(filename);
864     if (textEditor != null) {
865       // If a line number was given, go to it
866       if (line > 0) {
867         try {
868           line--; // document is 0 based
869           IDocument document = textEditor.getDocumentProvider().getDocument(
870               textEditor.getEditorInput());
871           textEditor.selectAndReveal(document.getLineOffset(line), document
872               .getLineLength(line));
873         } catch (BadLocationException e) {
874           // invalid text position -> do nothing
875         }
876       }
877     }
878   }
879
880   /**
881    * Open a file in the Workbench that may or may not exist in the workspace.
882    * Must be run on the UI thread.
883    * 
884    * @param filename
885    * @param offset
886    * @throws CoreException
887    */
888   public void openFileAndGotoOffset(String filename, int offset, int length)
889       throws CoreException {
890     ITextEditor textEditor = openFileInTextEditor(filename);
891     if (textEditor != null) {
892       // If a line number was given, go to it
893       if (offset >= 0) {
894         IDocument document = textEditor.getDocumentProvider().getDocument(
895             textEditor.getEditorInput());
896         textEditor.selectAndReveal(offset, length);
897       }
898     }
899   }
900
901   public void openFileAndFindString(String filename, String findString)
902       throws CoreException {
903     ITextEditor textEditor = openFileInTextEditor(filename);
904     if (textEditor != null) {
905       //                If a string was given, go to it
906       if (findString != null) {
907         try {
908           IDocument document = textEditor.getDocumentProvider().getDocument(
909               textEditor.getEditorInput());
910           int offset = document.search(0, findString, true, false, true);
911           textEditor.selectAndReveal(offset, findString.length());
912         } catch (BadLocationException e) {
913           // invalid text position -> do nothing
914         }
915       }
916     }
917   }
918
919   public void setLastEditorFile(IFile textEditor) {
920     this.fLastEditorFile = textEditor;
921   }
922
923   /*
924    * @see org.eclipse.core.runtime.Plugin#stop
925    */
926   public void stop(BundleContext context) throws Exception {
927     try {
928       //                        JavaCore.stop(this, context);
929       plugin.savePluginPreferences();
930       IWorkspace workspace = ResourcesPlugin.getWorkspace();
931       workspace.removeResourceChangeListener(JavaModelManager
932           .getJavaModelManager().deltaState);
933       workspace.removeSaveParticipant(plugin);
934
935       JavaModelManager.getJavaModelManager().shutdown();
936
937       ColorManager.getDefault().dispose();
938       // save the information from the php index files if necessary
939       Collection collection = fIndexManagerMap.values();
940       Iterator iterator = collection.iterator();
941       IdentifierIndexManager indexManager = null;
942       while (iterator.hasNext()) {
943         indexManager = (IdentifierIndexManager) iterator.next();
944         indexManager.writeFile();
945       }
946       if (fImageDescriptorRegistry != null)
947         fImageDescriptorRegistry.dispose();
948
949       //                        AllTypesCache.terminate();
950
951       if (fImageDescriptorRegistry != null)
952         fImageDescriptorRegistry.dispose();
953
954       unregisterAdapters();
955
956       //                        if (fASTProvider != null) {
957       //                                fASTProvider.dispose();
958       //                                fASTProvider= null;
959       //                        }
960
961       if (fWorkingCopyManager != null) {
962         fWorkingCopyManager.shutdown();
963         fWorkingCopyManager = null;
964       }
965
966       if (fCompilationUnitDocumentProvider != null) {
967         fCompilationUnitDocumentProvider.shutdown();
968         fCompilationUnitDocumentProvider = null;
969       }
970
971       if (fJavaTextTools != null) {
972         fJavaTextTools.dispose();
973         fJavaTextTools = null;
974       }
975       //                        JavaDocLocations.shutdownJavadocLocations();
976
977       uninstallPreferenceStoreBackwardsCompatibility();
978
979       //                        RefactoringCore.getUndoManager().shutdown();
980     } finally {
981       super.stop(context);
982     }
983   }
984
985   /**
986    * @see org.eclipse.ui.plugin.AbstractUIPlugin#shutdown()
987    */
988   //  public void shutdown() throws CoreException {
989   //    // moved down (see below):
990   //    // super.shutdown();
991   //    // externalTools.shutDown();
992   //    ColorManager.getDefault().dispose();
993   //    // save the information from the php index files if necessary
994   //    Collection collection = fIndexManagerMap.values();
995   //    Iterator iterator = collection.iterator();
996   //    IdentifierIndexManager indexManager = null;
997   //    while (iterator.hasNext()) {
998   //      indexManager = (IdentifierIndexManager) iterator.next();
999   //      indexManager.writeFile();
1000   //    }
1001   //    if (fImageDescriptorRegistry != null)
1002   //      fImageDescriptorRegistry.dispose();
1003   //    // unregisterAdapters();
1004   //    super.shutdown();
1005   //    if (fWorkingCopyManager != null) {
1006   //      fWorkingCopyManager.shutdown();
1007   //      fWorkingCopyManager = null;
1008   //    }
1009   //    if (fCompilationUnitDocumentProvider != null) {
1010   //      fCompilationUnitDocumentProvider.shutdown();
1011   //      fCompilationUnitDocumentProvider = null;
1012   //    }
1013   //    if (fJavaTextTools != null) {
1014   //      fJavaTextTools.dispose();
1015   //      fJavaTextTools = null;
1016   //    }
1017   //    // JavaDocLocations.shutdownJavadocLocations();
1018   //    //
1019   //    //
1020   // JFaceResources.getFontRegistry().removeListener(fFontPropertyChangeListener);
1021   //    // begin JavaCore#shutdown()
1022   //    //savePluginPreferences();
1023   //    savePluginPreferences();
1024   //    IWorkspace workspace = ResourcesPlugin.getWorkspace();
1025   //    workspace.removeResourceChangeListener(JavaModelManager.getJavaModelManager().deltaState);
1026   //    workspace.removeSaveParticipant(this);
1027   //    ((JavaModelManager) JavaModelManager.getJavaModelManager()).shutdown();
1028   //    // end JavaCore#shutdown()
1029   //  }
1030   /**
1031    * Installs backwards compatibility for the preference store.
1032    */
1033   private void installPreferenceStoreBackwardsCompatibility() {
1034
1035     /*
1036      * Installs backwards compatibility: propagate the Java editor font from a
1037      * pre-2.1 plug-in to the Platform UI's preference store to preserve the
1038      * Java editor font from a pre-2.1 workspace. This is done only once.
1039      */
1040     String fontPropagatedKey = "fontPropagated"; //$NON-NLS-1$
1041     if (getPreferenceStore().contains(JFaceResources.TEXT_FONT)
1042         && !getPreferenceStore().isDefault(JFaceResources.TEXT_FONT)) {
1043       if (!getPreferenceStore().getBoolean(fontPropagatedKey))
1044         PreferenceConverter.setValue(PlatformUI.getWorkbench()
1045             .getPreferenceStore(), PreferenceConstants.EDITOR_TEXT_FONT,
1046             PreferenceConverter.getFontDataArray(getPreferenceStore(),
1047                 JFaceResources.TEXT_FONT));
1048     }
1049     getPreferenceStore().setValue(fontPropagatedKey, true);
1050
1051     /*
1052      * Backwards compatibility: set the Java editor font in this plug-in's
1053      * preference store to let older versions access it. Since 2.1 the Java
1054      * editor font is managed by the workbench font preference page.
1055      */
1056     PreferenceConverter.putValue(getPreferenceStore(),
1057         JFaceResources.TEXT_FONT, JFaceResources.getFontRegistry().getFontData(
1058             PreferenceConstants.EDITOR_TEXT_FONT));
1059
1060     fFontPropertyChangeListener = new IPropertyChangeListener() {
1061       public void propertyChange(PropertyChangeEvent event) {
1062         if (PreferenceConstants.EDITOR_TEXT_FONT.equals(event.getProperty()))
1063           PreferenceConverter.putValue(getPreferenceStore(),
1064               JFaceResources.TEXT_FONT, JFaceResources.getFontRegistry()
1065                   .getFontData(PreferenceConstants.EDITOR_TEXT_FONT));
1066       }
1067     };
1068     JFaceResources.getFontRegistry().addListener(fFontPropertyChangeListener);
1069
1070     /*
1071      * Backwards compatibility: propagate the Java editor tab width from a
1072      * pre-3.0 plug-in to the new preference key. This is done only once.
1073      */
1074     final String oldTabWidthKey = PreferenceConstants.EDITOR_TAB_WIDTH;
1075     final String newTabWidthKey = AbstractDecoratedTextEditorPreferenceConstants.EDITOR_TAB_WIDTH;
1076     String tabWidthPropagatedKey = "tabWidthPropagated"; //$NON-NLS-1$
1077     if (getPreferenceStore().contains(oldTabWidthKey)
1078         && !getPreferenceStore().isDefault(oldTabWidthKey)) {
1079       if (!getPreferenceStore().getBoolean(tabWidthPropagatedKey))
1080         getPreferenceStore().setValue(newTabWidthKey,
1081             getPreferenceStore().getInt(oldTabWidthKey));
1082     }
1083     getPreferenceStore().setValue(tabWidthPropagatedKey, true);
1084
1085     /*
1086      * Backwards compatibility: set the Java editor tab width in this plug-in's
1087      * preference store with the old key to let older versions access it. Since
1088      * 3.0 the tab width is managed by the extended texteditor and uses a new
1089      * key.
1090      */
1091     getPreferenceStore().putValue(oldTabWidthKey,
1092         getPreferenceStore().getString(newTabWidthKey));
1093
1094     fPropertyChangeListener = new IPropertyChangeListener() {
1095       public void propertyChange(PropertyChangeEvent event) {
1096         if (newTabWidthKey.equals(event.getProperty()))
1097           getPreferenceStore().putValue(oldTabWidthKey,
1098               getPreferenceStore().getString(newTabWidthKey));
1099       }
1100     };
1101     getPreferenceStore().addPropertyChangeListener(fPropertyChangeListener);
1102
1103     /*
1104      * Backward compatibility for the refactoring preference key.
1105      */
1106     //          getPreferenceStore().setValue(
1107     //                  PreferenceConstants.REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD,
1108     //                  RefactoringCore.getConditionCheckingFailedSeverity());
1109   }
1110
1111   /**
1112    * Uninstalls backwards compatibility for the preference store.
1113    */
1114   private void uninstallPreferenceStoreBackwardsCompatibility() {
1115     JFaceResources.getFontRegistry()
1116         .removeListener(fFontPropertyChangeListener);
1117     getPreferenceStore().removePropertyChangeListener(fPropertyChangeListener);
1118   }
1119
1120   /*
1121    * (non - Javadoc) Method declared in Plugin
1122    */
1123   public void start(BundleContext context) throws Exception {
1124     super.start(context);
1125     
1126     //          JavaCore.start(this, context);
1127     final JavaModelManager manager = JavaModelManager.getJavaModelManager();
1128     try {
1129       manager.configurePluginDebugOptions();
1130
1131       // request state folder creation (workaround 19885)
1132       //      JavaCore.getPlugin().getStateLocation();
1133       getStateLocation();
1134       // retrieve variable values
1135       //JavaCore.getPlugin().getPluginPreferences().addPropertyChangeListener(new
1136       // JavaModelManager.PluginPreferencesListener());
1137       //                        manager.loadVariablesAndContainers();
1138
1139       final IWorkspace workspace = ResourcesPlugin.getWorkspace();
1140                 workspace.addResourceChangeListener(
1141                         manager.deltaState,
1142                         IResourceChangeEvent.PRE_BUILD
1143                                 | IResourceChangeEvent.POST_BUILD
1144                                 | IResourceChangeEvent.POST_CHANGE
1145                                 | IResourceChangeEvent.PRE_DELETE
1146                                 | IResourceChangeEvent.PRE_CLOSE);
1147
1148 //              startIndexing();
1149                 ISavedState savedState = workspace.addSaveParticipant(PHPeclipsePlugin.this, manager);
1150
1151                 // process deltas since last activated in indexer thread so that indexes are up-to-date.
1152                 // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=38658
1153 //              Job processSavedState = new Job(Util.bind("savedState.jobName")) { //$NON-NLS-1$
1154 //                      protected IStatus run(IProgressMonitor monitor) {
1155 //                              try {
1156 //                                      // add save participant and process delta atomically
1157 //                                      // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=59937
1158 //                                      workspace.run(
1159 //                                              new IWorkspaceRunnable() {
1160 //                                                      public void run(IProgressMonitor progress) throws CoreException {
1161 //                                                              ISavedState savedState = workspace.addSaveParticipant(PHPeclipsePlugin.this, manager);
1162 //                                                              if (savedState != null) {
1163 //                                                                      // the event type coming from the saved state is always POST_AUTO_BUILD
1164 //                                                                      // force it to be POST_CHANGE so that the delta processor can handle it
1165 //                                                                      manager.deltaState.getDeltaProcessor().overridenEventType = IResourceChangeEvent.POST_CHANGE;
1166 //                                                                      savedState.processResourceChangeEvents(manager.deltaState);
1167 //                                                              }
1168 //                                                      }
1169 //                                              },
1170 //                                              monitor);
1171 //                              } catch (CoreException e) {
1172 //                                      return e.getStatus();
1173 //                              }
1174 //                              return Status.OK_STATUS;
1175 //                      }
1176 //              };
1177 //              processSavedState.setSystem(true);
1178 //              processSavedState.setPriority(Job.SHORT); // process asap
1179 //              processSavedState.schedule();
1180     } catch (RuntimeException e) {
1181       manager.shutdown();
1182       throw e;
1183     }
1184
1185     registerAdapters();
1186
1187     //  if (USE_WORKING_COPY_OWNERS) {
1188     WorkingCopyOwner.setPrimaryBufferProvider(new WorkingCopyOwner() {
1189       public IBuffer createBuffer(ICompilationUnit workingCopy) {
1190         ICompilationUnit original = workingCopy.getPrimary();
1191         IResource resource = original.getResource();
1192         if (resource instanceof IFile)
1193           return new DocumentAdapter(workingCopy, (IFile) resource);
1194         return DocumentAdapter.NULL;
1195       }
1196     });
1197     //  }
1198
1199     installPreferenceStoreBackwardsCompatibility();
1200
1201   }
1202
1203   //    registerAdapters();
1204   //
1205   //     // externalTools.startUp();
1206   //    getStandardDisplay().asyncExec(new Runnable() {
1207   //      public void run() {
1208   //        //initialize the variable context manager
1209   //        VariableContextManager.getDefault();
1210   //      }
1211   //    });
1212   //
1213   //    // if (USE_WORKING_COPY_OWNERS) {
1214   //    WorkingCopyOwner.setPrimaryBufferProvider(new WorkingCopyOwner() {
1215   //      public IBuffer createBuffer(ICompilationUnit workingCopy) {
1216   //        ICompilationUnit original = workingCopy.getPrimary();
1217   //        IResource resource = original.getResource();
1218   //        if (resource instanceof IFile)
1219   //          return new DocumentAdapter(workingCopy, (IFile) resource);
1220   //        return DocumentAdapter.NULL;
1221   //      }
1222   //    });
1223   //    // }
1224
1225   //    installPreferenceStoreBackwardsCompatibility();
1226
1227   //            AllTypesCache.initialize();
1228
1229   // Initialize AST provider
1230   //            getASTProvider();
1231   //  }
1232
1233   //  public void startup() throws CoreException {
1234   //    super.startup();
1235   //    // begin JavaCore.startup();
1236   //    JavaModelManager manager = JavaModelManager.getJavaModelManager();
1237   //    try {
1238   //      manager.configurePluginDebugOptions();
1239   //      // request state folder creation (workaround 19885)
1240   //      // JavaCore.getPlugin().getStateLocation();
1241   //      getStateLocation();
1242   //      // retrieve variable values
1243   //      //
1244   // JavaCore.getPlugin().getPluginPreferences().addPropertyChangeListener(new
1245   //      // JavaModelManager.PluginPreferencesListener());
1246   //      getPluginPreferences().addPropertyChangeListener(
1247   //          new JavaModelManager.PluginPreferencesListener());
1248   //      // TODO khartlage temp-del
1249   //      // manager.loadVariablesAndContainers();
1250   //      final IWorkspace workspace = ResourcesPlugin.getWorkspace();
1251   //            workspace.addResourceChangeListener(
1252   //                    manager.deltaState,
1253   //                    IResourceChangeEvent.PRE_BUILD
1254   //                            | IResourceChangeEvent.POST_BUILD
1255   //                            | IResourceChangeEvent.POST_CHANGE
1256   //                            | IResourceChangeEvent.PRE_DELETE
1257   //                            | IResourceChangeEvent.PRE_CLOSE);
1258   //      // startIndexing();
1259   //      workspace.addSaveParticipant(PHPeclipsePlugin.getDefault(), manager);
1260   //    } catch (CoreException e) {
1261   //    } catch (RuntimeException e) {
1262   //      manager.shutdown();
1263   //      throw e;
1264   //    }
1265   //    // end JavaCore.startup();
1266   //    IAdapterManager platformManager = Platform.getAdapterManager();
1267   //    platformManager.registerAdapters(new PHPElementAdapterFactory(),
1268   //        PHPElement.class);
1269   //    platformManager.registerAdapters(new ResourceAdapterFactory(),
1270   //        IResource.class);
1271   //    // externalTools.startUp();
1272   //    getStandardDisplay().asyncExec(new Runnable() {
1273   //      public void run() {
1274   //        //initialize the variable context manager
1275   //        VariableContextManager.getDefault();
1276   //      }
1277   //    });
1278   //  }
1279
1280   private void registerAdapters() {
1281     fJavaElementAdapterFactory = new JavaElementAdapterFactory();
1282     //          fMarkerAdapterFactory= new MarkerAdapterFactory();
1283     //          fEditorInputAdapterFactory= new EditorInputAdapterFactory();
1284     fResourceAdapterFactory = new ResourceAdapterFactory();
1285     //          fLogicalPackageAdapterFactory= new LogicalPackageAdapterFactory();
1286
1287     IAdapterManager manager = Platform.getAdapterManager();
1288     manager.registerAdapters(fJavaElementAdapterFactory, IJavaElement.class);
1289     //          manager.registerAdapters(fMarkerAdapterFactory, IMarker.class);
1290     //          manager.registerAdapters(fEditorInputAdapterFactory, IEditorInput.class);
1291     manager.registerAdapters(fResourceAdapterFactory, IResource.class);
1292     //          manager.registerAdapters(fLogicalPackageAdapterFactory,
1293     // LogicalPackage.class);
1294   }
1295
1296   private void unregisterAdapters() {
1297     IAdapterManager manager = Platform.getAdapterManager();
1298     manager.unregisterAdapters(fJavaElementAdapterFactory);
1299     //          manager.unregisterAdapters(fMarkerAdapterFactory);
1300     //          manager.unregisterAdapters(fEditorInputAdapterFactory);
1301     manager.unregisterAdapters(fResourceAdapterFactory);
1302     //          manager.unregisterAdapters(fLogicalPackageAdapterFactory);
1303   }
1304
1305   /**
1306    * Returns a combined preference store, this store is read-only.
1307    * 
1308    * @return the combined preference store
1309    * 
1310    * @since 3.0
1311    */
1312   public IPreferenceStore getCombinedPreferenceStore() {
1313     if (fCombinedPreferenceStore == null) {
1314       IPreferenceStore generalTextStore = EditorsUI.getPreferenceStore();
1315       fCombinedPreferenceStore = new ChainedPreferenceStore(
1316           new IPreferenceStore[] {
1317               getPreferenceStore(),
1318               new PreferencesAdapter(PHPeclipsePlugin.getDefault()
1319                   .getPluginPreferences()), generalTextStore });
1320     }
1321     return fCombinedPreferenceStore;
1322   }
1323
1324   public synchronized IBufferFactory getBufferFactory() {
1325     if (fBufferFactory == null)
1326       fBufferFactory = new CustomBufferFactory();
1327     return fBufferFactory;
1328   }
1329
1330   /**
1331    * Returns the registry of the extensions to the
1332    * <code>org.eclipse.jdt.ui.javaFoldingStructureProvider</code> extension
1333    * point.
1334    * 
1335    * @return the registry of contributed
1336    *         <code>IJavaFoldingStructureProvider</code>
1337    * @since 3.0
1338    */
1339   public synchronized JavaFoldingStructureProviderRegistry getFoldingStructureProviderRegistry() {
1340     if (fFoldingStructureProviderRegistry == null)
1341       fFoldingStructureProviderRegistry = new JavaFoldingStructureProviderRegistry();
1342     return fFoldingStructureProviderRegistry;
1343   }
1344
1345   /**
1346    * Runs the given action as an atomic Java model operation.
1347    * <p>
1348    * After running a method that modifies java elements, registered listeners
1349    * receive after-the-fact notification of what just transpired, in the form of
1350    * a element changed event. This method allows clients to call a number of
1351    * methods that modify java elements and only have element changed event
1352    * notifications reported at the end of the entire batch.
1353    * </p>
1354    * <p>
1355    * If this method is called outside the dynamic scope of another such call,
1356    * this method runs the action and then reports a single element changed event
1357    * describing the net effect of all changes done to java elements by the
1358    * action.
1359    * </p>
1360    * <p>
1361    * If this method is called in the dynamic scope of another such call, this
1362    * method simply runs the action.
1363    * </p>
1364    * 
1365    * @param action
1366    *          the action to perform
1367    * @param monitor
1368    *          a progress monitor, or <code>null</code> if progress reporting
1369    *          and cancellation are not desired
1370    * @exception CoreException
1371    *              if the operation failed.
1372    * @since 2.1
1373    */
1374   public static void run(IWorkspaceRunnable action, IProgressMonitor monitor)
1375       throws CoreException {
1376     run(action, ResourcesPlugin.getWorkspace().getRoot(), monitor);
1377   }
1378
1379   /**
1380    * Runs the given action as an atomic Java model operation.
1381    * <p>
1382    * After running a method that modifies java elements, registered listeners
1383    * receive after-the-fact notification of what just transpired, in the form of
1384    * a element changed event. This method allows clients to call a number of
1385    * methods that modify java elements and only have element changed event
1386    * notifications reported at the end of the entire batch.
1387    * </p>
1388    * <p>
1389    * If this method is called outside the dynamic scope of another such call,
1390    * this method runs the action and then reports a single element changed event
1391    * describing the net effect of all changes done to java elements by the
1392    * action.
1393    * </p>
1394    * <p>
1395    * If this method is called in the dynamic scope of another such call, this
1396    * method simply runs the action.
1397    * </p>
1398    * <p>
1399    * The supplied scheduling rule is used to determine whether this operation
1400    * can be run simultaneously with workspace changes in other threads. See
1401    * <code>IWorkspace.run(...)</code> for more details.
1402    * </p>
1403    * 
1404    * @param action
1405    *          the action to perform
1406    * @param rule
1407    *          the scheduling rule to use when running this operation, or
1408    *          <code>null</code> if there are no scheduling restrictions for
1409    *          this operation.
1410    * @param monitor
1411    *          a progress monitor, or <code>null</code> if progress reporting
1412    *          and cancellation are not desired
1413    * @exception CoreException
1414    *              if the operation failed.
1415    * @since 3.0
1416    */
1417   public static void run(IWorkspaceRunnable action, ISchedulingRule rule,
1418       IProgressMonitor monitor) throws CoreException {
1419     IWorkspace workspace = ResourcesPlugin.getWorkspace();
1420     if (workspace.isTreeLocked()) {
1421       new BatchOperation(action).run(monitor);
1422     } else {
1423       // use IWorkspace.run(...) to ensure that a build will be done in
1424       // autobuild mode
1425       workspace.run(new BatchOperation(action), rule, IWorkspace.AVOID_UPDATE,
1426           monitor);
1427     }
1428   }
1429 }