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