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