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