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