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