Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 8f75cd0118f08a7c23b27e1250ccb38d07435603 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
/*
* Copyright (c) 2002 IBM Corporation and others.
* All rights reserved.   This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
* 
* Contributors:
*   IBM - Initial API and implementation
*   Jens Lukowski/Innoopract - initial renaming/restructuring
* 
*/
package org.eclipse.wst.sse.ui;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.UnsupportedCharsetException;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Vector;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.source.IAnnotationModel;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.dialogs.ContainerGenerator;
import org.eclipse.ui.editors.text.FileDocumentProvider;
import org.eclipse.ui.texteditor.AbstractMarkerAnnotationModel;
import org.eclipse.wst.encoding.EncodingMemento;
import org.eclipse.wst.encoding.EncodingRule;
import org.eclipse.wst.encoding.exceptions.CharConversionErrorWithDetail;
import org.eclipse.wst.encoding.exceptions.MalformedInputExceptionWithDetail;
import org.eclipse.wst.encoding.exceptions.MalformedOutputExceptionWithDetail;
import org.eclipse.wst.sse.core.FactoryRegistry;
import org.eclipse.wst.sse.core.IFactoryRegistry;
import org.eclipse.wst.sse.core.IModelManager;
import org.eclipse.wst.sse.core.IModelManagerPlugin;
import org.eclipse.wst.sse.core.IModelStateListenerExtended;
import org.eclipse.wst.sse.core.IStructuredModel;
import org.eclipse.wst.sse.core.exceptions.SourceEditingRuntimeException;
import org.eclipse.wst.sse.core.text.IStructuredDocument;
import org.eclipse.wst.sse.core.undo.StructuredTextUndoManager;
import org.eclipse.wst.sse.ui.nls.ResourceHandler;
import org.eclipse.wst.sse.ui.registry.AdapterFactoryProvider;
import org.eclipse.wst.sse.ui.registry.AdapterFactoryRegistry;
import org.eclipse.wst.sse.ui.util.Assert;


/**
 * This version of an IDocumentProvider is the editor side counter part to
 * IModelManager. It is responsible for providing the structuredModel, which
 * is actually deferred to the IModelManager. But other, non-deffered
 * responsibilities include providing editing related models, such as
 * annotation models, undo command stack, etc.
 */
public class FileModelProvider extends FileDocumentProvider implements IModelProvider {
	/**
	 * @deprecated - termporary flag to change the behavior of createDocument
	 *             during revert/reset
	 */
	private boolean fReuseModelDocument = true;

	// workaround for save-as in C4
	private Vector fChangingElements = new Vector(1);

	protected class InternalModelStateListener implements IModelStateListenerExtended {
		public void modelAboutToBeChanged(IStructuredModel model) {
			// do nothing
		}

		public void modelAboutToBeReinitialized(IStructuredModel model) {
			// do nothing
		}

		public void modelChanged(IStructuredModel model) {
			// do nothing
		}

		public void modelDirtyStateChanged(IStructuredModel model, boolean isDirty) {
			fireModelDirtyStateChanged(model, isDirty);
		}

		public void modelReinitialized(IStructuredModel model) {
			reinitializeFactories(model);
		}

		public void modelResourceDeleted(IStructuredModel model) {
			fireModelDeleted(model);
		}

		public void modelResourceMoved(IStructuredModel originalmodel, IStructuredModel movedmodel) {
			fireModelMoved(originalmodel, movedmodel);
		}
	}

	/**
	 * Collection of info that goes with a model.
	 */
	protected class ModelInfo {
		public IAnnotationModel fAnnotationModel;
		public IEditorInput fElement;
		public FileSynchronizer fFileSynchronizer;
		public boolean fShouldReleaseOnInfoDispose;
		public IStructuredModel fStructuredModel;

		public ModelInfo(IStructuredModel structuredModel, IEditorInput element, IAnnotationModel model, boolean selfCreated) {
			fElement = element;
			fStructuredModel = structuredModel;
			fAnnotationModel = model;
			fShouldReleaseOnInfoDispose = selfCreated;
			fFileSynchronizer = createModelSynchronizer(element, structuredModel);
		}
	}

	private static FileModelProvider fInstance = null;
	private static IModelManager fModelManager;

	/** NLS strings */
	//    private static final String UNSUPPORTED_ENCODING_WARNING =
	// ResourceHandler.getString("1This_encoding({0})_is_not__WARN_");
	// //$NON-NLS-1$
	//$NON-NLS-1$ = "This encoding({0}) is not supported. The default encoding will be used instead."
	// CSSFileModelProvider will use this.
	protected static final String UNSUPPORTED_ENCODING_WARNING_TITLE = ResourceHandler.getString("Encoding_warning_UI_"); //$NON-NLS-1$ = "Encoding warning"

