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