improved include detection
[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 import java.io.File;
14 import java.util.ArrayList;
15 import java.util.Collection;
16 import java.util.HashMap;
17 import java.util.HashSet;
18 import java.util.Iterator;
19 import java.util.List;
20 import java.util.Set;
21
22 import net.sourceforge.phpdt.core.IBuffer;
23 import net.sourceforge.phpdt.core.IBufferFactory;
24 import net.sourceforge.phpdt.core.ICompilationUnit;
25 import net.sourceforge.phpdt.core.IJavaElement;
26 import net.sourceforge.phpdt.core.JavaCore;
27 import net.sourceforge.phpdt.core.WorkingCopyOwner;
28 import net.sourceforge.phpdt.externaltools.internal.model.ColorManager;
29 import net.sourceforge.phpdt.externaltools.internal.model.ExternalToolsPlugin;
30 import net.sourceforge.phpdt.externaltools.internal.model.VariableContextManager;
31 import net.sourceforge.phpdt.internal.ui.JavaElementAdapterFactory;
32 import net.sourceforge.phpdt.internal.ui.ResourceAdapterFactory;
33 import net.sourceforge.phpdt.internal.ui.preferences.MembersOrderPreferenceCache;
34 import net.sourceforge.phpdt.internal.ui.preferences.TemplatePreferencePage;
35 import net.sourceforge.phpdt.internal.ui.text.java.hover.JavaEditorTextHoverDescriptor;
36 import net.sourceforge.phpdt.internal.ui.viewsupport.ImageDescriptorRegistry;
37 import net.sourceforge.phpdt.internal.ui.viewsupport.ProblemMarkerManager;
38 import net.sourceforge.phpdt.ui.IContextMenuConstants;
39 import net.sourceforge.phpdt.ui.IWorkingCopyManager;
40 import net.sourceforge.phpdt.ui.PreferenceConstants;
41 import net.sourceforge.phpdt.ui.text.JavaTextTools;
42 import net.sourceforge.phpeclipse.builder.ExternalEditorInput;
43 import net.sourceforge.phpeclipse.builder.ExternalStorageDocumentProvider;
44 import net.sourceforge.phpeclipse.builder.FileStorage;
45 import net.sourceforge.phpeclipse.builder.IdentifierIndexManager;
46 import net.sourceforge.phpeclipse.phpeditor.CustomBufferFactory;
47 import net.sourceforge.phpeclipse.phpeditor.DocumentAdapter;
48 import net.sourceforge.phpeclipse.phpeditor.PHPDocumentProvider;
49 import net.sourceforge.phpeclipse.phpeditor.PHPSyntaxRdr;
50 import net.sourceforge.phpeclipse.phpeditor.WorkingCopyManager;
51 import net.sourceforge.phpeclipse.phpeditor.util.PHPColorProvider;
52
53 import org.eclipse.core.boot.BootLoader;
54 import org.eclipse.core.resources.IFile;
55 import org.eclipse.core.resources.IProject;
56 import org.eclipse.core.resources.IResource;
57 import org.eclipse.core.resources.IWorkspace;
58 import org.eclipse.core.resources.ResourcesPlugin;
59 import org.eclipse.core.runtime.CoreException;
60 import org.eclipse.core.runtime.IAdapterManager;
61 import org.eclipse.core.runtime.IPath;
62 import org.eclipse.core.runtime.IPluginDescriptor;
63 import org.eclipse.core.runtime.IStatus;
64 import org.eclipse.core.runtime.Path;
65 import org.eclipse.core.runtime.Platform;
66 import org.eclipse.core.runtime.Status;
67 import net.sourceforge.phpdt.internal.ui.text.folding.JavaFoldingStructureProviderRegistry;
68
69 import net.sourceforge.phpdt.internal.ui.text.PreferencesAdapter;
70 import org.eclipse.jface.action.GroupMarker;
71 import org.eclipse.jface.action.IMenuManager;
72 import org.eclipse.jface.action.Separator;
73 import org.eclipse.jface.preference.IPreferenceStore;
74 import org.eclipse.jface.preference.PreferenceConverter;
75 import org.eclipse.jface.resource.JFaceResources;
76 import org.eclipse.jface.text.BadLocationException;
77 import org.eclipse.jface.text.IDocument;
78 import org.eclipse.jface.util.IPropertyChangeListener;
79 import org.eclipse.jface.util.PropertyChangeEvent;
80 import org.eclipse.swt.widgets.Display;
81 import org.eclipse.swt.widgets.Shell;
82 import org.eclipse.ui.IEditorDescriptor;
83 import org.eclipse.ui.IEditorInput;
84 import org.eclipse.ui.IEditorPart;
85 import org.eclipse.ui.IEditorRegistry;
86 import org.eclipse.ui.IWorkbench;
87 import org.eclipse.ui.IWorkbenchPage;
88 import org.eclipse.ui.IWorkbenchWindow;
89 import org.eclipse.ui.PlatformUI;
90 import org.eclipse.ui.editors.text.EditorsUI;
91 import org.eclipse.ui.ide.IDE;
92 import org.eclipse.ui.plugin.AbstractUIPlugin;
93 import org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants;
94 import org.eclipse.ui.texteditor.ChainedPreferenceStore;
95 import org.eclipse.ui.texteditor.IDocumentProvider;
96 import org.eclipse.ui.texteditor.ITextEditor;
97 import org.eclipse.ui.texteditor.MarkerAnnotationPreferences;
98 import org.osgi.framework.BundleContext;
99 /**
100  * The main plugin class to be used in the desktop.
101  */
102 public class PHPeclipsePlugin extends AbstractUIPlugin
103     implements
104       IPreferenceConstants {
105   /**
106    * The id of the PHP plugin (value <code>"net.sourceforge.phpeclipse"</code>).
107    */
108   public static final String PLUGIN_ID = "net.sourceforge.phpeclipse"; //$NON-NLS-1$
109   /**
110    * id of builder - matches plugin.xml (concatenate pluginid.builderid)
111    */
112   public static final String BUILDER_PARSER_ID = PLUGIN_ID + ".parserbuilder";
113   //public static final String BUILDER_INDEX_ID = PLUGIN_ID + ".indexbuilder";
114   /** General debug flag */
115   public static final boolean DEBUG = false;
116   /**
117    * The maximum number of allowed proposals by category
118    */
119   public final static int MAX_PROPOSALS = 200;
120   private static ExternalToolsPlugin externalTools;
121   /**
122    * The Java virtual machine that we are running on.
123    */
124   private static int jvm;
125   /** MRJ 2.0 */
126   private static final int MRJ_2_0 = 0;
127   /** MRJ 2.1 or later */
128   private static final int MRJ_2_1 = 1;
129   /** Java on Mac OS X 10.0 (MRJ 3.0) */
130   private static final int MRJ_3_0 = 3;
131   /** MRJ 3.1 */
132   private static final int MRJ_3_1 = 4;
133   /** JVM constant for any other platform */
134   private static final int OTHER = -1;
135   // public static final String PHP_RESOURCES_VIEW_ID = PLUGIN_ID +
136   // ".resourcesview.ViewPHPResources"; //$NON-NLS-1$
137   public static final String PHP_CODING_ACTION_SET_ID = PLUGIN_ID
138       + ".ui.CodingActionSet"; //$NON-NLS-1$
139   public final static String PHP_NATURE_ID = PLUGIN_ID + ".phpnature";
140   public static final String PHPPARSER_ORIGINAL = "net.sourceforge.phpdt.internal.compiler.parser.Parser";
141   public static final String PHPPARSER_NEW = "test.PHPParser";
142   /** Change this if you want to switch PHP Parser. */
143   public static final String PHPPARSER = PHPPARSER_ORIGINAL;
144   //The shared instance.
145   private static PHPeclipsePlugin plugin;
146   /** Windows 9x */
147   private static final int WINDOWS_9x = 6;
148   /** Windows NT */
149   private static final int WINDOWS_NT = 5;
150   private ImageDescriptorRegistry fImageDescriptorRegistry;
151   private HashMap fIndexManagerMap = new HashMap();
152   private IWorkingCopyManager fWorkingCopyManager;
153         private IBufferFactory fBufferFactory;
154   private PHPDocumentProvider fCompilationUnitDocumentProvider;
155   private JavaTextTools fJavaTextTools;
156   private ProblemMarkerManager fProblemMarkerManager;
157   private MembersOrderPreferenceCache fMembersOrderPreferenceCache;
158   private IFile fLastEditorFile = null;
159   private JavaEditorTextHoverDescriptor[] fJavaEditorTextHoverDescriptors;
160   
161   private JavaElementAdapterFactory fJavaElementAdapterFactory;
162 //      private MarkerAdapterFactory fMarkerAdapterFactory;
163 //      private EditorInputAdapterFactory fEditorInputAdapterFactory;
164         private ResourceAdapterFactory fResourceAdapterFactory; 
165 //      private LogicalPackageAdapterFactory fLogicalPackageAdapterFactory;
166         private IPropertyChangeListener fFontPropertyChangeListener;
167         /**
168          * Property change listener on this plugin's preference store.
169          * 
170          * @since 3.0
171          */
172         private IPropertyChangeListener fPropertyChangeListener;
173         
174         /**
175          * The combined preference store.
176          * @since 3.0
177          */
178         private IPreferenceStore fCombinedPreferenceStore;
179         /**
180          * The extension point registry for the <code>org.eclipse.jdt.ui.javaFoldingStructureProvider</code>
181          * extension point.
182          * 
183          * @since 3.0
184          */
185         private JavaFoldingStructureProviderRegistry fFoldingStructureProviderRegistry;
186   /**
187    * The constructor.
188    */
189   public PHPeclipsePlugin(IPluginDescriptor descriptor) {
190     super(descriptor);
191     plugin = this;
192     setJVM();
193     externalTools = new ExternalToolsPlugin();
194     //    try {
195     //      resourceBundle =
196     // ResourceBundle.getBundle("net.sourceforge.PHPeclipsePluginResources");
197     //    } catch (MissingResourceException x) {
198     //      resourceBundle = null;
199     //    }
200   }
201   /**
202    * Returns all Java editor text hovers contributed to the workbench.
203    * 
204    * @return an array of JavaEditorTextHoverDescriptor
205    * @since 2.1
206    */
207   public JavaEditorTextHoverDescriptor[] getJavaEditorTextHoverDescriptors() {
208     if (fJavaEditorTextHoverDescriptors == null)
209       fJavaEditorTextHoverDescriptors = JavaEditorTextHoverDescriptor
210           .getContributedHovers();
211     return fJavaEditorTextHoverDescriptors;
212   }
213   /**
214    * Resets the Java editor text hovers contributed to the workbench.
215    * <p>
216    * This will force a rebuild of the descriptors the next time a client asks
217    * for them.
218    * </p>
219    * 
220    * @return an array of JavaEditorTextHoverDescriptor
221    * @since 2.1
222    */
223   public void resetJavaEditorTextHoverDescriptors() {
224     fJavaEditorTextHoverDescriptors = null;
225   }
226   /**
227    * Creates the PHP plugin standard groups in a context menu.
228    */
229   public static void createStandardGroups(IMenuManager menu) {
230     if (!menu.isEmpty())
231       return;
232     menu.add(new Separator(IContextMenuConstants.GROUP_NEW));
233     menu.add(new GroupMarker(IContextMenuConstants.GROUP_GOTO));
234     menu.add(new Separator(IContextMenuConstants.GROUP_OPEN));
235     menu.add(new GroupMarker(IContextMenuConstants.GROUP_SHOW));
236     menu.add(new Separator(IContextMenuConstants.GROUP_REORGANIZE));
237     menu.add(new Separator(IContextMenuConstants.GROUP_GENERATE));
238     menu.add(new Separator(IContextMenuConstants.GROUP_SEARCH));
239     menu.add(new Separator(IContextMenuConstants.GROUP_BUILD));
240     menu.add(new Separator(IContextMenuConstants.GROUP_ADDITIONS));
241     menu.add(new Separator(IContextMenuConstants.GROUP_VIEWER_SETUP));
242     menu.add(new Separator(IContextMenuConstants.GROUP_PROPERTIES));
243   }
244   public static IWorkbenchPage getActivePage() {
245     return getDefault().internalGetActivePage();
246   }
247   public static Shell getActiveWorkbenchShell() {
248     return getActiveWorkbenchWindow().getShell();
249   }
250   /**
251    * Returns an array of all editors that have an unsaved content. If the
252    * identical content is presented in more than one editor, only one of those
253    * editor parts is part of the result.
254    * 
255    * @return an array of all dirty editor parts.
256    */
257   public static IEditorPart[] getDirtyEditors() {
258     Set inputs = new HashSet();
259     List result = new ArrayList(0);
260     IWorkbench workbench = getDefault().getWorkbench();
261     IWorkbenchWindow[] windows = workbench.getWorkbenchWindows();
262     for (int i = 0; i < windows.length; i++) {
263       IWorkbenchPage[] pages = windows[i].getPages();
264       for (int x = 0; x < pages.length; x++) {
265         IEditorPart[] editors = pages[x].getDirtyEditors();
266         for (int z = 0; z < editors.length; z++) {
267           IEditorPart ep = editors[z];
268           IEditorInput input = ep.getEditorInput();
269           if (!inputs.contains(input)) {
270             inputs.add(input);
271             result.add(ep);
272           }
273         }
274       }
275     }
276     return (IEditorPart[]) result.toArray(new IEditorPart[result.size()]);
277   }
278   public static IWorkbenchWindow getActiveWorkbenchWindow() {
279     return getDefault().getWorkbench().getActiveWorkbenchWindow();
280   }
281   /**
282    * Returns the shared instance.
283    */
284   public static PHPeclipsePlugin getDefault() {
285     return plugin;
286   }
287   public static ImageDescriptorRegistry getImageDescriptorRegistry() {
288     return getDefault().internalGetImageDescriptorRegistry();
289   }
290   static IPath getInstallLocation() {
291     return new Path(getDefault().getDescriptor().getInstallURL().getFile());
292   }
293   public static int getJVM() {
294     return jvm;
295   }
296   public static String getPluginId() {
297     return getDefault().getDescriptor().getUniqueIdentifier();
298   }
299   /**
300    * Returns the standard display to be used. The method first checks, if the
301    * thread calling this method has an associated display. If so, this display
302    * is returned. Otherwise the method returns the default display.
303    */
304   public static Display getStandardDisplay() {
305     Display display = Display.getCurrent();
306     if (display == null) {
307       display = Display.getDefault();
308     }
309     return display;
310   }
311   //  public static ExternalToolsPlugin getExternalTools() {
312   //    return externalTools;
313   //  }
314   /**
315    * Returns the workspace instance.
316    */
317   public static IWorkspace getWorkspace() {
318     return ResourcesPlugin.getWorkspace();
319   }
320   public static boolean isDebug() {
321     return getDefault().isDebugging();
322   }
323   //  public static void logErrorMessage(String message) {
324   //    log(new Status(IStatus.ERROR, getPluginId(),
325   // JavaStatusConstants.INTERNAL_ERROR, message, null));
326   //  }
327   //
328   //  public static void logErrorStatus(String message, IStatus status) {
329   //    if (status == null) {
330   //      logErrorMessage(message);
331   //      return;
332   //    }
333   //    MultiStatus multi= new MultiStatus(getPluginId(),
334   // JavaStatusConstants.INTERNAL_ERROR, message, null);
335   //    multi.add(status);
336   //    log(multi);
337   //  }
338   //
339   //  public static void log(Throwable e) {
340   //    log(new Status(IStatus.ERROR, getPluginId(),
341   // JavaStatusConstants.INTERNAL_ERROR,
342   // JavaUIMessages.getString("JavaPlugin.internal_error"), e)); //$NON-NLS-1$
343   //  }
344   public static void log(int severity, String message) {
345     Status status = new Status(severity, PLUGIN_ID, IStatus.OK, message, null);
346     log(status);
347   }
348   public static void log(IStatus status) {
349     getDefault().getLog().log(status);
350   }
351   public static void log(Throwable e) {
352     log(new Status(IStatus.ERROR, PLUGIN_ID, IStatus.ERROR,
353         "PHPeclipsePlugin.internalErrorOccurred", e)); //$NON-NLS-1$
354   }
355   private static void setJVM() {
356     String osName = System.getProperty("os.name");
357     if (osName.startsWith("Mac OS")) {
358       String mrjVersion = System.getProperty("mrj.version");
359       String majorMRJVersion = mrjVersion.substring(0, 3);
360       jvm = OTHER;
361       try {
362         double version = Double.valueOf(majorMRJVersion).doubleValue();
363         if (version == 2) {
364           jvm = MRJ_2_0;
365         } else if (version >= 2.1 && version < 3) {
366           jvm = MRJ_2_1;
367         } else if (version == 3.0) {
368           jvm = MRJ_3_0;
369         } else if (version >= 3.1) {
370           jvm = MRJ_3_1;
371         }
372       } catch (NumberFormatException nfe) {
373       }
374     } else if (osName.startsWith("Windows")) {
375       if (osName.indexOf("9") != -1) {
376         jvm = WINDOWS_9x;
377       } else {
378         jvm = WINDOWS_NT;
379       }
380     }
381   }
382   // TODO: refactor this into a better method name !
383   public synchronized PHPDocumentProvider getCompilationUnitDocumentProvider() {
384     if (fCompilationUnitDocumentProvider == null)
385       fCompilationUnitDocumentProvider = new PHPDocumentProvider();
386     return fCompilationUnitDocumentProvider;
387   }
388
389   /**
390    * Get the identifier index manager for the given project
391    * 
392    * @param iProject
393    *            the current project
394    * @return
395    */
396   public IdentifierIndexManager getIndexManager(IProject iProject) {
397     String indexFilename = iProject.getLocation() + File.separator
398         + "project.index";
399     IdentifierIndexManager indexManager = (IdentifierIndexManager) fIndexManagerMap
400         .get(indexFilename);
401     if (indexManager == null) {
402       indexManager = new IdentifierIndexManager(indexFilename);
403       fIndexManagerMap.put(indexFilename, indexManager);
404     }
405     return indexManager;
406   }
407   public synchronized IWorkingCopyManager getWorkingCopyManager() {
408     if (fWorkingCopyManager == null) {
409       PHPDocumentProvider provider = getCompilationUnitDocumentProvider();
410       fWorkingCopyManager = new WorkingCopyManager(provider);
411     }
412     return fWorkingCopyManager;
413   }
414   public synchronized MembersOrderPreferenceCache getMemberOrderPreferenceCache() {
415     if (fMembersOrderPreferenceCache == null)
416       fMembersOrderPreferenceCache = new MembersOrderPreferenceCache();
417     return fMembersOrderPreferenceCache;
418   }
419   public synchronized ProblemMarkerManager getProblemMarkerManager() {
420     if (fProblemMarkerManager == null)
421       fProblemMarkerManager = new ProblemMarkerManager();
422     return fProblemMarkerManager;
423   }
424         
425   public synchronized JavaTextTools getJavaTextTools() {
426     if (fJavaTextTools == null)
427       fJavaTextTools = new JavaTextTools(getPreferenceStore());
428     return fJavaTextTools;
429   }
430   public IFile getLastEditorFile() {
431     return fLastEditorFile;
432   }
433   /**
434    * Returns the string from the plugin's resource bundle, or 'key' if not
435    * found.
436    */
437   //  public static String getResourceString(String key) {
438   //    ResourceBundle bundle = PHPeclipsePlugin.getDefault().getResourceBundle();
439   //    try {
440   //      return bundle.getString(key);
441   //    } catch (MissingResourceException e) {
442   //      return key;
443   //    }
444   //  }
445   /**
446    * Returns the plugin's resource bundle,
447    */
448   //  public ResourceBundle getResourceBundle() {
449   //    return resourceBundle;
450   //  }
451   protected void initializeDefaultPreferences(IPreferenceStore store) {
452     // windows preferences:
453     store.setDefault(LOCALHOST_PREF, "http://localhost");
454 //    store.setDefault(SHOW_EXTERNAL_PREVIEW_PREF, "true");
455     store.setDefault(USE_EXTERNAL_BROWSER_PREF, "false");
456     store.setDefault(SHOW_OUTPUT_IN_CONSOLE, "true");
457     store.setDefault(PHP_OBFUSCATOR_DEFAULT, "c:\\temp");
458     store.setDefault(PHP_BOOKMARK_DEFAULT, "");
459     
460     store.setDefault(PHP_AUTO_PREVIEW_DEFAULT, "true");
461     store.setDefault(PHP_BRING_TO_TOP_PREVIEW_DEFAULT, "true");
462     
463     String windowsSystem = BootLoader.getWS();
464     if (jvm == WINDOWS_9x) {
465       store.setDefault(EXTERNAL_BROWSER_PREF,
466           "command.com /c start iexplore {0}");
467     } else if (windowsSystem.equals(BootLoader.WS_WIN32)) {
468       store.setDefault(EXTERNAL_BROWSER_PREF,
469           "rundll32 url.dll,FileProtocolHandler {0}");
470     } else if (windowsSystem.equals(BootLoader.WS_CARBON)) {
471       // TODO How do we start Safari on Mac OS X ?
472       store.setDefault(EXTERNAL_BROWSER_PREF, "netscape {0}");
473     } else {
474       store.setDefault(PHP_OBFUSCATOR_DEFAULT, "/tmp");
475       store.setDefault(EXTERNAL_BROWSER_PREF, "netscape {0}");
476     }
477     store.setDefault(DOCUMENTROOT_PREF, getWorkspace().getRoot().getLocation()
478         .toString());
479     //  if ((jvm == WINDOWS_9x) || (jvm == WINDOWS_NT)) {
480     //  
481     if (windowsSystem.equals(BootLoader.WS_WIN32)) {
482       store.setDefault(PHP_RUN_PREF, "c:\\apache\\php\\php.exe");
483       store.setDefault(EXTERNAL_PARSER_PREF, "c:\\apache\\php\\php -l -f {0}");
484       store.setDefault(MYSQL_RUN_PREF, "c:\\apache\\mysql\\bin\\mysqld-nt.exe");
485       store.setDefault(APACHE_RUN_PREF, "c:\\apache\\apache.exe");
486     } else {
487       store.setDefault(PHP_RUN_PREF, "/apache/php/php");
488       store.setDefault(EXTERNAL_PARSER_PREF, "/apache/php/php -l -f {0}");
489       store.setDefault(MYSQL_RUN_PREF, "/apache/mysql/bin/mysqld");
490       store.setDefault(APACHE_RUN_PREF, "/apache/apache");
491     }
492     store.setDefault(MYSQL_PREF, "--standalone");
493     store.setDefault(APACHE_START_PREF, "-c \"DocumentRoot \"{0}\"\"");
494     store.setDefault(APACHE_STOP_PREF, "-k shutdown");
495     store.setDefault(APACHE_RESTART_PREF, "-k restart");
496     store.setDefault(MYSQL_START_BACKGROUND, "true");
497     store.setDefault(APACHE_START_BACKGROUND, "true");
498     store.setDefault(APACHE_STOP_BACKGROUND, "true");
499     store.setDefault(APACHE_RESTART_BACKGROUND, "true");
500     store.setDefault(PHP_PARSER_DEFAULT, PHP_EXTERNAL_PARSER);
501     store.setDefault(PHP_INTERNAL_PARSER, "false");
502     store.setDefault(PHP_EXTERNAL_PARSER, "true");
503     //    store.setDefault(PHP_PARSE_ON_SAVE, "true");
504     // show line numbers:
505     //   store.setDefault(LINE_NUMBER_RULER, "false");
506     //    store.setDefault(FORMATTER_TAB_SIZE, "4");
507     // php syntax highlighting
508     store.setDefault(PHP_USERDEF_XMLFILE, "");
509     //assume there is none chooA
510     PreferenceConverter.setDefault(store, PHP_MULTILINE_COMMENT,
511         PHPColorProvider.MULTI_LINE_COMMENT);
512     PreferenceConverter.setDefault(store, PHP_SINGLELINE_COMMENT,
513         PHPColorProvider.SINGLE_LINE_COMMENT);
514     PreferenceConverter.setDefault(store, PHP_TAG, PHPColorProvider.TAG);
515     PreferenceConverter
516         .setDefault(store, PHP_KEYWORD, PHPColorProvider.KEYWORD);
517     PreferenceConverter.setDefault(store, PHP_VARIABLE,
518         PHPColorProvider.VARIABLE);
519     PreferenceConverter.setDefault(store, PHP_FUNCTIONNAME,
520         PHPColorProvider.FUNCTION_NAME);
521     PreferenceConverter.setDefault(store, PHP_CONSTANT,
522         PHPColorProvider.CONSTANT);
523     PreferenceConverter.setDefault(store, PHP_TYPE, PHPColorProvider.TYPE);
524     PreferenceConverter.setDefault(store, PHP_STRING, PHPColorProvider.STRING);
525     PreferenceConverter
526         .setDefault(store, PHP_DEFAULT, PHPColorProvider.DEFAULT);
527     PreferenceConverter.setDefault(store, PHPDOC_KEYWORD,
528         PHPColorProvider.PHPDOC_KEYWORD);
529     PreferenceConverter.setDefault(store, PHPDOC_TAG,
530         PHPColorProvider.PHPDOC_TAG);
531     PreferenceConverter.setDefault(store, PHPDOC_LINK,
532         PHPColorProvider.PHPDOC_LINK);
533     PreferenceConverter.setDefault(store, PHPDOC_DEFAULT,
534         PHPColorProvider.PHPDOC_DEFAULT);
535     //    PreferenceConverter.setDefault(
536     //      store,
537     //      PHP_EDITOR_BACKGROUND,
538     //      PHPColorProvider.BACKGROUND);
539     //    PreferenceConverter.setDefault(
540     //      store,
541     //      LINKED_POSITION_COLOR,
542     //      PHPColorProvider.LINKED_POSITION_COLOR);
543     //    PreferenceConverter.setDefault(
544     //      store,
545     //      LINE_NUMBER_COLOR,
546     //      PHPColorProvider.LINE_NUMBER_COLOR);
547     //    // set default PHPDoc colors:
548     //    PreferenceConverter.setDefault(
549     //      store,
550     //      PHPDOC_KEYWORD,
551     //      PHPColorProvider.PHPDOC_KEYWORD);
552     //    PreferenceConverter.setDefault(
553     //      store,
554     //      PHPDOC_LINK,
555     //      PHPColorProvider.PHPDOC_LINK);
556     //    PreferenceConverter.setDefault(
557     //      store,
558     //      PHPDOC_DEFAULT,
559     //      PHPColorProvider.PHPDOC_DEFAULT);
560     //    PreferenceConverter.setDefault(
561     //      store,
562     //      PHPDOC_TAG,
563     //      PHPColorProvider.PHPDOC_TAG);
564     //    store.setDefault(PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT, "true");
565     //    PreferenceConverter.setDefault(
566     //      store,
567     //      PREFERENCE_COLOR_BACKGROUND,
568     //      PHPColorProvider.BACKGROUND_COLOR);
569     //language stuff
570     //    store.setDefault(RESOURCE_BUNDLE, LANGUAGE_DEFAULT);
571     //    store.setDefault(RESOURCE_BUNDLE_EN_GB, "true");
572     //    store.setDefault(RESOURCE_BUNDLE_DE, "false");
573     //    store.setDefault(RESOURCE_BUNDLE_FR, "false");
574     //    store.setDefault(RESOURCE_BUNDLE_ES, "false");
575     TemplatePreferencePage.initDefaults(store);
576     //this will initialize the static fields in the syntaxrdr class
577     new PHPSyntaxRdr();
578     JavaCore.initializeDefaultPluginPreferences();
579     PreferenceConstants.initializeDefaultValues(store);
580     externalTools.initializeDefaultPreferences(store);
581     MarkerAnnotationPreferences.initializeDefaultValues(store); 
582   }
583   private IWorkbenchPage internalGetActivePage() {
584     IWorkbenchWindow window = getWorkbench().getActiveWorkbenchWindow();
585     if (window != null)
586       return window.getActivePage();
587     return null;
588   }
589   private ImageDescriptorRegistry internalGetImageDescriptorRegistry() {
590     if (fImageDescriptorRegistry == null)
591       fImageDescriptorRegistry = new ImageDescriptorRegistry();
592     return fImageDescriptorRegistry;
593   }
594   /**
595    * Open a file in the Workbench that may or may not exist in the workspace.
596    * Must be run on the UI thread.
597    * 
598    * @param filename
599    * @throws CoreException
600    */
601   public ITextEditor openFileInTextEditor(String filename) throws CoreException {
602     //  reject directories
603     if (new File(filename).isDirectory())
604       return null;
605     IWorkbench workbench = PlatformUI.getWorkbench();
606     IWorkbenchWindow window = workbench.getWorkbenchWindows()[0];
607     IWorkbenchPage page = window.getActivePage();
608     IPath path = new Path(filename);
609     // If the file exists in the workspace, open it
610     IFile file = getWorkspace().getRoot().getFileForLocation(path);
611     IEditorPart editor;
612     ITextEditor textEditor;
613     if (file != null && file.exists()) {
614       editor = IDE.openEditor(page, file, true);
615       textEditor = (ITextEditor) editor.getAdapter(ITextEditor.class);
616     } else {
617       // Otherwise open the stream directly
618       if (page == null)
619         return null;
620       FileStorage storage = new FileStorage(path);
621       IEditorRegistry registry = getWorkbench().getEditorRegistry();
622       IEditorDescriptor desc = registry.getDefaultEditor(filename);
623       if (desc == null) {
624         desc = registry.findEditor(IEditorRegistry.SYSTEM_EXTERNAL_EDITOR_ID);
625      //   desc = registry.getDefaultEditor();
626       }
627       IEditorInput input = new ExternalEditorInput(storage);
628       editor = page.openEditor(input, desc.getId());
629       textEditor = (ITextEditor) editor.getAdapter(ITextEditor.class);
630       // If the storage provider is not ours, we can't guarantee read/write.
631       if (textEditor != null) {
632         IDocumentProvider documentProvider = textEditor.getDocumentProvider();
633         if (!(documentProvider instanceof ExternalStorageDocumentProvider)) {
634           storage.setReadOnly();
635         }
636       }
637     }
638     return textEditor;
639   }
640   /**
641    * Open a file in the Workbench that may or may not exist in the workspace.
642    * Must be run on the UI thread.
643    * 
644    * @param filename
645    * @param line
646    * @throws CoreException
647    */
648   public void openFileAndGotoLine(String filename, int line)
649       throws CoreException {
650     ITextEditor textEditor = openFileInTextEditor(filename);
651     if (textEditor != null) {
652       // If a line number was given, go to it
653       if (line > 0) {
654         try {
655           line--; // document is 0 based
656           IDocument document = textEditor.getDocumentProvider().getDocument(
657               textEditor.getEditorInput());
658           textEditor.selectAndReveal(document.getLineOffset(line), document
659               .getLineLength(line));
660         } catch (BadLocationException e) {
661           // invalid text position -> do nothing
662         }
663       }
664     }
665   }
666   /**
667    * Open a file in the Workbench that may or may not exist in the workspace.
668    * Must be run on the UI thread.
669    * 
670    * @param filename
671    * @param offset
672    * @throws CoreException
673    */
674   public void openFileAndGotoOffset(String filename, int offset, int length)
675       throws CoreException {
676     ITextEditor textEditor = openFileInTextEditor(filename);
677     if (textEditor != null) {
678       // If a line number was given, go to it
679       if (offset >= 0) {
680         IDocument document = textEditor.getDocumentProvider().getDocument(
681             textEditor.getEditorInput());
682         textEditor.selectAndReveal(offset, length);
683       }
684     }
685   }
686   public void openFileAndFindString(String filename, String findString)
687       throws CoreException {
688     ITextEditor textEditor = openFileInTextEditor(filename);
689     if (textEditor != null) {
690       //                If a string was given, go to it
691       if (findString != null) {
692         try {
693           IDocument document = textEditor.getDocumentProvider().getDocument(
694               textEditor.getEditorInput());
695           int offset = document.search(0, findString, true, false, true);
696           textEditor.selectAndReveal(offset, findString.length());
697         } catch (BadLocationException e) {
698           // invalid text position -> do nothing
699         }
700       }
701     }
702   }
703   public void setLastEditorFile(IFile textEditor) {
704     this.fLastEditorFile = textEditor;
705   }
706         /*
707          * @see org.eclipse.core.runtime.Plugin#stop
708          */
709         public void stop(BundleContext context) throws Exception {
710                 try {
711                         JavaCore.stop(this, context);
712                         
713                         ColorManager.getDefault().dispose();
714                     // save the information from the php index files if necessary
715                     Collection collection = fIndexManagerMap.values();
716                     Iterator iterator = collection.iterator();
717                     IdentifierIndexManager indexManager = null;
718                     while (iterator.hasNext()) {
719                       indexManager = (IdentifierIndexManager) iterator.next();
720                       indexManager.writeFile();
721                     }
722                     if (fImageDescriptorRegistry != null)
723                       fImageDescriptorRegistry.dispose();
724                     
725 //                      AllTypesCache.terminate();
726         
727                         if (fImageDescriptorRegistry != null)
728                                 fImageDescriptorRegistry.dispose();
729                         
730                         unregisterAdapters();
731         
732 //                      if (fASTProvider != null) {
733 //                              fASTProvider.dispose();
734 //                              fASTProvider= null;
735 //                      }
736                         
737                         if (fWorkingCopyManager != null) {
738                                 fWorkingCopyManager.shutdown();
739                                 fWorkingCopyManager= null;
740                         }
741                         
742                         if (fCompilationUnitDocumentProvider != null) {
743                                 fCompilationUnitDocumentProvider.shutdown();
744                                 fCompilationUnitDocumentProvider= null;
745                         }
746                                         
747                         if (fJavaTextTools != null) {
748                                 fJavaTextTools.dispose();
749                                 fJavaTextTools= null;
750                         }
751 //                      JavaDocLocations.shutdownJavadocLocations();
752                         
753                         uninstallPreferenceStoreBackwardsCompatibility();
754                         
755 //                      RefactoringCore.getUndoManager().shutdown();
756                 } finally {     
757                         super.stop(context);
758                 }
759         }
760   /**
761    * @see org.eclipse.ui.plugin.AbstractUIPlugin#shutdown()
762    */
763 //  public void shutdown() throws CoreException {
764 //    // moved down (see below):
765 //    //    super.shutdown();
766 //    //  externalTools.shutDown();
767 //    ColorManager.getDefault().dispose();
768 //    // save the information from the php index files if necessary
769 //    Collection collection = fIndexManagerMap.values();
770 //    Iterator iterator = collection.iterator();
771 //    IdentifierIndexManager indexManager = null;
772 //    while (iterator.hasNext()) {
773 //      indexManager = (IdentifierIndexManager) iterator.next();
774 //      indexManager.writeFile();
775 //    }
776 //    if (fImageDescriptorRegistry != null)
777 //      fImageDescriptorRegistry.dispose();
778 //    //                                unregisterAdapters();
779 //    super.shutdown();
780 //    if (fWorkingCopyManager != null) {
781 //      fWorkingCopyManager.shutdown();
782 //      fWorkingCopyManager = null;
783 //    }
784 //    if (fCompilationUnitDocumentProvider != null) {
785 //      fCompilationUnitDocumentProvider.shutdown();
786 //      fCompilationUnitDocumentProvider = null;
787 //    }
788 //    if (fJavaTextTools != null) {
789 //      fJavaTextTools.dispose();
790 //      fJavaTextTools = null;
791 //    }
792 //    //                                JavaDocLocations.shutdownJavadocLocations();
793 //    //                
794 //    //                                JFaceResources.getFontRegistry().removeListener(fFontPropertyChangeListener);
795 //    // begin JavaCore#shutdown()
796 //    //savePluginPreferences();
797 //    savePluginPreferences();
798 //    IWorkspace workspace = ResourcesPlugin.getWorkspace();
799 //      workspace.removeResourceChangeListener(JavaModelManager.getJavaModelManager().deltaState);
800 //      workspace.removeSaveParticipant(this);
801 //      ((JavaModelManager) JavaModelManager.getJavaModelManager()).shutdown();
802 //    //         end JavaCore#shutdown()
803 //  }
804         /**
805          * Installs backwards compatibility for the preference store.
806          */
807         private void installPreferenceStoreBackwardsCompatibility() {
808
809                 /*
810                  * Installs backwards compatibility: propagate the Java editor font from a
811                  * pre-2.1 plug-in to the Platform UI's preference store to preserve
812                  * the Java editor font from a pre-2.1 workspace. This is done only
813                  * once.
814                  */
815                 String fontPropagatedKey= "fontPropagated"; //$NON-NLS-1$
816                 if (getPreferenceStore().contains(JFaceResources.TEXT_FONT) && !getPreferenceStore().isDefault(JFaceResources.TEXT_FONT)) {
817                         if (!getPreferenceStore().getBoolean(fontPropagatedKey))
818                                 PreferenceConverter.setValue(PlatformUI.getWorkbench().getPreferenceStore(), PreferenceConstants.EDITOR_TEXT_FONT, PreferenceConverter.getFontDataArray(getPreferenceStore(), JFaceResources.TEXT_FONT));
819                 }
820                 getPreferenceStore().setValue(fontPropagatedKey, true);
821
822                 /*
823                  * Backwards compatibility: set the Java editor font in this plug-in's
824                  * preference store to let older versions access it. Since 2.1 the
825                  * Java editor font is managed by the workbench font preference page.
826                  */
827                 PreferenceConverter.putValue(getPreferenceStore(), JFaceResources.TEXT_FONT, JFaceResources.getFontRegistry().getFontData(PreferenceConstants.EDITOR_TEXT_FONT));
828
829                 fFontPropertyChangeListener= new IPropertyChangeListener() {
830                         public void propertyChange(PropertyChangeEvent event) {
831                                 if (PreferenceConstants.EDITOR_TEXT_FONT.equals(event.getProperty()))
832                                         PreferenceConverter.putValue(getPreferenceStore(), JFaceResources.TEXT_FONT, JFaceResources.getFontRegistry().getFontData(PreferenceConstants.EDITOR_TEXT_FONT));
833                         }
834                 };
835                 JFaceResources.getFontRegistry().addListener(fFontPropertyChangeListener);
836                 
837                 /*
838                  * Backwards compatibility: propagate the Java editor tab width from a
839                  * pre-3.0 plug-in to the new preference key. This is done only once.
840                  */
841                 final String oldTabWidthKey= PreferenceConstants.EDITOR_TAB_WIDTH;
842                 final String newTabWidthKey= AbstractDecoratedTextEditorPreferenceConstants.EDITOR_TAB_WIDTH;
843                 String tabWidthPropagatedKey= "tabWidthPropagated"; //$NON-NLS-1$
844                 if (getPreferenceStore().contains(oldTabWidthKey) && !getPreferenceStore().isDefault(oldTabWidthKey)) {
845                         if (!getPreferenceStore().getBoolean(tabWidthPropagatedKey))
846                                 getPreferenceStore().setValue(newTabWidthKey, getPreferenceStore().getInt(oldTabWidthKey));
847                 }
848                 getPreferenceStore().setValue(tabWidthPropagatedKey, true);
849
850                 /*
851                  * Backwards compatibility: set the Java editor tab width in this plug-in's
852                  * preference store with the old key to let older versions access it.
853                  * Since 3.0 the tab width is managed by the extended texteditor and
854                  * uses a new key.
855                  */
856                 getPreferenceStore().putValue(oldTabWidthKey, getPreferenceStore().getString(newTabWidthKey));
857
858                 fPropertyChangeListener= new IPropertyChangeListener() {
859                         public void propertyChange(PropertyChangeEvent event) {
860                                 if (newTabWidthKey.equals(event.getProperty()))
861                                         getPreferenceStore().putValue(oldTabWidthKey, getPreferenceStore().getString(newTabWidthKey));
862                         }
863                 };
864                 getPreferenceStore().addPropertyChangeListener(fPropertyChangeListener);
865                 
866                 /*
867                  * Backward compatibility for the refactoring preference key. 
868                  */
869 //              getPreferenceStore().setValue(
870 //                      PreferenceConstants.REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD, 
871 //                      RefactoringCore.getConditionCheckingFailedSeverity());
872         }
873         
874         /**
875          * Uninstalls backwards compatibility for the preference store.
876          */
877         private void uninstallPreferenceStoreBackwardsCompatibility() {
878                 JFaceResources.getFontRegistry().removeListener(fFontPropertyChangeListener);
879                 getPreferenceStore().removePropertyChangeListener(fPropertyChangeListener);
880         }
881   /* (non - Javadoc)
882          * Method declared in Plugin
883          */
884         public void start(BundleContext context) throws Exception {
885                 super.start(context);
886                 
887                 JavaCore.start(this, context);
888                 
889                 registerAdapters();
890                 
891                  //  externalTools.startUp();
892             getStandardDisplay().asyncExec(new Runnable() {
893               public void run() {
894                 //initialize the variable context manager
895                 VariableContextManager.getDefault();
896               }
897             });
898             
899 //              if (USE_WORKING_COPY_OWNERS) {
900                         WorkingCopyOwner.setPrimaryBufferProvider(new WorkingCopyOwner() {
901                                 public IBuffer createBuffer(ICompilationUnit workingCopy) {
902                                         ICompilationUnit original= workingCopy.getPrimary();
903                                         IResource resource= original.getResource();
904                                         if (resource instanceof IFile)
905                                                 return new DocumentAdapter(workingCopy, (IFile) resource);
906                                         return DocumentAdapter.NULL;
907                                 }
908                         });
909 //              }
910         
911                 installPreferenceStoreBackwardsCompatibility();
912                 
913 //              AllTypesCache.initialize();
914                 
915                 // Initialize AST provider
916 //              getASTProvider();
917         }
918 //  public void startup() throws CoreException {
919 //    super.startup();
920 //    // begin JavaCore.startup();
921 //    JavaModelManager manager = JavaModelManager.getJavaModelManager();
922 //    try {
923 //      manager.configurePluginDebugOptions();
924 //      // request state folder creation (workaround 19885)
925 //      //              JavaCore.getPlugin().getStateLocation();
926 //      getStateLocation();
927 //      // retrieve variable values
928 //      //              JavaCore.getPlugin().getPluginPreferences().addPropertyChangeListener(new
929 //      // JavaModelManager.PluginPreferencesListener());
930 //      getPluginPreferences().addPropertyChangeListener(
931 //          new JavaModelManager.PluginPreferencesListener());
932 //      //      TODO khartlage temp-del
933 //      //              manager.loadVariablesAndContainers();
934 //      final IWorkspace workspace = ResourcesPlugin.getWorkspace();
935 //              workspace.addResourceChangeListener(
936 //                      manager.deltaState,
937 //                      IResourceChangeEvent.PRE_BUILD
938 //                              | IResourceChangeEvent.POST_BUILD
939 //                              | IResourceChangeEvent.POST_CHANGE
940 //                              | IResourceChangeEvent.PRE_DELETE
941 //                              | IResourceChangeEvent.PRE_CLOSE);
942 //      //              startIndexing();
943 //      workspace.addSaveParticipant(PHPeclipsePlugin.getDefault(), manager);
944 //    } catch (CoreException e) {
945 //    } catch (RuntimeException e) {
946 //      manager.shutdown();
947 //      throw e;
948 //    }
949 //    //         end JavaCore.startup();
950 //    IAdapterManager platformManager = Platform.getAdapterManager();
951 //    platformManager.registerAdapters(new PHPElementAdapterFactory(),
952 //        PHPElement.class);
953 //    platformManager.registerAdapters(new ResourceAdapterFactory(),
954 //        IResource.class);
955 //    //  externalTools.startUp();
956 //    getStandardDisplay().asyncExec(new Runnable() {
957 //      public void run() {
958 //        //initialize the variable context manager
959 //        VariableContextManager.getDefault();
960 //      }
961 //    });
962 //  }
963         
964         
965         private void registerAdapters() {
966                 fJavaElementAdapterFactory= new JavaElementAdapterFactory();
967 //              fMarkerAdapterFactory= new MarkerAdapterFactory();
968 //              fEditorInputAdapterFactory= new EditorInputAdapterFactory();
969                 fResourceAdapterFactory= new ResourceAdapterFactory();
970 //              fLogicalPackageAdapterFactory= new LogicalPackageAdapterFactory();
971
972                 IAdapterManager manager= Platform.getAdapterManager();          
973                 manager.registerAdapters(fJavaElementAdapterFactory, IJavaElement.class);
974 //              manager.registerAdapters(fMarkerAdapterFactory, IMarker.class);
975 //              manager.registerAdapters(fEditorInputAdapterFactory, IEditorInput.class);
976                 manager.registerAdapters(fResourceAdapterFactory, IResource.class);
977 //              manager.registerAdapters(fLogicalPackageAdapterFactory, LogicalPackage.class);
978         }
979         
980         private void unregisterAdapters() {
981                 IAdapterManager manager= Platform.getAdapterManager();
982                 manager.unregisterAdapters(fJavaElementAdapterFactory);
983 //              manager.unregisterAdapters(fMarkerAdapterFactory);
984 //              manager.unregisterAdapters(fEditorInputAdapterFactory);
985                 manager.unregisterAdapters(fResourceAdapterFactory);
986 //              manager.unregisterAdapters(fLogicalPackageAdapterFactory);
987         }
988         
989         /**
990          * Returns a combined preference store, this store is read-only.
991          * 
992          * @return the combined preference store
993          * 
994          * @since 3.0
995          */
996         public IPreferenceStore getCombinedPreferenceStore() {
997                 if (fCombinedPreferenceStore == null) {
998                         IPreferenceStore generalTextStore= EditorsUI.getPreferenceStore(); 
999                         fCombinedPreferenceStore= new ChainedPreferenceStore(new IPreferenceStore[] { getPreferenceStore(), new PreferencesAdapter(JavaCore.getPlugin().getPluginPreferences()), generalTextStore });
1000                 }
1001                 return fCombinedPreferenceStore;
1002         }
1003         
1004         public synchronized IBufferFactory getBufferFactory() {
1005                 if (fBufferFactory == null)
1006                         fBufferFactory= new CustomBufferFactory();
1007                 return fBufferFactory;
1008         }
1009         /**
1010          * Returns the registry of the extensions to the <code>org.eclipse.jdt.ui.javaFoldingStructureProvider</code>
1011          * extension point.
1012          * 
1013          * @return the registry of contributed <code>IJavaFoldingStructureProvider</code>
1014          * @since 3.0
1015          */
1016         public synchronized JavaFoldingStructureProviderRegistry getFoldingStructureProviderRegistry() {
1017                 if (fFoldingStructureProviderRegistry == null)
1018                         fFoldingStructureProviderRegistry= new JavaFoldingStructureProviderRegistry();
1019                 return fFoldingStructureProviderRegistry;
1020         }
1021 }