Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 084f21e9c1aa2dfd6219f58a6bca5fe717dcfffa (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
/*******************************************************************************
 * Copyright (c) 2005, 2010 Intel Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 * Intel Corporation - Initial API and implementation
 *******************************************************************************/

package org.eclipse.cdt.managedbuilder.internal.core;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;

import org.eclipse.cdt.managedbuilder.core.IConfiguration;
import org.eclipse.cdt.managedbuilder.core.IManagedBuildInfo;
import org.eclipse.cdt.managedbuilder.core.IManagedOptionValueHandler;
import org.eclipse.cdt.managedbuilder.core.IManagedProject;
import org.eclipse.cdt.managedbuilder.core.IResourceConfiguration;
import org.eclipse.cdt.managedbuilder.core.ManagedBuildManager;
import org.eclipse.cdt.managedbuilder.core.ManagedBuilderCorePlugin;
import org.eclipse.cdt.managedbuilder.core.ManagedCProjectNature;
import org.eclipse.cdt.managedbuilder.makegen.IManagedBuilderMakefileGenerator;
import org.eclipse.core.resources.IProject;
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.IResourceRuleFactory;
import org.eclipse.core.resources.ISaveContext;
import org.eclipse.core.resources.ISaveParticipant;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.ISchedulingRule;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.core.runtime.jobs.MultiRule;

public class ResourceChangeHandler implements IResourceChangeListener, ISaveParticipant {
	
	private Map<IProject, IManagedBuildInfo> fRmProjectToBuildInfoMap = new HashMap<IProject, IManagedBuildInfo>();

	private class ResourceConfigurationChecker implements IResourceDeltaVisitor{
		private IResourceDelta fRootDelta;
		private HashMap<IProject, IManagedBuilderMakefileGenerator> fBuildFileGeneratorMap = new HashMap<IProject, IManagedBuilderMakefileGenerator>();
		private HashSet<IPath> fValidatedFilesSet = new HashSet<IPath>();
		private HashSet<IProject> fModifiedProjects = new HashSet<IProject>();

		public ResourceConfigurationChecker(IResourceDelta rootDelta){
			fRootDelta = rootDelta;
		}
		
		public IProject[] getModifiedProjects(){
			return fModifiedProjects.toArray(new IProject[fModifiedProjects.size()]);
		}

		public boolean visit(IResourceDelta delta) throws CoreException {
			IResource dResource = delta.getResource();
			int rcType = dResource.getType(); 
			
			if(rcType == IResource.PROJECT || rcType == IResource.FOLDER){
				IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
				IProject project = null;
				IResource rcToCheck = null;
				switch (delta.getKind()) {
				case IResourceDelta.REMOVED :
					if (rcType == IResource.PROJECT){
						IManagedBuildInfo info = fRmProjectToBuildInfoMap.remove(dResource);

						if((delta.getFlags() & IResourceDelta.MOVED_TO) == 0) {
							if(info != null){
								sendClose(info);
								PropertyManager.getInstance().clearProperties(info.getManagedProject());
							}
							break;
						}
					}
				case IResourceDelta.CHANGED :
					if ((delta.getFlags() & IResourceDelta.MOVED_TO) != 0) {
						IPath path = delta.getMovedToPath();
						if(path != null){
							project = root.findMember(path.segment(0)).getProject();
							if(project != null && rcType == IResource.FOLDER)
								rcToCheck = root.getFolder(substituteProject(dResource.getFullPath(),project.getName()));
						}
						break;
					}
				default:
					project = dResource.getProject();
					if(rcType == IResource.FOLDER)
						rcToCheck = dResource;
					break;
				}

				if(project != null) {
					IManagedBuilderMakefileGenerator makeGen = getInitializedGenerator(project);
					if(makeGen != null){
						if(rcToCheck == null || !makeGen.isGeneratedResource(rcToCheck))
							return true;
					}
				}
				return false;
			} else if (rcType == IResource.FILE && !dResource.isDerived()) {
				int flags = delta.getFlags();
				switch (delta.getKind()) {
				case IResourceDelta.REMOVED :
					if ((flags & IResourceDelta.MOVED_TO) == 0) {
						handleDeleteFile(dResource.getFullPath());
						break;
					}
				case IResourceDelta.ADDED :
				case IResourceDelta.CHANGED :
				    if ((flags & IResourceDelta.MOVED_TO) != 0) {
				    	IPath path = delta.getMovedToPath();
				    	if (path != null) {
				    		handleRenamedFile(
				    				  dResource.getFullPath(),
				    				  path);
				    	}
				    } else if ((flags & IResourceDelta.MOVED_FROM) != 0) {
						IPath path = delta.getMovedFromPath();
				    	if (path != null) {
				    		handleRenamedFile(
				    				  path,
				    				  dResource.getFullPath());
				    	}
				    }
					break;

				default:
					break;
				}
				return false;
			}
			return true;	//  visit the children
		}
		
		private IPath substituteProject(IPath path, String projectName){
			return new Path(projectName).makeAbsolute().append(path.removeFirstSegments(1));
		}

		private void handleRenamedFile(IPath fromPath, IPath toPath){
			if(!fValidatedFilesSet.add(fromPath))
				return;

			IProject fromProject = findModifiedProject(fromPath.segment(0));
			if(fromProject == null)
				return;
			IManagedBuilderMakefileGenerator fromMakeGen = getInitializedGenerator(fromProject);
			IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
			if(fromMakeGen == null || fromMakeGen.isGeneratedResource(root.getFile(substituteProject(fromPath,fromProject.getName()))))
				return;
			
			IManagedBuildInfo fromInfo = ManagedBuildManager.getBuildInfo(fromProject);

			IProject toProject = root.findMember(toPath.uptoSegment(1)).getProject();
			IManagedBuildInfo toInfo = toProject != null ? 
					ManagedBuildManager.getBuildInfo(toProject) :
						null;
			IManagedBuilderMakefileGenerator toMakeGen = toProject != null ? 
					getInitializedGenerator(toProject) :
						null;
			if(toMakeGen != null && toMakeGen.isGeneratedResource(root.getFile(toPath)))
				toInfo = null;

			if(fromInfo == toInfo){
				//the resource was moved within the project scope
				if(updateResourceConfigurations(fromInfo,fromPath,toPath) && toProject != null)
					fModifiedProjects.add(toProject);
			} else {
				if(fromInfo != null && toInfo != null){
					//TODO: this is the case when the resource
					//is moved from one managed project to another
					//should we handle this?
					//e.g. add resource configurations to the destination project?
				}
				if(fromInfo != null && removeResourceConfigurations(fromInfo,fromPath))
					fModifiedProjects.add(fromProject);
			}
		}
		
		private void handleDeleteFile(IPath path){
			IProject project = findModifiedProject(path.segment(0));
			if(project != null){
				IManagedBuildInfo info = ManagedBuildManager.getBuildInfo(project);
				if(info != null 
						&& removeResourceConfigurations(info,path))
					fModifiedProjects.add(project);
			}
		}
		
		//finds the project geven the initial project name
		//That is:
		// if the project of a given name was renamed returns the renamed project
		// if the project of a given name was removed returns null
		// if the project of a given name was neither renamed or removed 
		//   returns the project of that name or null if the project does not exist
		//
		private IProject findModifiedProject(final String oldProjectName){
			IResourceDelta projectDelta = fRootDelta.findMember(new Path(oldProjectName));
			boolean replaced = false;
			if(projectDelta != null) {
				switch(projectDelta.getKind()){
					case IResourceDelta.REMOVED :
					    if ((projectDelta.getFlags() & IResourceDelta.MOVED_TO) == 0) {
					    	return null;
					    }
					case IResourceDelta.CHANGED :
					    if ((projectDelta.getFlags() & IResourceDelta.MOVED_TO) != 0) {
					    	IPath path = projectDelta.getMovedToPath();
					    	if(path != null)
					    		return ResourcesPlugin.getWorkspace().getRoot().findMember(path).getProject();
					    }
					    break;
				}
			}

			final IProject project[] = new IProject[1];
			try {
				fRootDelta.accept(new IResourceDeltaVisitor() {
					public boolean visit(IResourceDelta delta) throws CoreException {
						IResource dResource = delta.getResource();
						int rcType = dResource.getType();
						if(rcType == IResource.ROOT) {
							return true;
						} else if(rcType == IResource.PROJECT){
							switch(delta.getKind()){
							case IResourceDelta.ADDED :
							case IResourceDelta.CHANGED :
						      if ((delta.getFlags() & IResourceDelta.MOVED_FROM) != 0) {
						    	  IPath path = delta.getMovedFromPath();
						    	  if (path != null && path.segment(0).equals(oldProjectName)) {
						    		  project[0] = dResource.getProject();
						    	  }
						      }
							break;
							default:
								break;
							}
						}
						return false;
					}
				});
			} catch (CoreException e) {
			}

			if(project[0] == null && !replaced)
				project[0] = ResourcesPlugin.getWorkspace().getRoot().findMember(oldProjectName).getProject();
			return project[0];
		}

		private IManagedBuilderMakefileGenerator getInitializedGenerator(IProject project){
			IManagedBuilderMakefileGenerator makeGen = fBuildFileGeneratorMap.get(project);
			if (makeGen == null) {
				try {
					if (project.hasNature(ManagedCProjectNature.MNG_NATURE_ID)) {
						// Determine if we can access the build info before actually trying
						// If not, don't try, to avoid putting up a dialog box warning the user
						if (!ManagedBuildManager.canGetBuildInfo(project)) return null;
						
						IManagedBuildInfo buildInfo = ManagedBuildManager.getBuildInfo(project);
						if (buildInfo != null){
							IConfiguration defaultCfg = buildInfo.getDefaultConfiguration();
							if (defaultCfg != null) {
								makeGen = ManagedBuildManager.getBuildfileGenerator(defaultCfg);
								makeGen.initialize(project,buildInfo,new NullProgressMonitor());
								fBuildFileGeneratorMap.put(project,makeGen);
							}
						}
					}
				} catch (CoreException e){
					return null;
				}
			}
			return makeGen;
		}
	}

	public void sendClose(IProject project){
		sendClose(ManagedBuildManager.getBuildInfo(project,false));
	}

	private void sendClose(IManagedBuildInfo info){
		if(info != null){
			IManagedProject managedProj = info.getManagedProject();
			if (managedProj != null) {
				IConfiguration cfgs[] = managedProj.getConfigurations();
			
				for(int i = 0; i < cfgs.length; i++)
					ManagedBuildManager.performValueHandlerEvent(cfgs[i], IManagedOptionValueHandler.EVENT_CLOSE, true);
			}
		}
	}

	/*
	 *  I R e s o u r c e C h a n g e L i s t e n e r 
	 */

	/* (non-Javadoc)
	 * 
	 *  Handle the renaming and deletion of project resources
	 *  This is necessary in order to update ResourceConfigurations and AdditionalInputs
	 *  
	 * @see org.eclipse.core.resources.IResourceChangeListener#resourceChanged(org.eclipse.core.resources.IResourceChangeEvent)
	 */
	public void resourceChanged(IResourceChangeEvent event) {
		if (event.getSource() instanceof IWorkspace) {
			
			switch (event.getType()) {
				case IResourceChangeEvent.PRE_CLOSE:
					IResource proj = event.getResource();
					if(proj instanceof IProject)
						sendClose((IProject)proj);
					break;
				case IResourceChangeEvent.PRE_DELETE :
					IResource rc = event.getResource();
					if(rc instanceof IProject){
						IProject project = (IProject)rc;
						try {
							if (project.hasNature(ManagedCProjectNature.MNG_NATURE_ID)) {
								IManagedBuildInfo info = ManagedBuildManager.getBuildInfo(project);
								if(info != null)
									fRmProjectToBuildInfoMap.put(project, info);
							}
						} catch (CoreException e) {
						}
					}
				case IResourceChangeEvent.POST_CHANGE :
				case IResourceChangeEvent.POST_BUILD :
					IResourceDelta resDelta = event.getDelta();
					if (resDelta == null) {
						break;
					}
					try {
						ResourceConfigurationChecker rcChecker = new ResourceConfigurationChecker(resDelta);
						resDelta.accept(rcChecker);
						
						//saving info for the modified projects 
						initInfoSerialization(rcChecker.getModifiedProjects());
					
					} catch (CoreException e) {
						ManagedBuilderCorePlugin.log(e);
					}
					break;
				default :
					break;
			}
		}
	}
	
	private void initInfoSerialization(final IProject projects[]){
		if(projects.length == 0)
			return;
		IWorkspace workspace = ResourcesPlugin.getWorkspace();
		IResourceRuleFactory ruleFactory = workspace.getRuleFactory();
		ISchedulingRule buildInfoSaveRule;
		if(projects.length == 1){
			buildInfoSaveRule = ruleFactory.modifyRule(projects[0]);
		} else {
			ISchedulingRule rules[] = new ISchedulingRule[projects.length];
			for(int i = 0; i < rules.length; i++)
				rules[i] = ruleFactory.modifyRule(projects[i]);
			buildInfoSaveRule = MultiRule.combine(rules);
		}

		Job savingJob = new Job(ManagedMakeMessages.getResourceString("ResourceChangeHandler.buildInfoSerializationJob")){ 	//$NON-NLS-1$
			@Override
			protected IStatus run(IProgressMonitor monitor) {
				for(int i = 0; i < projects.length; i++){
					ManagedBuildManager.saveBuildInfo(projects[i],true);
				}
				return new Status(
						IStatus.OK,
						ManagedBuilderCorePlugin.getUniqueIdentifier(),
						IStatus.OK,
						new String(),
						null);
			}
		};
		savingJob.setRule(buildInfoSaveRule);
		
		savingJob.schedule();
	}

	private boolean updateResourceConfigurations(IManagedBuildInfo info, IPath oldPath, IPath newPath){
		boolean changed = false;
		if(!oldPath.equals(newPath)){
			IManagedProject mngProj = info.getManagedProject();
			if(mngProj != null){
				IConfiguration configs[] = mngProj.getConfigurations();
				if(configs != null && configs.length > 0){
					for(int i = 0; i < configs.length; i++){
						if(updateResourceConfiguration(configs[i],oldPath,newPath))
							changed = true;
					}
				}
			}
		}
		return changed;
	}
	
	private boolean removeResourceConfigurations(IManagedBuildInfo info, IPath path){
		boolean changed = false;
		IManagedProject mngProj = info.getManagedProject();
		if(mngProj != null){
			IConfiguration configs[] = mngProj.getConfigurations();
			if(configs != null && configs.length > 0){
				for(int i = 0; i < configs.length; i++){
					if(removeResourceConfiguration(configs[i],path))
						changed = true;
				}
			}
		}
		return changed;
	}
	
	private boolean updateResourceConfiguration(IConfiguration config, IPath oldPath, IPath newPath){
		IResourceConfiguration rcCfg = config.getResourceConfiguration(oldPath.toString());
		if(rcCfg != null && !oldPath.equals(newPath)){
//			config.removeResourceConfiguration(rcCfg);
			rcCfg.setResourcePath(newPath.toString());
//			rcCfg.setRebuildState(true);
//			((Configuration)config).addResourceConfiguration((ResourceConfiguration)rcCfg);
//			config.setRebuildState(true);
			return true;
		}
		return false;
	}
	
	private boolean removeResourceConfiguration(IConfiguration config, IPath path){
		IResourceConfiguration rcCfg = config.getResourceConfiguration(path.toString());
		if(rcCfg != null){
			config.removeResourceConfiguration(rcCfg);
//			config.setRebuildState(true);
			return true;
		}
		return false;
	}

	/*
	 *  I S a v e P a r t i c i p a n t 
	 */

	/* (non-Javadoc)
	 * @see org.eclipse.core.resources.ISaveParticipant#saving(org.eclipse.core.resources.ISaveContext)
	 */
	public void saving(ISaveContext context) throws CoreException {
		PropertyManager.getInstance().serialize();

		//Request a resource delta to be used on next activation.
	    context.needDelta();
	}

	/* (non-Javadoc)
	 * @see org.eclipse.core.resources.ISaveParticipant#doneSaving(org.eclipse.core.resources.ISaveContext)
	 */
	public void doneSaving(ISaveContext context) {
	}

	/* (non-Javadoc)
	 * @see org.eclipse.core.resources.ISaveParticipant#prepareToSave(org.eclipse.core.resources.ISaveContext)
	 */
	public void prepareToSave(ISaveContext context) throws CoreException {
	}

	/* (non-Javadoc)
	 * @see org.eclipse.core.resources.ISaveParticipant#rollback(org.eclipse.core.resources.ISaveContext)
	 */
	public void rollback(ISaveContext context) {
	}

}

Back to the top