	public synchronized static FileModelProvider getInstance() {
		if (fInstance == null)
			fInstance = new FileModelProvider();
		return fInstance;
	}

	/**
	 * Utility method also used in subclasses
	 */
	protected static IModelManager getModelManager() {
		if (fModelManager == null) {
			// get the model manager from the plugin
			// note: we can use the static "ID" variable, since we pre-req
			// that plugin
			IModelManagerPlugin plugin = (IModelManagerPlugin) Platform.getPlugin(IModelManagerPlugin.ID);
			fModelManager = plugin.getModelManager();
		}
		return fModelManager;
	}

	private InternalModelStateListener fInternalModelStateListener;
	/** IStructuredModel information of all connected elements */
	private Map fModelInfoMap = new HashMap();

	protected FileModelProvider() {
		fInternalModelStateListener = new InternalModelStateListener();
	}

	/**
	 * Register additional (viewer related) factories Note: this can be called
	 * twice, one for when model first created and loaded to editor. And
	 * possible later, if a model "reinit" takes place.
	 */
	protected void addProviderFactories(IStructuredModel structuredModel) {
		// its an error to call with null argument
		if (structuredModel == null)
			return;
		EditorPlugin plugin = ((EditorPlugin) Platform.getPlugin(EditorPlugin.ID));
		AdapterFactoryRegistry adapterRegistry = plugin.getAdapterFactoryRegistry();
		Iterator adapterFactoryList = adapterRegistry.getAdapterFactories();
		IFactoryRegistry factoryRegistry = structuredModel.getFactoryRegistry();
		if (factoryRegistry == null) {
			factoryRegistry = new FactoryRegistry();
			structuredModel.setFactoryRegistry(factoryRegistry);
		}
		// And all those appropriate for this particular type of content
		while (adapterFactoryList.hasNext()) {
			try {
				AdapterFactoryProvider provider = (AdapterFactoryProvider) adapterFactoryList.next();
				if (provider.isFor(structuredModel.getModelHandler())) {
					provider.addAdapterFactories(structuredModel);
				}
			}
			catch (Exception e) {
				Logger.logException(e);
			}
		}
	}

	/**
	 * Overridden to properly use the annotation model stored within the
	 * ModelInfo
	 * 
	 * @see org.eclipse.ui.texteditor.AbstractDocumentProvider#createAnnotationModel(Object)
	 */
	protected IAnnotationModel createAnnotationModel(Object element) throws CoreException {
		IAnnotationModel model = null;
		if (element instanceof IEditorInput) {
			IFile file = (IFile) ((IEditorInput) element).getAdapter(IFile.class);
			if (file != null) {
				model = getAnnotationModel(element);
				if (model == null)
					model = new StructuredResourceMarkerAnnotationModel(file);
			}
		}
		if (model == null)
			model = super.createAnnotationModel(element);
		return model;
	}

	/**
	 * @see org.eclipse.ui.texteditor.AbstractDocumentProvider#createDocument(java.lang.Object)
	 */
	protected IDocument createDocument(Object element) {
		IDocument document = null;
		if (element instanceof IEditorInput) {
			// create a new IDocument for the element; should always reflect
			// the contents of the resource
			ModelInfo info = getModelInfoFor((IEditorInput) element);
			if (info == null) {
				throw new SourceEditingRuntimeException(new IllegalArgumentException("no corresponding model info found")); //$NON-NLS-1$
			}
			IStructuredModel model = info.fStructuredModel;
			if (model != null) {
				//                // Nitin, Do you recall why this 'model.isDirty' clause was
				// here?
				//				if (model.isDirty() && element instanceof IFileEditorInput)
				// {
				//					document = createNewStructuredDocument(((IFileEditorInput)
				// element));
				//				}
				if (!fReuseModelDocument && element instanceof IFileEditorInput) {
					//document =
					// createNewStructuredDocument(((IFileEditorInput)
					// element));
					try {
						// update document from file contents
						InputStream is = ((IFileEditorInput) element).getFile().getContents();
						BufferedReader reader = new BufferedReader(new InputStreamReader(is));

						StringBuffer text = new StringBuffer();
						String current = null;
						// read first line
						current = reader.readLine();
						while (current != null) {
							text.append(current);
							current = reader.readLine();
							if (current != null) {
								// possibly get line separator preferences?
								// for now use use system line separator
								text.append(System.getProperty("line.separator")); //$NON-NLS-1$
							}
						}
						is.close();
						reader.close();

						int currentLength = model.getStructuredDocument().getLength();
						model.getStructuredDocument().replace(0, currentLength, text.toString());
						model.setDirtyState(false);
						document = model.getStructuredDocument();
					}
					catch (CoreException e) {
						Logger.logException(e);
					}
					catch (IOException e) {
						Logger.logException(e);
					}
					catch (BadLocationException e) {
						Logger.logException(e);
					}

				}
				if (document == null) {
					document = model.getStructuredDocument();
				}
			}
		}
		return document;
	}

