Skip to main content
summaryrefslogtreecommitdiffstats
blob: d8acbd11282ee5799bc986cc714ff68fe5b4d3b6 (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
/*******************************************************************************
 * Copyright (c) 2000, 2004 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 Corporation - initial API and implementation
 *******************************************************************************/
package org.eclipse.core.internal.filebuffers;

import java.io.File;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IResourceChangeListener;
import org.eclipse.core.resources.IResourceDelta;
import org.eclipse.core.resources.IResourceDeltaVisitor;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.ILog;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Status;

import org.eclipse.core.filebuffers.FileBuffers;


public abstract class ResourceFileBuffer extends AbstractFileBuffer {
	
		/**
		 * Runnable encapsulating an element state change. This runnable ensures 
		 * that a element change failed message is sent out to the element state
		 * listeners in case an exception occurred.
		 */
		private class SafeFileChange implements Runnable {
				
			/**
			 * Creates a new safe runnable for the given file.
			 */
			public SafeFileChange() {
			}
					
			/** 
			 * Execute the change.
			 * Subclass responsibility.
			 * 
			 * @exception an exception in case of error
			 */
			protected void execute() throws Exception {
			}
			
			/**
			 * Does everything necessary prior to execution.
			 */
			public void preRun() {
				fManager.fireStateChanging(ResourceFileBuffer.this);
			}
				
			/*
			 * @see java.lang.Runnable#run()
			 */
			public void run() {
				
				if (isDisposed()) {
					fManager.fireStateChangeFailed(ResourceFileBuffer.this);
					return;
				}
				
				try {
					execute();
				} catch (Exception x) {
					FileBuffersPlugin.getDefault().getLog().log(new Status(IStatus.ERROR, FileBuffersPlugin.PLUGIN_ID, IStatus.OK, "Exception when synchronizing", x)); //$NON-NLS-1$
					fManager.fireStateChangeFailed(ResourceFileBuffer.this);
				}
			}
		}
		
		/**
		 * Synchronizes the document with external resource changes.
		 */
		private class FileSynchronizer implements IResourceChangeListener, IResourceDeltaVisitor {
				
			/** A flag indicating whether this synchronizer is installed or not. */
			private boolean fIsInstalled= false;
				
			/**
			 * Creates a new file synchronizer. Is not yet installed on a file.
			 */
			public FileSynchronizer() {
			}
						
			/**
			 * Installs the synchronizer on the file.
			 */
			public void install() {
				fFile.getWorkspace().addResourceChangeListener(this);
				fIsInstalled= true;
			}
				
			/**
			 * Uninstalls the synchronizer from the file.
			 */
			public void uninstall() {
				fFile.getWorkspace().removeResourceChangeListener(this);
				fIsInstalled= false;
			}
				
			/*
			 * @see IResourceChangeListener#resourceChanged(IResourceChangeEvent)
			 */
			public void resourceChanged(IResourceChangeEvent e) {
				IResourceDelta delta= e.getDelta();
				try {
					if (delta != null && fIsInstalled)
						delta.accept(this);
				} catch (CoreException x) {
					handleCoreException(x); 
				}
			}
				
			/*
			 * @see IResourceDeltaVisitor#visit(org.eclipse.core.resources.IResourceDelta)
			 */
			public boolean visit(IResourceDelta delta) throws CoreException {
								
				if (delta != null && fFile.equals(delta.getResource())) {
						
					SafeFileChange fileChange= null;
						
					switch (delta.getKind()) {
						case IResourceDelta.CHANGED:
							if ((IResourceDelta.CONTENT & delta.getFlags()) != 0) {
								if (!isDisposed() && !fCanBeSaved && !isSynchronized()) {
									fileChange= new SafeFileChange() {
										protected void execute() throws Exception {
											handleFileContentChanged();
										}
									};
								}
							}
							break;
						case IResourceDelta.REMOVED:
							if ((IResourceDelta.MOVED_TO & delta.getFlags()) != 0) {
								final IPath path= delta.getMovedToPath();
								fileChange= new SafeFileChange() {
									protected void execute() throws Exception {
										handleFileMoved(path);
									}
								};
							} else {
								if (!isDisposed() && !fCanBeSaved) {
									fileChange= new SafeFileChange() {
										protected void execute() throws Exception {
											handleFileDeleted();
										}
									};
								}
							}
							break;
					}
						
					if (fileChange != null) {
						fileChange.preRun();
						fManager.execute(fileChange, fSynchronizationContextCount > 0);
					}
				}
					
				return true; // because we are sitting on files anyway
			}
		}
		
		
		
	/** The location */
	protected IPath fLocation;
	/** The element for which the info is stored */
	protected IFile fFile;
	/** How often the element has been connected */
	protected int fReferenceCount;
	/** Can the element be saved */
	protected boolean fCanBeSaved= false;
	/** Has element state been validated */
	protected boolean fIsStateValidated= false;
	/** The status of this element */
	protected IStatus fStatus;
	/** The file synchronizer. */
	protected FileSynchronizer fFileSynchronizer;
	/** The time stamp at which this buffer synchronized with the underlying file. */
	protected long fSynchronizationStamp= IFile.NULL_STAMP;
	/** How often the synchronization context has been requested */
	protected int fSynchronizationContextCount;
	/** The text file buffer manager */
	protected TextFileBufferManager fManager;
	
	
	
	
	public ResourceFileBuffer(TextFileBufferManager manager) {
		super();
		fManager= manager;
	}
	
	abstract protected void handleFileContentChanged();
	
	abstract protected void addFileBufferContentListeners();
	
	abstract protected void removeFileBufferContentListeners();
	
	abstract protected void initializeFileBufferContent(IProgressMonitor monitor) throws CoreException;
	
	abstract protected void commitFileBufferContent(IProgressMonitor monitor, boolean overwrite) throws CoreException;
	
	public void create(IPath location, IProgressMonitor monitor) throws CoreException {
		IFile file= FileBuffers.getWorkspaceFileAtLocation(location);
		if (file == null || !file.exists())
			throw new CoreException(new Status(IStatus.ERROR, FileBuffersPlugin.PLUGIN_ID, IStatus.OK, FileBuffersMessages.getString("FileBuffer.error.fileDoesNotExist"), null)); //$NON-NLS-1$
		
		fLocation= location;
		fFile= file;
		fFileSynchronizer= new FileSynchronizer();
		
		refreshFile(monitor);
		initializeFileBufferContent(monitor);
		fSynchronizationStamp= fFile.getModificationStamp();
		
		addFileBufferContentListeners();
	}
	
	public void connect() {
		++ fReferenceCount;
		if (fReferenceCount == 1)
			connected();
	}
	
	/**
	 * Called when this file buffer has been connected. This is the case when
	 * there is exactly one connection.
	 * <p>
	 * Clients may extend this method.
	 */
	protected void connected() {
		fFileSynchronizer.install();
	}

	public void disconnect() throws CoreException {
		-- fReferenceCount;
		if (fReferenceCount == 0)
			disconnected();
	}
	
	/**
	 * Called when this file buffer has been disconnected. This is the case when
	 * the number of connections drops to <code>0</code>.
	 * <p>
	 * Clients may extend this method.
	 */
	protected void disconnected() {
		if (fFileSynchronizer != null)
			fFileSynchronizer.uninstall();
		fFileSynchronizer= null;
	}

	/**
	 * Returns whether this file buffer has already been disposed.
	 * 
	 * @return <code>true</code> if already disposed, <code>false</code> otherwise
	 */
	public boolean isDisposed() {
		return fFileSynchronizer == null;
	}
	
	/*
	 * @see org.eclipse.core.filebuffers.IFileBuffer#getLocation()
	 */
	public IPath getLocation() {
		return fLocation;
	}

	/*
	 * @see org.eclipse.core.filebuffers.IFileBuffer#commit(org.eclipse.core.runtime.IProgressMonitor, boolean)
	 */
	public void commit(IProgressMonitor monitor, boolean overwrite) throws CoreException {
		if (!isDisposed() && fCanBeSaved) {
			
			fManager.fireStateChanging(this);
			
			try {
				commitFileBufferContent(monitor, overwrite);
			} catch (CoreException x) {
				fManager.fireStateChangeFailed(this);
				throw x;
			} catch (RuntimeException x) {
				fManager.fireStateChangeFailed(this);
				throw x;				
			}
			
			fCanBeSaved= false;
			addFileBufferContentListeners();
			fManager.fireDirtyStateChanged(this, fCanBeSaved);
		}
	}

	/*
	 * @see org.eclipse.core.filebuffers.IFileBuffer#isDirty()
	 */
	public boolean isDirty() {
		return fCanBeSaved;
	}
	
	/*
	 * @see org.eclipse.core.filebuffers.IFileBuffer#isShared()
	 */
	public boolean isShared() {
		return fReferenceCount > 1;
	}

	/*
	 * @see org.eclipse.core.filebuffers.IFileBuffer#validateState(org.eclipse.core.runtime.IProgressMonitor, java.lang.Object)
	 */
	public void validateState(IProgressMonitor monitor, Object computationContext) throws CoreException {
		if (!isDisposed() && !fIsStateValidated)  {
			
			if (fFile.isReadOnly()) {
				IWorkspace workspace= fFile.getWorkspace();
				fStatus= workspace.validateEdit(new IFile[] { fFile }, computationContext);
				if (fStatus.isOK())
					handleFileContentChanged();
			}
			fIsStateValidated= true;
			fManager.fireStateValidationChanged(this, fIsStateValidated);
		}
	}

	/*
	 * @see org.eclipse.core.filebuffers.IFileBuffer#isStateValidated()
	 */
	public boolean isStateValidated() {
		return fIsStateValidated;
	}
	
	/*
	 * @see org.eclipse.core.filebuffers.IFileBuffer#resetStateValidation()
	 */
	public void resetStateValidation() {
		if (fIsStateValidated) {
			fIsStateValidated= false;
			fManager.fireStateValidationChanged(this, fIsStateValidated);
		}
	}

	/**
	 * Sends out the notification that the file serving as document input has been moved.
	 * 
	 * @param newLocation the path of the new location of the file
	 */
	protected void handleFileMoved(IPath newLocation) {
		fManager.fireUnderlyingFileMoved(this, newLocation);
	}
	
	/**
	 * Sends out the notification that the file serving as document input has been deleted.
	 */
	protected void handleFileDeleted() {
		fManager.fireUnderlyingFileDeleted(this);
	}
	
	/**
	 * Refreshes the given  file.
	 */
	protected void refreshFile(IProgressMonitor monitor) {
		try {
			fFile.refreshLocal(IFile.DEPTH_INFINITE, monitor);
		} catch (OperationCanceledException x) {
		} catch (CoreException x) {
			handleCoreException(x);
		}
	}

	/**
	 * Defines the standard procedure to handle <code>CoreExceptions</code>. Exceptions
	 * are written to the plug-in log.
	 *
	 * @param exception the exception to be logged
	 * @param message the message to be logged
	 */
	protected void handleCoreException(CoreException exception) {
		ILog log= FileBuffersPlugin.getDefault().getLog();
		log.log(exception.getStatus());
	}
	
	/*
	 * @see org.eclipse.core.filebuffers.IFileBuffer#isSynchronized()
	 */
	public boolean isSynchronized() {
		return fSynchronizationStamp == fFile.getModificationStamp() && fFile.isSynchronized(IResource.DEPTH_ZERO);
	}
	
	/*
	 * @see org.eclipse.core.filebuffers.IFileBuffer#getModificationStamp()
	 */
	public long getModificationStamp() {
		File file= FileBuffers.getSystemFileAtLocation(getLocation());
		if (file != null)
			return file.lastModified();
		return IResource.NULL_STAMP;
	}
	
	/**
	 * Requests the file buffer manager's synchronization context for this file buffer.
	 */
	public void requestSynchronizationContext() {
		++ fSynchronizationContextCount;
	}
	
	/**
	 * Releases the file buffer manager's synchronization context for this file buffer.
	 */
	public void releaseSynchronizationContext() {
		-- fSynchronizationContextCount;
	}
}

Back to the top