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