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