Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: bb8b5c9c4cdaaca8c646c4f7174d91129ac22543 (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
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
package org.eclipse.cdt.internal.core.model;

/*
 * (c) Copyright IBM Corp. 2000, 2001.
 * All Rights Reserved.
 */

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.eclipse.cdt.core.CCProjectNature;
import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.CDescriptorEvent;
import org.eclipse.cdt.core.CProjectNature;
import org.eclipse.cdt.core.IBinaryParser;
import org.eclipse.cdt.core.ICDescriptor;
import org.eclipse.cdt.core.ICDescriptorListener;
import org.eclipse.cdt.core.ICExtensionReference;
import org.eclipse.cdt.core.IBinaryParser.IBinaryArchive;
import org.eclipse.cdt.core.IBinaryParser.IBinaryFile;
import org.eclipse.cdt.core.IBinaryParser.IBinaryObject;
import org.eclipse.cdt.core.filetype.IResolverChangeListener;
import org.eclipse.cdt.core.filetype.ResolverChangeEvent;
import org.eclipse.cdt.core.model.CModelException;
import org.eclipse.cdt.core.model.CoreModel;
import org.eclipse.cdt.core.model.ElementChangedEvent;
import org.eclipse.cdt.core.model.ICContainer;
import org.eclipse.cdt.core.model.ICElement;
import org.eclipse.cdt.core.model.ICElementDelta;
import org.eclipse.cdt.core.model.ICModel;
import org.eclipse.cdt.core.model.ICProject;
import org.eclipse.cdt.core.model.IElementChangedListener;
import org.eclipse.cdt.core.model.IIncludeReference;
import org.eclipse.cdt.core.model.IParent;
import org.eclipse.cdt.core.model.ISourceRoot;
import org.eclipse.cdt.core.model.ITranslationUnit;
import org.eclipse.cdt.core.model.IWorkingCopy;
import org.eclipse.cdt.internal.core.search.indexing.IndexManager;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
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.IResourceStatus;
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.ISafeRunnable;
import org.eclipse.core.runtime.Platform;

public class CModelManager implements IResourceChangeListener, ICDescriptorListener, IResolverChangeListener {

	public static boolean VERBOSE = false;

	/**
	 * Unique handle onto the CModel
	 */
	final CModel cModel = new CModel();

	public static HashSet OptionNames = new HashSet(20);

	public static final int DEFAULT_CHANGE_EVENT = 0; // must not collide with ElementChangedEvent event masks

	/**
	 * Used to convert <code>IResourceDelta</code>s into <code>ICElementDelta</code>s.
	 */
	protected DeltaProcessor fDeltaProcessor = new DeltaProcessor();

	protected ResolverProcessor fResolverProcessor = new ResolverProcessor();

	/**
	 * Queue of deltas created explicily by the C Model that
	 * have yet to be fired.
	 */
	List fCModelDeltas = Collections.synchronizedList(new ArrayList());

	/**
	 * Queue of reconcile deltas on working copies that have yet to be fired.
	 * This is a table form IWorkingCopy to IJavaElementDelta
	 */
	HashMap reconcileDeltas = new HashMap();

	/**
	 * Turns delta firing on/off. By default it is on.
	 */
	protected boolean fFire = true;

	/**
	 * Collection of listeners for C element deltas
	 */
	protected List fElementChangedListeners = Collections.synchronizedList(new ArrayList());

	/**
	 * A map from ITranslationUnit to IWorkingCopy of the shared working copies.
	 */
	public Map sharedWorkingCopies = new HashMap();
	/**
	 * Set of elements which are out of sync with their buffers.
	 */
	protected Map elementsOutOfSynchWithBuffers = new HashMap(11);

	/*
	 * Temporary cache of newly opened elements
	 */
	private ThreadLocal temporaryCache = new ThreadLocal();

	/**
	 * Infos cache.
	 */
	protected CModelCache cache = new CModelCache();

	/**
	 * This is a cache of the projects before any project addition/deletion has started.
	 */
	public ICProject[] cProjectsCache;

	/**
	 * The list of started BinaryRunners on projects.
	 */
	private HashMap binaryRunners = new HashMap();

	/**
	 * Map of the binary parser for each project.
	 */
	private HashMap binaryParsersMap = new HashMap();

	/**
	 * The lis of the SourceMappers on projects.
	 */
	private HashMap sourceMappers = new HashMap();

	public static final IWorkingCopy[] NoWorkingCopy = new IWorkingCopy[0];

	static CModelManager factory = null;

	private CModelManager() {
	}

	public static CModelManager getDefault() {
		if (factory == null) {
			factory = new CModelManager();

			// Register to the workspace;
			ResourcesPlugin.getWorkspace().addResourceChangeListener(factory,
																		IResourceChangeEvent.POST_CHANGE
																				| IResourceChangeEvent.PRE_DELETE
																				| IResourceChangeEvent.PRE_CLOSE);

			// Register the Core Model on the Descriptor
			// Manager, it needs to know about changes.
			CCorePlugin.getDefault().getCDescriptorManager().addDescriptorListener(factory);
			// Register the Core Model on the Resolver
			// Manager, it needs to know about changes.
			CCorePlugin.getDefault().getResolverModel().addResolverChangeListener(factory);
		}
		return factory;
	}

	/**
	 * Returns the CModel for the given workspace, creating
	 * it if it does not yet exist.
	 */
	public ICModel getCModel(IWorkspaceRoot root) {
		return getCModel();
	}

	public CModel getCModel() {
		return cModel;
	}

	public ICElement create(IPath path) {
		IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
		// Assume it is fullpath relative to workspace
		IResource res = root.findMember(path);
		if (res == null) {
			IPath rootPath = root.getLocation();
			if (path.equals(rootPath)) {
				return getCModel(root);
			}
			res = root.getContainerForLocation(path);
			if (res == null || !res.exists()) {
				res = root.getFileForLocation(path);
			}
			if (res != null && !res.exists()) {
				res = null;
			}
		}
		// TODO: for extenal resources ??
		return create(res, null);
	}

	public ICElement create(IResource resource, ICProject cproject) {
		if (resource == null) {
			return null;
		}

		int type = resource.getType();
		switch (type) {
			case IResource.PROJECT :
				return create((IProject)resource);
			case IResource.FILE :
				return create((IFile)resource, cproject);
			case IResource.FOLDER :
				return create((IFolder)resource, cproject);
			case IResource.ROOT :
				return getCModel((IWorkspaceRoot)resource);
			default :
				return null;
		}
	}

	public ICProject create(IProject project) {
		if (project == null) {
			return null;
		}
		return cModel.getCProject(project);
	}

	public ICContainer create(IFolder folder, ICProject cproject) {
		if (folder == null) {
			return null;
		}
		if (cproject == null) {
			cproject = create(folder.getProject());
		}
		ICContainer celement = null;
		IPath resourcePath = folder.getFullPath();
		try {
			ISourceRoot[] roots = cproject.getAllSourceRoots();
			for (int i = 0; i < roots.length; ++i) {
				ISourceRoot root = roots[i];
				IPath rootPath = root.getPath();
				if (rootPath.equals(resourcePath)) {
					celement = root;
					break; // We are done.
				} else if (root.isOnSourceEntry(folder)) {
					IPath path = resourcePath.removeFirstSegments(rootPath.segmentCount());
					String[] segments = path.segments();
					ICContainer cfolder = root;
					for (int j = 0; j < segments.length; j++) {
						cfolder = cfolder.getCContainer(segments[j]);
					}
					celement = cfolder;
				}
			}
		} catch (CModelException e) {
			//
		}
		return celement;
	}

	public ICElement create(IFile file, ICProject cproject) {
		if (file == null) {
			return null;
		}
		if (cproject == null) {
			cproject = create(file.getProject());
		}
		boolean checkIfBinary = false;
		ICElement celement = null;
		try {
			ISourceRoot[] roots = cproject.getAllSourceRoots();
			for (int i = 0; i < roots.length; ++i) {
				ISourceRoot root = roots[i];
				if (root.isOnSourceEntry(file)) {
					IPath rootPath = root.getPath();
					IPath resourcePath = file.getFullPath();
					IPath path = resourcePath.removeFirstSegments(rootPath.segmentCount());
					String fileName = path.lastSegment();
					path = path.removeLastSegments(1);
					String[] segments = path.segments();
					ICContainer cfolder = root;
					for (int j = 0; j < segments.length; j++) {
						cfolder = cfolder.getCContainer(segments[j]);
					}

					if (CoreModel.isValidTranslationUnitName(cproject.getProject(), fileName)) {
						celement = cfolder.getTranslationUnit(fileName);
					} else if (cproject.isOnOutputEntry(file)) {
						IBinaryFile bin = createBinaryFile(file);
						if (bin != null) {
							if (bin.getType() == IBinaryFile.ARCHIVE) {
								celement = new Archive(cfolder, file, (IBinaryArchive)bin);
								ArchiveContainer vlib = (ArchiveContainer)cproject.getArchiveContainer();
								vlib.addChild(celement);
							} else {
								celement = new Binary(cfolder, file, (IBinaryObject)bin);
								BinaryContainer vbin = (BinaryContainer)cproject.getBinaryContainer();
								vbin.addChild(celement);
							}
						}
						checkIfBinary = true;
					}
					break;
				}
			}

			// try in the outputEntry and save in the container
			// But do not create an ICElement since they are not in the Model per say
			if (celement == null && !checkIfBinary && cproject.isOnOutputEntry(file)) {
				IBinaryFile bin = createBinaryFile(file);
				if (bin != null) {
					if (bin.getType() == IBinaryFile.ARCHIVE) {
						ArchiveContainer vlib = (ArchiveContainer)cproject.getArchiveContainer();
						celement = new Archive(vlib, file, (IBinaryArchive)bin);
						vlib.addChild(celement);
					} else {
						BinaryContainer vbin = (BinaryContainer)cproject.getBinaryContainer();
						celement = new Binary(vbin, file, (IBinaryObject)bin);
						vbin.addChild(celement);
					}
				}
			}
		} catch (CModelException e) {
			//
		}
		return celement;
	}

	public ICElement create(IFile file, IBinaryFile bin, ICProject cproject) {
		if (file == null) {
			return null;
		}
		if (bin == null) {
			return create(file, cproject);
		}
		if (cproject == null) {
			cproject = create(file.getProject());
		}
		ICElement celement = null;
		try {
			ISourceRoot[] roots = cproject.getAllSourceRoots();
			for (int i = 0; i < roots.length; ++i) {
				ISourceRoot root = roots[i];
				if (root.isOnSourceEntry(file)) {
					IPath rootPath = root.getPath();
					IPath resourcePath = file.getFullPath();
					IPath path = resourcePath.removeFirstSegments(rootPath.segmentCount());
					path = path.removeLastSegments(1);
					String[] segments = path.segments();
					ICContainer cfolder = root;
					for (int j = 0; j < segments.length; j++) {
						cfolder = cfolder.getCContainer(segments[j]);
					}

					if (bin.getType() == IBinaryFile.ARCHIVE) {
						celement = new Archive(cfolder, file, (IBinaryArchive)bin);
						ArchiveContainer vlib = (ArchiveContainer)cproject.getArchiveContainer();
						vlib.addChild(celement);
					} else {
						celement = new Binary(cfolder, file, (IBinaryObject)bin);
						BinaryContainer vbin = (BinaryContainer)cproject.getBinaryContainer();
						vbin.addChild(celement);
					}
					break;
				}
			}

			// try in the outputEntry and save in the container
			// But do not create a ICElement since they are not in the Model per say
			if (celement == null) {
				if (bin.getType() == IBinaryFile.ARCHIVE) {
					ArchiveContainer vlib = (ArchiveContainer)cproject.getArchiveContainer();
					celement = new Archive(vlib, file, (IBinaryArchive)bin);
					vlib.addChild(celement);
				} else {
					BinaryContainer vbin = (BinaryContainer)cproject.getBinaryContainer();
					celement = new Binary(vbin, file, (IBinaryObject)bin);
					vbin.addChild(celement);
				}
			}
		} catch (CModelException e) {
			//
		}
		return celement;
	}

	public ITranslationUnit createTranslationUnitFrom(ICProject cproject, IPath path) {
		if (path == null || cproject == null) {
			return null;
		}
		if (path.isAbsolute()) {
			File file = path.toFile();
			if (file == null || !file.isFile()) {
				return null;
			}
			try {
				IIncludeReference[] includeReferences = cproject.getIncludeReferences();
				for (int i = 0; i < includeReferences.length; i++) {
					if (includeReferences[i].isOnIncludeEntry(path)) {
						return new ExternalTranslationUnit(includeReferences[i], path);
					}
				}
			} catch (CModelException e) {
			}
		} else {
			try {
				IIncludeReference[] includeReferences = cproject.getIncludeReferences();
				for (int i = 0; i < includeReferences.length; i++) {
					IPath includePath = includeReferences[i].getPath().append(path);
					File file = includePath.toFile();
					if (file != null && file.isFile()) {
						return new ExternalTranslationUnit(includeReferences[i], includePath);
					}
				}
			} catch (CModelException e) {
			}
		}
		return null;
	}

	public void releaseCElement(ICElement celement) {

		// Guard.
		if (celement == null)
			return;

		//System.out.println("RELEASE " + celement.getElementName());

		// Remove from the containers.
		if (celement instanceof IParent) {
			CElementInfo info = (CElementInfo)peekAtInfo(celement);
			if (info != null) {
				ICElement[] children = info.getChildren();
				for (int i = 0; i < children.length; i++) {
					releaseCElement(children[i]);
				}
			}

			// Make sure any object specifics not part of the children be destroy
			// For example the CProject needs to destroy the BinaryContainer and ArchiveContainer
			if (celement instanceof CElement) {
				try {
					((CElement)celement).closing(info);
				} catch (CModelException e) {
					//
				}
			}

			// If an entire folder was deleted we need to update the
			// BinaryContainer/ArchiveContainer also.
			if (celement.getElementType() == ICElement.C_CCONTAINER) {
				ICProject cproject = celement.getCProject();
				CProjectInfo pinfo = (CProjectInfo)peekAtInfo(cproject);
				ArrayList list = new ArrayList(5);
				if (pinfo != null && pinfo.vBin != null) {
					if (peekAtInfo(pinfo.vBin) != null) {
						try {
							ICElement[] bins = pinfo.vBin.getChildren();
							for (int i = 0; i < bins.length; i++) {
								if (celement.getPath().isPrefixOf(bins[i].getPath())) {
									//pinfo.vBin.removeChild(bins[i]);
									list.add(bins[i]);
								}
							}
						} catch (CModelException e) {
							// ..
						}
					}
				}
				if (pinfo != null && pinfo.vLib != null) {
					if (peekAtInfo(pinfo.vLib) != null) {
						try {
							ICElement[] ars = pinfo.vLib.getChildren();
							for (int i = 0; i < ars.length; i++) {
								if (celement.getPath().isPrefixOf(ars[i].getPath())) {
									//pinfo.vLib.removeChild(ars[i]);
									list.add(ars[i]);
								}
							}
						} catch (CModelException e) {
							// ..
						}
					}
				}
				// release any binary/archive that was in the path
				for (int i = 0; i < list.size(); i++) {
					ICElement b = (ICElement)list.get(i);
					releaseCElement(b);
				}
			}
		}

		// Remove the child from the parent list.
		//Parent parent = (Parent)celement.getParent();
		//if (parent != null && peekAtInfo(parent) != null) {
		//	parent.removeChild(celement);
		//}

		removeInfo(celement);
	}

	public BinaryParserConfig[] getBinaryParser(IProject project) {
		BinaryParserConfig[] parsers = (BinaryParserConfig[])binaryParsersMap.get(project);
		if (parsers == null) {
			try {
				ICDescriptor cdesc = CCorePlugin.getDefault().getCProjectDescription(project, false);
				if (cdesc != null) {
					ICExtensionReference[] cextensions = cdesc.get(CCorePlugin.BINARY_PARSER_UNIQ_ID, true);
					if (cextensions.length > 0) {
						ArrayList list = new ArrayList(cextensions.length);
						for (int i = 0; i < cextensions.length; i++) {
							BinaryParserConfig config = new BinaryParserConfig(cextensions[i]);
							list.add(config);
						}
						parsers = new BinaryParserConfig[list.size()];
						list.toArray(parsers);
					}
				}
			} catch (CoreException e) {
			}
			if (parsers == null) {
				try {
					BinaryParserConfig config = new BinaryParserConfig(CCorePlugin.getDefault().getDefaultBinaryParser(), CCorePlugin.DEFAULT_BINARY_PARSER_UNIQ_ID);
					parsers = new BinaryParserConfig[]{config};
				} catch (CoreException e1) {
				}
			}
		}
		if (parsers != null) {
			binaryParsersMap.put(project, parsers);
			return parsers;
		}
		return new BinaryParserConfig[0];
	}

	public IBinaryFile createBinaryFile(IFile file) {
		BinaryParserConfig[] parsers = getBinaryParser(file.getProject());
		int hints = 0;
		for (int i = 0; i < parsers.length; i++) {
			IBinaryParser parser = null;
			try {
				parser = parsers[i].getBinaryParser();
				if (parser.getHintBufferSize() > hints) {
					hints = parser.getHintBufferSize();
				}
			} catch (CoreException e) {
			}
		}
		byte[] bytes = new byte[hints];
		if (hints > 0) {
			try {
				InputStream is = file.getContents();
				int count = is.read(bytes);
				is.close();
				if (count > 0 && count < bytes.length) {
					byte[] array = new byte[count];
					System.arraycopy(bytes, 0, array, 0, count);
					bytes = array;
				}
			} catch (CoreException e) {
				return null;
			} catch (IOException e) {
				return null;
			}
		}

		IPath location = file.getLocation();

		for (int i = 0; i < parsers.length; i++) {
			try {
				IBinaryParser parser = parsers[i].getBinaryParser();
				IBinaryFile binFile = parser.getBinary(bytes, location);
				if (binFile != null) {
					return binFile;
				}
			} catch (IOException e) {
			} catch (CoreException e) {
			}
		}
		return null;
	}
	/**
	 * TODO: this is a temporary hack until, the CDescriptor manager is
	 * in place and could fire deltas of Parser change.
	 */
	public void resetBinaryParser(IProject project) {
		if (project != null) {
			ICProject cproject = create(project);
			if (cproject != null) {
				// Let the function remove the children
				// but it has the side of effect of removing the CProject also
				// so we have to recall create again.
				try {
					cproject.close();
				} catch (CModelException e) {
					e.printStackTrace();
				}
				binaryParsersMap.remove(project);

				// Fired and ICElementDelta.PARSER_CHANGED
				CElementDelta delta = new CElementDelta(getCModel());
				delta.binaryParserChanged(cproject);
				registerCModelDelta(delta);
				fire(ElementChangedEvent.POST_CHANGE);
			}
		}
	}

	public BinaryRunner getBinaryRunner(ICProject project, boolean start) {
		BinaryRunner runner = null;
		synchronized (binaryRunners) {
			runner = (BinaryRunner)binaryRunners.get(project.getProject());
			if (runner == null) {
				runner = new BinaryRunner(project.getProject());
				binaryRunners.put(project.getProject(), runner);
				if (start) {
					runner.start();
				}
			}
		}
		return runner;
	}

	public void removeBinaryRunner(ICProject cproject) {
		removeBinaryRunner(cproject.getProject());
	}

	public void removeBinaryRunner(IProject project) {
		BinaryRunner runner = (BinaryRunner)binaryRunners.remove(project);
		if (runner != null) {
			runner.stop();
		}
	}

	public SourceMapper getSourceMapper(ICProject cProject) {
		SourceMapper mapper = null;
		synchronized (sourceMappers) {
			mapper = (SourceMapper)sourceMappers.get(cProject);
			if (mapper == null) {
				mapper = new SourceMapper(cProject);
				sourceMappers.put(cProject, mapper);
			}
		}
		return mapper;
	}
	/**
	 * addElementChangedListener method comment.
	 */
	public void addElementChangedListener(IElementChangedListener listener) {
		synchronized (fElementChangedListeners) {
			if (!fElementChangedListeners.contains(listener)) {
				fElementChangedListeners.add(listener);
			}
		}
	}

	/**
	 * removeElementChangedListener method comment.
	 */
	public void removeElementChangedListener(IElementChangedListener listener) {
		synchronized (fElementChangedListeners) {
			int i = fElementChangedListeners.indexOf(listener);
			if (i != -1) {
				fElementChangedListeners.remove(i);
			}
		}
	}

	/**
	 * Registers the given delta with this manager. This API is to be
	 * used to registerd deltas that are created explicitly by the C
	 * Model. Deltas created as translations of <code>IResourceDeltas</code>
	 * are to be registered with <code>#registerResourceDelta</code>.
	 */
	public void registerCModelDelta(ICElementDelta delta) {
		fCModelDeltas.add(delta);
	}

	/**
	 * Notifies this C Model Manager that some resource changes have happened
	 * on the platform, and that the C Model should update any required
	 * internal structures such that its elements remain consistent.
	 * Translates <code>IResourceDeltas</code> into <code>ICElementDeltas</code>.
	 * 
	 * @see IResourceDelta
	 * @see IResource
	 */
	public void resourceChanged(IResourceChangeEvent event) {

		if (event.getSource() instanceof IWorkspace) {
			IResourceDelta delta = event.getDelta();
			IResource resource = event.getResource();
			switch (event.getType()) {
				case IResourceChangeEvent.PRE_DELETE :
					try {
					if (resource.getType() == IResource.PROJECT && 	
					    ( ((IProject)resource).hasNature(CProjectNature.C_NATURE_ID) ||
					      ((IProject)resource).hasNature(CCProjectNature.CC_NATURE_ID) )){
						this.deleting((IProject) resource);}
					} catch (CoreException e) {
					}
					break;

				case IResourceChangeEvent.POST_CHANGE :
					try {
						if (delta != null) {
							ICElementDelta[] translatedDeltas = fDeltaProcessor.processResourceDelta(delta);
							if (translatedDeltas.length > 0) {
								for (int i = 0; i < translatedDeltas.length; i++) {
									registerCModelDelta(translatedDeltas[i]);
								}
							}
							fire(ElementChangedEvent.POST_CHANGE);
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
					break;
			}
		}
	}

	/* (non-Javadoc)
	 * @see org.eclipse.cdt.core.ICDescriptorListener#descriptorChanged(org.eclipse.cdt.core.CDescriptorEvent)
	 */
	public void descriptorChanged(CDescriptorEvent event) {
		int flags = event.getFlags();
		if ( (flags & CDescriptorEvent.EXTENSION_CHANGED) != 0) {
			ICDescriptor cdesc = event.getDescriptor();
			if (cdesc != null) {
				IProject project = cdesc.getProject();
				try {
					ICExtensionReference[] newExts = CCorePlugin.getDefault().getBinaryParserExtensions(project);
					BinaryParserConfig[] currentConfigs = getBinaryParser(project);
					// anything added/removed
					if (newExts.length != currentConfigs.length) {
						resetBinaryParser(project);
					} else { // may reorder
						for (int i = 0; i < newExts.length; i++) {
							if (!newExts[i].getID().equals(currentConfigs[i].getId())) {
								resetBinaryParser(project);
								break;
							}
						}
					}
				} catch (CoreException e) {
					resetBinaryParser(project);
				}
			}
		}
	}

	/* (non-Javadoc)
	 * @see org.eclipse.cdt.core.filetype.IResolverChangeListener#resolverChanged(org.eclipse.cdt.core.filetype.ResolverChangeEvent)
	 */
	public void resolverChanged(ResolverChangeEvent event) {
		fResolverProcessor.processResolverChanges(event);
	}

	public void fire(int eventType) {
		fire(null, eventType);
	}

	/**
	 * Fire C Model deltas, flushing them after the fact. 
	 * If the firing mode has been turned off, this has no effect. 
	 */
	public void fire(ICElementDelta customDeltas, int eventType) {
		if (fFire) {
			ICElementDelta deltaToNotify;
			if (customDeltas == null) {
				deltaToNotify = mergeDeltas(this.fCModelDeltas);
			} else {
				deltaToNotify = customDeltas;
			}

			IElementChangedListener[] listeners;
			int listenerCount;
			int[] listenerMask;
			// Notification
			synchronized (fElementChangedListeners) {
				listeners = new IElementChangedListener[fElementChangedListeners.size()];
				fElementChangedListeners.toArray(listeners);
				listenerCount = listeners.length;
				listenerMask = null;
			}

			switch (eventType) {
				case DEFAULT_CHANGE_EVENT :
					firePreAutoBuildDelta(deltaToNotify, listeners, listenerMask, listenerCount);
					firePostChangeDelta(deltaToNotify, listeners, listenerMask, listenerCount);
					fireReconcileDelta(listeners, listenerMask, listenerCount);
					break;
				case ElementChangedEvent.PRE_AUTO_BUILD :
					firePreAutoBuildDelta(deltaToNotify, listeners, listenerMask, listenerCount);
					break;
				case ElementChangedEvent.POST_CHANGE :
					firePostChangeDelta(deltaToNotify, listeners, listenerMask, listenerCount);
					fireReconcileDelta(listeners, listenerMask, listenerCount);
					break;
				case ElementChangedEvent.POST_RECONCILE :
					fireReconcileDelta(listeners, listenerMask, listenerCount);
					break;
			}
		}
	}

	private void firePreAutoBuildDelta(ICElementDelta deltaToNotify,
		IElementChangedListener[] listeners, int[] listenerMask, int listenerCount) {

		if (VERBOSE) {
			System.out.println("FIRING PRE_AUTO_BUILD Delta [" + Thread.currentThread() + "]:"); //$NON-NLS-1$//$NON-NLS-2$
			System.out.println(deltaToNotify == null ? "<NONE>" : deltaToNotify.toString()); //$NON-NLS-1$
		}
		if (deltaToNotify != null) {
			notifyListeners(deltaToNotify, ElementChangedEvent.PRE_AUTO_BUILD, listeners, listenerMask, listenerCount);
		}
	}

	private void firePostChangeDelta(ICElementDelta deltaToNotify, IElementChangedListener[] listeners, int[] listenerMask, int listenerCount) {

		// post change deltas
		if (VERBOSE) {
			System.out.println("FIRING POST_CHANGE Delta [" + Thread.currentThread() + "]:"); //$NON-NLS-1$//$NON-NLS-2$
			System.out.println(deltaToNotify == null ? "<NONE>" : deltaToNotify.toString()); //$NON-NLS-1$
		}
		if (deltaToNotify != null) {
				// flush now so as to keep listener reactions to post their own deltas for subsequent iteration
			this.flush();
			notifyListeners(deltaToNotify, ElementChangedEvent.POST_CHANGE, listeners, listenerMask, listenerCount);
		}
	}

	private void fireReconcileDelta(IElementChangedListener[] listeners, int[] listenerMask, int listenerCount) {
		ICElementDelta deltaToNotify = mergeDeltas(this.reconcileDeltas.values());
		if (VERBOSE) {
			System.out.println("FIRING POST_RECONCILE Delta [" + Thread.currentThread() + "]:"); //$NON-NLS-1$//$NON-NLS-2$
			System.out.println(deltaToNotify == null ? "<NONE>" : deltaToNotify.toString()); //$NON-NLS-1$
		}
		if (deltaToNotify != null) {
			// flush now so as to keep listener reactions to post their own deltas for subsequent iteration
			this.reconcileDeltas = new HashMap();
			notifyListeners(deltaToNotify, ElementChangedEvent.POST_RECONCILE, listeners, listenerMask, listenerCount);
		}
	}

	public void notifyListeners(ICElementDelta deltaToNotify, int eventType,
		IElementChangedListener[] listeners, int[] listenerMask, int listenerCount) {

		final ElementChangedEvent extraEvent = new ElementChangedEvent(deltaToNotify, eventType);
		for (int i = 0; i < listenerCount; i++) {
			if (listenerMask == null || (listenerMask[i] & eventType) != 0) {
				final IElementChangedListener listener = listeners[i];
				long start = -1;
				if (VERBOSE) {
					System.out.print("Listener #" + (i + 1) + "=" + listener.toString());//$NON-NLS-1$//$NON-NLS-2$
					start = System.currentTimeMillis();
				}
				// wrap callbacks with Safe runnable for subsequent listeners to be called when some are causing grief
				Platform.run(new ISafeRunnable() {

					public void handleException(Throwable exception) {
						//CCorePlugin.log(exception, "Exception occurred in listener of C element change notification"); //$NON-NLS-1$
						CCorePlugin.log(exception);
					}
					public void run() throws Exception {
						listener.elementChanged(extraEvent);
					}
				});
				if (VERBOSE) {
					System.out.println(" -> " + (System.currentTimeMillis() - start) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$
				}
			}
		}
	}

	/**
	 * Flushes all deltas without firing them.
	 */
	protected void flush() {
		fCModelDeltas.clear();
	}

	private ICElementDelta mergeDeltas(Collection deltas) {

		synchronized (deltas) {
			if (deltas.size() == 0)
				return null;
			if (deltas.size() == 1)
				return (ICElementDelta)deltas.iterator().next();
			if (deltas.size() <= 1)
				return null;

			Iterator iterator = deltas.iterator();
			ICElement cRoot = getCModel();
			CElementDelta rootDelta = new CElementDelta(cRoot);
			boolean insertedTree = false;
			while (iterator.hasNext()) {
				CElementDelta delta = (CElementDelta)iterator.next();
				ICElement element = delta.getElement();
				if (cRoot.equals(element)) {
					ICElementDelta[] children = delta.getAffectedChildren();
					for (int j = 0; j < children.length; j++) {
						CElementDelta projectDelta = (CElementDelta)children[j];
						rootDelta.insertDeltaTree(projectDelta.getElement(), projectDelta);
						insertedTree = true;
					}
					IResourceDelta[] resourceDeltas = delta.getResourceDeltas();
					if (resourceDeltas != null) {
						for (int i = 0, length = resourceDeltas.length; i < length; i++) {
							rootDelta.addResourceDelta(resourceDeltas[i]);
							insertedTree = true;
						}
					}
				} else {
					rootDelta.insertDeltaTree(element, delta);
					insertedTree = true;
				}
			}
			if (insertedTree) {
				return rootDelta;
			}
			return null;
		}
	}

	/**
	 * Runs a C Model Operation
	 */
	public void runOperation(CModelOperation operation, IProgressMonitor monitor) throws CModelException {
		boolean hadAwaitingDeltas = !fCModelDeltas.isEmpty();
		try {
			if (operation.isReadOnly()) {
				operation.run(monitor);
			} else {
		// use IWorkspace.run(...) to ensure that a build will be done in autobuild mode
				getCModel().getUnderlyingResource().getWorkspace()
					.run(operation, operation.getSchedulingRule(), IWorkspace.AVOID_UPDATE, monitor);
			}
		} catch (CoreException ce) {
			if (ce instanceof CModelException) {
				throw (CModelException)ce;
			} else if (ce.getStatus().getCode() == IResourceStatus.OPERATION_FAILED) {
				Throwable e = ce.getStatus().getException();
				if (e instanceof CModelException) {
					throw (CModelException)e;
				}
			}
			throw new CModelException(ce);
		} finally {
// fire only if there were no awaiting deltas (if there were, they would come from a resource modifying operation)
			// and the operation has not modified any resource
			if (!hadAwaitingDeltas && !operation.hasModifiedResource()) {
				fire(ElementChangedEvent.POST_CHANGE);
			} // else deltas are fired while processing the resource delta
		}
	}

	/**
	 * Returns the set of elements which are out of synch with their buffers.
	 */
	protected Map getElementsOutOfSynchWithBuffers() {
		return this.elementsOutOfSynchWithBuffers;
	}

	/**
	 * Returns the info for the element.
	 */
	public synchronized Object getInfo(ICElement element) {
		HashMap tempCache = (HashMap)this.temporaryCache.get();
		if (tempCache != null) {
			Object result = tempCache.get(element);
			if (result != null) {
				return result;
			}
		}
		return this.cache.getInfo(element);
	}

	/**
	 *  Returns the info for this element without
	 *  disturbing the cache ordering.
	 */
	protected synchronized Object peekAtInfo(ICElement element) {
		HashMap tempCache = (HashMap)this.temporaryCache.get();
		if (tempCache != null) {
			Object result = tempCache.get(element);
			if (result != null) {
				return result;
			}
		}
		return this.cache.peekAtInfo(element);
	}

	/*
	 * Puts the infos in the given map (keys are ICElements and values are CElementInfos)
	 * in the C model cache in an atomic way.
	 * First checks that the info for the opened element (or one of its ancestors) has not been 
	 * added to the cache. If it is the case, another thread has opened the element (or one of
	 * its ancestors). So returns without updating the cache.
	 */
	protected synchronized void putInfos(ICElement openedElement, Map newElements) {
		// remove children
		Object existingInfo = this.cache.peekAtInfo(openedElement);
		if (openedElement instanceof IParent && existingInfo instanceof CElementInfo) {
			ICElement[] children = ((CElementInfo)existingInfo).getChildren();
			for (int i = 0, size = children.length; i < size; ++i) {
				CElement child = (CElement)children[i];
				try {
					child.close();
				} catch (CModelException e) {
					// ignore
				}
			}
		}

		Iterator iterator = newElements.keySet().iterator();
		while (iterator.hasNext()) {
			ICElement element = (ICElement)iterator.next();
			Object info = newElements.get(element);
			this.cache.putInfo(element, info);
		}
	}

	/**
	 * Removes all cached info from the C Model, including all children,
	 * but does not close this element.
	 */
	protected synchronized void removeChildrenInfo(ICElement openedElement) {
		// remove children
		Object existingInfo = this.cache.peekAtInfo(openedElement);
		if (openedElement instanceof IParent && existingInfo instanceof CElementInfo) {
			ICElement[] children = ((CElementInfo)existingInfo).getChildren();
			for (int i = 0, size = children.length; i < size; ++i) {
				CElement child = (CElement)children[i];
				try {
					child.close();
				} catch (CModelException e) {
					// ignore
				}
			}
		}
	}

	/**
	 * Removes the info of this model element.
	 */
	protected synchronized void removeInfo(ICElement element) {
		this.cache.removeInfo(element);
	}

	/*
	 * Returns the temporary cache for newly opened elements for the current thread.
	 * Creates it if not already created.
	 */
	public HashMap getTemporaryCache() {
		HashMap result = (HashMap)this.temporaryCache.get();
		if (result == null) {
			result = new HashMap();
			this.temporaryCache.set(result);
		}
		return result;
	}

	/*
	 * Returns whether there is a temporary cache for the current thread.
	 */
	public boolean hasTemporaryCache() {
		return this.temporaryCache.get() != null;
	}

	/*
	 * Resets the temporary cache for newly created elements to null.
	 */
	public void resetTemporaryCache() {
		this.temporaryCache.set(null);
	}

	/**
	 *  
	 */
	public void startup() {
		// Do any initialization.
	}

	/**
	 *  
	 */
	public void shutdown() {
		if (this.fDeltaProcessor.indexManager != null) { // no more indexing
			this.fDeltaProcessor.indexManager.shutdown();
		}

		// Remove ourself from the DescriptorManager.
		CCorePlugin.getDefault().getCDescriptorManager().removeDescriptorListener(factory);
		// Remove ourself from the ResolverManager.
		CCorePlugin.getDefault().getResolverModel().removeResolverChangeListener(factory);

		// Do any shutdown of services.
		ResourcesPlugin.getWorkspace().removeResourceChangeListener(factory);

		BinaryRunner[] runners = (BinaryRunner[])binaryRunners.values().toArray(new BinaryRunner[0]);
		for (int i = 0; i < runners.length; i++) {
			runners[i].stop();
		}
	}

	public IndexManager getIndexManager() {
		return this.fDeltaProcessor.indexManager;
	}

	public void deleting(IProject project) {
		//	discard all indexing jobs for this project
		this.getIndexManager().discardJobs(project.getName());
		removeBinaryRunner(project);
	}

}

Back to the top