Added some examples for context menu on Outline
[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 net.sourceforge.phpdt.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 net.sourceforge.phpdt.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 net.sourceforge.phpdt.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 net.sourceforge.phpdt.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 //      IDocumentProvider provider= new TextFileDocumentProvider(new JavaStorageDocumentProvider());
838         IDocumentProvider provider= new TextFileDocumentProvider();
839         provider= new ForwardingDocumentProvider(IPHPPartitions.PHP_PARTITIONING, new JavaDocumentSetupParticipant(), provider);
840         setParentDocumentProvider(provider);
841
842         fGlobalAnnotationModelListener= new GlobalAnnotationModelListener();
843         fPropertyListener= new IPropertyChangeListener() {
844                 public void propertyChange(PropertyChangeEvent event) {
845                         if (HANDLE_TEMPORARY_PROBLEMS.equals(event.getProperty()))
846                                 enableHandlingTemporaryProblems();
847                 }
848         };
849         PHPeclipsePlugin.getDefault().getPreferenceStore().addPropertyChangeListener(fPropertyListener);
850
851   }
852
853   /**
854    * Sets the document provider's save policy.
855    */
856   public void setSavePolicy(ISavePolicy savePolicy) {
857     fSavePolicy = savePolicy;
858   }
859
860   /**
861    * Creates a compilation unit from the given file.
862    *
863    * @param file the file from which to create the compilation unit
864    */
865   protected ICompilationUnit createCompilationUnit(IFile file) {
866     Object element = JavaCore.create(file);
867     if (element instanceof ICompilationUnit)
868       return (ICompilationUnit) element;
869     return null;
870   }
871
872
873   /*
874          * @see org.eclipse.ui.editors.text.TextFileDocumentProvider#createEmptyFileInfo()
875          */
876         protected FileInfo createEmptyFileInfo() {
877                 return new CompilationUnitInfo();
878         }
879         /*
880          * @see org.eclipse.ui.editors.text.TextFileDocumentProvider#createAnnotationModel(org.eclipse.core.resources.IFile)
881          */
882         protected IAnnotationModel createAnnotationModel(IFile file) {
883                 return new CompilationUnitAnnotationModel(file);
884         }
885   /*
886          * @see AbstractDocumentProvider#createElementInfo(Object)
887          */
888 //  protected ElementInfo createElementInfo(Object element) throws CoreException {
889 //
890 //    if (!(element instanceof IFileEditorInput))
891 //      return super.createElementInfo(element);
892 //
893 //    IFileEditorInput input = (IFileEditorInput) element;
894 //    ICompilationUnit original = createCompilationUnit(input.getFile());
895 //    if (original != null) {
896 //
897 //      try {
898 //
899 //        try {
900 //          refreshFile(input.getFile());
901 //        } catch (CoreException x) {
902 //          handleCoreException(x, PHPEditorMessages.getString("PHPDocumentProvider.error.createElementInfo")); //$NON-NLS-1$
903 //        }
904 //
905 //        IAnnotationModel m = createCompilationUnitAnnotationModel(input);
906 //        IProblemRequestor r = m instanceof IProblemRequestor ? (IProblemRequestor) m : null;
907 //        ICompilationUnit c = (ICompilationUnit) original.getSharedWorkingCopy(getProgressMonitor(), fBufferFactory, r);
908 //
909 //        DocumentAdapter a = null;
910 //        try {
911 //          a = (DocumentAdapter) c.getBuffer();
912 //        } catch (ClassCastException x) {
913 //          IStatus status = new Status(IStatus.ERROR, PHPeclipsePlugin.PLUGIN_ID, PHPStatusConstants.TEMPLATE_IO_EXCEPTION, "Shared working copy has wrong buffer", x); //$NON-NLS-1$
914 //          throw new CoreException(status);
915 //        }
916 //
917 //        _FileSynchronizer f = new _FileSynchronizer(input);
918 //        f.install();
919 //
920 //        CompilationUnitInfo info = new CompilationUnitInfo(a.getDocument(), m, f, c);
921 //        info.setModificationStamp(computeModificationStamp(input.getFile()));
922 //        info.fStatus = a.getStatus();
923 //        info.fEncoding = getPersistedEncoding(input);
924 //
925 //        if (r instanceof IProblemRequestorExtension) {
926 //          IProblemRequestorExtension extension = (IProblemRequestorExtension) r;
927 //          extension.setIsActive(isHandlingTemporaryProblems());
928 //        }
929 //        m.addAnnotationModelListener(fGlobalAnnotationModelListener);
930 //
931 //        return info;
932 //
933 //      } catch (JavaModelException x) {
934 //        throw new CoreException(x.getStatus());
935 //      }
936 //    } else {
937 //      return super.createElementInfo(element);
938 //    }
939 //  }
940
941   /*
942    * @see AbstractDocumentProvider#disposeElementInfo(Object, ElementInfo)
943    */
944 //  protected void disposeElementInfo(Object element, ElementInfo info) {
945 //
946 //    if (info instanceof CompilationUnitInfo) {
947 //      CompilationUnitInfo cuInfo = (CompilationUnitInfo) info;
948 //      cuInfo.fCopy.destroy();
949 //      cuInfo.fModel.removeAnnotationModelListener(fGlobalAnnotationModelListener);
950 //    }
951 //
952 //    super.disposeElementInfo(element, info);
953 //  }
954
955   /*
956          * @see AbstractDocumentProvider#doSaveDocument(IProgressMonitor, Object, IDocument, boolean)
957          */
958 //  protected void doSaveDocument(IProgressMonitor monitor, Object element, IDocument document, boolean overwrite)
959 //    throws CoreException {
960 //
961 //    ElementInfo elementInfo = getElementInfo(element);
962 //    if (elementInfo instanceof CompilationUnitInfo) {
963 //      CompilationUnitInfo info = (CompilationUnitInfo) elementInfo;
964 //
965 //      // update structure, assumes lock on info.fCopy
966 //      info.fCopy.reconcile();
967 //
968 //      ICompilationUnit original = (ICompilationUnit) info.fCopy.getOriginalElement();
969 //      IResource resource = original.getResource();
970 //
971 //      if (resource == null) {
972 //        // underlying resource has been deleted, just recreate file, ignore the rest
973 //        super.doSaveDocument(monitor, element, document, overwrite);
974 //        return;
975 //      }
976 //
977 //      if (resource != null && !overwrite)
978 //        checkSynchronizationState(info.fModificationStamp, resource);
979 //
980 //      if (fSavePolicy != null)
981 //        fSavePolicy.preSave(info.fCopy);
982 //
983 //      // inform about the upcoming content change
984 //      fireElementStateChanging(element);
985 //      try {
986 //        fIsAboutToSave = true;
987 //        // commit working copy
988 //        info.fCopy.commit(overwrite, monitor);
989 //      } catch (CoreException x) {
990 //        // inform about the failure
991 //        fireElementStateChangeFailed(element);
992 //        throw x;
993 //      } catch (RuntimeException x) {
994 //        // inform about the failure
995 //        fireElementStateChangeFailed(element);
996 //        throw x;
997 //      } finally {
998 //        fIsAboutToSave = false;
999 //      }
1000 //
1001 //      // If here, the dirty state of the editor will change to "not dirty".
1002 //      // Thus, the state changing flag will be reset.
1003 //
1004 //      AbstractMarkerAnnotationModel model = (AbstractMarkerAnnotationModel) info.fModel;
1005 //      model.updateMarkers(info.fDocument);
1006 //
1007 //      if (resource != null)
1008 //        info.setModificationStamp(computeModificationStamp(resource));
1009 //
1010 //      if (fSavePolicy != null) {
1011 //        ICompilationUnit unit = fSavePolicy.postSave(original);
1012 //        if (unit != null) {
1013 //          IResource r = unit.getResource();
1014 //          IMarker[] markers = r.findMarkers(IMarker.MARKER, true, IResource.DEPTH_ZERO);
1015 //          if (markers != null && markers.length > 0) {
1016 //            for (int i = 0; i < markers.length; i++)
1017 //              model.updateMarker(markers[i], info.fDocument, null);
1018 //          }
1019 //        }
1020 //      }
1021 //
1022 //    } else {
1023 //      super.doSaveDocument(monitor, element, document, overwrite);
1024 //    }
1025 //  }
1026
1027         /*
1028          * @see org.eclipse.ui.editors.text.TextFileDocumentProvider#createFileInfo(java.lang.Object)
1029          */
1030         protected FileInfo createFileInfo(Object element) throws CoreException {
1031                 if (!(element instanceof IFileEditorInput))
1032                         return null;
1033
1034                 IFileEditorInput input= (IFileEditorInput) element;
1035                 ICompilationUnit original= createCompilationUnit(input.getFile());
1036                 if (original == null)
1037                         return null;
1038
1039                 FileInfo info= super.createFileInfo(element);
1040                 if (!(info instanceof CompilationUnitInfo))
1041                         return null;
1042
1043                 CompilationUnitInfo cuInfo= (CompilationUnitInfo) info;
1044                 setUpSynchronization(cuInfo);
1045
1046                 IProblemRequestor requestor= cuInfo.fModel instanceof IProblemRequestor ? (IProblemRequestor) cuInfo.fModel : null;
1047
1048                 original.becomeWorkingCopy(requestor, getProgressMonitor());
1049                 cuInfo.fCopy= original;
1050
1051                 if (cuInfo.fModel instanceof CompilationUnitAnnotationModel)   {
1052                         CompilationUnitAnnotationModel model= (CompilationUnitAnnotationModel) cuInfo.fModel;
1053                         model.setCompilationUnit(cuInfo.fCopy);
1054                 }
1055
1056                 if (cuInfo.fModel != null)
1057                         cuInfo.fModel.addAnnotationModelListener(fGlobalAnnotationModelListener);
1058
1059                 if (requestor instanceof IProblemRequestorExtension) {
1060                         IProblemRequestorExtension extension= (IProblemRequestorExtension) requestor;
1061                         extension.setIsActive(isHandlingTemporaryProblems());
1062                 }
1063
1064                 return cuInfo;
1065         }
1066
1067     private void setUpSynchronization(CompilationUnitInfo cuInfo) {
1068         IDocument document= cuInfo.fTextFileBuffer.getDocument();
1069         IAnnotationModel model= cuInfo.fModel;
1070
1071         if (document instanceof ISynchronizable && model instanceof ISynchronizable) {
1072             Object lock= ((ISynchronizable) document).getLockObject();
1073             ((ISynchronizable) model).setLockObject(lock);
1074         }
1075     }
1076
1077     /*
1078          * @see org.eclipse.ui.editors.text.TextFileDocumentProvider#disposeFileInfo(java.lang.Object, org.eclipse.ui.editors.text.TextFileDocumentProvider.FileInfo)
1079          */
1080         protected void disposeFileInfo(Object element, FileInfo info) {
1081                 if (info instanceof CompilationUnitInfo) {
1082                         CompilationUnitInfo cuInfo= (CompilationUnitInfo) info;
1083
1084                         try  {
1085                             cuInfo.fCopy.discardWorkingCopy();
1086                         } catch (JavaModelException x)  {
1087                             handleCoreException(x, x.getMessage());
1088                         }
1089
1090                         if (cuInfo.fModel != null)
1091                                 cuInfo.fModel.removeAnnotationModelListener(fGlobalAnnotationModelListener);
1092                 }
1093                 super.disposeFileInfo(element, info);
1094         }
1095
1096   protected void commitWorkingCopy(IProgressMonitor monitor, Object element, CompilationUnitInfo info, boolean overwrite) throws CoreException {
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 /*
1154  * @see org.eclipse.ui.editors.text.TextFileDocumentProvider#createSaveOperation(java.lang.Object, org.eclipse.jface.text.IDocument, boolean)
1155  */
1156 protected DocumentProviderOperation createSaveOperation(final Object element, final IDocument document, final boolean overwrite) throws CoreException {
1157 //      final FileInfo info= getFileInfo(element);
1158 //      if (info instanceof CompilationUnitInfo) {
1159 //              return new DocumentProviderOperation() {
1160 //                      /*
1161 //                       * @see org.eclipse.ui.editors.text.TextFileDocumentProvider.DocumentProviderOperation#execute(org.eclipse.core.runtime.IProgressMonitor)
1162 //                       */
1163 //                      protected void execute(IProgressMonitor monitor) throws CoreException {
1164 //                              commitWorkingCopy(monitor, element, (CompilationUnitInfo) info, overwrite);
1165 //                      }
1166 //                      /*
1167 //                       * @see org.eclipse.ui.editors.text.TextFileDocumentProvider.DocumentProviderOperation#getSchedulingRule()
1168 //                       */
1169 //                      public ISchedulingRule getSchedulingRule() {
1170 //                              if (info.fElement instanceof IFileEditorInput) {
1171 //                                      IFile file= ((IFileEditorInput) info.fElement).getFile();
1172 //                                      IResourceRuleFactory ruleFactory= ResourcesPlugin.getWorkspace().getRuleFactory();
1173 //                                      if (file == null || !file.exists())
1174 //                                              return ruleFactory.createRule(file);
1175 //                                      else
1176 //                                              return ruleFactory.modifyRule(file);
1177 //                              } else
1178 //                                      return null;
1179 //                      }
1180 //              };
1181 //      }
1182 //      return null;
1183         final FileInfo info= getFileInfo(element);
1184         if (info instanceof CompilationUnitInfo) {
1185                 return new DocumentProviderOperation() {
1186                         /*
1187                          * @see org.eclipse.ui.editors.text.TextFileDocumentProvider.DocumentProviderOperation#execute(org.eclipse.core.runtime.IProgressMonitor)
1188                          */
1189                         protected void execute(IProgressMonitor monitor) throws CoreException {
1190                                 commitWorkingCopy(monitor, element, (CompilationUnitInfo) info, overwrite);
1191                         }
1192                         /*
1193                          * @see org.eclipse.ui.editors.text.TextFileDocumentProvider.DocumentProviderOperation#getSchedulingRule()
1194                          */
1195                         public ISchedulingRule getSchedulingRule() {
1196                                 if (info.fElement instanceof IFileEditorInput) {
1197                                         IFile file= ((IFileEditorInput) info.fElement).getFile();
1198                                         return computeSchedulingRule(file);
1199                                 } else
1200                                         return null;
1201                         }
1202                 };
1203         }
1204         return null;
1205 }
1206
1207   /* (non-Javadoc)
1208    * Method declared on AbstractDocumentProvider
1209    */
1210 //  protected IDocument createDocument(Object element) throws CoreException {
1211 //    if (element instanceof IEditorInput) {
1212 //      Document document = new PartiallySynchronizedDocument();
1213 //      if (setDocumentContent(document, (IEditorInput) element, getEncoding(element))) {
1214 //        initializeDocument(document, (IEditorInput) element);
1215 //
1216 //        //
1217 //        //    IDocument document = super.createDocument(element);
1218 //        //    if (document != null) {
1219 //        //        IDocumentPartitioner partitioner = null;
1220 //        //        if (element instanceof FileEditorInput) {
1221 //        //          IFile file = (IFile) ((FileEditorInput) element).getAdapter(IFile.class);
1222 //        //          String filename = file.getLocation().toString();
1223 //        //          String extension = filename.substring(filename.lastIndexOf("."), filename.length());
1224 //        //          //   System.out.println(extension);
1225 //        //          if (extension.equalsIgnoreCase(".html") || extension.equalsIgnoreCase(".htm")) {
1226 //        //            // html
1227 //        //            partitioner = createHTMLPartitioner();
1228 //        //          } else if (extension.equalsIgnoreCase(".xml")) {
1229 //        //            // xml
1230 //        //            partitioner = createXMLPartitioner();
1231 //        //          } else if (extension.equalsIgnoreCase(".js")) {
1232 //        //            // javascript
1233 //        //            partitioner = createJavaScriptPartitioner();
1234 //        //          } else if (extension.equalsIgnoreCase(".css")) {
1235 //        //            // cascading style sheets
1236 //        //            partitioner = createCSSPartitioner();
1237 //        //          } else if (extension.equalsIgnoreCase(".tpl")) {
1238 //        //            // smarty ?
1239 //        //            partitioner = createSmartyPartitioner();
1240 //        //          } else if (extension.equalsIgnoreCase(".inc")) {
1241 //        //            // php include files ?
1242 //        //            partitioner = createIncludePartitioner();
1243 //        //          }
1244 //        //        }
1245 //        //
1246 //        //        if (partitioner == null) {
1247 //        //          partitioner = createPHPPartitioner();
1248 //        //        }
1249 //        //        document.setDocumentPartitioner(partitioner);
1250 //        //        partitioner.connect(document);
1251 //      }
1252 //      return document;
1253 //    }
1254 //    return null;
1255 //  }
1256
1257   //  /**
1258   //   * Return a partitioner for .html files.
1259   //   */
1260   //  private IDocumentPartitioner createHTMLPartitioner() {
1261   //    return new DefaultPartitioner(getHTMLPartitionScanner(), TYPES);
1262   //  }
1263   //
1264   //  private IDocumentPartitioner createIncludePartitioner() {
1265   //    return new DefaultPartitioner(getPHPPartitionScanner(), TYPES);
1266   //  }
1267   //
1268   //  private IDocumentPartitioner createJavaScriptPartitioner() {
1269   //    return new DefaultPartitioner(getHTMLPartitionScanner(), TYPES);
1270   //  }
1271
1272   /**
1273    * Creates a line tracker working with the same line delimiters as the document
1274    * of the given element. Assumes the element to be managed by this document provider.
1275    *
1276    * @param element the element serving as blue print
1277    * @return a line tracker based on the same line delimiters as the element's document
1278    */
1279   public ILineTracker createLineTracker(Object element) {
1280     return new DefaultLineTracker();
1281   }
1282
1283   //  /**
1284   //   * Return a partitioner for .php files.
1285   //   */
1286   //  private IDocumentPartitioner createPHPPartitioner() {
1287   //    return new DefaultPartitioner(getPHPPartitionScanner(), TYPES);
1288   //  }
1289   //
1290   //  private IDocumentPartitioner createSmartyPartitioner() {
1291   //    return new DefaultPartitioner(getSmartyPartitionScanner(), TYPES);
1292   //  }
1293   //
1294   //  private IDocumentPartitioner createXMLPartitioner() {
1295   //    return new DefaultPartitioner(getXMLPartitionScanner(), TYPES);
1296   //  }
1297   //
1298   //  /**
1299   //   * Return a scanner for creating html partitions.
1300   //   */
1301   //  private PHPPartitionScanner getHTMLPartitionScanner() {
1302   //    if (HTML_PARTITION_SCANNER == null)
1303   //      HTML_PARTITION_SCANNER = new PHPPartitionScanner(IPHPPartitionScannerConstants.HTML_FILE);
1304   //    return HTML_PARTITION_SCANNER;
1305   //  }
1306   //  /**
1307   //   * Return a scanner for creating php partitions.
1308   //   */
1309   //  private PHPPartitionScanner getPHPPartitionScanner() {
1310   //    if (PHP_PARTITION_SCANNER == null)
1311   //      PHP_PARTITION_SCANNER = new PHPPartitionScanner(IPHPPartitionScannerConstants.PHP_FILE);
1312   //    return PHP_PARTITION_SCANNER;
1313   //  }
1314   //
1315   //  /**
1316   //   * Return a scanner for creating smarty partitions.
1317   //   */
1318   //  private PHPPartitionScanner getSmartyPartitionScanner() {
1319   //    if (SMARTY_PARTITION_SCANNER == null)
1320   //      SMARTY_PARTITION_SCANNER = new PHPPartitionScanner(IPHPPartitionScannerConstants.SMARTY_FILE);
1321   //    return SMARTY_PARTITION_SCANNER;
1322   //  }
1323   //
1324   //  /**
1325   //   * Return a scanner for creating xml partitions.
1326   //   */
1327   //  private PHPPartitionScanner getXMLPartitionScanner() {
1328   //    if (XML_PARTITION_SCANNER == null)
1329   //      XML_PARTITION_SCANNER = new PHPPartitionScanner(IPHPPartitionScannerConstants.XML_FILE);
1330   //    return XML_PARTITION_SCANNER;
1331   //  }
1332
1333 //  protected void initializeDocument(IDocument document, IEditorInput editorInput) {
1334 //    if (document != null) {
1335 //      JavaTextTools tools = PHPeclipsePlugin.getDefault().getJavaTextTools();
1336 //      IDocumentPartitioner partitioner = null;
1337 //      if (editorInput != null && editorInput instanceof FileEditorInput) {
1338 //        IFile file = (IFile) ((FileEditorInput) editorInput).getAdapter(IFile.class);
1339 //        String filename = file.getLocation().toString();
1340 //        String extension = filename.substring(filename.lastIndexOf("."), filename.length());
1341 //        partitioner = tools.createDocumentPartitioner(extension);
1342 //      } else {
1343 //        partitioner = tools.createDocumentPartitioner(".php");
1344 //      }
1345 //      document.setDocumentPartitioner(partitioner);
1346 //      partitioner.connect(document);
1347 //    }
1348 //  }
1349
1350   /*
1351    * @see org.eclipse.ui.texteditor.AbstractDocumentProvider#doResetDocument(java.lang.Object, org.eclipse.core.runtime.IProgressMonitor)
1352    */
1353 //  protected void doResetDocument(Object element, IProgressMonitor monitor) throws CoreException {
1354 //    if (element == null)
1355 //      return;
1356 //
1357 //    ElementInfo elementInfo= getElementInfo(element);
1358 //    if (elementInfo instanceof CompilationUnitInfo) {
1359 //      CompilationUnitInfo info= (CompilationUnitInfo) elementInfo;
1360 //
1361 //      IDocument document;
1362 //      IStatus status= null;
1363 //
1364 //      try {
1365 //
1366 //        ICompilationUnit original= (ICompilationUnit) info.fCopy.getOriginalElement();
1367 //        IResource resource= original.getResource();
1368 //        if (resource instanceof IFile) {
1369 //
1370 //          IFile file= (IFile) resource;
1371 //
1372 //          try {
1373 //            refreshFile(file, monitor);
1374 //          } catch (CoreException x) {
1375 //            handleCoreException(x, PHPEditorMessages.getString("CompilationUnitDocumentProvider.error.resetDocument")); //$NON-NLS-1$
1376 //          }
1377 //
1378 //          IFileEditorInput input= new FileEditorInput(file);
1379 //          document= super.createDocument(input);
1380 //
1381 //        } else {
1382 //          document= createEmptyDocument();
1383 //        }
1384 //
1385 //      } catch (CoreException x) {
1386 //        document= createEmptyDocument();
1387 //        status= x.getStatus();
1388 //      }
1389 //
1390 //      fireElementContentAboutToBeReplaced(element);
1391 //
1392 //      removeUnchangedElementListeners(element, info);
1393 //      info.fDocument.set(document.get());
1394 //      info.fCanBeSaved= false;
1395 //      info.fStatus= status;
1396 //      addUnchangedElementListeners(element, info);
1397 //
1398 //      fireElementContentReplaced(element);
1399 //      fireElementDirtyStateChanged(element, false);
1400 //
1401 //    } else {
1402 //      super.doResetDocument(element, monitor);
1403 //    }
1404 //  }
1405
1406   /*
1407    * @see AbstractDocumentProvider#resetDocument(Object)
1408    */
1409 //  public void resetDocument(Object element) throws CoreException {
1410 //    if (element == null)
1411 //      return;
1412 //
1413 //    ElementInfo elementInfo = getElementInfo(element);
1414 //    if (elementInfo instanceof CompilationUnitInfo) {
1415 //      CompilationUnitInfo info = (CompilationUnitInfo) elementInfo;
1416 //
1417 //      IDocument document;
1418 //      IStatus status = null;
1419 //
1420 //      try {
1421 //
1422 //        ICompilationUnit original = (ICompilationUnit) info.fCopy.getOriginalElement();
1423 //        IResource resource = original.getResource();
1424 //        if (resource instanceof IFile) {
1425 //
1426 //          IFile file = (IFile) resource;
1427 //
1428 //          try {
1429 //            refreshFile(file);
1430 //          } catch (CoreException x) {
1431 //            handleCoreException(x, PHPEditorMessages.getString("PHPDocumentProvider.error.resetDocument")); //$NON-NLS-1$
1432 //          }
1433 //
1434 //          IFileEditorInput input = new FileEditorInput(file);
1435 //          document = super.createDocument(input);
1436 //
1437 //        } else {
1438 //          document = new Document();
1439 //        }
1440 //
1441 //      } catch (CoreException x) {
1442 //        document = new Document();
1443 //        status = x.getStatus();
1444 //      }
1445 //
1446 //      fireElementContentAboutToBeReplaced(element);
1447 //
1448 //      removeUnchangedElementListeners(element, info);
1449 //      info.fDocument.set(document.get());
1450 //      info.fCanBeSaved = false;
1451 //      info.fStatus = status;
1452 //      addUnchangedElementListeners(element, info);
1453 //
1454 //      fireElementContentReplaced(element);
1455 //      fireElementDirtyStateChanged(element, false);
1456 //
1457 //    } else {
1458 //      super.resetDocument(element);
1459 //    }
1460 //  }
1461   /**
1462          * Saves the content of the given document to the given element.
1463          * This is only performed when this provider initiated the save.
1464          *
1465          * @param monitor the progress monitor
1466          * @param element the element to which to save
1467          * @param document the document to save
1468          * @param overwrite <code>true</code> if the save should be enforced
1469          */
1470   public void saveDocumentContent(IProgressMonitor monitor, Object element, IDocument document, boolean overwrite)
1471     throws CoreException {
1472         if (!fIsAboutToSave)
1473                 return;
1474         super.saveDocument(monitor, element, document, overwrite);
1475 //    if (!fIsAboutToSave)
1476 //      return;
1477 //
1478 //    if (element instanceof IFileEditorInput) {
1479 //      IFileEditorInput input = (IFileEditorInput) element;
1480 //      try {
1481 //        String encoding = getEncoding(element);
1482 //        if (encoding == null)
1483 //          encoding = ResourcesPlugin.getEncoding();
1484 //        InputStream stream = new ByteArrayInputStream(document.get().getBytes(encoding));
1485 //        IFile file = input.getFile();
1486 //        file.setContents(stream, overwrite, true, monitor);
1487 //      } catch (IOException x) {
1488 //        IStatus s = new Status(IStatus.ERROR, PHPeclipsePlugin.PLUGIN_ID, IStatus.OK, x.getMessage(), x);
1489 //        throw new CoreException(s);
1490 //      }
1491 //    }
1492   }
1493   /**
1494    * Returns the underlying resource for the given element.
1495    *
1496    * @param the element
1497    * @return the underlying resource of the given element
1498    */
1499 //  public IResource getUnderlyingResource(Object element) {
1500 //    if (element instanceof IFileEditorInput) {
1501 //      IFileEditorInput input = (IFileEditorInput) element;
1502 //      return input.getFile();
1503 //    }
1504 //    return null;
1505 //  }
1506
1507         /*
1508          * @see net.sourceforge.phpdt.internal.ui.javaeditor.ICompilationUnitDocumentProvider#getWorkingCopy(java.lang.Object)
1509          */
1510         public ICompilationUnit getWorkingCopy(Object element) {
1511                 FileInfo fileInfo= getFileInfo(element);
1512                 if (fileInfo instanceof CompilationUnitInfo) {
1513                         CompilationUnitInfo info= (CompilationUnitInfo) fileInfo;
1514                         return info.fCopy;
1515                 }
1516                 return null;
1517         }
1518
1519
1520   /*
1521          * @see net.sourceforge.phpdt.internal.ui.javaeditor.ICompilationUnitDocumentProvider#shutdown()
1522          */
1523         public void shutdown() {
1524                 PHPeclipsePlugin.getDefault().getPreferenceStore().removePropertyChangeListener(fPropertyListener);
1525                 Iterator e= getConnectedElementsIterator();
1526                 while (e.hasNext())
1527                         disconnect(e.next());
1528         }
1529
1530   /**
1531    * Returns the preference whether handling temporary problems is enabled.
1532    */
1533   protected boolean isHandlingTemporaryProblems() {
1534     IPreferenceStore store = PHPeclipsePlugin.getDefault().getPreferenceStore();
1535     return store.getBoolean(HANDLE_TEMPORARY_PROBLEMS);
1536   }
1537
1538   /**
1539          * Switches the state of problem acceptance according to the value in the preference store.
1540          */
1541         protected void enableHandlingTemporaryProblems() {
1542                 boolean enable= isHandlingTemporaryProblems();
1543                 for (Iterator iter= getFileInfosIterator(); iter.hasNext();) {
1544                         FileInfo info= (FileInfo) iter.next();
1545                         if (info.fModel instanceof IProblemRequestorExtension) {
1546                                 IProblemRequestorExtension  extension= (IProblemRequestorExtension) info.fModel;
1547                                 extension.setIsActive(enable);
1548                         }
1549                 }
1550         }
1551
1552   /**
1553    * Adds a listener that reports changes from all compilation unit annotation models.
1554    */
1555   public void addGlobalAnnotationModelListener(IAnnotationModelListener listener) {
1556     fGlobalAnnotationModelListener.addListener(listener);
1557   }
1558
1559   /**
1560    * Removes the listener.
1561    */
1562   public void removeGlobalAnnotationModelListener(IAnnotationModelListener listener) {
1563     fGlobalAnnotationModelListener.removeListener(listener);
1564   }
1565
1566         /**
1567          * Computes the scheduling rule needed to create or modify a resource. If
1568          * the resource exists, its modify rule is returned. If it does not, the
1569          * resource hierarchy is iterated towards the workspace root to find the
1570          * first parent of <code>toCreateOrModify</code> that exists. Then the
1571          * 'create' rule for the last non-existing resource is returned.
1572          * <p>
1573          * XXX This is a workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=67601
1574          * IResourceRuleFactory.createRule should iterate the hierarchy itself.
1575          * </p>
1576          * <p>
1577          * XXX to be replaced by call to TextFileDocumentProvider.computeSchedulingRule after 3.0
1578          * </p>
1579          *
1580          * @param toCreateOrModify the resource to create or modify
1581          * @return the minimal scheduling rule needed to modify or create a resource
1582          */
1583    protected ISchedulingRule computeSchedulingRule(IResource toCreateOrModify) {
1584                 IResourceRuleFactory factory= ResourcesPlugin.getWorkspace().getRuleFactory();
1585                 if (toCreateOrModify.exists()) {
1586                         return factory.modifyRule(toCreateOrModify);
1587                 } else {
1588                         IResource parent= toCreateOrModify;
1589                         do {
1590                                 toCreateOrModify= parent;
1591                                 parent= toCreateOrModify.getParent();
1592                         } while (parent != null && !parent.exists());
1593
1594                         return factory.createRule(toCreateOrModify);
1595                 }
1596         }
1597 }