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