	/**
	 * Create a new IStructuredDocument for the file
	 * 
	 * @param element
	 * @return
	 */
	private IStructuredDocument createNewStructuredDocument(IFileEditorInput element) {
		IStructuredDocument document = null;
		try {
			document = getModelManager().createStructuredDocumentFor(element.getFile());
		}
		catch (IOException e) {
			throw new SourceEditingRuntimeException(new IllegalArgumentException("Invalid input type for creating Structured Document (I/O)")); //$NON-NLS-1$
		}
		catch (CoreException e) {
			throw new SourceEditingRuntimeException(new IllegalArgumentException("Invalid input type for creating Structured Document " + e.getStatus().getMessage())); //$NON-NLS-1$
		}
		return document;
	}

	/**
	 * Also create ModelInfo - extra resource synchronization classes should
	 * be stored within the ModelInfo
	 */
	protected ElementInfo createElementInfo(Object element) throws CoreException {
		// create the corresponding ModelInfo if necessary
		if (getModelInfoFor((IEditorInput) element) == null) {
			createModelInfo((IEditorInput) element);
		}
		ElementInfo info = super.createElementInfo(element);
		return info;
	}

	public void createModelInfo(IEditorInput input) {
		if (!(input instanceof IFileEditorInput)) {
			throw new SourceEditingRuntimeException(new IllegalArgumentException("This model provider only supports IFileEditorInputs")); //$NON-NLS-1$
		}
		if (getModelInfoFor(input) == null) {
			IStructuredModel structuredModel = selfCreateModel((IFileEditorInput) input);
			createModelInfo(input, structuredModel, true);
		}
	}

	/**
	 * To be used when model is provided to us, ensures that when setInput is
	 * used on this input, the given model will be used.
	 */
	public void createModelInfo(IEditorInput input, IStructuredModel structuredModel, boolean releaseModelOnDisconnect) {
		if (!(input instanceof IFileEditorInput)) {
			throw new SourceEditingRuntimeException(new IllegalArgumentException("This model provider only supports IFileEditorInputs")); //$NON-NLS-1$
		}
		else if (structuredModel == null) {
			throw new SourceEditingRuntimeException(new IllegalArgumentException("No model loaded for input: " + input.getName())); //$NON-NLS-1$
		}
		// we have to make sure factories are added, whether we created or
		// not.
		if (getModelInfoFor(input) != null || getModelInfoFor(structuredModel) != null)
			return;
		addProviderFactories(structuredModel);
		IAnnotationModel annotationModel = null;
		try {
			annotationModel = createAnnotationModel(input);
		}
		catch (CoreException e) {
			// just continue without one
		}
		ModelInfo modelInfo = new ModelInfo(structuredModel, input, annotationModel, releaseModelOnDisconnect);
		fModelInfoMap.put(input, modelInfo);
		if (modelInfo.fFileSynchronizer != null) {
			modelInfo.fFileSynchronizer.install();
		}
		modelInfo.fStructuredModel.addModelStateListener(fInternalModelStateListener);
		// fix once approved
		// we only resetSynchronizationStamp on model if its not set already
		if (input.getAdapter(IFile.class) != null && modelInfo.fStructuredModel.getSynchronizationStamp() == IResource.NULL_STAMP) {
			modelInfo.fStructuredModel.resetSynchronizationStamp((IResource) input.getAdapter(IFile.class));
		}
	}

	protected FileSynchronizer createModelSynchronizer(IEditorInput input, IStructuredModel model) {
		return null;
	}

	protected void disposeElementInfo(Object element, ElementInfo info) {
		super.disposeElementInfo(element, info);
		if (element instanceof IEditorInput) {
			IEditorInput input = (IEditorInput) element;
			ModelInfo modelInfo = getModelInfoFor(input);
			if (modelInfo.fFileSynchronizer != null) {
				modelInfo.fFileSynchronizer.uninstall();
			}
			disposeModelInfo(modelInfo);
		}
	}

