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