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