Better event handling for browser preview refreshs in Wikipedia plugin
[phpeclipse.git] / net.sourceforge.phpeclipse / src / net / sourceforge / phpeclipse / phpeditor / PHPDocumentProvider.java
1 package net.sourceforge.phpeclipse.phpeditor;
2
3 /**********************************************************************
4 Copyright (c) 2000, 2002 IBM Corp. and others.
5 All rights reserved. This program and the accompanying materials
6 are made available under the terms of the Common Public License v1.0
7 which accompanies this distribution, and is available at
8 http://www.eclipse.org/legal/cpl-v10.html
9
10 Contributors:
11     IBM Corporation - Initial implementation
12     www.phpeclipse.de
13 **********************************************************************/
14
15 import java.util.ArrayList;
16 import java.util.Iterator;
17 import java.util.List;
18
19 import net.sourceforge.phpdt.core.ICompilationUnit;
20 import net.sourceforge.phpdt.core.IProblemRequestor;
21 import net.sourceforge.phpdt.core.JavaCore;
22 import net.sourceforge.phpdt.core.JavaModelException;
23 import net.sourceforge.phpdt.core.compiler.IProblem;
24 import net.sourceforge.phpdt.internal.ui.text.IPHPPartitions;
25 import net.sourceforge.phpdt.internal.ui.text.java.IProblemRequestorExtension;
26 import net.sourceforge.phpdt.internal.ui.text.spelling.SpellReconcileStrategy.SpellProblem;
27 import net.sourceforge.phpdt.ui.PreferenceConstants;
28 import net.sourceforge.phpeclipse.PHPeclipsePlugin;
29
30 import org.eclipse.core.resources.IFile;
31 import org.eclipse.core.resources.IMarker;
32 import org.eclipse.core.resources.IResource;
33 import org.eclipse.core.resources.IResourceRuleFactory;
34 import org.eclipse.core.resources.ResourcesPlugin;
35 import org.eclipse.core.runtime.CoreException;
36 import org.eclipse.core.runtime.IProgressMonitor;
37 import org.eclipse.core.runtime.jobs.ISchedulingRule;
38 import org.eclipse.jface.preference.IPreferenceStore;
39 import org.eclipse.jface.text.Assert;
40 import org.eclipse.jface.text.BadLocationException;
41 import org.eclipse.jface.text.DefaultLineTracker;
42 import org.eclipse.jface.text.Document;
43 import org.eclipse.jface.text.IDocument;
44 import org.eclipse.jface.text.ILineTracker;
45 import org.eclipse.jface.text.ISynchronizable;
46 import org.eclipse.jface.text.Position;
47 import org.eclipse.jface.text.source.Annotation;
48 import org.eclipse.jface.text.source.AnnotationModelEvent;
49 import org.eclipse.jface.text.source.IAnnotationAccessExtension;
50 import org.eclipse.jface.text.source.IAnnotationModel;
51 import org.eclipse.jface.text.source.IAnnotationModelListener;
52 import org.eclipse.jface.text.source.IAnnotationModelListenerExtension;
53 import org.eclipse.jface.text.source.IAnnotationPresentation;
54 import org.eclipse.jface.text.source.ImageUtilities;
55 import org.eclipse.jface.util.IPropertyChangeListener;
56 import org.eclipse.jface.util.ListenerList;
57 import org.eclipse.jface.util.PropertyChangeEvent;
58 import org.eclipse.swt.SWT;
59 import org.eclipse.swt.graphics.GC;
60 import org.eclipse.swt.graphics.Image;
61 import org.eclipse.swt.graphics.Rectangle;
62 import org.eclipse.swt.widgets.Canvas;
63 import org.eclipse.swt.widgets.Display;
64 import org.eclipse.ui.IFileEditorInput;
65 import org.eclipse.ui.editors.text.EditorsUI;
66 import org.eclipse.ui.editors.text.ForwardingDocumentProvider;
67 import org.eclipse.ui.editors.text.TextFileDocumentProvider;
68 import org.eclipse.ui.texteditor.AbstractMarkerAnnotationModel;
69 import org.eclipse.ui.texteditor.AnnotationPreference;
70 import org.eclipse.ui.texteditor.AnnotationPreferenceLookup;
71 import org.eclipse.ui.texteditor.IDocumentProvider;
72 import org.eclipse.ui.texteditor.MarkerAnnotation;
73 import org.eclipse.ui.texteditor.MarkerUtilities;
74 import org.eclipse.ui.texteditor.ResourceMarkerAnnotationModel;
75
76 /** 
77  * The PHPDocumentProvider provides the IDocuments used by java editors.
78  */
79
80 public class PHPDocumentProvider extends TextFileDocumentProvider implements ICompilationUnitDocumentProvider {
81   /**
82                          * Here for visibility issues only.
83                          */
84
85   /**
86                  * Bundle of all required informations to allow working copy management. 
87                  */
88         /**
89          * Bundle of all required informations to allow working copy management. 
90          */
91         static protected class CompilationUnitInfo extends FileInfo {
92                 public ICompilationUnit fCopy;
93         }
94         
95         /**
96          * Annotation model dealing with java marker annotations and temporary problems.
97          * Also acts as problem requestor for its compilation unit. Initialiy inactive. Must explicitly be
98          * activated.
99          */
100         protected static class CompilationUnitAnnotationModel extends ResourceMarkerAnnotationModel implements IProblemRequestor, IProblemRequestorExtension {
101                 
102                 private static class ProblemRequestorState {
103                         boolean fInsideReportingSequence= false;
104                         List fReportedProblems;
105                 }
106                 
107                 private ThreadLocal fProblemRequestorState= new ThreadLocal();
108                 private int fStateCount= 0;
109                 
110                 private ICompilationUnit fCompilationUnit;
111                 private List fGeneratedAnnotations;
112                 private IProgressMonitor fProgressMonitor;
113                 private boolean fIsActive= false;
114                 
115                 private ReverseMap fReverseMap= new ReverseMap();
116                 private List fPreviouslyOverlaid= null; 
117                 private List fCurrentlyOverlaid= new ArrayList();
118
119                 
120                 public CompilationUnitAnnotationModel(IResource resource) {
121                         super(resource);
122                 }
123                 
124                 public void setCompilationUnit(ICompilationUnit unit)  {
125                         fCompilationUnit= unit;
126                 }
127                 
128                 protected MarkerAnnotation createMarkerAnnotation(IMarker marker) {
129                         String markerType= MarkerUtilities.getMarkerType(marker);
130                         if (markerType != null && markerType.startsWith(JavaMarkerAnnotation.JAVA_MARKER_TYPE_PREFIX))
131                                 return new JavaMarkerAnnotation(marker);
132                         return super.createMarkerAnnotation(marker);
133                 }
134                 
135                 /*
136                  * @see org.eclipse.jface.text.source.AnnotationModel#createAnnotationModelEvent()
137                  */
138                 protected AnnotationModelEvent createAnnotationModelEvent() {
139                         return new CompilationUnitAnnotationModelEvent(this, getResource());
140                 }
141                 
142                 protected Position createPositionFromProblem(IProblem problem) {
143                         int start= problem.getSourceStart();
144                         if (start < 0)
145                                 return null;
146                                 
147                         int length= problem.getSourceEnd() - problem.getSourceStart() + 1;
148                         if (length < 0)
149                                 return null;
150                                 
151                         return new Position(start, length);
152                 }
153                 
154                 /*
155                  * @see IProblemRequestor#beginReporting()
156                  */
157                 public void beginReporting() {
158                         ProblemRequestorState state= (ProblemRequestorState) fProblemRequestorState.get();
159                         if (state == null)
160                                 internalBeginReporting(false);                          
161                 }
162                 
163                 /*
164                  * @see org.eclipse.jdt.internal.ui.text.java.IProblemRequestorExtension#beginReportingSequence()
165                  */
166                 public void beginReportingSequence() {
167                         ProblemRequestorState state= (ProblemRequestorState) fProblemRequestorState.get();
168                         if (state == null)
169                                 internalBeginReporting(true);
170                 }
171                 
172                 /**
173                  * Sets up the infrastructure necessary for problem reporting.
174                  * 
175                  * @param insideReportingSequence <code>true</code> if this method
176                  *            call is issued from inside a reporting sequence
177                  */
178                 private void internalBeginReporting(boolean insideReportingSequence) {
179                         if (fCompilationUnit != null) {
180                 // && fCompilationUnit.getJavaProject().isOnClasspath(fCompilationUnit)) {
181                                 ProblemRequestorState state= new ProblemRequestorState();
182                                 state.fInsideReportingSequence= insideReportingSequence;
183                                 state.fReportedProblems= new ArrayList();
184                                 synchronized (getLockObject()) {
185                                         fProblemRequestorState.set(state);
186                                         ++fStateCount;
187                                 }
188                         }
189                 }
190
191                 /*
192                  * @see IProblemRequestor#acceptProblem(IProblem)
193                  */
194                 public void acceptProblem(IProblem problem) {
195                         if (isActive()) {
196                                 ProblemRequestorState state= (ProblemRequestorState) fProblemRequestorState.get();
197                                 if (state != null)
198                                         state.fReportedProblems.add(problem);
199                         }
200                 }
201                 
202                 /*
203                  * @see IProblemRequestor#endReporting()
204                  */
205                 public void endReporting() {
206                         ProblemRequestorState state= (ProblemRequestorState) fProblemRequestorState.get();
207                         if (state != null && !state.fInsideReportingSequence)
208                                 internalEndReporting(state);
209                 }
210                 
211                 /*
212                  * @see org.eclipse.jdt.internal.ui.text.java.IProblemRequestorExtension#endReportingSequence()
213                  */
214                 public void endReportingSequence() {
215                         ProblemRequestorState state= (ProblemRequestorState) fProblemRequestorState.get();
216                         if (state != null && state.fInsideReportingSequence)
217                                 internalEndReporting(state);
218                 }
219                 
220                 private void internalEndReporting(ProblemRequestorState state) {
221                         int stateCount= 0;
222                         synchronized(getLockObject()) {
223                                 -- fStateCount;
224                                 stateCount= fStateCount;
225                                 fProblemRequestorState.set(null);
226                         }
227                         
228                         if (stateCount == 0 && isActive())
229                                 reportProblems(state.fReportedProblems);
230                 }
231                 
232                 /**
233                  * Signals the end of problem reporting.
234                  */
235                 private void reportProblems(List reportedProblems) {
236                         if (fProgressMonitor != null && fProgressMonitor.isCanceled())
237                                 return;
238                                 
239                         boolean temporaryProblemsChanged= false;
240                         
241                         synchronized (getLockObject()) {
242                                 
243                                 boolean isCanceled= false;
244
245                                 fPreviouslyOverlaid= fCurrentlyOverlaid;
246                                 fCurrentlyOverlaid= new ArrayList();
247
248                                 if (fGeneratedAnnotations.size() > 0) {
249                                         temporaryProblemsChanged= true; 
250                                         removeAnnotations(fGeneratedAnnotations, false, true);
251                                         fGeneratedAnnotations.clear();
252                                 }
253                                 
254                                 if (reportedProblems != null && reportedProblems.size() > 0) {
255                                                                                         
256                                         Iterator e= reportedProblems.iterator();
257                                         while (e.hasNext()) {
258                                                 
259                                                 if (fProgressMonitor != null && fProgressMonitor.isCanceled()) {
260                                                         isCanceled= true;
261                                                         break;
262                                                 }
263                                                         
264                                                 IProblem problem= (IProblem) e.next();
265                                                 Position position= createPositionFromProblem(problem);
266                                                 if (position != null) {
267                                                         
268                                                         try {
269                                                                 ProblemAnnotation annotation= new ProblemAnnotation(problem, fCompilationUnit);
270                                                                 overlayMarkers(position, annotation);                                                           
271                                                                 addAnnotation(annotation, position, false);
272                                                                 fGeneratedAnnotations.add(annotation);
273                                                         
274                                                                 temporaryProblemsChanged= true;
275                                                         } catch (BadLocationException x) {
276                                                                 // ignore invalid position
277                                                         }
278                                                 }
279                                         }
280                                 }
281                                 
282                                 removeMarkerOverlays(isCanceled);
283                                 fPreviouslyOverlaid= null;
284                         }
285                                 
286                         if (temporaryProblemsChanged)
287                                 fireModelChanged();
288                 }
289
290                 private void removeMarkerOverlays(boolean isCanceled) {
291                         if (isCanceled) {
292                                 fCurrentlyOverlaid.addAll(fPreviouslyOverlaid);
293                         } else if (fPreviouslyOverlaid != null) {
294                                 Iterator e= fPreviouslyOverlaid.iterator();
295                                 while (e.hasNext()) {
296                                         JavaMarkerAnnotation annotation= (JavaMarkerAnnotation) e.next();
297                                         annotation.setOverlay(null);
298                                 }
299                         }                       
300                 }
301                 
302                 /**
303                  * Overlays value with problem annotation.
304                  * @param problemAnnotation
305                  */
306                 private void setOverlay(Object value, ProblemAnnotation problemAnnotation) {
307                         if (value instanceof  JavaMarkerAnnotation) {
308                                 JavaMarkerAnnotation annotation= (JavaMarkerAnnotation) value;
309                                 if (annotation.isProblem()) {
310                                         annotation.setOverlay(problemAnnotation);
311                                         fPreviouslyOverlaid.remove(annotation);
312                                         fCurrentlyOverlaid.add(annotation);
313                                 }
314                         } else {
315                         }
316                 }
317                 
318                 private void  overlayMarkers(Position position, ProblemAnnotation problemAnnotation) {
319                         Object value= getAnnotations(position);
320                         if (value instanceof List) {
321                                 List list= (List) value;
322                                 for (Iterator e = list.iterator(); e.hasNext();)
323                                         setOverlay(e.next(), problemAnnotation);
324                         } else {
325                                 setOverlay(value, problemAnnotation);
326                         }
327                 }
328                 
329                 /**
330                  * Tells this annotation model to collect temporary problems from now on.
331                  */
332                 private void startCollectingProblems() {
333                         fGeneratedAnnotations= new ArrayList();  
334                 }
335                 
336                 /**
337                  * Tells this annotation model to no longer collect temporary problems.
338                  */
339                 private void stopCollectingProblems() {
340                         if (fGeneratedAnnotations != null)
341                                 removeAnnotations(fGeneratedAnnotations, true, true);
342                         fGeneratedAnnotations= null;
343                 }
344                 
345                 /*
346                  * @see IProblemRequestor#isActive()
347                  */
348                 public boolean isActive() {
349                         return fIsActive;
350                 }
351                 
352                 /*
353                  * @see IProblemRequestorExtension#setProgressMonitor(IProgressMonitor)
354                  */
355                 public void setProgressMonitor(IProgressMonitor monitor) {
356                         fProgressMonitor= monitor;
357                 }
358                 
359                 /*
360                  * @see IProblemRequestorExtension#setIsActive(boolean)
361                  */
362                 public void setIsActive(boolean isActive) {
363                         if (fIsActive != isActive) {
364                                 fIsActive= isActive;
365                                 if (fIsActive)
366                                         startCollectingProblems();
367                                 else
368                                         stopCollectingProblems();
369                         }
370                 }
371                 
372                 private Object getAnnotations(Position position) {
373                         return fReverseMap.get(position);
374                 }
375                                         
376                 /*
377                  * @see AnnotationModel#addAnnotation(Annotation, Position, boolean)
378                  */
379                 protected void addAnnotation(Annotation annotation, Position position, boolean fireModelChanged) throws BadLocationException {                          
380                         super.addAnnotation(annotation, position, fireModelChanged);
381
382                         Object cached= fReverseMap.get(position);
383                         if (cached == null)
384                                 fReverseMap.put(position, annotation);
385                         else if (cached instanceof List) {
386                                 List list= (List) cached;
387                                 list.add(annotation);
388                         } else if (cached instanceof Annotation) {
389                                 List list= new ArrayList(2);
390                                 list.add(cached);
391                                 list.add(annotation);
392                                 fReverseMap.put(position, list);
393                         }
394                 }
395                 
396                 /*
397                  * @see AnnotationModel#removeAllAnnotations(boolean)
398                  */
399                 protected void removeAllAnnotations(boolean fireModelChanged) {
400                         super.removeAllAnnotations(fireModelChanged);
401                         fReverseMap.clear();
402                 }
403                 
404                 /*
405                  * @see AnnotationModel#removeAnnotation(Annotation, boolean)
406                  */
407                 protected void removeAnnotation(Annotation annotation, boolean fireModelChanged) {
408                         Position position= getPosition(annotation);
409                         Object cached= fReverseMap.get(position);
410                         if (cached instanceof List) {
411                                 List list= (List) cached;
412                                 list.remove(annotation);
413                                 if (list.size() == 1) {
414                                         fReverseMap.put(position, list.get(0));
415                                         list.clear();
416                                 }
417                         } else if (cached instanceof Annotation) {
418                                 fReverseMap.remove(position);
419                         }
420                         super.removeAnnotation(annotation, fireModelChanged);
421                 }
422         }
423   
424    
425   
426   protected static class GlobalAnnotationModelListener implements IAnnotationModelListener, IAnnotationModelListenerExtension {
427
428     private ListenerList fListenerList;
429
430     public GlobalAnnotationModelListener() {
431       fListenerList = new ListenerList();
432     }
433
434     public void addListener(IAnnotationModelListener listener) {
435       fListenerList.add(listener);
436     }
437
438     /**
439      * @see IAnnotationModelListenerExtension#modelChanged(AnnotationModelEvent)
440      */
441     public void modelChanged(AnnotationModelEvent event) {
442       Object[] listeners = fListenerList.getListeners();
443       for (int i = 0; i < listeners.length; i++) {
444         Object curr = listeners[i];
445         if (curr instanceof IAnnotationModelListenerExtension) {
446           ((IAnnotationModelListenerExtension) curr).modelChanged(event);
447         }
448       }
449     }
450
451     /**
452      * @see IAnnotationModelListener#modelChanged(IAnnotationModel)
453      */
454     public void modelChanged(IAnnotationModel model) {
455       Object[] listeners = fListenerList.getListeners();
456       for (int i = 0; i < listeners.length; i++) {
457         ((IAnnotationModelListener) listeners[i]).modelChanged(model);
458       }
459     }
460
461     public void removeListener(IAnnotationModelListener listener) {
462       fListenerList.remove(listener);
463     }
464   }
465
466   /**
467          * Annotation representating an <code>IProblem</code>.
468          */
469         static protected class ProblemAnnotation extends Annotation implements IJavaAnnotation, IAnnotationPresentation {
470                 
471                 private static final String SPELLING_ANNOTATION_TYPE= "org.eclipse.ui.workbench.texteditor.spelling";
472
473                 //XXX: To be fully correct these constants should be non-static
474                 /** 
475                  * The layer in which task problem annotations are located.
476                  */
477                 private static final int TASK_LAYER;
478                 /** 
479                  * The layer in which info problem annotations are located.
480                  */
481                 private static final int INFO_LAYER;
482                 /** 
483                  * The layer in which warning problem annotations representing are located.
484                  */
485                 private static final int WARNING_LAYER;
486                 /** 
487                  * The layer in which error problem annotations representing are located.
488                  */
489                 private static final int ERROR_LAYER;
490                 
491                 static {
492                         AnnotationPreferenceLookup lookup= EditorsUI.getAnnotationPreferenceLookup();
493                         TASK_LAYER= computeLayer("org.eclipse.ui.workbench.texteditor.task", lookup); //$NON-NLS-1$
494                         INFO_LAYER= computeLayer("net.sourceforge.phpdt.ui.info", lookup); //$NON-NLS-1$
495                         WARNING_LAYER= computeLayer("net.sourceforge.phpdt.ui.warning", lookup); //$NON-NLS-1$
496                         ERROR_LAYER= computeLayer("net.sourceforge.phpdt.ui.error", lookup); //$NON-NLS-1$
497                 }
498                 
499                 private static int computeLayer(String annotationType, AnnotationPreferenceLookup lookup) {
500                         Annotation annotation= new Annotation(annotationType, false, null);
501                         AnnotationPreference preference= lookup.getAnnotationPreference(annotation);
502                         if (preference != null)
503                                 return preference.getPresentationLayer() + 1;
504                         else
505                                 return IAnnotationAccessExtension.DEFAULT_LAYER + 1;
506                 }
507
508 //              private static Image fgQuickFixImage;
509 //              private static Image fgQuickFixErrorImage;
510 //              private static boolean fgQuickFixImagesInitialized= false;
511                 
512                 private ICompilationUnit fCompilationUnit;
513                 private List fOverlaids;
514                 private IProblem fProblem;
515                 private Image fImage;
516                 private boolean fQuickFixImagesInitialized= false;
517                 private int fLayer= IAnnotationAccessExtension.DEFAULT_LAYER;
518                 
519                 public ProblemAnnotation(IProblem problem, ICompilationUnit cu) {
520                         
521                         fProblem= problem;
522                         fCompilationUnit= cu;
523                         
524                         if (SpellProblem.Spelling == fProblem.getID()) {
525                                 setType(SPELLING_ANNOTATION_TYPE);
526                                 fLayer= WARNING_LAYER;
527                         } else if (IProblem.Task == fProblem.getID()) {
528                                 setType(JavaMarkerAnnotation.TASK_ANNOTATION_TYPE);
529                                 fLayer= TASK_LAYER;
530                         } else if (fProblem.isWarning()) {
531                                 setType(JavaMarkerAnnotation.WARNING_ANNOTATION_TYPE);
532                                 fLayer= WARNING_LAYER;
533                         } else if (fProblem.isError()) {
534                                 setType(JavaMarkerAnnotation.ERROR_ANNOTATION_TYPE);
535                                 fLayer= ERROR_LAYER;
536                         } else {
537                                 setType(JavaMarkerAnnotation.INFO_ANNOTATION_TYPE);
538                                 fLayer= INFO_LAYER;
539                         }
540                 }
541                 
542                 /*
543                  * @see org.eclipse.jface.text.source.IAnnotationPresentation#getLayer()
544                  */
545                 public int getLayer() {
546                         return fLayer;
547                 }
548                 
549                 private void initializeImages() {
550                         // http://bugs.eclipse.org/bugs/show_bug.cgi?id=18936
551 //                      if (!fQuickFixImagesInitialized) {
552 //                              if (isProblem() && indicateQuixFixableProblems() && JavaCorrectionProcessor.hasCorrections(this)) { // no light bulb for tasks
553 //                                      if (!fgQuickFixImagesInitialized) {
554 //                                              fgQuickFixImage= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_FIXABLE_PROBLEM);
555 //                                              fgQuickFixErrorImage= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_FIXABLE_ERROR);
556 //                                              fgQuickFixImagesInitialized= true;
557 //                                      }
558 //                                      if (JavaMarkerAnnotation.ERROR_ANNOTATION_TYPE.equals(getType()))
559 //                                              fImage= fgQuickFixErrorImage;
560 //                                      else
561 //                                              fImage= fgQuickFixImage;
562 //                              }
563 //                              fQuickFixImagesInitialized= true;
564 //                      }
565                 }
566
567                 private boolean indicateQuixFixableProblems() {
568                         return PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_CORRECTION_INDICATION);
569                 }
570                 
571                 /*
572                  * @see Annotation#paint
573                  */
574                 public void paint(GC gc, Canvas canvas, Rectangle r) {
575                         initializeImages();
576                         if (fImage != null)
577                                 ImageUtilities.drawImage(fImage, gc, canvas, r, SWT.CENTER, SWT.TOP);
578                 }
579                 /*
580                  * @see IJavaAnnotation#getImage(Display)
581                  */
582                 public Image getImage(Display display) {
583                         initializeImages();
584                         return fImage;
585                 }
586                 
587                 /*
588                  * @see IJavaAnnotation#getMessage()
589                  */
590                 public String getText() {
591                         return fProblem.getMessage();
592                 }
593                 
594                 /*
595                  * @see IJavaAnnotation#getArguments()
596                  */
597                 public String[] getArguments() {
598                         return isProblem() ? fProblem.getArguments() : null;
599                 }
600
601                 /*
602                  * @see IJavaAnnotation#getId()
603                  */
604                 public int getId() {
605                         return fProblem.getID();
606                 }
607
608                 /*
609                  * @see IJavaAnnotation#isProblem()
610                  */
611                 public boolean isProblem() {
612                         String type= getType();
613                         return  JavaMarkerAnnotation.WARNING_ANNOTATION_TYPE.equals(type)  || 
614                                                 JavaMarkerAnnotation.ERROR_ANNOTATION_TYPE.equals(type) ||
615                                                 SPELLING_ANNOTATION_TYPE.equals(type);
616                 }
617                 
618                 /*
619                  * @see IJavaAnnotation#hasOverlay()
620                  */
621                 public boolean hasOverlay() {
622                         return false;
623                 }
624                 
625                 /*
626                  * @see org.eclipse.jdt.internal.ui.javaeditor.IJavaAnnotation#getOverlay()
627                  */
628                 public IJavaAnnotation getOverlay() {
629                         return null;
630                 }
631                 
632                 /*
633                  * @see IJavaAnnotation#addOverlaid(IJavaAnnotation)
634                  */
635                 public void addOverlaid(IJavaAnnotation annotation) {
636                         if (fOverlaids == null)
637                                 fOverlaids= new ArrayList(1);
638                         fOverlaids.add(annotation);
639                 }
640
641                 /*
642                  * @see IJavaAnnotation#removeOverlaid(IJavaAnnotation)
643                  */
644                 public void removeOverlaid(IJavaAnnotation annotation) {
645                         if (fOverlaids != null) {
646                                 fOverlaids.remove(annotation);
647                                 if (fOverlaids.size() == 0)
648                                         fOverlaids= null;
649                         }
650                 }
651                 
652                 /*
653                  * @see IJavaAnnotation#getOverlaidIterator()
654                  */
655                 public Iterator getOverlaidIterator() {
656                         if (fOverlaids != null)
657                                 return fOverlaids.iterator();
658                         return null;
659                 }
660                 
661                 /*
662                  * @see org.eclipse.jdt.internal.ui.javaeditor.IJavaAnnotation#getCompilationUnit()
663                  */
664                 public ICompilationUnit getCompilationUnit() {
665                         return fCompilationUnit;
666                 }
667         }
668         
669  
670   /**
671                  * Internal structure for mapping positions to some value. 
672                  * The reason for this specific structure is that positions can
673                  * change over time. Thus a lookup is based on value and not
674                  * on hash value.
675                  */
676   protected static class ReverseMap {
677
678     static class Entry {
679       Position fPosition;
680       Object fValue;
681     }
682     private int fAnchor = 0;
683
684     private List fList = new ArrayList(2);
685
686     public ReverseMap() {
687     }
688
689     public void clear() {
690       fList.clear();
691     }
692
693     public Object get(Position position) {
694
695       Entry entry;
696
697       // behind anchor
698       int length = fList.size();
699       for (int i = fAnchor; i < length; i++) {
700         entry = (Entry) fList.get(i);
701         if (entry.fPosition.equals(position)) {
702           fAnchor = i;
703           return entry.fValue;
704         }
705       }
706
707       // before anchor
708       for (int i = 0; i < fAnchor; i++) {
709         entry = (Entry) fList.get(i);
710         if (entry.fPosition.equals(position)) {
711           fAnchor = i;
712           return entry.fValue;
713         }
714       }
715
716       return null;
717     }
718
719     private int getIndex(Position position) {
720       Entry entry;
721       int length = fList.size();
722       for (int i = 0; i < length; i++) {
723         entry = (Entry) fList.get(i);
724         if (entry.fPosition.equals(position))
725           return i;
726       }
727       return -1;
728     }
729
730     public void put(Position position, Object value) {
731       int index = getIndex(position);
732       if (index == -1) {
733         Entry entry = new Entry();
734         entry.fPosition = position;
735         entry.fValue = value;
736         fList.add(entry);
737       } else {
738         Entry entry = (Entry) fList.get(index);
739         entry.fValue = value;
740       }
741     }
742
743     public void remove(Position position) {
744       int index = getIndex(position);
745       if (index > -1)
746         fList.remove(index);
747     }
748   }
749
750   /**
751                  * Document that can also be used by a background reconciler.
752                  */
753   protected static class PartiallySynchronizedDocument extends Document {
754
755     /*
756      * @see IDocumentExtension#startSequentialRewrite(boolean)
757      */
758     synchronized public void startSequentialRewrite(boolean normalized) {
759       super.startSequentialRewrite(normalized);
760     }
761
762     /*
763      * @see IDocumentExtension#stopSequentialRewrite()
764      */
765     synchronized public void stopSequentialRewrite() {
766       super.stopSequentialRewrite();
767     }
768
769     /*
770      * @see IDocument#get()
771      */
772     synchronized public String get() {
773       return super.get();
774     }
775
776     /*
777      * @see IDocument#get(int, int)
778      */
779     synchronized public String get(int offset, int length) throws BadLocationException {
780       return super.get(offset, length);
781     }
782
783     /*
784      * @see IDocument#getChar(int)
785      */
786     synchronized public char getChar(int offset) throws BadLocationException {
787       return super.getChar(offset);
788     }
789
790     /*
791      * @see IDocument#replace(int, int, String)
792      */
793     synchronized public void replace(int offset, int length, String text) throws BadLocationException {
794       super.replace(offset, length, text);
795     }
796
797     /*
798      * @see IDocument#set(String)
799      */
800     synchronized public void set(String text) {
801       super.set(text);
802     }
803   };
804   //
805   //  private static PHPPartitionScanner HTML_PARTITION_SCANNER = null;
806   //
807   //  private static PHPPartitionScanner PHP_PARTITION_SCANNER = null;
808   //  private static PHPPartitionScanner SMARTY_PARTITION_SCANNER = null;
809   //
810   //  // private final static String[] TYPES= new String[] { PHPPartitionScanner.PHP, PHPPartitionScanner.JAVA_DOC, PHPPartitionScanner.JAVA_MULTILINE_COMMENT };
811   //  private final static String[] TYPES =
812   //    new String[] {
813   //      IPHPPartitionScannerConstants.PHP,
814   //      IPHPPartitionScannerConstants.PHP_MULTILINE_COMMENT,
815   //      IPHPPartitionScannerConstants.HTML,
816   //      IPHPPartitionScannerConstants.HTML_MULTILINE_COMMENT,
817   //      IPHPPartitionScannerConstants.JAVASCRIPT,
818   //      IPHPPartitionScannerConstants.CSS,
819   //      IPHPPartitionScannerConstants.SMARTY,
820   //      IPHPPartitionScannerConstants.SMARTY_MULTILINE_COMMENT };
821   //  private static PHPPartitionScanner XML_PARTITION_SCANNER = null;
822
823   /* Preference key for temporary problems */
824   private final static String HANDLE_TEMPORARY_PROBLEMS = PreferenceConstants.EDITOR_EVALUTE_TEMPORARY_PROBLEMS;
825
826   /** Indicates whether the save has been initialized by this provider */
827   private boolean fIsAboutToSave = false;
828   /** The save policy used by this provider */
829   private ISavePolicy fSavePolicy;
830   /** Internal property changed listener */
831   private IPropertyChangeListener fPropertyListener;
832
833   /** annotation model listener added to all created CU annotation models */
834   private GlobalAnnotationModelListener fGlobalAnnotationModelListener;
835
836   public PHPDocumentProvider() {
837 //      setParentDocumentProvider(new TextFileDocumentProvider(new JavaStorageDocumentProvider()));             
838 //      
839 //      fPropertyListener= new IPropertyChangeListener() {
840 //              public void propertyChange(PropertyChangeEvent event) {
841 //                      if (HANDLE_TEMPORARY_PROBLEMS.equals(event.getProperty()))
842 //                              enableHandlingTemporaryProblems();
843 //              }
844 //      };
845 //      fGlobalAnnotationModelListener= new GlobalAnnotationModelListener();
846 //      PHPeclipsePlugin.getDefault().getPreferenceStore().addPropertyChangeListener(fPropertyListener);
847         
848         IDocumentProvider provider= new TextFileDocumentProvider(new JavaStorageDocumentProvider());
849         provider= new ForwardingDocumentProvider(IPHPPartitions.PHP_PARTITIONING, new JavaDocumentSetupParticipant(), provider);
850         setParentDocumentProvider(provider);
851         
852         fGlobalAnnotationModelListener= new GlobalAnnotationModelListener();
853         fPropertyListener= new IPropertyChangeListener() {
854                 public void propertyChange(PropertyChangeEvent event) {
855                         if (HANDLE_TEMPORARY_PROBLEMS.equals(event.getProperty()))
856                                 enableHandlingTemporaryProblems();
857                 }
858         };
859         PHPeclipsePlugin.getDefault().getPreferenceStore().addPropertyChangeListener(fPropertyListener);
860
861   }
862
863   /**
864    * Sets the document provider's save policy.
865    */
866   public void setSavePolicy(ISavePolicy savePolicy) {
867     fSavePolicy = savePolicy;
868   }
869
870   /**
871    * Creates a compilation unit from the given file.
872    * 
873    * @param file the file from which to create the compilation unit
874    */
875   protected ICompilationUnit createCompilationUnit(IFile file) {
876     Object element = JavaCore.create(file);
877     if (element instanceof ICompilationUnit)
878       return (ICompilationUnit) element;
879     return null;
880   }
881   
882
883   /*
884          * @see org.eclipse.ui.editors.text.TextFileDocumentProvider#createEmptyFileInfo()
885          */
886         protected FileInfo createEmptyFileInfo() {
887                 return new CompilationUnitInfo();
888         }
889         /*
890          * @see org.eclipse.ui.editors.text.TextFileDocumentProvider#createAnnotationModel(org.eclipse.core.resources.IFile)
891          */
892         protected IAnnotationModel createAnnotationModel(IFile file) {
893                 return new CompilationUnitAnnotationModel(file);
894         }
895   /*
896          * @see AbstractDocumentProvider#createElementInfo(Object)
897          */
898 //  protected ElementInfo createElementInfo(Object element) throws CoreException {
899 //
900 //    if (!(element instanceof IFileEditorInput))
901 //      return super.createElementInfo(element);
902 //
903 //    IFileEditorInput input = (IFileEditorInput) element;
904 //    ICompilationUnit original = createCompilationUnit(input.getFile());
905 //    if (original != null) {
906 //
907 //      try {
908 //
909 //        try {
910 //          refreshFile(input.getFile());
911 //        } catch (CoreException x) {
912 //          handleCoreException(x, PHPEditorMessages.getString("PHPDocumentProvider.error.createElementInfo")); //$NON-NLS-1$
913 //        }
914 //
915 //        IAnnotationModel m = createCompilationUnitAnnotationModel(input);
916 //        IProblemRequestor r = m instanceof IProblemRequestor ? (IProblemRequestor) m : null;
917 //        ICompilationUnit c = (ICompilationUnit) original.getSharedWorkingCopy(getProgressMonitor(), fBufferFactory, r);
918 //
919 //        DocumentAdapter a = null;
920 //        try {
921 //          a = (DocumentAdapter) c.getBuffer();
922 //        } catch (ClassCastException x) {
923 //          IStatus status = new Status(IStatus.ERROR, PHPeclipsePlugin.PLUGIN_ID, PHPStatusConstants.TEMPLATE_IO_EXCEPTION, "Shared working copy has wrong buffer", x); //$NON-NLS-1$
924 //          throw new CoreException(status);
925 //        }
926 //
927 //        _FileSynchronizer f = new _FileSynchronizer(input);
928 //        f.install();
929 //
930 //        CompilationUnitInfo info = new CompilationUnitInfo(a.getDocument(), m, f, c);
931 //        info.setModificationStamp(computeModificationStamp(input.getFile()));
932 //        info.fStatus = a.getStatus();
933 //        info.fEncoding = getPersistedEncoding(input);
934 //
935 //        if (r instanceof IProblemRequestorExtension) {
936 //          IProblemRequestorExtension extension = (IProblemRequestorExtension) r;
937 //          extension.setIsActive(isHandlingTemporaryProblems());
938 //        }
939 //        m.addAnnotationModelListener(fGlobalAnnotationModelListener);
940 //
941 //        return info;
942 //
943 //      } catch (JavaModelException x) {
944 //        throw new CoreException(x.getStatus());
945 //      }
946 //    } else {
947 //      return super.createElementInfo(element);
948 //    }
949 //  }
950
951   /*
952    * @see AbstractDocumentProvider#disposeElementInfo(Object, ElementInfo)
953    */
954 //  protected void disposeElementInfo(Object element, ElementInfo info) {
955 //
956 //    if (info instanceof CompilationUnitInfo) {
957 //      CompilationUnitInfo cuInfo = (CompilationUnitInfo) info;
958 //      cuInfo.fCopy.destroy();
959 //      cuInfo.fModel.removeAnnotationModelListener(fGlobalAnnotationModelListener);
960 //    }
961 //
962 //    super.disposeElementInfo(element, info);
963 //  }
964
965   /*
966          * @see AbstractDocumentProvider#doSaveDocument(IProgressMonitor, Object, IDocument, boolean)
967          */
968 //  protected void doSaveDocument(IProgressMonitor monitor, Object element, IDocument document, boolean overwrite)
969 //    throws CoreException {
970 //
971 //    ElementInfo elementInfo = getElementInfo(element);
972 //    if (elementInfo instanceof CompilationUnitInfo) {
973 //      CompilationUnitInfo info = (CompilationUnitInfo) elementInfo;
974 //
975 //      // update structure, assumes lock on info.fCopy
976 //      info.fCopy.reconcile();
977 //
978 //      ICompilationUnit original = (ICompilationUnit) info.fCopy.getOriginalElement();
979 //      IResource resource = original.getResource();
980 //
981 //      if (resource == null) {
982 //        // underlying resource has been deleted, just recreate file, ignore the rest
983 //        super.doSaveDocument(monitor, element, document, overwrite);
984 //        return;
985 //      }
986 //
987 //      if (resource != null && !overwrite)
988 //        checkSynchronizationState(info.fModificationStamp, resource);
989 //
990 //      if (fSavePolicy != null)
991 //        fSavePolicy.preSave(info.fCopy);
992 //
993 //      // inform about the upcoming content change
994 //      fireElementStateChanging(element);
995 //      try {
996 //        fIsAboutToSave = true;
997 //        // commit working copy
998 //        info.fCopy.commit(overwrite, monitor);
999 //      } catch (CoreException x) {
1000 //        // inform about the failure
1001 //        fireElementStateChangeFailed(element);
1002 //        throw x;
1003 //      } catch (RuntimeException x) {
1004 //        // inform about the failure
1005 //        fireElementStateChangeFailed(element);
1006 //        throw x;
1007 //      } finally {
1008 //        fIsAboutToSave = false;
1009 //      }
1010 //
1011 //      // If here, the dirty state of the editor will change to "not dirty".
1012 //      // Thus, the state changing flag will be reset.
1013 //
1014 //      AbstractMarkerAnnotationModel model = (AbstractMarkerAnnotationModel) info.fModel;
1015 //      model.updateMarkers(info.fDocument);
1016 //
1017 //      if (resource != null)
1018 //        info.setModificationStamp(computeModificationStamp(resource));
1019 //
1020 //      if (fSavePolicy != null) {
1021 //        ICompilationUnit unit = fSavePolicy.postSave(original);
1022 //        if (unit != null) {
1023 //          IResource r = unit.getResource();
1024 //          IMarker[] markers = r.findMarkers(IMarker.MARKER, true, IResource.DEPTH_ZERO);
1025 //          if (markers != null && markers.length > 0) {
1026 //            for (int i = 0; i < markers.length; i++)
1027 //              model.updateMarker(markers[i], info.fDocument, null);
1028 //          }
1029 //        }
1030 //      }
1031 //
1032 //    } else {
1033 //      super.doSaveDocument(monitor, element, document, overwrite);
1034 //    }
1035 //  }
1036
1037         /*
1038          * @see org.eclipse.ui.editors.text.TextFileDocumentProvider#createFileInfo(java.lang.Object)
1039          */
1040         protected FileInfo createFileInfo(Object element) throws CoreException {
1041                 if (!(element instanceof IFileEditorInput))
1042                         return null;
1043                         
1044                 IFileEditorInput input= (IFileEditorInput) element;
1045                 ICompilationUnit original= createCompilationUnit(input.getFile());
1046                 if (original == null)
1047                         return null;
1048                 
1049                 FileInfo info= super.createFileInfo(element);
1050                 if (!(info instanceof CompilationUnitInfo))
1051                         return null;
1052                         
1053                 CompilationUnitInfo cuInfo= (CompilationUnitInfo) info;
1054                 setUpSynchronization(cuInfo);
1055                         
1056                 IProblemRequestor requestor= cuInfo.fModel instanceof IProblemRequestor ? (IProblemRequestor) cuInfo.fModel : null;
1057
1058                 original.becomeWorkingCopy(requestor, getProgressMonitor());
1059                 cuInfo.fCopy= original;
1060                 
1061                 if (cuInfo.fModel instanceof CompilationUnitAnnotationModel)   {
1062                         CompilationUnitAnnotationModel model= (CompilationUnitAnnotationModel) cuInfo.fModel;
1063                         model.setCompilationUnit(cuInfo.fCopy);
1064                 } 
1065                 
1066                 if (cuInfo.fModel != null)
1067                         cuInfo.fModel.addAnnotationModelListener(fGlobalAnnotationModelListener);
1068                 
1069                 if (requestor instanceof IProblemRequestorExtension) {
1070                         IProblemRequestorExtension extension= (IProblemRequestorExtension) requestor;
1071                         extension.setIsActive(isHandlingTemporaryProblems());
1072                 }
1073                 
1074                 return cuInfo;
1075         }
1076         
1077     private void setUpSynchronization(CompilationUnitInfo cuInfo) {
1078         IDocument document= cuInfo.fTextFileBuffer.getDocument();
1079         IAnnotationModel model= cuInfo.fModel;
1080         
1081         if (document instanceof ISynchronizable && model instanceof ISynchronizable) {
1082             Object lock= ((ISynchronizable) document).getLockObject();
1083             ((ISynchronizable) model).setLockObject(lock);
1084         }
1085     }
1086     
1087     /*
1088          * @see org.eclipse.ui.editors.text.TextFileDocumentProvider#disposeFileInfo(java.lang.Object, org.eclipse.ui.editors.text.TextFileDocumentProvider.FileInfo)
1089          */
1090         protected void disposeFileInfo(Object element, FileInfo info) {
1091                 if (info instanceof CompilationUnitInfo) {
1092                         CompilationUnitInfo cuInfo= (CompilationUnitInfo) info;
1093                         
1094                         try  {
1095                             cuInfo.fCopy.discardWorkingCopy();
1096                         } catch (JavaModelException x)  {
1097                             handleCoreException(x, x.getMessage());
1098                         }                       
1099                         
1100                         if (cuInfo.fModel != null)
1101                                 cuInfo.fModel.removeAnnotationModelListener(fGlobalAnnotationModelListener);
1102                 }
1103                 super.disposeFileInfo(element, info);
1104         }
1105         
1106   protected void commitWorkingCopy(IProgressMonitor monitor, Object element, CompilationUnitInfo info, boolean overwrite) throws CoreException {
1107     synchronized (info.fCopy) {
1108                 info.fCopy.reconcile();
1109         }
1110         
1111         IDocument document= info.fTextFileBuffer.getDocument();
1112         IResource resource= info.fCopy.getResource();
1113         
1114         Assert.isTrue(resource instanceof IFile);
1115         if (!resource.exists()) {
1116                 // underlying resource has been deleted, just recreate file, ignore the rest
1117                 createFileFromDocument(monitor, (IFile) resource, document);
1118                 return;
1119         }
1120         
1121         if (fSavePolicy != null)
1122                 fSavePolicy.preSave(info.fCopy);
1123         
1124         try {
1125                 
1126                 fIsAboutToSave= true;
1127                 info.fCopy.commitWorkingCopy(overwrite, monitor);
1128                         
1129         } catch (CoreException x) {
1130                 // inform about the failure
1131                 fireElementStateChangeFailed(element);
1132                 throw x;
1133         } catch (RuntimeException x) {
1134                 // inform about the failure
1135                 fireElementStateChangeFailed(element);
1136                 throw x;
1137         } finally {
1138                 fIsAboutToSave= false;
1139         }
1140         
1141         // If here, the dirty state of the editor will change to "not dirty".
1142         // Thus, the state changing flag will be reset.
1143         if (info.fModel instanceof AbstractMarkerAnnotationModel) {
1144                 AbstractMarkerAnnotationModel model= (AbstractMarkerAnnotationModel) info.fModel;
1145                 model.updateMarkers(document);
1146         }
1147         
1148         if (fSavePolicy != null) {
1149                 ICompilationUnit unit= fSavePolicy.postSave(info.fCopy);
1150                 if (unit != null && info.fModel instanceof AbstractMarkerAnnotationModel) {
1151                         IResource r= unit.getResource();
1152                         IMarker[] markers= r.findMarkers(IMarker.MARKER, true, IResource.DEPTH_ZERO);
1153                         if (markers != null && markers.length > 0) {
1154                                 AbstractMarkerAnnotationModel model= (AbstractMarkerAnnotationModel) info.fModel;                                               
1155                                 for (int i= 0; i < markers.length; i++)
1156                                         model.updateMarker(document, markers[i], null);
1157                         }
1158                 }
1159         }
1160         
1161 }
1162
1163 /*
1164  * @see org.eclipse.ui.editors.text.TextFileDocumentProvider#createSaveOperation(java.lang.Object, org.eclipse.jface.text.IDocument, boolean)
1165  */
1166 protected DocumentProviderOperation createSaveOperation(final Object element, final IDocument document, final boolean overwrite) throws CoreException {
1167 //      final FileInfo info= getFileInfo(element);
1168 //      if (info instanceof CompilationUnitInfo) {
1169 //              return new DocumentProviderOperation() {
1170 //                      /*
1171 //                       * @see org.eclipse.ui.editors.text.TextFileDocumentProvider.DocumentProviderOperation#execute(org.eclipse.core.runtime.IProgressMonitor)
1172 //                       */
1173 //                      protected void execute(IProgressMonitor monitor) throws CoreException {
1174 //                              commitWorkingCopy(monitor, element, (CompilationUnitInfo) info, overwrite);
1175 //                      }
1176 //                      /*
1177 //                       * @see org.eclipse.ui.editors.text.TextFileDocumentProvider.DocumentProviderOperation#getSchedulingRule()
1178 //                       */
1179 //                      public ISchedulingRule getSchedulingRule() {
1180 //                              if (info.fElement instanceof IFileEditorInput) {
1181 //                                      IFile file= ((IFileEditorInput) info.fElement).getFile();
1182 //                                      IResourceRuleFactory ruleFactory= ResourcesPlugin.getWorkspace().getRuleFactory();
1183 //                                      if (file == null || !file.exists())
1184 //                                              return ruleFactory.createRule(file);
1185 //                                      else
1186 //                                              return ruleFactory.modifyRule(file);
1187 //                              } else
1188 //                                      return null;
1189 //                      }
1190 //              };
1191 //      }
1192 //      return null;
1193         final FileInfo info= getFileInfo(element);
1194         if (info instanceof CompilationUnitInfo) {
1195                 return new DocumentProviderOperation() {
1196                         /*
1197                          * @see org.eclipse.ui.editors.text.TextFileDocumentProvider.DocumentProviderOperation#execute(org.eclipse.core.runtime.IProgressMonitor)
1198                          */
1199                         protected void execute(IProgressMonitor monitor) throws CoreException {
1200                                 commitWorkingCopy(monitor, element, (CompilationUnitInfo) info, overwrite);
1201                         }
1202                         /*
1203                          * @see org.eclipse.ui.editors.text.TextFileDocumentProvider.DocumentProviderOperation#getSchedulingRule()
1204                          */
1205                         public ISchedulingRule getSchedulingRule() {
1206                                 if (info.fElement instanceof IFileEditorInput) {
1207                                         IFile file= ((IFileEditorInput) info.fElement).getFile();
1208                                         return computeSchedulingRule(file);
1209                                 } else
1210                                         return null;
1211                         }
1212                 };
1213         }
1214         return null;
1215 }
1216
1217   /* (non-Javadoc)
1218    * Method declared on AbstractDocumentProvider
1219    */
1220 //  protected IDocument createDocument(Object element) throws CoreException {
1221 //    if (element instanceof IEditorInput) {
1222 //      Document document = new PartiallySynchronizedDocument();
1223 //      if (setDocumentContent(document, (IEditorInput) element, getEncoding(element))) {
1224 //        initializeDocument(document, (IEditorInput) element);
1225 //
1226 //        //    
1227 //        //    IDocument document = super.createDocument(element);
1228 //        //    if (document != null) {
1229 //        //        IDocumentPartitioner partitioner = null;
1230 //        //        if (element instanceof FileEditorInput) {
1231 //        //          IFile file = (IFile) ((FileEditorInput) element).getAdapter(IFile.class);
1232 //        //          String filename = file.getLocation().toString();
1233 //        //          String extension = filename.substring(filename.lastIndexOf("."), filename.length());
1234 //        //          //   System.out.println(extension);
1235 //        //          if (extension.equalsIgnoreCase(".html") || extension.equalsIgnoreCase(".htm")) {
1236 //        //            // html
1237 //        //            partitioner = createHTMLPartitioner();
1238 //        //          } else if (extension.equalsIgnoreCase(".xml")) {
1239 //        //            // xml
1240 //        //            partitioner = createXMLPartitioner();
1241 //        //          } else if (extension.equalsIgnoreCase(".js")) {
1242 //        //            // javascript
1243 //        //            partitioner = createJavaScriptPartitioner();
1244 //        //          } else if (extension.equalsIgnoreCase(".css")) {
1245 //        //            // cascading style sheets
1246 //        //            partitioner = createCSSPartitioner();
1247 //        //          } else if (extension.equalsIgnoreCase(".tpl")) {
1248 //        //            // smarty ?
1249 //        //            partitioner = createSmartyPartitioner();
1250 //        //          } else if (extension.equalsIgnoreCase(".inc")) {
1251 //        //            // php include files ?
1252 //        //            partitioner = createIncludePartitioner();
1253 //        //          }
1254 //        //        }
1255 //        //
1256 //        //        if (partitioner == null) {
1257 //        //          partitioner = createPHPPartitioner();
1258 //        //        }
1259 //        //        document.setDocumentPartitioner(partitioner);
1260 //        //        partitioner.connect(document);
1261 //      }
1262 //      return document;
1263 //    }
1264 //    return null;
1265 //  }
1266
1267   //  /**
1268   //   * Return a partitioner for .html files.
1269   //   */
1270   //  private IDocumentPartitioner createHTMLPartitioner() {
1271   //    return new DefaultPartitioner(getHTMLPartitionScanner(), TYPES);
1272   //  }
1273   //
1274   //  private IDocumentPartitioner createIncludePartitioner() {
1275   //    return new DefaultPartitioner(getPHPPartitionScanner(), TYPES);
1276   //  }
1277   //
1278   //  private IDocumentPartitioner createJavaScriptPartitioner() {
1279   //    return new DefaultPartitioner(getHTMLPartitionScanner(), TYPES);
1280   //  }
1281
1282   /**
1283    * Creates a line tracker working with the same line delimiters as the document
1284    * of the given element. Assumes the element to be managed by this document provider.
1285    * 
1286    * @param element the element serving as blue print
1287    * @return a line tracker based on the same line delimiters as the element's document
1288    */
1289   public ILineTracker createLineTracker(Object element) {
1290     return new DefaultLineTracker();
1291   }
1292
1293   //  /**
1294   //   * Return a partitioner for .php files.
1295   //   */
1296   //  private IDocumentPartitioner createPHPPartitioner() {
1297   //    return new DefaultPartitioner(getPHPPartitionScanner(), TYPES);
1298   //  }
1299   //
1300   //  private IDocumentPartitioner createSmartyPartitioner() {
1301   //    return new DefaultPartitioner(getSmartyPartitionScanner(), TYPES);
1302   //  }
1303   //
1304   //  private IDocumentPartitioner createXMLPartitioner() {
1305   //    return new DefaultPartitioner(getXMLPartitionScanner(), TYPES);
1306   //  }
1307   //
1308   //  /**
1309   //   * Return a scanner for creating html partitions.
1310   //   */
1311   //  private PHPPartitionScanner getHTMLPartitionScanner() {
1312   //    if (HTML_PARTITION_SCANNER == null)
1313   //      HTML_PARTITION_SCANNER = new PHPPartitionScanner(IPHPPartitionScannerConstants.HTML_FILE);
1314   //    return HTML_PARTITION_SCANNER;
1315   //  }
1316   //  /**
1317   //   * Return a scanner for creating php partitions.
1318   //   */
1319   //  private PHPPartitionScanner getPHPPartitionScanner() {
1320   //    if (PHP_PARTITION_SCANNER == null)
1321   //      PHP_PARTITION_SCANNER = new PHPPartitionScanner(IPHPPartitionScannerConstants.PHP_FILE);
1322   //    return PHP_PARTITION_SCANNER;
1323   //  }
1324   //
1325   //  /**
1326   //   * Return a scanner for creating smarty partitions.
1327   //   */
1328   //  private PHPPartitionScanner getSmartyPartitionScanner() {
1329   //    if (SMARTY_PARTITION_SCANNER == null)
1330   //      SMARTY_PARTITION_SCANNER = new PHPPartitionScanner(IPHPPartitionScannerConstants.SMARTY_FILE);
1331   //    return SMARTY_PARTITION_SCANNER;
1332   //  }
1333   //
1334   //  /**
1335   //   * Return a scanner for creating xml partitions.
1336   //   */
1337   //  private PHPPartitionScanner getXMLPartitionScanner() {
1338   //    if (XML_PARTITION_SCANNER == null)
1339   //      XML_PARTITION_SCANNER = new PHPPartitionScanner(IPHPPartitionScannerConstants.XML_FILE);
1340   //    return XML_PARTITION_SCANNER;
1341   //  }
1342
1343 //  protected void initializeDocument(IDocument document, IEditorInput editorInput) {
1344 //    if (document != null) {
1345 //      JavaTextTools tools = PHPeclipsePlugin.getDefault().getJavaTextTools();
1346 //      IDocumentPartitioner partitioner = null;
1347 //      if (editorInput != null && editorInput instanceof FileEditorInput) {
1348 //        IFile file = (IFile) ((FileEditorInput) editorInput).getAdapter(IFile.class);
1349 //        String filename = file.getLocation().toString();
1350 //        String extension = filename.substring(filename.lastIndexOf("."), filename.length());
1351 //        partitioner = tools.createDocumentPartitioner(extension);
1352 //      } else {
1353 //        partitioner = tools.createDocumentPartitioner(".php");
1354 //      }
1355 //      document.setDocumentPartitioner(partitioner);
1356 //      partitioner.connect(document);
1357 //    }
1358 //  }
1359
1360   /*
1361    * @see org.eclipse.ui.texteditor.AbstractDocumentProvider#doResetDocument(java.lang.Object, org.eclipse.core.runtime.IProgressMonitor)
1362    */
1363 //  protected void doResetDocument(Object element, IProgressMonitor monitor) throws CoreException {
1364 //    if (element == null)
1365 //      return;
1366 //    
1367 //    ElementInfo elementInfo= getElementInfo(element);         
1368 //    if (elementInfo instanceof CompilationUnitInfo) {
1369 //      CompilationUnitInfo info= (CompilationUnitInfo) elementInfo;
1370 //      
1371 //      IDocument document;
1372 //      IStatus status= null;
1373 //      
1374 //      try {
1375 //        
1376 //        ICompilationUnit original= (ICompilationUnit) info.fCopy.getOriginalElement();
1377 //        IResource resource= original.getResource();
1378 //        if (resource instanceof IFile) {
1379 //          
1380 //          IFile file= (IFile) resource;
1381 //          
1382 //          try {
1383 //            refreshFile(file, monitor);
1384 //          } catch (CoreException x) {
1385 //            handleCoreException(x, PHPEditorMessages.getString("CompilationUnitDocumentProvider.error.resetDocument")); //$NON-NLS-1$
1386 //          }
1387 //          
1388 //          IFileEditorInput input= new FileEditorInput(file);
1389 //          document= super.createDocument(input);
1390 //          
1391 //        } else {
1392 //          document= createEmptyDocument();
1393 //        }
1394 //        
1395 //      } catch (CoreException x) {
1396 //        document= createEmptyDocument();
1397 //        status= x.getStatus();
1398 //      }
1399 //      
1400 //      fireElementContentAboutToBeReplaced(element);
1401 //      
1402 //      removeUnchangedElementListeners(element, info);
1403 //      info.fDocument.set(document.get());
1404 //      info.fCanBeSaved= false;
1405 //      info.fStatus= status;
1406 //      addUnchangedElementListeners(element, info);
1407 //      
1408 //      fireElementContentReplaced(element);
1409 //      fireElementDirtyStateChanged(element, false);
1410 //      
1411 //    } else {
1412 //      super.doResetDocument(element, monitor);
1413 //    }
1414 //  }
1415   
1416   /*
1417    * @see AbstractDocumentProvider#resetDocument(Object)
1418    */
1419 //  public void resetDocument(Object element) throws CoreException {
1420 //    if (element == null)
1421 //      return;
1422 //
1423 //    ElementInfo elementInfo = getElementInfo(element);
1424 //    if (elementInfo instanceof CompilationUnitInfo) {
1425 //      CompilationUnitInfo info = (CompilationUnitInfo) elementInfo;
1426 //
1427 //      IDocument document;
1428 //      IStatus status = null;
1429 //
1430 //      try {
1431 //
1432 //        ICompilationUnit original = (ICompilationUnit) info.fCopy.getOriginalElement();
1433 //        IResource resource = original.getResource();
1434 //        if (resource instanceof IFile) {
1435 //
1436 //          IFile file = (IFile) resource;
1437 //
1438 //          try {
1439 //            refreshFile(file);
1440 //          } catch (CoreException x) {
1441 //            handleCoreException(x, PHPEditorMessages.getString("PHPDocumentProvider.error.resetDocument")); //$NON-NLS-1$
1442 //          }
1443 //
1444 //          IFileEditorInput input = new FileEditorInput(file);
1445 //          document = super.createDocument(input);
1446 //
1447 //        } else {
1448 //          document = new Document();
1449 //        }
1450 //
1451 //      } catch (CoreException x) {
1452 //        document = new Document();
1453 //        status = x.getStatus();
1454 //      }
1455 //
1456 //      fireElementContentAboutToBeReplaced(element);
1457 //
1458 //      removeUnchangedElementListeners(element, info);
1459 //      info.fDocument.set(document.get());
1460 //      info.fCanBeSaved = false;
1461 //      info.fStatus = status;
1462 //      addUnchangedElementListeners(element, info);
1463 //
1464 //      fireElementContentReplaced(element);
1465 //      fireElementDirtyStateChanged(element, false);
1466 //
1467 //    } else {
1468 //      super.resetDocument(element);
1469 //    }
1470 //  }
1471   /**
1472          * Saves the content of the given document to the given element.
1473          * This is only performed when this provider initiated the save.
1474          * 
1475          * @param monitor the progress monitor
1476          * @param element the element to which to save
1477          * @param document the document to save
1478          * @param overwrite <code>true</code> if the save should be enforced
1479          */
1480   public void saveDocumentContent(IProgressMonitor monitor, Object element, IDocument document, boolean overwrite)
1481     throws CoreException {
1482         if (!fIsAboutToSave)
1483                 return;
1484         super.saveDocument(monitor, element, document, overwrite);
1485 //    if (!fIsAboutToSave)
1486 //      return;
1487 //
1488 //    if (element instanceof IFileEditorInput) {
1489 //      IFileEditorInput input = (IFileEditorInput) element;
1490 //      try {
1491 //        String encoding = getEncoding(element);
1492 //        if (encoding == null)
1493 //          encoding = ResourcesPlugin.getEncoding();
1494 //        InputStream stream = new ByteArrayInputStream(document.get().getBytes(encoding));
1495 //        IFile file = input.getFile();
1496 //        file.setContents(stream, overwrite, true, monitor);
1497 //      } catch (IOException x) {
1498 //        IStatus s = new Status(IStatus.ERROR, PHPeclipsePlugin.PLUGIN_ID, IStatus.OK, x.getMessage(), x);
1499 //        throw new CoreException(s);
1500 //      }
1501 //    }
1502   }
1503   /**
1504    * Returns the underlying resource for the given element.
1505    * 
1506    * @param the element
1507    * @return the underlying resource of the given element
1508    */
1509 //  public IResource getUnderlyingResource(Object element) {
1510 //    if (element instanceof IFileEditorInput) {
1511 //      IFileEditorInput input = (IFileEditorInput) element;
1512 //      return input.getFile();
1513 //    }
1514 //    return null;
1515 //  }
1516
1517         /*
1518          * @see org.eclipse.jdt.internal.ui.javaeditor.ICompilationUnitDocumentProvider#getWorkingCopy(java.lang.Object)
1519          */
1520         public ICompilationUnit getWorkingCopy(Object element) {
1521                 FileInfo fileInfo= getFileInfo(element);                
1522                 if (fileInfo instanceof CompilationUnitInfo) {
1523                         CompilationUnitInfo info= (CompilationUnitInfo) fileInfo;
1524                         return info.fCopy;
1525                 }
1526                 return null;
1527         }
1528
1529
1530   /*
1531          * @see org.eclipse.jdt.internal.ui.javaeditor.ICompilationUnitDocumentProvider#shutdown()
1532          */
1533         public void shutdown() {
1534                 PHPeclipsePlugin.getDefault().getPreferenceStore().removePropertyChangeListener(fPropertyListener);
1535                 Iterator e= getConnectedElementsIterator();
1536                 while (e.hasNext())
1537                         disconnect(e.next());
1538         }
1539
1540   /**
1541    * Returns the preference whether handling temporary problems is enabled.
1542    */
1543   protected boolean isHandlingTemporaryProblems() {
1544     IPreferenceStore store = PHPeclipsePlugin.getDefault().getPreferenceStore();
1545     return store.getBoolean(HANDLE_TEMPORARY_PROBLEMS);
1546   }
1547
1548   /**
1549          * Switches the state of problem acceptance according to the value in the preference store.
1550          */
1551         protected void enableHandlingTemporaryProblems() {
1552                 boolean enable= isHandlingTemporaryProblems();
1553                 for (Iterator iter= getFileInfosIterator(); iter.hasNext();) {
1554                         FileInfo info= (FileInfo) iter.next();
1555                         if (info.fModel instanceof IProblemRequestorExtension) {
1556                                 IProblemRequestorExtension  extension= (IProblemRequestorExtension) info.fModel;
1557                                 extension.setIsActive(enable);
1558                         }
1559                 }
1560         }
1561
1562   /**
1563    * Adds a listener that reports changes from all compilation unit annotation models.
1564    */
1565   public void addGlobalAnnotationModelListener(IAnnotationModelListener listener) {
1566     fGlobalAnnotationModelListener.addListener(listener);
1567   }
1568
1569   /**
1570    * Removes the listener.
1571    */
1572   public void removeGlobalAnnotationModelListener(IAnnotationModelListener listener) {
1573     fGlobalAnnotationModelListener.removeListener(listener);
1574   }
1575  
1576         /**
1577          * Computes the scheduling rule needed to create or modify a resource. If
1578          * the resource exists, its modify rule is returned. If it does not, the 
1579          * resource hierarchy is iterated towards the workspace root to find the
1580          * first parent of <code>toCreateOrModify</code> that exists. Then the
1581          * 'create' rule for the last non-existing resource is returned.
1582          * <p>
1583          * XXX This is a workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=67601
1584          * IResourceRuleFactory.createRule should iterate the hierarchy itself. 
1585          * </p>
1586          * <p> 
1587          * XXX to be replaced by call to TextFileDocumentProvider.computeSchedulingRule after 3.0
1588          * </p>
1589          * 
1590          * @param toCreateOrModify the resource to create or modify
1591          * @return the minimal scheduling rule needed to modify or create a resource
1592          */
1593         private ISchedulingRule computeSchedulingRule(IResource toCreateOrModify) {
1594                 IResourceRuleFactory factory= ResourcesPlugin.getWorkspace().getRuleFactory();
1595                 if (toCreateOrModify.exists()) {
1596                         return factory.modifyRule(toCreateOrModify);
1597                 } else {
1598                         IResource parent= toCreateOrModify;
1599                         do {
1600                                 toCreateOrModify= parent;
1601                                 parent= toCreateOrModify.getParent();
1602                         } while (parent != null && !parent.exists());
1603                         
1604                         return factory.createRule(toCreateOrModify);
1605                 }
1606         }
1607 }