1 package net.sourceforge.phpeclipse.phpeditor;
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
11 IBM Corporation - Initial implementation
12 Klaus Hartlage - www.eclipseproject.de
13 **********************************************************************/
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;
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;
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;
79 * The PHPDocumentProvider provides the IDocuments used by java editors.
82 public class PHPDocumentProvider extends TextFileDocumentProvider {
84 * Here for visibility issues only.
88 * Bundle of all required informations to allow working copy management.
91 * Bundle of all required informations to allow working copy management.
93 static protected class CompilationUnitInfo extends FileInfo {
94 public ICompilationUnit fCopy;
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
102 protected static class CompilationUnitAnnotationModel extends ResourceMarkerAnnotationModel implements IProblemRequestor, IProblemRequestorExtension {
104 private static class ProblemRequestorState {
105 boolean fInsideReportingSequence= false;
106 List fReportedProblems;
109 private ThreadLocal fProblemRequestorState= new ThreadLocal();
110 private int fStateCount= 0;
112 private ICompilationUnit fCompilationUnit;
113 private List fGeneratedAnnotations;
114 private IProgressMonitor fProgressMonitor;
115 private boolean fIsActive= false;
117 private ReverseMap fReverseMap= new ReverseMap();
118 private List fPreviouslyOverlaid= null;
119 private List fCurrentlyOverlaid= new ArrayList();
122 public CompilationUnitAnnotationModel(IResource resource) {
126 public void setCompilationUnit(ICompilationUnit unit) {
127 fCompilationUnit= unit;
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);
138 * @see org.eclipse.jface.text.source.AnnotationModel#createAnnotationModelEvent()
140 protected AnnotationModelEvent createAnnotationModelEvent() {
141 return new CompilationUnitAnnotationModelEvent(this, getResource());
144 protected Position createPositionFromProblem(IProblem problem) {
145 int start= problem.getSourceStart();
149 int length= problem.getSourceEnd() - problem.getSourceStart() + 1;
153 return new Position(start, length);
157 * @see IProblemRequestor#beginReporting()
159 public void beginReporting() {
160 ProblemRequestorState state= (ProblemRequestorState) fProblemRequestorState.get();
162 internalBeginReporting(false);
166 * @see org.eclipse.jdt.internal.ui.text.java.IProblemRequestorExtension#beginReportingSequence()
168 public void beginReportingSequence() {
169 ProblemRequestorState state= (ProblemRequestorState) fProblemRequestorState.get();
171 internalBeginReporting(true);
175 * Sets up the infrastructure necessary for problem reporting.
177 * @param insideReportingSequence <code>true</code> if this method
178 * call is issued from inside a reporting sequence
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);
194 * @see IProblemRequestor#acceptProblem(IProblem)
196 public void acceptProblem(IProblem problem) {
198 ProblemRequestorState state= (ProblemRequestorState) fProblemRequestorState.get();
200 state.fReportedProblems.add(problem);
205 * @see IProblemRequestor#endReporting()
207 public void endReporting() {
208 ProblemRequestorState state= (ProblemRequestorState) fProblemRequestorState.get();
209 if (state != null && !state.fInsideReportingSequence)
210 internalEndReporting(state);
214 * @see org.eclipse.jdt.internal.ui.text.java.IProblemRequestorExtension#endReportingSequence()
216 public void endReportingSequence() {
217 ProblemRequestorState state= (ProblemRequestorState) fProblemRequestorState.get();
218 if (state != null && state.fInsideReportingSequence)
219 internalEndReporting(state);
222 private void internalEndReporting(ProblemRequestorState state) {
224 synchronized(getLockObject()) {
226 stateCount= fStateCount;
227 fProblemRequestorState.set(null);
230 if (stateCount == 0 && isActive())
231 reportProblems(state.fReportedProblems);
235 * Signals the end of problem reporting.
237 private void reportProblems(List reportedProblems) {
238 if (fProgressMonitor != null && fProgressMonitor.isCanceled())
241 boolean temporaryProblemsChanged= false;
243 synchronized (getLockObject()) {
245 boolean isCanceled= false;
247 fPreviouslyOverlaid= fCurrentlyOverlaid;
248 fCurrentlyOverlaid= new ArrayList();
250 if (fGeneratedAnnotations.size() > 0) {
251 temporaryProblemsChanged= true;
252 removeAnnotations(fGeneratedAnnotations, false, true);
253 fGeneratedAnnotations.clear();
256 if (reportedProblems != null && reportedProblems.size() > 0) {
258 Iterator e= reportedProblems.iterator();
259 while (e.hasNext()) {
261 if (fProgressMonitor != null && fProgressMonitor.isCanceled()) {
266 IProblem problem= (IProblem) e.next();
267 Position position= createPositionFromProblem(problem);
268 if (position != null) {
271 ProblemAnnotation annotation= new ProblemAnnotation(problem, fCompilationUnit);
272 overlayMarkers(position, annotation);
273 addAnnotation(annotation, position, false);
274 fGeneratedAnnotations.add(annotation);
276 temporaryProblemsChanged= true;
277 } catch (BadLocationException x) {
278 // ignore invalid position
284 removeMarkerOverlays(isCanceled);
285 fPreviouslyOverlaid= null;
288 if (temporaryProblemsChanged)
292 private void removeMarkerOverlays(boolean 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);
305 * Overlays value with problem annotation.
306 * @param problemAnnotation
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);
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);
327 setOverlay(value, problemAnnotation);
332 * Tells this annotation model to collect temporary problems from now on.
334 private void startCollectingProblems() {
335 fGeneratedAnnotations= new ArrayList();
339 * Tells this annotation model to no longer collect temporary problems.
341 private void stopCollectingProblems() {
342 if (fGeneratedAnnotations != null)
343 removeAnnotations(fGeneratedAnnotations, true, true);
344 fGeneratedAnnotations= null;
348 * @see IProblemRequestor#isActive()
350 public boolean isActive() {
355 * @see IProblemRequestorExtension#setProgressMonitor(IProgressMonitor)
357 public void setProgressMonitor(IProgressMonitor monitor) {
358 fProgressMonitor= monitor;
362 * @see IProblemRequestorExtension#setIsActive(boolean)
364 public void setIsActive(boolean isActive) {
365 if (fIsActive != isActive) {
368 startCollectingProblems();
370 stopCollectingProblems();
374 private Object getAnnotations(Position position) {
375 return fReverseMap.get(position);
379 * @see AnnotationModel#addAnnotation(Annotation, Position, boolean)
381 protected void addAnnotation(Annotation annotation, Position position, boolean fireModelChanged) throws BadLocationException {
382 super.addAnnotation(annotation, position, fireModelChanged);
384 Object cached= fReverseMap.get(position);
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);
393 list.add(annotation);
394 fReverseMap.put(position, list);
399 * @see AnnotationModel#removeAllAnnotations(boolean)
401 protected void removeAllAnnotations(boolean fireModelChanged) {
402 super.removeAllAnnotations(fireModelChanged);
407 * @see AnnotationModel#removeAnnotation(Annotation, boolean)
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));
419 } else if (cached instanceof Annotation) {
420 fReverseMap.remove(position);
422 super.removeAnnotation(annotation, fireModelChanged);
428 protected static class GlobalAnnotationModelListener implements IAnnotationModelListener, IAnnotationModelListenerExtension {
430 private ListenerList fListenerList;
432 public GlobalAnnotationModelListener() {
433 fListenerList = new ListenerList();
436 public void addListener(IAnnotationModelListener listener) {
437 fListenerList.add(listener);
441 * @see IAnnotationModelListenerExtension#modelChanged(AnnotationModelEvent)
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);
454 * @see IAnnotationModelListener#modelChanged(IAnnotationModel)
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);
463 public void removeListener(IAnnotationModelListener listener) {
464 fListenerList.remove(listener);
469 * Annotation representating an <code>IProblem</code>.
471 static protected class ProblemAnnotation extends Annotation implements IJavaAnnotation, IAnnotationPresentation {
473 private static final String SPELLING_ANNOTATION_TYPE= "org.eclipse.ui.workbench.texteditor.spelling";
475 //XXX: To be fully correct these constants should be non-static
477 * The layer in which task problem annotations are located.
479 private static final int TASK_LAYER;
481 * The layer in which info problem annotations are located.
483 private static final int INFO_LAYER;
485 * The layer in which warning problem annotations representing are located.
487 private static final int WARNING_LAYER;
489 * The layer in which error problem annotations representing are located.
491 private static final int ERROR_LAYER;
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$
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;
507 return IAnnotationAccessExtension.DEFAULT_LAYER + 1;
510 // private static Image fgQuickFixImage;
511 // private static Image fgQuickFixErrorImage;
512 // private static boolean fgQuickFixImagesInitialized= false;
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;
521 public ProblemAnnotation(IProblem problem, ICompilationUnit cu) {
524 fCompilationUnit= cu;
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);
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);
539 setType(JavaMarkerAnnotation.INFO_ANNOTATION_TYPE);
545 * @see org.eclipse.jface.text.source.IAnnotationPresentation#getLayer()
547 public int getLayer() {
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;
560 // if (JavaMarkerAnnotation.ERROR_ANNOTATION_TYPE.equals(getType()))
561 // fImage= fgQuickFixErrorImage;
563 // fImage= fgQuickFixImage;
565 // fQuickFixImagesInitialized= true;
569 private boolean indicateQuixFixableProblems() {
570 return PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_CORRECTION_INDICATION);
574 * @see Annotation#paint
576 public void paint(GC gc, Canvas canvas, Rectangle r) {
579 ImageUtilities.drawImage(fImage, gc, canvas, r, SWT.CENTER, SWT.TOP);
582 * @see IJavaAnnotation#getImage(Display)
584 public Image getImage(Display display) {
590 * @see IJavaAnnotation#getMessage()
592 public String getText() {
593 return fProblem.getMessage();
597 * @see IJavaAnnotation#getArguments()
599 public String[] getArguments() {
600 return isProblem() ? fProblem.getArguments() : null;
604 * @see IJavaAnnotation#getId()
607 return fProblem.getID();
611 * @see IJavaAnnotation#isProblem()
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);
621 * @see IJavaAnnotation#hasOverlay()
623 public boolean hasOverlay() {
628 * @see org.eclipse.jdt.internal.ui.javaeditor.IJavaAnnotation#getOverlay()
630 public IJavaAnnotation getOverlay() {
635 * @see IJavaAnnotation#addOverlaid(IJavaAnnotation)
637 public void addOverlaid(IJavaAnnotation annotation) {
638 if (fOverlaids == null)
639 fOverlaids= new ArrayList(1);
640 fOverlaids.add(annotation);
644 * @see IJavaAnnotation#removeOverlaid(IJavaAnnotation)
646 public void removeOverlaid(IJavaAnnotation annotation) {
647 if (fOverlaids != null) {
648 fOverlaids.remove(annotation);
649 if (fOverlaids.size() == 0)
655 * @see IJavaAnnotation#getOverlaidIterator()
657 public Iterator getOverlaidIterator() {
658 if (fOverlaids != null)
659 return fOverlaids.iterator();
664 * @see org.eclipse.jdt.internal.ui.javaeditor.IJavaAnnotation#getCompilationUnit()
666 public ICompilationUnit getCompilationUnit() {
667 return fCompilationUnit;
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
678 protected static class ReverseMap {
684 private int fAnchor = 0;
686 private List fList = new ArrayList(2);
688 public ReverseMap() {
691 public void clear() {
695 public Object get(Position position) {
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)) {
710 for (int i = 0; i < fAnchor; i++) {
711 entry = (Entry) fList.get(i);
712 if (entry.fPosition.equals(position)) {
721 private int getIndex(Position position) {
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))
732 public void put(Position position, Object value) {
733 int index = getIndex(position);
735 Entry entry = new Entry();
736 entry.fPosition = position;
737 entry.fValue = value;
740 Entry entry = (Entry) fList.get(index);
741 entry.fValue = value;
745 public void remove(Position position) {
746 int index = getIndex(position);
753 * Document that can also be used by a background reconciler.
755 protected static class PartiallySynchronizedDocument extends Document {
758 * @see IDocumentExtension#startSequentialRewrite(boolean)
760 synchronized public void startSequentialRewrite(boolean normalized) {
761 super.startSequentialRewrite(normalized);
765 * @see IDocumentExtension#stopSequentialRewrite()
767 synchronized public void stopSequentialRewrite() {
768 super.stopSequentialRewrite();
772 * @see IDocument#get()
774 synchronized public String get() {
779 * @see IDocument#get(int, int)
781 synchronized public String get(int offset, int length) throws BadLocationException {
782 return super.get(offset, length);
786 * @see IDocument#getChar(int)
788 synchronized public char getChar(int offset) throws BadLocationException {
789 return super.getChar(offset);
793 * @see IDocument#replace(int, int, String)
795 synchronized public void replace(int offset, int length, String text) throws BadLocationException {
796 super.replace(offset, length, text);
800 * @see IDocument#set(String)
802 synchronized public void set(String text) {
807 // private static PHPPartitionScanner HTML_PARTITION_SCANNER = null;
809 // private static PHPPartitionScanner PHP_PARTITION_SCANNER = null;
810 // private static PHPPartitionScanner SMARTY_PARTITION_SCANNER = null;
812 // // private final static String[] TYPES= new String[] { PHPPartitionScanner.PHP, PHPPartitionScanner.JAVA_DOC, PHPPartitionScanner.JAVA_MULTILINE_COMMENT };
813 // private final static String[] TYPES =
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;
825 /* Preference key for temporary problems */
826 private final static String HANDLE_TEMPORARY_PROBLEMS = PreferenceConstants.EDITOR_EVALUTE_TEMPORARY_PROBLEMS;
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;
835 /** annotation model listener added to all created CU annotation models */
836 private GlobalAnnotationModelListener fGlobalAnnotationModelListener;
838 public PHPDocumentProvider() {
839 setParentDocumentProvider(new TextFileDocumentProvider(new JavaStorageDocumentProvider()));
841 fPropertyListener= new IPropertyChangeListener() {
842 public void propertyChange(PropertyChangeEvent event) {
843 if (HANDLE_TEMPORARY_PROBLEMS.equals(event.getProperty()))
844 enableHandlingTemporaryProblems();
847 fGlobalAnnotationModelListener= new GlobalAnnotationModelListener();
848 PHPeclipsePlugin.getDefault().getPreferenceStore().addPropertyChangeListener(fPropertyListener);
853 * Sets the document provider's save policy.
855 public void setSavePolicy(ISavePolicy savePolicy) {
856 fSavePolicy = savePolicy;
860 * Creates a compilation unit from the given file.
862 * @param file the file from which to create the compilation unit
864 protected ICompilationUnit createCompilationUnit(IFile file) {
865 Object element = JavaCore.create(file);
866 if (element instanceof ICompilationUnit)
867 return (ICompilationUnit) element;
873 * @see org.eclipse.ui.editors.text.TextFileDocumentProvider#createEmptyFileInfo()
875 protected FileInfo createEmptyFileInfo() {
876 return new CompilationUnitInfo();
879 * @see org.eclipse.ui.editors.text.TextFileDocumentProvider#createAnnotationModel(org.eclipse.core.resources.IFile)
881 protected IAnnotationModel createAnnotationModel(IFile file) {
882 return new CompilationUnitAnnotationModel(file);
885 * @see AbstractDocumentProvider#createElementInfo(Object)
887 // protected ElementInfo createElementInfo(Object element) throws CoreException {
889 // if (!(element instanceof IFileEditorInput))
890 // return super.createElementInfo(element);
892 // IFileEditorInput input = (IFileEditorInput) element;
893 // ICompilationUnit original = createCompilationUnit(input.getFile());
894 // if (original != null) {
899 // refreshFile(input.getFile());
900 // } catch (CoreException x) {
901 // handleCoreException(x, PHPEditorMessages.getString("PHPDocumentProvider.error.createElementInfo")); //$NON-NLS-1$
904 // IAnnotationModel m = createCompilationUnitAnnotationModel(input);
905 // IProblemRequestor r = m instanceof IProblemRequestor ? (IProblemRequestor) m : null;
906 // ICompilationUnit c = (ICompilationUnit) original.getSharedWorkingCopy(getProgressMonitor(), fBufferFactory, r);
908 // DocumentAdapter a = null;
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);
916 // _FileSynchronizer f = new _FileSynchronizer(input);
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);
924 // if (r instanceof IProblemRequestorExtension) {
925 // IProblemRequestorExtension extension = (IProblemRequestorExtension) r;
926 // extension.setIsActive(isHandlingTemporaryProblems());
928 // m.addAnnotationModelListener(fGlobalAnnotationModelListener);
932 // } catch (JavaModelException x) {
933 // throw new CoreException(x.getStatus());
936 // return super.createElementInfo(element);
941 * @see AbstractDocumentProvider#disposeElementInfo(Object, ElementInfo)
943 // protected void disposeElementInfo(Object element, ElementInfo info) {
945 // if (info instanceof CompilationUnitInfo) {
946 // CompilationUnitInfo cuInfo = (CompilationUnitInfo) info;
947 // cuInfo.fCopy.destroy();
948 // cuInfo.fModel.removeAnnotationModelListener(fGlobalAnnotationModelListener);
951 // super.disposeElementInfo(element, info);
955 * @see AbstractDocumentProvider#doSaveDocument(IProgressMonitor, Object, IDocument, boolean)
957 // protected void doSaveDocument(IProgressMonitor monitor, Object element, IDocument document, boolean overwrite)
958 // throws CoreException {
960 // ElementInfo elementInfo = getElementInfo(element);
961 // if (elementInfo instanceof CompilationUnitInfo) {
962 // CompilationUnitInfo info = (CompilationUnitInfo) elementInfo;
964 // // update structure, assumes lock on info.fCopy
965 // info.fCopy.reconcile();
967 // ICompilationUnit original = (ICompilationUnit) info.fCopy.getOriginalElement();
968 // IResource resource = original.getResource();
970 // if (resource == null) {
971 // // underlying resource has been deleted, just recreate file, ignore the rest
972 // super.doSaveDocument(monitor, element, document, overwrite);
976 // if (resource != null && !overwrite)
977 // checkSynchronizationState(info.fModificationStamp, resource);
979 // if (fSavePolicy != null)
980 // fSavePolicy.preSave(info.fCopy);
982 // // inform about the upcoming content change
983 // fireElementStateChanging(element);
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);
992 // } catch (RuntimeException x) {
993 // // inform about the failure
994 // fireElementStateChangeFailed(element);
997 // fIsAboutToSave = false;
1000 // // If here, the dirty state of the editor will change to "not dirty".
1001 // // Thus, the state changing flag will be reset.
1003 // AbstractMarkerAnnotationModel model = (AbstractMarkerAnnotationModel) info.fModel;
1004 // model.updateMarkers(info.fDocument);
1006 // if (resource != null)
1007 // info.setModificationStamp(computeModificationStamp(resource));
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);
1022 // super.doSaveDocument(monitor, element, document, overwrite);
1027 * @see org.eclipse.ui.editors.text.TextFileDocumentProvider#createFileInfo(java.lang.Object)
1029 protected FileInfo createFileInfo(Object element) throws CoreException {
1030 if (!(element instanceof IFileEditorInput))
1033 IFileEditorInput input= (IFileEditorInput) element;
1034 ICompilationUnit original= createCompilationUnit(input.getFile());
1035 if (original == null)
1038 FileInfo info= super.createFileInfo(element);
1039 if (!(info instanceof CompilationUnitInfo))
1042 CompilationUnitInfo cuInfo= (CompilationUnitInfo) info;
1043 setUpSynchronization(cuInfo);
1045 IProblemRequestor requestor= cuInfo.fModel instanceof IProblemRequestor ? (IProblemRequestor) cuInfo.fModel : null;
1047 original.becomeWorkingCopy(requestor, getProgressMonitor());
1048 cuInfo.fCopy= original;
1050 if (cuInfo.fModel instanceof CompilationUnitAnnotationModel) {
1051 CompilationUnitAnnotationModel model= (CompilationUnitAnnotationModel) cuInfo.fModel;
1052 model.setCompilationUnit(cuInfo.fCopy);
1055 if (cuInfo.fModel != null)
1056 cuInfo.fModel.addAnnotationModelListener(fGlobalAnnotationModelListener);
1058 if (requestor instanceof IProblemRequestorExtension) {
1059 IProblemRequestorExtension extension= (IProblemRequestorExtension) requestor;
1060 extension.setIsActive(isHandlingTemporaryProblems());
1066 private void setUpSynchronization(CompilationUnitInfo cuInfo) {
1067 IDocument document= cuInfo.fTextFileBuffer.getDocument();
1068 IAnnotationModel model= cuInfo.fModel;
1070 if (document instanceof ISynchronizable && model instanceof ISynchronizable) {
1071 Object lock= ((ISynchronizable) document).getLockObject();
1072 ((ISynchronizable) model).setLockObject(lock);
1077 * @see org.eclipse.ui.editors.text.TextFileDocumentProvider#disposeFileInfo(java.lang.Object, org.eclipse.ui.editors.text.TextFileDocumentProvider.FileInfo)
1079 protected void disposeFileInfo(Object element, FileInfo info) {
1080 if (info instanceof CompilationUnitInfo) {
1081 CompilationUnitInfo cuInfo= (CompilationUnitInfo) info;
1084 cuInfo.fCopy.discardWorkingCopy();
1085 } catch (JavaModelException x) {
1086 handleCoreException(x, x.getMessage());
1089 if (cuInfo.fModel != null)
1090 cuInfo.fModel.removeAnnotationModelListener(fGlobalAnnotationModelListener);
1092 super.disposeFileInfo(element, info);
1095 protected void commitWorkingCopy(IProgressMonitor monitor, Object element, CompilationUnitInfo info, boolean overwrite) throws CoreException {
1097 synchronized (info.fCopy) {
1098 info.fCopy.reconcile();
1101 IDocument document= info.fTextFileBuffer.getDocument();
1102 IResource resource= info.fCopy.getResource();
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);
1111 if (fSavePolicy != null)
1112 fSavePolicy.preSave(info.fCopy);
1116 fIsAboutToSave= true;
1117 info.fCopy.commitWorkingCopy(overwrite, monitor);
1119 } catch (CoreException x) {
1120 // inform about the failure
1121 fireElementStateChangeFailed(element);
1123 } catch (RuntimeException x) {
1124 // inform about the failure
1125 fireElementStateChangeFailed(element);
1128 fIsAboutToSave= false;
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);
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);
1153 * @see org.eclipse.ui.editors.text.TextFileDocumentProvider#createSaveOperation(java.lang.Object, org.eclipse.jface.text.IDocument, boolean)
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() {
1160 * @see org.eclipse.ui.editors.text.TextFileDocumentProvider.DocumentProviderOperation#execute(org.eclipse.core.runtime.IProgressMonitor)
1162 protected void execute(IProgressMonitor monitor) throws CoreException {
1163 commitWorkingCopy(monitor, element, (CompilationUnitInfo) info, overwrite);
1166 * @see org.eclipse.ui.editors.text.TextFileDocumentProvider.DocumentProviderOperation#getSchedulingRule()
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);
1175 return ruleFactory.modifyRule(file);
1185 * Method declared on AbstractDocumentProvider
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);
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")) {
1204 // // partitioner = createHTMLPartitioner();
1205 // // } else if (extension.equalsIgnoreCase(".xml")) {
1207 // // partitioner = createXMLPartitioner();
1208 // // } else if (extension.equalsIgnoreCase(".js")) {
1210 // // partitioner = createJavaScriptPartitioner();
1211 // // } else if (extension.equalsIgnoreCase(".css")) {
1212 // // // cascading style sheets
1213 // // partitioner = createCSSPartitioner();
1214 // // } else if (extension.equalsIgnoreCase(".tpl")) {
1216 // // partitioner = createSmartyPartitioner();
1217 // // } else if (extension.equalsIgnoreCase(".inc")) {
1218 // // // php include files ?
1219 // // partitioner = createIncludePartitioner();
1223 // // if (partitioner == null) {
1224 // // partitioner = createPHPPartitioner();
1226 // // document.setDocumentPartitioner(partitioner);
1227 // // partitioner.connect(document);
1235 // * Return a partitioner for .html files.
1237 // private IDocumentPartitioner createHTMLPartitioner() {
1238 // return new DefaultPartitioner(getHTMLPartitionScanner(), TYPES);
1241 // private IDocumentPartitioner createIncludePartitioner() {
1242 // return new DefaultPartitioner(getPHPPartitionScanner(), TYPES);
1245 // private IDocumentPartitioner createJavaScriptPartitioner() {
1246 // return new DefaultPartitioner(getHTMLPartitionScanner(), TYPES);
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.
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
1256 public ILineTracker createLineTracker(Object element) {
1257 return new DefaultLineTracker();
1261 // * Return a partitioner for .php files.
1263 // private IDocumentPartitioner createPHPPartitioner() {
1264 // return new DefaultPartitioner(getPHPPartitionScanner(), TYPES);
1267 // private IDocumentPartitioner createSmartyPartitioner() {
1268 // return new DefaultPartitioner(getSmartyPartitionScanner(), TYPES);
1271 // private IDocumentPartitioner createXMLPartitioner() {
1272 // return new DefaultPartitioner(getXMLPartitionScanner(), TYPES);
1276 // * Return a scanner for creating html partitions.
1278 // private PHPPartitionScanner getHTMLPartitionScanner() {
1279 // if (HTML_PARTITION_SCANNER == null)
1280 // HTML_PARTITION_SCANNER = new PHPPartitionScanner(IPHPPartitionScannerConstants.HTML_FILE);
1281 // return HTML_PARTITION_SCANNER;
1284 // * Return a scanner for creating php partitions.
1286 // private PHPPartitionScanner getPHPPartitionScanner() {
1287 // if (PHP_PARTITION_SCANNER == null)
1288 // PHP_PARTITION_SCANNER = new PHPPartitionScanner(IPHPPartitionScannerConstants.PHP_FILE);
1289 // return PHP_PARTITION_SCANNER;
1293 // * Return a scanner for creating smarty partitions.
1295 // private PHPPartitionScanner getSmartyPartitionScanner() {
1296 // if (SMARTY_PARTITION_SCANNER == null)
1297 // SMARTY_PARTITION_SCANNER = new PHPPartitionScanner(IPHPPartitionScannerConstants.SMARTY_FILE);
1298 // return SMARTY_PARTITION_SCANNER;
1302 // * Return a scanner for creating xml partitions.
1304 // private PHPPartitionScanner getXMLPartitionScanner() {
1305 // if (XML_PARTITION_SCANNER == null)
1306 // XML_PARTITION_SCANNER = new PHPPartitionScanner(IPHPPartitionScannerConstants.XML_FILE);
1307 // return XML_PARTITION_SCANNER;
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);
1320 // partitioner = tools.createDocumentPartitioner(".php");
1322 // document.setDocumentPartitioner(partitioner);
1323 // partitioner.connect(document);
1328 * @see org.eclipse.ui.texteditor.AbstractDocumentProvider#doResetDocument(java.lang.Object, org.eclipse.core.runtime.IProgressMonitor)
1330 // protected void doResetDocument(Object element, IProgressMonitor monitor) throws CoreException {
1331 // if (element == null)
1334 // ElementInfo elementInfo= getElementInfo(element);
1335 // if (elementInfo instanceof CompilationUnitInfo) {
1336 // CompilationUnitInfo info= (CompilationUnitInfo) elementInfo;
1338 // IDocument document;
1339 // IStatus status= null;
1343 // ICompilationUnit original= (ICompilationUnit) info.fCopy.getOriginalElement();
1344 // IResource resource= original.getResource();
1345 // if (resource instanceof IFile) {
1347 // IFile file= (IFile) resource;
1350 // refreshFile(file, monitor);
1351 // } catch (CoreException x) {
1352 // handleCoreException(x, PHPEditorMessages.getString("CompilationUnitDocumentProvider.error.resetDocument")); //$NON-NLS-1$
1355 // IFileEditorInput input= new FileEditorInput(file);
1356 // document= super.createDocument(input);
1359 // document= createEmptyDocument();
1362 // } catch (CoreException x) {
1363 // document= createEmptyDocument();
1364 // status= x.getStatus();
1367 // fireElementContentAboutToBeReplaced(element);
1369 // removeUnchangedElementListeners(element, info);
1370 // info.fDocument.set(document.get());
1371 // info.fCanBeSaved= false;
1372 // info.fStatus= status;
1373 // addUnchangedElementListeners(element, info);
1375 // fireElementContentReplaced(element);
1376 // fireElementDirtyStateChanged(element, false);
1379 // super.doResetDocument(element, monitor);
1384 * @see AbstractDocumentProvider#resetDocument(Object)
1386 // public void resetDocument(Object element) throws CoreException {
1387 // if (element == null)
1390 // ElementInfo elementInfo = getElementInfo(element);
1391 // if (elementInfo instanceof CompilationUnitInfo) {
1392 // CompilationUnitInfo info = (CompilationUnitInfo) elementInfo;
1394 // IDocument document;
1395 // IStatus status = null;
1399 // ICompilationUnit original = (ICompilationUnit) info.fCopy.getOriginalElement();
1400 // IResource resource = original.getResource();
1401 // if (resource instanceof IFile) {
1403 // IFile file = (IFile) resource;
1406 // refreshFile(file);
1407 // } catch (CoreException x) {
1408 // handleCoreException(x, PHPEditorMessages.getString("PHPDocumentProvider.error.resetDocument")); //$NON-NLS-1$
1411 // IFileEditorInput input = new FileEditorInput(file);
1412 // document = super.createDocument(input);
1415 // document = new Document();
1418 // } catch (CoreException x) {
1419 // document = new Document();
1420 // status = x.getStatus();
1423 // fireElementContentAboutToBeReplaced(element);
1425 // removeUnchangedElementListeners(element, info);
1426 // info.fDocument.set(document.get());
1427 // info.fCanBeSaved = false;
1428 // info.fStatus = status;
1429 // addUnchangedElementListeners(element, info);
1431 // fireElementContentReplaced(element);
1432 // fireElementDirtyStateChanged(element, false);
1435 // super.resetDocument(element);
1439 * Saves the content of the given document to the given element.
1440 * This is only performed when this provider initiated the save.
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
1447 public void saveDocumentContent(IProgressMonitor monitor, Object element, IDocument document, boolean overwrite)
1448 throws CoreException {
1450 if (!fIsAboutToSave)
1453 if (element instanceof IFileEditorInput) {
1454 IFileEditorInput input = (IFileEditorInput) element;
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);
1469 * Returns the underlying resource for the given element.
1471 * @param the element
1472 * @return the underlying resource of the given element
1474 public IResource getUnderlyingResource(Object element) {
1475 if (element instanceof IFileEditorInput) {
1476 IFileEditorInput input = (IFileEditorInput) element;
1477 return input.getFile();
1483 * @see org.eclipse.jdt.internal.ui.javaeditor.ICompilationUnitDocumentProvider#getWorkingCopy(java.lang.Object)
1485 public ICompilationUnit getWorkingCopy(Object element) {
1486 FileInfo fileInfo= getFileInfo(element);
1487 if (fileInfo instanceof CompilationUnitInfo) {
1488 CompilationUnitInfo info= (CompilationUnitInfo) fileInfo;
1496 * @see org.eclipse.jdt.internal.ui.javaeditor.ICompilationUnitDocumentProvider#shutdown()
1498 public void shutdown() {
1499 PHPeclipsePlugin.getDefault().getPreferenceStore().removePropertyChangeListener(fPropertyListener);
1500 Iterator e= getConnectedElementsIterator();
1502 disconnect(e.next());
1506 * Returns the preference whether handling temporary problems is enabled.
1508 protected boolean isHandlingTemporaryProblems() {
1509 IPreferenceStore store = PHPeclipsePlugin.getDefault().getPreferenceStore();
1510 return store.getBoolean(HANDLE_TEMPORARY_PROBLEMS);
1514 * Switches the state of problem acceptance according to the value in the preference store.
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);
1528 * Adds a listener that reports changes from all compilation unit annotation models.
1530 public void addGlobalAnnotationModelListener(IAnnotationModelListener listener) {
1531 fGlobalAnnotationModelListener.addListener(listener);
1535 * Removes the listener.
1537 public void removeGlobalAnnotationModelListener(IAnnotationModelListener listener) {
1538 fGlobalAnnotationModelListener.removeListener(listener);