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