Skip to main content

This CGIT instance is deprecated, and repositories have been moved to Gitlab or Github. See the repository descriptions for specific locations.

summaryrefslogtreecommitdiffstats
blob: 06e5416272b3d6ca92db46dba947752a70e8d2b3 (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
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
/*******************************************************************************
 * Copyright (c) 2001, 2008 IBM 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:
 *     IBM Corporation - initial API and implementation
 *     Jens Lukowski/Innoopract - initial renaming/restructuring
 *     
 *******************************************************************************/
package org.eclipse.wst.sse.core.internal.model;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.jobs.ILock;
import org.eclipse.wst.sse.core.StructuredModelManager;
import org.eclipse.wst.sse.core.internal.ILockable;
import org.eclipse.wst.sse.core.internal.Logger;
import org.eclipse.wst.sse.core.internal.SSECoreMessages;
import org.eclipse.wst.sse.core.internal.encoding.EncodingRule;
import org.eclipse.wst.sse.core.internal.ltk.modelhandler.IModelHandler;
import org.eclipse.wst.sse.core.internal.provisional.DocumentChanged;
import org.eclipse.wst.sse.core.internal.provisional.IModelLifecycleListener;
import org.eclipse.wst.sse.core.internal.provisional.IModelManager;
import org.eclipse.wst.sse.core.internal.provisional.IModelStateListener;
import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
import org.eclipse.wst.sse.core.internal.provisional.IndexedRegion;
import org.eclipse.wst.sse.core.internal.provisional.events.AboutToBeChangedEvent;
import org.eclipse.wst.sse.core.internal.provisional.events.IModelAboutToBeChangedListener;
import org.eclipse.wst.sse.core.internal.provisional.events.IStructuredDocumentListener;
import org.eclipse.wst.sse.core.internal.provisional.events.NewDocumentEvent;
import org.eclipse.wst.sse.core.internal.provisional.events.NoChangeEvent;
import org.eclipse.wst.sse.core.internal.provisional.events.RegionChangedEvent;
import org.eclipse.wst.sse.core.internal.provisional.events.RegionsReplacedEvent;
import org.eclipse.wst.sse.core.internal.provisional.events.StructuredDocumentRegionsReplacedEvent;
import org.eclipse.wst.sse.core.internal.provisional.exceptions.ResourceInUse;
import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument;
import org.eclipse.wst.sse.core.internal.undo.IStructuredTextUndoManager;
import org.eclipse.wst.sse.core.internal.util.URIResolver;
import org.eclipse.wst.sse.core.internal.util.Utilities;


public abstract class AbstractStructuredModel implements IStructuredModel {

	private static final String MODEL_MANAGER_NULL = "Warning: AbstractStructuredModel::close:  model manager was null during a close of a model (which should be impossible)"; //$NON-NLS-1$

	class DirtyStateWatcher implements IStructuredDocumentListener {

		public void newModel(NewDocumentEvent structuredDocumentEvent) {

			// I don't think its safe to assume a new model
			// is always "fresh", so we'll leave dirty state
			// unchanged;
			// but we'll tell everyone about it.
			setDirtyState(fDirtyState);
		}

		public void noChange(NoChangeEvent structuredDocumentEvent) {

			// don't change dirty state
		}

		public void nodesReplaced(StructuredDocumentRegionsReplacedEvent structuredDocumentEvent) {

			setDirtyState(true);
			// no need to listen any more
			if (fStructuredDocument != null) {
				fStructuredDocument.removeDocumentChangedListener(fDirtyStateWatcher);
			}
		}

		public void regionChanged(RegionChangedEvent structuredDocumentEvent) {

			setDirtyState(true);
			// no need to listen any more
			if (fStructuredDocument != null) {
				fStructuredDocument.removeDocumentChangedListener(fDirtyStateWatcher);
			}
		}

		public void regionsReplaced(RegionsReplacedEvent structuredDocumentEvent) {

			setDirtyState(true);
			// no need to listen any more
			if (fStructuredDocument != null) {
				fStructuredDocument.removeDocumentChangedListener(fDirtyStateWatcher);
			}
		}
	}

	class DocumentToModelNotifier implements IStructuredDocumentListener, IModelAboutToBeChangedListener {

		/*
		 * (non-Javadoc)
		 * 
		 * @see org.eclipse.wst.sse.core.events.IModelAboutToBeChangedListener#modelAboutToBeChanged(org.eclipse.wst.sse.core.events.AboutToBeChangedEvent)
		 */
		public void modelAboutToBeChanged(AboutToBeChangedEvent structuredDocumentEvent) {
			// If we didn't originate the change, take note we are about to
			// change based on our underlying document changing.
			// If we did originate the change, we, or client, should have
			// already called aboutToChangeModel.
			if (structuredDocumentEvent.getOriginalRequester() != this) {
				aboutToChangeModel();
			}

		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see org.eclipse.wst.sse.core.events.IStructuredDocumentListener#newModel(org.eclipse.wst.sse.core.events.NewDocumentEvent)
		 */
		public void newModel(NewDocumentEvent structuredDocumentEvent) {
			// if we didn't originate the change, take note we have changed
			if (structuredDocumentEvent.getOriginalRequester() != this) {
				changedModel();
			}
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see org.eclipse.wst.sse.core.events.IStructuredDocumentListener#noChange(org.eclipse.wst.sse.core.events.NoChangeEvent)
		 */
		public void noChange(NoChangeEvent structuredDocumentEvent) {
			// if we didn't originate the change, take note we have changed
			if (structuredDocumentEvent.getOriginalRequester() != this) {
				changedModel();
			}
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see org.eclipse.wst.sse.core.events.IStructuredDocumentListener#nodesReplaced(org.eclipse.wst.sse.core.events.StructuredDocumentRegionsReplacedEvent)
		 */
		public void nodesReplaced(StructuredDocumentRegionsReplacedEvent structuredDocumentEvent) {
			// if we didn't originate the change, take note we have changed
			if (structuredDocumentEvent.getOriginalRequester() != this) {
				changedModel();
			}
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see org.eclipse.wst.sse.core.events.IStructuredDocumentListener#regionChanged(org.eclipse.wst.sse.core.events.RegionChangedEvent)
		 */
		public void regionChanged(RegionChangedEvent structuredDocumentEvent) {
			// if we didn't originate the change, take note we have changed
			if (structuredDocumentEvent.getOriginalRequester() != this) {
				changedModel();
			}
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see org.eclipse.wst.sse.core.events.IStructuredDocumentListener#regionsReplaced(org.eclipse.wst.sse.core.events.RegionsReplacedEvent)
		 */
		public void regionsReplaced(RegionsReplacedEvent structuredDocumentEvent) {
			// if we didn't originate the change, take note we have changed
			if (structuredDocumentEvent.getOriginalRequester() != this) {
				changedModel();
			}
		}

	}

	private FactoryRegistry factoryRegistry;
	private String fBaseLocation;
	boolean fDirtyState;
	DirtyStateWatcher fDirtyStateWatcher;
	DocumentToModelNotifier fDocumentToModelNotifier;
	private String fExplicitContentTypeIdentifier;
	private String fId;

	private LifecycleNotificationManager fLifecycleNotificationManager;

	private final Object fListenerLock = new byte[0];
	protected ILock fLockObject;
	// private String fLineDelimiter;
	// private Object fType;
	private IModelHandler fModelHandler;
	// issue: we should not "hold on" to model manager, can 
	// easily get with StructuredModelManager.getModelManager();
	// but will need to add more null checks.
	private IModelManager fModelManager;
	private int fModelStateChanging;
	private Object[] fModelStateListeners;
	private boolean fNewState = false;
	private URIResolver fResolver;
	protected IStructuredDocument fStructuredDocument;
	/**
	 * The time stamp of the underlying resource's modification date, at the
	 * time this model was created, or the last time it was saved. Note: for
	 * this version, this variable is not set automatically, be needs to be
	 * managed by client. The FileModelProvider does this for most cases, but
	 * if client do not use FileModelProvider, they must set this variable
	 */
	public long fSynchronizationStamp = IResource.NULL_STAMP;
	private boolean reinitializationNeeded;
	private Object reinitializeStateData;

	/**
	 * AbstractStructuredModel constructor comment.
	 */
	public AbstractStructuredModel() {

		super();
		fDirtyStateWatcher = new DirtyStateWatcher();
		fDocumentToModelNotifier = new DocumentToModelNotifier();
	}


	/**
	 * This method is just for getting an instance of the model manager of the
	 * right Impl type, to be used "internally" for making protected calls
	 * directly to the impl class.
	 */
	private ModelManagerImpl _getModelManager() {
		// TODO_future: redesign so we don't need this 'Impl' version
		if (fModelManager == null) {
			fModelManager = StructuredModelManager.getModelManager();
		}

		return (ModelManagerImpl) fModelManager;
	}

	/**
	 * This API allows clients to declare that they are about to make a
	 * "large" change to the model. This change might be in terms of content
	 * or it might be in terms of the model id or base location. Note that in
	 * the case of embedded calls, notification to listeners is sent only
	 * once. Note that the client who is making these changes has the
	 * responsibility to restore the models state once finished with the
	 * changes. See getMemento and restoreState. The method
	 * isModelStateChanging can be used by a client to determine if the model
	 * is already in a change sequence.
	 */
	public void aboutToChangeModel() {


		// notice this is just a public avenue to our protected method
		internalAboutToBeChanged();
	}


	public void aboutToReinitializeModel() {



		// notice this is just a public avenue to our protected method
		fireModelAboutToBeReinitialized();
	}


	public void addModelLifecycleListener(IModelLifecycleListener listener) {

		synchronized (fListenerLock) {
			if (fLifecycleNotificationManager == null) {
				fLifecycleNotificationManager = new LifecycleNotificationManager();
			}
			fLifecycleNotificationManager.addListener(listener);
		}
	}

	public void addModelStateListener(IModelStateListener listener) {

		synchronized (fListenerLock) {

			if (!Utilities.contains(fModelStateListeners, listener)) {
				int oldSize = 0;
				if (fModelStateListeners != null) {
					// normally won't be null, but we need to be sure, for
					// first
					// time through
					oldSize = fModelStateListeners.length;
				}
				int newSize = oldSize + 1;
				Object[] newListeners = new Object[newSize];
				if (fModelStateListeners != null) {
					System.arraycopy(fModelStateListeners, 0, newListeners, 0, oldSize);
				}
				// add listener to last position
				newListeners[newSize - 1] = listener;
				//
				// now switch new for old
				fModelStateListeners = newListeners;
			}
		}
	}

	/**
	 * This lock to lock the small bits of data and operations in the models
	 * themselfes. this lock is "shared" with document, so, eventually,
	 * changes can be made safefly from either side.
	 */
	protected final void beginLock() {

		// if we get a different lock object
		// than we had before, besure to release
		// old one first before losing it.
		// ISSUE: this smells like an error condition,
		// when would this happen? better to check in set document?
		ILock documentLock = getLockObjectFromDocument();

		if (fLockObject != null && fLockObject != documentLock) {
			fLockObject.release();
			if (Logger.DEBUG_MODELSTATE) {
				Logger.log(Logger.INFO, "Model lock released early" + fLockObject + " apparently document switched?"); //$NON-NLS-1$ //$NON-NLS-2$
			}

		}
		fLockObject = documentLock;
		if (fLockObject != null) {
			fLockObject.acquire();
			if (Logger.DEBUG_MODELSTATE) {
				Logger.log(Logger.INFO, "Model lock acquired: " + fLockObject); //$NON-NLS-1$
			}
		}
	}

	public void beginRecording(Object requester) {

		beginRecording(requester, null, null);
	}

	public void beginRecording(Object requester, int cursorPosition, int selectionLength) {

		beginRecording(requester, null, null, cursorPosition, selectionLength);
	}

	public void beginRecording(Object requester, String label) {

		beginRecording(requester, label, null);
	}

	public void beginRecording(Object requester, String label, int cursorPosition, int selectionLength) {

		beginRecording(requester, label, null, cursorPosition, selectionLength);
	}

	public void beginRecording(Object requester, String label, String description) {

		if (getUndoManager() != null)
			getUndoManager().beginRecording(requester, label, description);
	}

	public void beginRecording(Object requester, String label, String description, int cursorPosition, int selectionLength) {

		if (getUndoManager() != null)
			getUndoManager().beginRecording(requester, label, description, cursorPosition, selectionLength);
	}

	/**
	 * This API allows a client controlled way of notifying all ModelEvent
	 * listners that the model has been changed. This method is a matched pair
	 * to aboutToChangeModel, and *must* be called after aboutToChangeModel
	 * ... or some listeners could be left waiting indefinitely for the
	 * changed event. So, its suggested that changedModel always be in a
	 * finally clause. Likewise, a client should never call changedModel
	 * without calling aboutToChangeModel first. In the case of embedded
	 * calls, the notification is just sent once.
	 */
	public void changedModel() {


		// notice this is just a public avenue to our protected method
		internalModelChanged();
		// also note!
		// if we've been "changed" by a client, we might still need
		// to be re-initialized, so we'll check and handle that here.
		// Note only does this provide a solution to some "missed"
		// re-inits, in provides a built in way for clients to
		// "force" the model to handle itself, by bracketing any
		// changes with aboutToChange and changed, the model itself
		// will check. But only call re-init if all other pending
		// modelChanged states have been handled.
		if (fModelStateChanging == 0 && isReinitializationNeeded()) {
			reinit();
		}
	}


	/**
	 * Based on similar method in FileDocumentProvider. It will provide what
	 * the modificationStamp would be if resetSynchronzationStamp(resource)
	 * were used, although for this 'compute' API, no changes to the instance
	 * are made.
	 */
	public long computeModificationStamp(IResource resource) {


		long modificationStamp = resource.getModificationStamp();
		IPath path = resource.getLocation();
		if (path == null) {
			return modificationStamp;
		}
		// Note: checking existence of file is a little different than
		// impl in
		// the FileDocumentProvider. See defect number 223790.
		File file = path.toFile();
		if (!file.exists()) {
			return modificationStamp;
		}
		modificationStamp = file.lastModified();
		return modificationStamp;
	}


	/**
	 * Provides a copy of the model, but a new ID must be provided. The
	 * principle of this copy is not to copy fields, etc., as is typically
	 * done in a clone method, but to return a model with the same content in
	 * the structuredDocument. Note: It is the callers responsibility to
	 * setBaseLocation, listners, etc., as appropriate. Type and Encoding are
	 * the only fields set by this method. If the newId provided already exist
	 * in the model manager, a ResourceInUse exception is thrown.
	 */
	public IStructuredModel copy(String newId) throws ResourceInUse {


		IStructuredModel newModel = null;
		// this first one should fail, if not, its treated as an error
		// If the caller wants to use an existing one, they can call
		// getExisting
		// after this failure
		newModel = getModelManager().getExistingModelForEdit(newId);
		if (newModel != null) {
			// be sure to release the reference we got "by accident" (and
			// no
			// longer need)
			newModel.releaseFromEdit();
			throw new ResourceInUse();
		}
		newModel = getModelManager().copyModelForEdit(getId(), newId);
		return newModel;
	}


	/**
	 * Disable undo management.
	 */
	public void disableUndoManagement() {

		if (getUndoManager() != null)
			getUndoManager().disableUndoManagement();
	}

	/**
	 * Enable undo management.
	 */
	public void enableUndoManagement() {

		if (getUndoManager() != null)
			getUndoManager().enableUndoManagement();
	}

	/**
	 * endLock is protected only for a very special purpose. So subclasses can
	 * call it to end the lock after updates have been made, but before
	 * notifications are sent
	 * 
	 */
	protected final void endLock() {
		if (fLockObject != null) {
			fLockObject.release();
			if (Logger.DEBUG_MODELSTATE) {
				Logger.log(Logger.INFO, "Model lock released: " + fLockObject); //$NON-NLS-1$
			}

		}
	}

	public void endRecording(Object requester) {

		if (getUndoManager() != null)
			getUndoManager().endRecording(requester);
	}

	public void endRecording(Object requester, int cursorPosition, int selectionLength) {

		if (getUndoManager() != null)
			getUndoManager().endRecording(requester, cursorPosition, selectionLength);
	}

	/**
	 * Informs all registered model state listeners that the the model is
	 * about to under go a change. This change might be in terms of contents
	 * or might be in terms of the model's id or base location.
	 */
	private void fireModelAboutToBeChanged() {

		// we must assign listeners to local variable, since the add and
		// remove listner
		// methods can change the actual instance of the listener array
		// from another thread
		if (fModelStateListeners != null) {
			Object[] holdListeners = fModelStateListeners;
			for (int i = 0; i < holdListeners.length; i++) {
				((IModelStateListener) holdListeners[i]).modelAboutToBeChanged(this);
			}
		}

	}

	protected void fireModelAboutToBeReinitialized() {

		// we must assign listeners to local variable, since the add and
		// remove
		// listner
		// methods can change the actual instance of the listener array from
		// another thread
		if (fModelStateListeners != null) {
			if (Logger.DEBUG_MODELSTATE) {
				Logger.log(Logger.INFO, "IModelStateListener event for " + getId() + " : modelAboutToBeReinitialized"); //$NON-NLS-1$ //$NON-NLS-2$
			}
			Object[] holdListeners = fModelStateListeners;
			for (int i = 0; i < holdListeners.length; i++) {
				// NOTE: trick for transition. We actual use the same
				// listeners
				// as modelState, but only send this to those that have
				// implemented ModelStateExtended.
				IModelStateListener listener = (IModelStateListener) holdListeners[i];
				listener.modelAboutToBeReinitialized(this);
			}
		}
	}

	private void fireModelChanged() {
		// we must assign listeners
		// to local variable, since the add
		// and remove listner
		// methods can change the actual instance of the listener
		// array from another thread
		if (fModelStateListeners != null) {
			Object[] holdListeners = fModelStateListeners;
			for (int i = 0; i < holdListeners.length; i++) {
				try {
					((IModelStateListener) holdListeners[i]).modelChanged(this);
				}
				// its so criticial that the begin/end arrive in
				// pairs,
				// if there happends to be an error in one of the
				// modelChanged,
				// they we want to be sure rest complete ok.
				catch (Exception e) {
					Logger.logException(e);
				}
			}

		}
	}

	/**
	 * Informs all registered model state listeners about a change in the
	 * dirty state of the model. The dirty state is entirely about changes in
	 * the content of the model (not, for example, about changes to id, or
	 * base location -- see modelMoved).
	 */
	protected void fireModelDirtyStateChanged(IStructuredModel element, boolean isDirty) {

		// we must assign listeners to local variable, since the add and
		// remove
		// listner
		// methods can change the actual instance of the listener array from
		// another thread
		if (fModelStateListeners != null) {
			if (Logger.DEBUG_MODELSTATE) {
				Logger.log(Logger.INFO, "IModelStateListener event for " + getId() + " : modelDirtyStateChanged"); //$NON-NLS-1$ //$NON-NLS-2$
			}
			Object[] holdListeners = fModelStateListeners;
			for (int i = 0; i < holdListeners.length; i++) {
				((IModelStateListener) holdListeners[i]).modelDirtyStateChanged(element, isDirty);
			}
		}
	}

	protected void fireModelReinitialized() {

		// we must assign listeners to local variable, since the add and
		// remove
		// listner
		// methods can change the actual instance of the listener array from
		// another thread
		if (fModelStateListeners != null) {
			if (Logger.DEBUG_MODELSTATE) {
				Logger.log(Logger.INFO, "IModelStateListener event for " + getId() + " : modelReinitialized"); //$NON-NLS-1$ //$NON-NLS-2$
			}
			Object[] holdListeners = fModelStateListeners;
			for (int i = 0; i < holdListeners.length; i++) {
				IModelStateListener listener = (IModelStateListener) holdListeners[i];
				listener.modelReinitialized(this);
			}
		}
	}

	/**
	 * Informs all registered model state listeners about the deletion of a
	 * model's underlying resource.
	 */
	protected void fireModelResourceDeleted(IStructuredModel element) {

		// we must assign listeners to local variable, since the add and
		// remove
		// listner
		// methods can change the actual instance of the listener array from
		// another thread
		if (fModelStateListeners != null) {
			if (Logger.DEBUG_MODELSTATE) {
				Logger.log(Logger.INFO, "IModelStateListener event for " + getId() + " : modelResourceDeleted"); //$NON-NLS-1$ //$NON-NLS-2$
			}
			Object[] holdListeners = fModelStateListeners;
			for (int i = 0; i < holdListeners.length; i++) {
				((IModelStateListener) holdListeners[i]).modelResourceDeleted(element);
			}
		}
	}

	/**
	 * Informs all registered model state listeners that the resource
	 * underlying a model has been moved. This is typically reflected in a
	 * change to the id, baseLocation, or both.
	 */
	protected void fireModelResourceMoved(IStructuredModel originalElement, IStructuredModel movedElement) {

		// we must assign listeners to local variable, since the add and
		// remove
		// listner
		// methods can change the actual instance of the listener array from
		// another thread
		if (fModelStateListeners != null) {
			if (Logger.DEBUG_MODELSTATE) {
				Logger.log(Logger.INFO, "IModelStateListener event for " + getId() + " : modelResourceMoved"); //$NON-NLS-1$ //$NON-NLS-2$
			}
			Object[] holdListeners = fModelStateListeners;
			for (int i = 0; i < holdListeners.length; i++) {
				((IModelStateListener) holdListeners[i]).modelResourceMoved(originalElement, movedElement);
			}
		}
	}

	public Object getAdapter(Class adapter) {

		return Platform.getAdapterManager().getAdapter(this, adapter);
	}

	/**
	 * @return java.lang.String
	 */
	public java.lang.String getBaseLocation() {

		return fBaseLocation;
	}

	/**
	 * @see org.eclipse.wst.sse.core.internal.provisional.IStructuredModel#getContentTypeIdentifier()
	 */
	public String getContentTypeIdentifier() {
		if (fExplicitContentTypeIdentifier != null)
			return fExplicitContentTypeIdentifier;
		return fModelHandler.getAssociatedContentTypeId();
	}

	/**
	 * 
	 */
	public FactoryRegistry getFactoryRegistry() {
		if (factoryRegistry == null) {
			factoryRegistry = new FactoryRegistry();
		}
		return factoryRegistry;
	}

	/**
	 * The id is the id that the model manager uses to identify this model
	 * 
	 * @ISSUE - no one should need to know ID, so this should be default access eventually. 
	 * If clients believe they do need ID, be sure to let us know (open a bug). 
	 */
	public String getId() {

		return fId;
	}

	public abstract IndexedRegion getIndexedRegion(int offset);

	/**
	 * @return
	 */
	private ILock getLockObjectFromDocument() {

		// we always "get afresh" the lock object from our document,
		// just in case the instance of the document changes.
		ILock result = null;
		IStructuredDocument doc = fStructuredDocument;
		if (doc != null) {
			if (doc instanceof ILockable) {
				// remember, more than one client can get the
				// lock object, its during the aquire that the
				// lock on the thread is obtained.
				result = ((ILockable) doc).getLockObject();
			}
		}
		return result;
	}

	/**
	 * Gets the contentTypeDescription.
	 * 
	 * @return Returns a ContentTypeDescription
	 */
	public IModelHandler getModelHandler() {

		return fModelHandler;
	}


	public IModelManager getModelManager() {

		return _getModelManager();
	}

	/**
	 * This function returns the reference count of underlying model.
	 */
	// TODO: try to refine the design not to use this function
	public int getReferenceCount() {


		if (getModelManager() == null)
			return 0;
		return getModelManager().getReferenceCount(getId());
	}


	/**
	 * This function returns the reference count of underlying model.
	 */
	// TODO: try to refine the design not to use this function
	public int getReferenceCountForEdit() {



		if (getModelManager() == null)
			return 0;
		return getModelManager().getReferenceCountForEdit(getId());
	}


	/**
	 * This function returns the reference count of underlying model.
	 */
	// TODO: try to refine the design not to use this function
	public int getReferenceCountForRead() {



		if (getModelManager() == null)
			return 0;
		return getModelManager().getReferenceCountForRead(getId());
	}

	public Object getReinitializeStateData() {

		return reinitializeStateData;
	}



	public URIResolver getResolver() {

		return fResolver;
	}


	public IStructuredDocument getStructuredDocument() {

		IStructuredDocument result = null;
		result = fStructuredDocument;
		return result;
	}

	/**
	 * Insert the method's description here. Creation date: (9/7/2001 2:30:26
	 * PM)
	 * 
	 * @return long
	 */
	public long getSynchronizationStamp() {

		return fSynchronizationStamp;
	}

	public IStructuredTextUndoManager getUndoManager() {

		IStructuredTextUndoManager structuredTextUndoManager = null;
		IStructuredDocument structuredDocument = getStructuredDocument();
		if (structuredDocument == null) {
			structuredTextUndoManager = null;
		}
		else {
			structuredTextUndoManager = structuredDocument.getUndoManager();
		}
		return structuredTextUndoManager;
	}

	public void initId(String id) {
		fId = id;
	}

	final protected void internalAboutToBeChanged() {

		// notice we only fire this event if we are not
		// already in a model state changing sequence
		if (fModelStateChanging == 0) {

			if (Logger.DEBUG_MODELSTATE) {
				Logger.log(Logger.INFO, "IModelStateListener event for " + getId() + " : modelAboutToBeChanged"); //$NON-NLS-1$ //$NON-NLS-2$
			}

			try {
				fireModelAboutToBeChanged();
			}
			catch (Exception e) {
				Logger.logException("Exception while notifying model state listers of about to change", e); //$NON-NLS-1$
			}
			finally {
				// begin lock after listeners notified, otherwise
				// deadlock could occur if they call us back.
				beginLock();
			}

		}
		// we always increment counter, for every request (so *must* receive
		// corresponding number of 'changedModel' requests)
		fModelStateChanging++;
	}

	/**
	 * Informs all registered model state listeners that an impending change
	 * is now complete. This method must only be called by 'modelChanged'
	 * since it keeps track of counts.
	 */
	final protected void internalModelChanged() {

		// always decrement
		fModelStateChanging--;


		// Check integrity
		// to be less than zero is a programming error,
		// but we'll reset to zero
		// and try to continue
		if (fModelStateChanging < 0) {
			fModelStateChanging = 0;
			// should not be locked, but just in case
			endLock();
			throw new IllegalStateException("Program Error: modelStateChanging was less than zero"); //$NON-NLS-1$
		}


		// We only fire this event if all pending requests are done.
		// That is, if we've received the same number of modelChanged as
		// we have aboutToChangeModel.
		if (fModelStateChanging == 0) {
			if (Logger.DEBUG_MODELSTATE) {
				Logger.log(Logger.INFO, "IModelStateListener event for " + getId() + " : modelChanged"); //$NON-NLS-1$ //$NON-NLS-2$
			}

			endLock();
			// notifify listeners outside of locked state (or deadlock
			// can occur if one of them calls us back.
			fireModelChanged();
		}
	}

	public boolean isDirty() {

		return fDirtyState;
	}

	/**
	 * This method has very special purpose, its used in subclass
	 * 'changedModel' to know when to do "ending" sorts of things, right
	 * before a call to super.ChangedModel would in deed put the model in
	 * 'end' state. Put another way, at the beginning of the subclasses's
	 * changedModel, the isModelStateChanging is true, but at end, it will be
	 * false. So, this method allows a small "peek ahead".
	 */
	protected boolean isModelChangeStateOnVergeOfEnding() {


		return fModelStateChanging == 1;
	}

	/**
	 * This method can be called to determine if the model is within a
	 * "aboutToChange" and "changed" sequence.
	 */
	public boolean isModelStateChanging() {


		return fModelStateChanging > 0;
	}

	public boolean isNew() {

		return fNewState;
	}

	public boolean isReinitializationNeeded() {

		return reinitializationNeeded;
	}

	public boolean isSaveNeeded() {


		if (!isSharedForEdit())
			return isDirty();
		else
			return false;
	}


	/**
	 * This function returns true if there are other references to the
	 * underlying model.
	 */
	public boolean isShared() {
		if (getModelManager() == null)
			return false;
		return getModelManager().isShared(getId());
	}


	/**
	 * This function returns true if there are other references to the
	 * underlying model.
	 */
	public boolean isSharedForEdit() {


		if (getModelManager() == null)
			return false;
		return getModelManager().isSharedForEdit(getId());
	}


	/**
	 * This function returns true if there are other references to the
	 * underlying model.
	 */
	public boolean isSharedForRead() {


		if (getModelManager() == null)
			return false;
		return getModelManager().isSharedForRead(getId());
	}


	public void modelReinitialized() {


		// notice this is just a public avenue to our protected method
		fireModelReinitialized();
	}

	public IStructuredModel newInstance() throws IOException {

		IStructuredModel newModel = null;
		// we delegate to the model manager, so loader, etc., can be
		// used.
		newModel = getModelManager().createNewInstance(this);
		return newModel;
	}

	public IStructuredModel reinit() {


		IStructuredModel result = null;
		if (fModelStateChanging == 0) {
			try {
				aboutToChangeModel();
				aboutToReinitializeModel();
				result = _getModelManager().reinitialize(this);
			}
			finally {
				setReinitializeNeeded(false);
				setReinitializeStateData(null);
				modelReinitialized();
				changedModel();
			}
		}
		else {
			if (Logger.DEBUG_MODELSTATE) {
				Logger.log(Logger.INFO, "indeed!!!"); //$NON-NLS-1$
			}
		}
		return result;
	}


	/**
	 * This function allows the model to free up any resources it might be
	 * using. In particular, itself, as stored in the IModelManager.
	 */
	public void releaseFromEdit() {


		if (getModelManager() == null) {
			throw new IllegalStateException(MODEL_MANAGER_NULL); //$NON-NLS-1$
		}
		else {
			/*
			 * Be sure to check the shared state before releasing. (Since
			 * isShared assumes a count of 1 means not shared ... and we want
			 * our '1' to be that one.) The problem, of course, is that
			 * between pre-cycle notification and post-release notification,
			 * the model could once again have become shared, rendering the
			 * release notification incorrect.
			 */
			boolean isShared = isShared();

			if (!isShared) {
				signalPreLifeCycleEventRelease(this);
			}

			_getModelManager().releaseFromEdit(this);
			if (!isShared) {
				signalPostLifeCycleListenerRelease(this);
			}
		}

	}

	/**
	 * This function allows the model to free up any resources it might be
	 * using. In particular, itself, as stored in the IModelManager.
	 */
	public void releaseFromRead() {

		if (getModelManager() == null) {
			throw new IllegalStateException(MODEL_MANAGER_NULL); //$NON-NLS-1$
		}
		else {
			/*
			 * Be sure to check the shared state before releasing. (Since
			 * isShared assumes a count of 1 means not shared ... and we want
			 * our '1' to be that one.) The problem, of course, is that
			 * between pre-cycle notification and post-release notification,
			 * the model could once again have become shared, rendering the
			 * release notification incorrect.
			 */
			boolean isShared = isShared();

			if (!isShared) {
				signalPreLifeCycleEventRelease(this);
			}

			_getModelManager().releaseFromRead(this);

			if (!isShared) {
				signalPostLifeCycleListenerRelease(this);
			}
		}
	}


	/**
	 * This function replenishes the model with the resource without saving
	 * any possible changes. It is used when one editor may be closing, and
	 * specifially says not to save the model, but another "display" of the
	 * model still needs to hang on to some model, so needs a fresh copy.
	 */
	public IStructuredModel reload(InputStream inputStream) throws IOException {
		IStructuredModel result = null;
		try {
			aboutToChangeModel();
			result = _getModelManager().reloadModel(getId(), inputStream);
		}
		catch (UnsupportedEncodingException e) {
			// log for now, unless we find reason not to
			Logger.log(Logger.INFO, e.getMessage());
		}
		finally {
			changedModel();
		}
		return result;
	}

	public void removeModelLifecycleListener(IModelLifecycleListener listener) {

		// if manager is null, then none have been added, so
		// no need to remove any
		if (fLifecycleNotificationManager == null)
			return;
		synchronized (fListenerLock) {
			fLifecycleNotificationManager.removeListener(listener);
		}
	}


	public void removeModelStateListener(IModelStateListener listener) {

		if (listener == null)
			return;
		if (fModelStateListeners == null)
			return;
		// if its not in the listeners, we'll ignore the request
		synchronized (fListenerLock) {
			if (Utilities.contains(fModelStateListeners, listener)) {
				int oldSize = fModelStateListeners.length;
				int newSize = oldSize - 1;
				Object[] newListeners = new Object[newSize];
				int index = 0;
				for (int i = 0; i < oldSize; i++) {
					if (fModelStateListeners[i] == listener) { // ignore
					}
					else {
						// copy old to new if its not the one we are
						// removing
						newListeners[index++] = fModelStateListeners[i];
					}
				}
				// now that we have a new array, let's switch it for the
				// old
				// one
				fModelStateListeners = newListeners;
			}
		}
	}


	/**
	 * A method that modifies the model's synchronization stamp to match the
	 * resource. Turns out there's several ways of doing it, so this ensures a
	 * common algorithm.
	 */
	public void resetSynchronizationStamp(IResource resource) {


		setSynchronizationStamp(computeModificationStamp(resource));
	}


	/**
	 * This API allows a client to initiate notification to all interested
	 * parties that a model's underlying resource has been deleted.
	 */
	public void resourceDeleted() {


		// notice this is just a public avenue to our protected method
		fireModelResourceDeleted(this);
	}


	/**
	 * This method allows a model client to initiate notification to all
	 * interested parties that a model's underlying resource location has
	 * changed. Note: we assume caller has already changed baseLocation, Id,
	 * etc., since its really up to the client to determine what's "new" about
	 * a moved model. Caution: 'this' and 'newModel' may be the same object.
	 * This is the case for current working with FileModelProvider, but have
	 * left the dual argument for future possibilities.
	 */
	public void resourceMoved(IStructuredModel newModel) {


		// notice this is just a public avenue to our protected method
		fireModelResourceMoved(this, newModel);
	}


	public void save() throws UnsupportedEncodingException, IOException, CoreException {

		int type = ModelLifecycleEvent.MODEL_SAVED | ModelLifecycleEvent.PRE_EVENT;
		ModelLifecycleEvent modelLifecycleEvent = new ModelLifecycleEvent(this, type);
		signalLifecycleEvent(modelLifecycleEvent);

		try {
			String stringId = getId();
			_getModelManager().saveModel(stringId, EncodingRule.CONTENT_BASED);
		}

		finally {
			// we put end notification in finally block, so even if
			// error occurs during save, listeners are still notified,
			// since their code could depend on receiving, to clean up
			// some state, or coordinate other resources.
			type = ModelLifecycleEvent.MODEL_SAVED | ModelLifecycleEvent.POST_EVENT;
			modelLifecycleEvent = new ModelLifecycleEvent(this, type);
			signalLifecycleEvent(modelLifecycleEvent);
		}
	}


	public void save(EncodingRule encodingRule) throws UnsupportedEncodingException, IOException, CoreException {

		int type = ModelLifecycleEvent.MODEL_SAVED | ModelLifecycleEvent.PRE_EVENT;
		ModelLifecycleEvent modelLifecycleEvent = new ModelLifecycleEvent(this, type);
		signalLifecycleEvent(modelLifecycleEvent);

		try {
			String stringId = getId();
			_getModelManager().saveModel(stringId, encodingRule);
		}
		finally {
			// we put end notification in finally block, so even if
			// error occurs during save, listeners are still notified,
			// since their code could depend on receiving, to clean up
			// some state, or coordinate other resources.
			type = ModelLifecycleEvent.MODEL_SAVED | ModelLifecycleEvent.POST_EVENT;
			modelLifecycleEvent = new ModelLifecycleEvent(this, type);
			signalLifecycleEvent(modelLifecycleEvent);
		}
	}


	public void save(IFile iFile) throws UnsupportedEncodingException, IOException, CoreException {

		int type = ModelLifecycleEvent.MODEL_SAVED | ModelLifecycleEvent.PRE_EVENT;
		ModelLifecycleEvent modelLifecycleEvent = new ModelLifecycleEvent(this, type);
		signalLifecycleEvent(modelLifecycleEvent);

		try {
			String stringId = getId();
			_getModelManager().saveModel(iFile, stringId, EncodingRule.CONTENT_BASED);
		}

		finally {
			// we put end notification in finally block, so even if
			// error occurs during save, listeners are still notified,
			// since their code could depend on receiving, to clean up
			// some state, or coordinate other resources.
			type = ModelLifecycleEvent.MODEL_SAVED | ModelLifecycleEvent.POST_EVENT;
			modelLifecycleEvent = new ModelLifecycleEvent(this, type);
			signalLifecycleEvent(modelLifecycleEvent);
		}
	}


	public void save(IFile iFile, EncodingRule encodingRule) throws UnsupportedEncodingException, IOException, CoreException {

		int type = ModelLifecycleEvent.MODEL_SAVED | ModelLifecycleEvent.PRE_EVENT;
		ModelLifecycleEvent modelLifecycleEvent = new ModelLifecycleEvent(this, type);
		signalLifecycleEvent(modelLifecycleEvent);

		try {
			String stringId = getId();
			_getModelManager().saveModel(iFile, stringId, encodingRule);
		}
		finally {
			// we put end notificatioon in finally block, so even if
			// error occurs during save, listeners are still notified,
			// since their code could depend on receiving, to clean up
			// some state, or coordinate other resources.
			type = ModelLifecycleEvent.MODEL_SAVED | ModelLifecycleEvent.POST_EVENT;
			modelLifecycleEvent = new ModelLifecycleEvent(this, type);
			signalLifecycleEvent(modelLifecycleEvent);
		}
	}


	public void save(OutputStream outputStream) throws UnsupportedEncodingException, CoreException, IOException {

		int type = ModelLifecycleEvent.MODEL_SAVED | ModelLifecycleEvent.PRE_EVENT;
		ModelLifecycleEvent modelLifecycleEvent = new ModelLifecycleEvent(this, type);
		signalLifecycleEvent(modelLifecycleEvent);

		try {
			String stringId = getId();
			_getModelManager().saveModel(stringId, outputStream, EncodingRule.CONTENT_BASED);
		}

		finally {
			// we put end notification in finally block, so even if
			// error occurs during save, listeners are still notified,
			// since their code could depend on receiving, to clean up
			// some state, or coordinate other resources.
			type = ModelLifecycleEvent.MODEL_SAVED | ModelLifecycleEvent.POST_EVENT;
			modelLifecycleEvent = new ModelLifecycleEvent(this, type);
			signalLifecycleEvent(modelLifecycleEvent);
		}
	}


	/**
	 * This attribute is typically used to denote the model's underlying
	 * resource.
	 */
	public void setBaseLocation(java.lang.String newBaseLocation) {

		fBaseLocation = newBaseLocation;
	}

	public void setContentTypeIdentifier(String contentTypeIdentifier) {
		fExplicitContentTypeIdentifier = contentTypeIdentifier;
	}

	/**
	 * 
	 */
	public void setDirtyState(boolean dirtyState) {

		// no need to process (set or fire event), if same value
		if (fDirtyState != dirtyState) {
			// pre-change notification
			int type = ModelLifecycleEvent.MODEL_DIRTY_STATE | ModelLifecycleEvent.PRE_EVENT;
			ModelLifecycleEvent modelLifecycleEvent = new ModelLifecycleEvent(this, type);
			signalLifecycleEvent(modelLifecycleEvent);


			// the actual change
			fDirtyState = dirtyState;

			// old notification
			// TODO: C3 remove old notification
			if (fDirtyState == false) {
				// if we are being set to not dirty (such as just been saved)
				// then we need to start listening for changes
				// again to know when to set state to true;
				getStructuredDocument().addDocumentChangedListener(fDirtyStateWatcher);
			}
			fireModelDirtyStateChanged(this, dirtyState);


			// post change notification
			type = ModelLifecycleEvent.MODEL_DIRTY_STATE | ModelLifecycleEvent.POST_EVENT;
			modelLifecycleEvent = new ModelLifecycleEvent(this, type);
			signalLifecycleEvent(modelLifecycleEvent);
		}
	}

	/**
	 * @deprecated - will likely be deprecated soon, in favor of direct 'adds'
	 *             ... but takes some redesign.
	 */
	public void setFactoryRegistry(FactoryRegistry factoryRegistry) {
		this.factoryRegistry = factoryRegistry;
	}

	/**
	 * The id is the id that the model manager uses to identify this model. If
	 * it is being set here, it means the model manger is already managing the
	 * model with another id, so we have to keep it in sync. This method calls
	 * notifies listners, if they haven't been notified already, that a "model
	 * state change" is about to occur.
	 */
	public void setId(String newId) throws ResourceInUse {


		// It makes no sense, I don't think, to have an id of null, so
		// we'll throw an illegal argument exception if someone trys. Note:
		// the IModelManager could not manage a model with an id of null,
		// since it uses hashtables, and you can't have a null id for a
		// hashtable.
		if (newId == null)
			throw new IllegalArgumentException(SSECoreMessages.A_model_s_id_can_not_be_nu_EXC_); //$NON-NLS-1$ = "A model's id can not be null"
		// To guard against throwing a spurious ResourceInUse exception,
		// which can occur when two pieces of code both want to change the id,
		// so the second request is spurious, we'll ignore any requests that
		// attempt to change the id to what it already is ... note, we use
		// 'equals', not identity ('==') so that things like
		// strings can be used. This is the same criteria that ids are
		// found in model manager -- well, actually, I just checked, and for
		// the hashtable impl, the criteria uses .equals AND the condition
		// that the hash values be identical (I'm assuming this is always
		// true, if equals is true, for now, I'm not sure
		// we can assume that hashtable will always be used, but in
		// general, should match.)
		//
		if (newId.equals(fId))
			return;
		// we must guard against reassigning an id to one that we already
		// are managing.
		if (getModelManager() != null) {
			boolean inUse = ((ModelManagerImpl)getModelManager()).isIdInUse(newId);
			if (inUse) {
				throw new ResourceInUse();
			}
		}
		try {
			// normal code path
			aboutToChangeModel();
			String oldId = fId;
			fId = newId;
			if (getModelManager() != null) {
				// if managed and the id has changed, notify to
				// IModelManager
				// TODO: try to refine the design not to do that
				if (oldId != null && newId != null && !newId.equals(oldId)) {
					getModelManager().moveModel(oldId, newId);
				}
			}
		}
		finally {
			// make sure this finally is only executed if 'about to Change
			// model' has
			// been executed.
			changedModel();
		}
	}

	/**
	 * Sets the contentTypeDescription.
	 * 
	 * @param contentTypeDescription
	 *            The contentTypeDescription to set
	 */
	public void setModelHandler(IModelHandler modelHandler) {

		// no need to fire events if modelHandler has been null
		// for this model --
		// this is an attempt at initialization optimization and may need
		// to change in future.
		boolean trueChange = false;
		if (fModelHandler != null)
			trueChange = true;
		if (trueChange) {
			internalAboutToBeChanged();
		}
		fModelHandler = modelHandler;
		if (trueChange) {
			internalModelChanged();
		}
	}



	public void setModelManager(IModelManager newModelManager) {

		fModelManager = newModelManager;
	}

	/**
	 * 
	 */
	public void setNewState(boolean newState) {

		fNewState = newState;
	}

	/**
	 * Sets a "flag" that reinitialization is needed.
	 */
	public void setReinitializeNeeded(boolean needed) {

		reinitializationNeeded = needed;
	}

	/**
	 * Holds any data that the reinit procedure might find useful in
	 * reinitializing the model. This is handy, since the reinitialization may
	 * not take place at once, and some "old" data may be needed to properly
	 * undo previous settings. Note: the parameter was intentionally made to
	 * be of type 'Object' so different models can use in different ways.
	 */
	public void setReinitializeStateData(Object object) {

		reinitializeStateData = object;
	}


	public void setResolver(URIResolver newResolver) {

		fResolver = newResolver;
	}


	public void setStructuredDocument(IStructuredDocument newStructuredDocument) {
		boolean lifeCycleNotification = false;
		if (fStructuredDocument != null) {
			fStructuredDocument.removeDocumentChangedListener(fDirtyStateWatcher);
			fStructuredDocument.removeDocumentAboutToChangeListener(fDocumentToModelNotifier);
			fStructuredDocument.removeDocumentChangedListener(fDocumentToModelNotifier);
			// prechange notification
			lifeCycleNotification = true;
			ModelLifecycleEvent modelLifecycleEvent = new DocumentChanged(ModelLifecycleEvent.PRE_EVENT, this, fStructuredDocument, newStructuredDocument);
			signalLifecycleEvent(modelLifecycleEvent);
		}

		// hold for life cycle notification
		IStructuredDocument previousDocument = fStructuredDocument;
		// the actual change
		fStructuredDocument = newStructuredDocument;


		// at the super class level, we'll listen for structuredDocument
		// changes
		// so we can set our dirty state flag
		if (fStructuredDocument != null) {
			fStructuredDocument.addDocumentChangedListener(fDirtyStateWatcher);
			fStructuredDocument.addDocumentAboutToChangeListener(fDocumentToModelNotifier);
			fStructuredDocument.addDocumentChangedListener(fDocumentToModelNotifier);
		}

		if (lifeCycleNotification) {
			// post change notification
			ModelLifecycleEvent modelLifecycleEvent = new DocumentChanged(ModelLifecycleEvent.POST_EVENT, this, previousDocument, newStructuredDocument);
			signalLifecycleEvent(modelLifecycleEvent);
		}
	}

	/**
	 * Insert the method's description here. Creation date: (9/7/2001 2:30:26
	 * PM)
	 * 
	 * @param newSynchronizationStamp
	 *            long
	 */
	protected void setSynchronizationStamp(long newSynchronizationStamp) {

		fSynchronizationStamp = newSynchronizationStamp;
	}

	public void setUndoManager(IStructuredTextUndoManager undoManager) {

		IStructuredDocument structuredDocument = getStructuredDocument();
		if (structuredDocument == null) {
			throw new IllegalStateException("document was null when undo manager set on model"); //$NON-NLS-1$
		}
		structuredDocument.setUndoManager(undoManager);
	}

	/**
	 * To be called only by "friendly" classes, such as ModelManager, and
	 * subclasses.
	 */
	void signalLifecycleEvent(ModelLifecycleEvent event) {
		if (fLifecycleNotificationManager == null)
			return;
		fLifecycleNotificationManager.signalLifecycleEvent(event);
	}

	private void signalPostLifeCycleListenerRelease(IStructuredModel structuredModel) {
		int type = ModelLifecycleEvent.MODEL_RELEASED | ModelLifecycleEvent.POST_EVENT;
		// what's wrong with this design that a cast is needed here!?
		ModelLifecycleEvent event = new ModelLifecycleEvent(structuredModel, type);
		((AbstractStructuredModel) structuredModel).signalLifecycleEvent(event);
	}

	private void signalPreLifeCycleEventRelease(IStructuredModel structuredModel) {
		int type = ModelLifecycleEvent.MODEL_RELEASED | ModelLifecycleEvent.PRE_EVENT;
		// what's wrong with this design that a cast is needed here!?
		ModelLifecycleEvent event = new ModelLifecycleEvent(structuredModel, type);
		((AbstractStructuredModel) structuredModel).signalLifecycleEvent(event);
	}
}

Back to the top