	/**
	 * disconnect from this model info
	 * 
	 * @param info
	 */
	public void disposeModelInfo(ModelInfo info) {
		info.fStructuredModel.removeModelStateListener(fInternalModelStateListener);
		if (info.fShouldReleaseOnInfoDispose) {
			info.fStructuredModel.releaseFromEdit();
		}
		if (info.fFileSynchronizer != null) {
			info.fFileSynchronizer.uninstall();
		}
		fModelInfoMap.remove(info.fElement);
	}

public void doSaveDocument(IProgressMonitor progressMonitor, Object element, IDocument document, boolean overwrite) throws CoreException {
		//TODO: still need to "transfer" much of this logic to model level
		boolean success = false;
		Assert.isTrue(element instanceof IFileEditorInput);
		IFileEditorInput input = (IFileEditorInput) element;
		IStructuredModel model = getModel(getInputFor(document));
		Assert.isNotNull(model);
		boolean localDirtyState = model.isDirty();
		IFile resource = input.getFile();
		try {
			if (!overwrite) {
				checkSynchronizationState(((FileInfo) getElementInfo(element)).fModificationStamp, resource);
			}
			// inform about the upcoming content change
			fireElementStateChanging(element);
			try {
				model.save(resource); //, encodingname, null);
			}
			catch (UnsupportedCharsetException exception) {
				Shell shell = getActiveShell();
				// FYI: made this indirect chain of calls to help get rid of
				// our specific Exception, need to test
				// that all is updated in right order, even when error.
				EncodingMemento encodingMemento = model.getStructuredDocument().getEncodingMemento();
				String foundEncoding = encodingMemento.getDetectedCharsetName();
				String defaultToUse = encodingMemento.getAppropriateDefault();
				boolean tryDefault = openUnsupportEncodingForSave(foundEncoding, defaultToUse, resource.getName(), shell);
				if (tryDefault) {
					model.save(resource, EncodingRule.FORCE_DEFAULT);
				}
				else {
					// User has canceled Save. Keep view opened
					progressMonitor.setCanceled(true);
					return;
				}
			}
			catch (MalformedOutputExceptionWithDetail exception) {
				Shell shell = getActiveShell();
				boolean userOK = openUnconvertableCharactersWarningForSave(exception, shell); //resource.getName()
				if (userOK) {
					model.save(resource, EncodingRule.IGNORE_CONVERSION_ERROR);
				}
				else {
					// User has canceled Save. Keep view opened
					progressMonitor.setCanceled(true);
					return;
				}
			}
			catch (CharConversionErrorWithDetail exception) {
				Shell shell = getActiveShell();
				boolean userOK = openUnconvertableCharactersWarningForSave(exception, shell); //resource.getName()
				if (userOK) {
					model.save(resource, EncodingRule.IGNORE_CONVERSION_ERROR);
				}
				else {
					// User has canceled Save. Keep view opened
					progressMonitor.setCanceled(true);
					//outStream.close();
					//outStream = null;
					return;
				}
			}
			if (!resource.exists())  {
				progressMonitor.beginTask(ResourceHandler.getString("FileDocumentProvider.task.saving"), 2000); //$NON-NLS-1$ 
				ContainerGenerator generator = new ContainerGenerator(resource.getParent().getFullPath());
				generator.generateContainer(new SubProgressMonitor(progressMonitor, 1000));
			}
			// if we get to here without an exception... success!
			success = true;
			model.setDirtyState(false);
			model.resetSynchronizationStamp(resource);

			// update markers
			if (getAnnotationModel(element) instanceof AbstractMarkerAnnotationModel) {
				((AbstractMarkerAnnotationModel) getAnnotationModel(element)).updateMarkers(document);
			}
			// reset the modification stamp record so we know we don't try to
			// reload on following resource change notifications
			FileInfo info = (FileInfo) getElementInfo(element);
			if (info != null) {
				info.fModificationStamp = computeModificationStamp(resource);
			}

			//For error handling test only!!!==========
			//
			//Uncomment the following line of code to simulate a
			// FileNotFoundException.
			//throw new FileNotFoundException();
			//
			//Uncomment the following line of code to simulate a
			// UnsupportedEncodingException.
			//throw new UnsupportedEncodingException();
			//
			//Uncomment the following line of code to simulate a IOException.
			//throw new IOException();
			//For error handling test only!!!==========
		}
		catch (java.io.FileNotFoundException exception) { 
			/*
			 * The FileNotFoundException's message may not be very meaningful
			 * to user. Since the SourceEditingRuntimeException(exception,
			 * message) form will use just the detail message in the passed-in
			 * exception (instead of concatenating the detail message with the
			 * additional message), we are converting this exception into a
			 * more informative message. Same idea applies to the following
			 * catch blocks.
			 */			
			progressMonitor.setCanceled(true);
			// inform about failure
			fireElementStateChangeFailed(element);
			throw new SourceEditingRuntimeException(ResourceHandler.getString("Unable_to_save_the_documen_ERROR_")); //$NON-NLS-1$ = "Unable to save the document. Output file not found."
		}
		catch (UnsupportedEncodingException exception) {
			progressMonitor.setCanceled(true);
			// inform about failure
			fireElementStateChangeFailed(element);
			throw new SourceEditingRuntimeException(ResourceHandler.getString("Unable_to_save_the_documen1_ERROR_")); //$NON-NLS-1$ = "Unable to save the document. Unsupported encoding."
		}
		catch (java.io.IOException exception) {
			progressMonitor.setCanceled(true);
			// inform about failure
			fireElementStateChangeFailed(element);
			throw new SourceEditingRuntimeException(ResourceHandler.getString("Unable_to_save_the_documen2_ERROR_")); //$NON-NLS-1$
			//$NON-NLS-1$ = "Unable to save the document. An I/O error occurred while saving the document."
		}
		catch (OperationCanceledException exception) {
			Logger.log(Logger.INFO, "Save Operation Canceled at user's request"); //$NON-NLS-1$
		}
		finally {
			if (!success) {
				model.setDirtyState(localDirtyState);
			}
		}
	}	protected void fireModelContentAboutToBeReplaced(IStructuredModel model) {
	}

