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