	protected void fireModelContentReplaced(IStructuredModel model) {
	}

	protected void fireModelDeleted(IStructuredModel model) {
	}

	protected void fireModelDirtyStateChanged(IStructuredModel model, final boolean isDirty) {
	}

	protected void fireModelMoved(IStructuredModel originalModel, IStructuredModel movedModel) {
	}

	protected Shell getActiveShell() {
		// Looks like Display tells me what is the current active Shell
		// so that it seems not to ask EditorPart to give me a Shell.
		// Same technique in used by
		// Infopop(org.eclipse.help.internal.ui.ContextHelpDialog(Object [],
		// int, int))
		Display dsp = getDisplay();
		Shell shell = dsp.getActiveShell();
		return shell;
	}

	private Display getDisplay() {

		return PlatformUI.getWorkbench().getDisplay();
	}

	/**
	 * Overridden to use ModelInfo's annotation model
	 * 
	 * @see org.eclipse.ui.texteditor.IDocumentProvider#getAnnotationModel(java.lang.Object)
	 */
	public IAnnotationModel getAnnotationModel(Object element) {
		// override behavior an retrieve the annotation model from the model
		// info
		ModelInfo info = getModelInfoFor((IEditorInput) element);
		if (info != null)
			return info.fAnnotationModel;
		return null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.editors.text.IStorageDocumentProvider#getEncoding(java.lang.Object)
	 */
	public String getEncoding(Object element) {
		EncodingMemento em = null;
		IStructuredModel model = getModel((IEditorInput) element);
		// model can be null if opened on non-expected file
		if (model != null) {
			em = model.getStructuredDocument().getEncodingMemento();
		}
		// DefaultEncodingSupport uses IANA names
		if (em != null)
			return em.getDetectedCharsetName();
		return super.getEncoding(element);
	}

	protected IEditorInput getInputFor(IDocument document) {
		IStructuredModel model = getModelManager().getExistingModelForRead(document);
		IEditorInput input = getInputFor(model);
		model.releaseFromRead();
		return input;
	}

	protected IEditorInput getInputFor(IStructuredModel structuredModel) {
		IEditorInput result = null;
		ModelInfo info = getModelInfoFor(structuredModel);
		if (info != null)
			result = info.fElement;
		return result;
	}

	public IStructuredModel getModel(IEditorInput element) {
		IStructuredModel result = null;
		ModelInfo info = getModelInfoFor(element);
		if (info != null) {
			result = info.fStructuredModel;
		}
		return result;
	}

	/*
	 * (non-Javadoc)
	 * 
	 */
	public IStructuredModel getModel(Object element) {
		Assert.isTrue(element instanceof IFileEditorInput);
		return getModel((IFileEditorInput) element);
	}

	protected ModelInfo getModelInfoFor(IEditorInput element) {
		ModelInfo result = (ModelInfo) fModelInfoMap.get(element);
		return result;
	}

	protected ModelInfo getModelInfoFor(IStructuredModel structuredModel) {
		ModelInfo result = null;
		if (structuredModel != null) {
			ModelInfo[] modelInfos = (ModelInfo[]) fModelInfoMap.values().toArray(new ModelInfo[0]);
			for (int i = 0; i < modelInfos.length; i++) {
				ModelInfo info = modelInfos[i];
				if (structuredModel.equals(info.fStructuredModel)) {
					result = info;
					break;
				}
			}
		}
		return result;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.editors.text.FileDocumentProvider#getPersistedEncoding(java.lang.Object)
	 */
	protected String getPersistedEncoding(Object element) {
		EncodingMemento em = null;
		IStructuredModel model = getModel((IEditorInput) element);
		if (model != null) {
			em = model.getStructuredDocument().getEncodingMemento();
		}
		// DefaultEncodingSupport uses IANA names
		if (em != null) {
			return em.getDetectedCharsetName();
		}
		else {
			// error condition
			return ""; //$NON-NLS-1$
		}
	}

	/**
	 * Defines the standard procedure to handle CoreExceptions.
	 * 
	 * @param exception
	 *            the exception to be logged
	 * @param message
	 *            the message to be logged
	 */
	protected void handleCoreException(CoreException exception, String message) {
		Logger.logException(message, exception);
	}

	/**
	 * Updates the element info and Document contents to a change of the file
	 * content and sends out appropriate notifications.
	 * 
	 * @param fileEditorInput
	 *            the input of a text editor
	 */
	protected void handleElementContentChanged(IFileEditorInput fileEditorInput) {
		FileInfo info = (FileInfo) getElementInfo(fileEditorInput);
		if (info == null)
			return;

		String oldContents = getModel(fileEditorInput).getStructuredDocument().get();

		try {
			refreshFile(fileEditorInput.getFile());
		}
		catch (CoreException x) {
			handleCoreException(x, "FileDocumentProvider.handleElementContentChanged"); //$NON-NLS-1$
		}

		// set the new content and fire content related events
		fireElementContentAboutToBeReplaced(fileEditorInput);
		removeUnchangedElementListeners(fileEditorInput, info);
		
		// direct superclass also removes but never adds?
		info.fDocument.removeDocumentListener(info);
		
		boolean reloaded = false;
		try {
			InputStream inStream = fileEditorInput.getFile().getContents(true);
			getModel(fileEditorInput).reload(inStream);
			reloaded = true;
		}
		catch (IOException e) {
			info.fStatus = new Status(IStatus.ERROR, EditorPlugin.ID, IStatus.ERROR, "error reloading " + fileEditorInput.getName(), e);
		}
		catch (CoreException e) {
			info.fStatus = e.getStatus();
		}
		info.fDocument = getModel(fileEditorInput).getStructuredDocument();

		info.fCanBeSaved = false;
		info.fModificationStamp = computeModificationStamp(fileEditorInput.getFile());
		if (reloaded) {
			info.fStatus = null;
		}

		addUnchangedElementListeners(fileEditorInput, info);
		fireElementContentReplaced(fileEditorInput);
		if (!reloaded) {
			info.fDocument.set(oldContents);
		}
	}

	/**
	 * @see org.eclipse.ui.editors.text.FileDocumentProvider#isModifiable(java.lang.Object)
	 */
	public boolean isModifiable(Object element) {
		return super.isModifiable(element); //!isReadOnly(element);
	}

	/**
	 * @see org.eclipse.ui.texteditor.IDocumentProvider#mustSaveDocument(java.lang.Object)
	 *      <br>
	 * 
	 * The rule is that if it is sharedForEdit, then it never "must be saved",
	 * but if its not sharedForEdit, then it depends on its dirty state.
	 */
	public boolean mustSaveDocument(Object element) {
		boolean result = false;
		if (getModel((IEditorInput) element) != null) {
			if (!getModel((IEditorInput) element).isSharedForEdit()) {
				result = getModel((IEditorInput) element).isDirty();
			}
		}
		return result;
	}

	protected boolean openUnconvertableCharactersWarningForSave(MalformedOutputExceptionWithDetail outputException, Shell topshell) {
		// open message dialog
		final String title = UNSUPPORTED_ENCODING_WARNING_TITLE;
		String userMessage = ResourceHandler.getString("cannot_convert_some_characters"); //$NON-NLS-1$
		MessageFormat form = new MessageFormat(userMessage);
		Object[] args = {outputException.getAttemptedIANAEncoding(), Integer.toString(outputException.getCharPosition())};
		final String msg = form.format(args);
		Shell shell = getActiveShell();
		MessageDialog warning = new MessageDialog(shell, title, null, msg, MessageDialog.QUESTION, new String[]{IDialogConstants.OK_LABEL, IDialogConstants.CANCEL_LABEL}, 0);
		if (warning.open() == 0)
			return true;
		return false;
	}

	private boolean openUnconvertableCharactersWarningForSave(CharConversionErrorWithDetail outputException, Shell topshell) {
		// open message dialog
		final String title = UNSUPPORTED_ENCODING_WARNING_TITLE;
		String userMessage = ResourceHandler.getString("cannot_convert_some_characters2"); //$NON-NLS-1$
		MessageFormat form = new MessageFormat(userMessage);
		Object[] args = {outputException.getCharsetName()};
		final String msg = form.format(args);
		Shell shell = getActiveShell();
		MessageDialog warning = new MessageDialog(shell, title, null, msg, MessageDialog.QUESTION, new String[]{IDialogConstants.OK_LABEL, IDialogConstants.CANCEL_LABEL}, 0);
		if (warning.open() == 0)
			return true;
		return false;
	}

	protected void openUndecodableCharacterError(MalformedInputExceptionWithDetail e) {
		// checked and coordinated among all editors.
		String title = ResourceHandler.getString("Error_opening_file_UI_"); //$NON-NLS-1$ = "Error opening file"
		String msg = e.toString();
		// if the exception char position < 0, perhaps we exceeded the max
		// buffer when detecting pos of error
		// if that is the case, display a different error message
		IStatus status;
		if ((e.getCharPosition() < 0) && (e.isExceededMax()))
			status = new Status(IStatus.ERROR, EditorPlugin.ID, 0, ResourceHandler.getString("8concat_ERROR_", (new Object[]{Integer.toString(e.getMaxBuffer()), e.getAttemptedIANAEncoding()})), e); //$NON-NLS-1$
		else
			status = new Status(IStatus.ERROR, EditorPlugin.ID, 0, ResourceHandler.getString("7concat_ERROR_", (new Object[]{(Integer.toString(e.getCharPosition())), e.getAttemptedIANAEncoding()})), e); //$NON-NLS-1$
		//$NON-NLS-1$ = "Could not be decoded character (at position {0}) according to the encoding parameter {1}"
		ErrorDialog.openError(getActiveShell(), title, msg, status);
	}

	protected void openUnsupportedEncodingWarningForLoad(String encoding, String defaultToUse) {
		// open message dialog
		final String title = UNSUPPORTED_ENCODING_WARNING_TITLE;
		MessageFormat form = new MessageFormat(ResourceHandler.getString("This_encoding_({0})_is_not_supported._The_default_encoding_({1})_will_be_used_instead._1")); //$NON-NLS-1$
		Object[] args = {encoding, defaultToUse};
		final String msg = form.format(args);
		Shell shell = getActiveShell();
		MessageDialog warning = new MessageDialog(shell, title, null, msg, MessageDialog.WARNING, new String[]{IDialogConstants.OK_LABEL}, 0);
		warning.open();
	}

	protected boolean openUnsupportEncodingForSave(String foundEncoding, String defaultEncodingToUse, String dialogTitle, Shell topshell) {
		if (topshell == null)
			return true; // if no topshell, return true;
		// open message dialog
		//  MessageFormat form = new
		// MessageFormat(ResourceHandler.getString("This_encoding({0})_is_not__WARN_"));
		// //$NON-NLS-1$ = "This encoding({0}) is not supported. Continue ?"
		MessageFormat form = new MessageFormat(ResourceHandler.getString("This_encoding_({0})_is_not_supported._Continue_the_save_using_the_default_({1})__2")); //$NON-NLS-1$
		Object[] args = {foundEncoding, defaultEncodingToUse};
		final String msg = form.format(args);
		MessageDialog warning = new MessageDialog(topshell, dialogTitle, null, msg, MessageDialog.QUESTION, new String[]{IDialogConstants.OK_LABEL, IDialogConstants.CANCEL_LABEL}, 0);
		if (warning.open() == 0)
			return true;
		return false;
	}

	/**
	 * Register additional (viewer related) factories Note: this can be called
	 * twice, one for when model first created and loaded to editor. And
	 * possible later, if a model "reinit" takes place.
	 */
	protected void reinitializeFactories(IStructuredModel structuredModel) {
		// its an error to call with null argument
		if (structuredModel == null)
			return;
		EditorPlugin plugin = ((EditorPlugin) Platform.getPlugin(EditorPlugin.ID));
		AdapterFactoryRegistry adapterRegistry = plugin.getAdapterFactoryRegistry();
		Iterator adapterList = adapterRegistry.getAdapterFactories();
		// And all those appropriate for this particular type of content
		while (adapterList.hasNext()) {
			try {
				AdapterFactoryProvider provider = (AdapterFactoryProvider) adapterList.next();
				if (provider.isFor(structuredModel.getModelHandler())) {
					provider.reinitializeFactories(structuredModel);
				}
			}
			catch (Exception e) {
				Logger.logException(e);
			}
		}
	}

	protected IStructuredModel selfCreateModel(IFileEditorInput input) {
		// this method should be called only after is established the
		// desired model is not in the active items list.
		IStructuredModel structuredModel = getModelManager().getExistingModelForEdit(input.getFile());
		if (structuredModel == null) {
			try {
				try {
					structuredModel = getModelManager().getModelForEdit(input.getFile()); //
				}
				catch (UnsupportedCharsetException exception) {
					// TODO-future: user should be given a choice here to try
					// other encodings other than 'default'
					EncodingMemento encodingMemento = null;
					if (exception instanceof org.eclipse.wst.encoding.exceptions.UnsupportedCharsetExceptionWithDetail) {
						org.eclipse.wst.encoding.exceptions.UnsupportedCharsetExceptionWithDetail detailedException = (org.eclipse.wst.encoding.exceptions.UnsupportedCharsetExceptionWithDetail) exception;
						encodingMemento = detailedException.getEncodingMemento();
					}

					String foundEncoding = encodingMemento.getDetectedCharsetName();
					String defaultToUse = encodingMemento.getAppropriateDefault();
					openUnsupportedEncodingWarningForLoad(foundEncoding, defaultToUse);
					try {
						structuredModel = getModelManager().getModelForEdit(input.getFile(), EncodingRule.FORCE_DEFAULT); //$NON-NLS-1$ //$NON-NLS-2$
					}
					catch (MalformedInputExceptionWithDetail ex) { // this
						openUndecodableCharacterError(ex);
						structuredModel = null; 
					}
				}
				catch (MalformedInputExceptionWithDetail e) { 
					openUndecodableCharacterError(e);

					structuredModel = getModelManager().getModelForEdit(input.getFile(), EncodingRule.IGNORE_CONVERSION_ERROR);
				}
			}
			catch (CoreException e) {
				throw new SourceEditingRuntimeException(e);
			}
			catch (IOException e) {
				throw new SourceEditingRuntimeException(e);
			}
		}
		return structuredModel;
	}

	/**
	 * This method is intended for those uses where the model has already been
	 * obtained and provided by the client (with its own id, not necessarily
	 * the one we would create by default). We require the input not to create
	 * a model, but to retrieve the annotation data that goes with this
	 * resouce.
	 */
	public void setModel(IStructuredModel model, IEditorInput input) {
		createModelInfo(input, model, false);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.texteditor.IDocumentProviderExtension#synchronize(java.lang.Object)
	 */
	public void doSynchronize(Object element, IProgressMonitor monitor) throws CoreException {
		super.doSynchronize(element, monitor);
		if (element instanceof IFileEditorInput) {
			IFileEditorInput input = (IFileEditorInput) element;
			getModel(input).resetSynchronizationStamp(input.getFile());
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.texteditor.AbstractDocumentProvider#doResetDocument(java.lang.Object,
	 *      org.eclipse.core.runtime.IProgressMonitor)
	 */
	protected void doResetDocument(Object element, IProgressMonitor monitor) throws CoreException {
		fReuseModelDocument = false;
		super.doResetDocument(element, monitor);
		fReuseModelDocument = true;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.texteditor.IDocumentProvider#aboutToChange(java.lang.Object)
	 */
	public void aboutToChange(Object element) {

		super.aboutToChange(element);

		// start recording for revert
		IStructuredModel model = getModel(element);
		if (model != null) {
			fChangingElements.add(element);
			StructuredTextUndoManager undoMgr = model.getUndoManager();
			int offset = undoMgr.getTextViewer().getTextWidget().getCaretOffset();
			undoMgr.beginRecording(this, offset, 0);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.texteditor.IDocumentProvider#changed(java.lang.Object)
	 */
	public void changed(Object element) {

		super.changed(element);

		// end recording for revert
		if (fChangingElements.contains(element)) {
			fChangingElements.remove(element);
			StructuredTextUndoManager undoMgr = getModel(element).getUndoManager();
			undoMgr.endRecording(this, 0, 0);
			undoMgr.getTextViewer().getTextWidget().setCaretOffset(0);
		}
	}

}

Back to the top