File: PCProject.m

package info (click to toggle)
projectcenter.app 0.6.2%2Bgit20190606-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 2,968 kB
  • sloc: objc: 20,132; ansic: 1,463; makefile: 38
file content (1845 lines) | stat: -rw-r--r-- 47,596 bytes parent folder | download
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
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
/*
   GNUstep ProjectCenter - http://www.gnustep.org/experience/ProjectCenter.html

   Copyright (C) 2000-2014 Free Software Foundation

   Authors: Philippe C.D. Robert
            Serg Stoyan

   This file is part of GNUstep.

   This application is free software; you can redistribute it and/or
   modify it under the terms of the GNU General Public
   License as published by the Free Software Foundation; either
   version 2 of the License, or (at your option) any later version.

   This application is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Library General Public License for more details.

   You should have received a copy of the GNU General Public
   License along with this library; if not, write to the Free
   Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111 USA.
*/

// TODO: Split into several files with categories
// TODO: Take care of Libraries(gnustep-gui, gnustep-base) 
//       and Non Project Files

#import <ProjectCenter/PCFileManager.h>
#import <ProjectCenter/PCProjectManager.h>
#import <ProjectCenter/PCProject.h>
#import <ProjectCenter/PCDefines.h>

#import <ProjectCenter/PCProjectWindow.h>
#import <ProjectCenter/PCProjectBrowser.h>
#import <ProjectCenter/PCProjectLoadedFiles.h>

#import <ProjectCenter/PCProjectInspector.h>
#import <ProjectCenter/PCProjectBuilder.h>
#import <ProjectCenter/PCProjectEditor.h>
#import <ProjectCenter/PCProjectLauncher.h>

#import <ProjectCenter/PCLogController.h>

#import <Protocols/CodeEditor.h>

#import "Modules/Preferences/Saving/PCSavingPrefs.h"
#import "Modules/Preferences/Misc/PCMiscPrefs.h"

// #import <AppKit/NSFileWrapper.h>
// #import <Foundation/NSData.h>

NSString 
*PCProjectDictDidChangeNotification = @"PCProjectDictDidChangeNotification";
NSString 
*PCProjectDictDidSaveNotification = @"PCProjectDictDidSaveNotification";
NSString 
*PCProjectBreakpointNotification = @"PCProjectBreakpointNotification";

@implementation PCProject

// ============================================================================
// ==== Init and free
// ============================================================================

- (id)init
{
  if ((self = [super init])) 
    {
      projectDict = [[NSMutableDictionary alloc] init];
      projectPath = [[NSString alloc] init];
      projectName = [[NSString alloc] init];
      buildOptions = [[NSMutableDictionary alloc] init];
      loadedSubprojects = [[NSMutableArray alloc] init];

      projectBuilder = nil;
      projectLauncher = nil;

      isSubproject = NO;
      activeSubproject = nil;
    }

  return self;
}

- (PCProject *)openWithWrapperAt:(NSString *)aPath
{
  BOOL isDir = NO;
  BOOL exists = [[NSFileManager defaultManager] fileExistsAtPath: aPath 
						isDirectory: &isDir];
  if(isDir && exists)
    {
      projectFileWrapper = [[NSFileWrapper alloc] initWithPath: aPath];
      if(projectFileWrapper != nil)
	{
	  NSDictionary *wrappers = [projectFileWrapper fileWrappers];
	  NSData *data = [[wrappers objectForKey: @"PC.project"] regularFileContents];
	  NSData *userData = [[wrappers objectForKey: [NSUserName() stringByAppendingPathExtension: @"project"]]
			       regularFileContents];
	  NSMutableDictionary *dict = [[[[NSString alloc] initWithData: data
							  encoding: NSASCIIStringEncoding] 
					 propertyList] mutableCopy];
	  NSDictionary *udict = [[[NSString alloc] initWithData: userData
						   encoding: NSASCIIStringEncoding] 
				  propertyList];
	  
	  if (udict != nil)
	    [dict addEntriesFromDictionary: udict]; 
	  [udict release];
	  [self assignProjectDict:dict atPath: aPath];
	}
    }
  else
    {
      NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithContentsOfFile: aPath];
      
      projectFileWrapper = [[NSFileWrapper alloc] 
			     initDirectoryWithFileWrappers: 
			       [NSMutableDictionary dictionaryWithCapacity: 3]];
      [projectFileWrapper addRegularFileWithContents:
			    [NSData dataWithBytes: [[dict description] cString]
				    length: [[dict description] length]]
			  preferredFilename: @"PC.project"];
      [self assignProjectDict: dict
	    atPath: aPath];
    }
  
  return self;
}

- (void)dealloc
{
#ifdef DEBUG
  NSLog (@"PCProject %@: dealloc", projectName);
#endif
  
  [[NSNotificationCenter defaultCenter] removeObserver:self];

  RELEASE(projectDict);
  RELEASE(projectName);
  RELEASE(projectPath);
  RELEASE(buildOptions);
  RELEASE(loadedSubprojects);

  // Initialized in -setProjectManager: of project and
  // in setSuperProject: of subproject
  RELEASE(projectWindow);
  RELEASE(projectBrowser);
  RELEASE(projectLoadedFiles);
  RELEASE(projectEditor);
  TEST_RELEASE(projectBuilder);
  TEST_RELEASE(projectLauncher);

  if (isSubproject == YES)
    {
      RELEASE(rootProject);
      RELEASE(superProject);
    }

  [super dealloc];
}

- (void)loadPreferences:(NSNotification *)aNotification
{
  id <PCPreferences> prefs = [projectManager prefController];

  rememberWindows = [prefs boolForKey:RememberWindows];
  keepBackup = [prefs boolForKey:KeepBackup];
}

// ============================================================================
// ==== Project handling
// ============================================================================

// --- Dictionary
- (BOOL)assignProjectDict:(NSDictionary *)pDict atPath:(NSString *)pPath
{
  NSString *tempPath = nil;

  NSAssert(pDict,@"No valid project dictionary!");

  PCLogStatus(self, @"assignProjectDict at %@", pPath);

  if (projectDict)
    {
      [projectDict release];
    }
  projectDict = [[NSMutableDictionary alloc] initWithDictionary:pDict];

  // Project path
  if ([[pPath lastPathComponent] isEqualToString:@"PC.project"] ||
      [[[pPath lastPathComponent] pathExtension] isEqualToString:@"pcproj"])
    {
      tempPath = [pPath stringByDeletingLastPathComponent];
      if ([[tempPath pathExtension] isEqualToString:@"pcproj"])
	{
	  tempPath = [tempPath stringByDeletingLastPathComponent];
	}
      [self setProjectPath:tempPath];
    }
  else
    {
      [self setProjectPath:pPath];
    }

  [self setProjectName:[projectDict objectForKey:PCProjectName]];
  [self writeMakefile];
  [self save];

  return YES;
}

- (BOOL)isValidDictionary:(NSDictionary *)aDict
{
  NSString     *_file;
  NSString     *key;
  Class        projClass = [self builderClass];
  NSDictionary *origin;
  NSArray      *keys;
  NSEnumerator *enumerator;

  _file = [[NSBundle bundleForClass:projClass] pathForResource:@"PC"
                                                        ofType:@"project"];

  origin = [NSMutableDictionary dictionaryWithContentsOfFile:_file];
  keys   = [origin allKeys];

  enumerator = [keys objectEnumerator];
  while ((key = [enumerator nextObject]))
    {
      if ([aDict objectForKey:key] == nil)
	{
	  PCLogInfo(self, @"invalid dict entry for key %@", key);
	  return NO;
	}
    }

  return YES;
}

- (void)validateProjectDict
{
  if ([self isValidDictionary:projectDict] == NO)
    {
      [self updateProjectDict];

      NSRunAlertPanel(@"Open Project!", 
		      @"The project file was converted from previous version!\n"
		      @"Please make sure that every project attribute contain"
		      @" valid values!", 
		      @"OK",nil,nil);
    }
}

- (void)setProjectDictObject:(id)object forKey:(NSString *)key notify:(BOOL)yn
{
  id                  currentObject = [projectDict objectForKey:key];
  NSMutableDictionary *notifObject = [NSMutableDictionary dictionary];

  if ([object isKindOfClass:[NSString class]]
      && [currentObject isEqualToString:object])
    {
      return;
    }

  [projectDict setObject:object forKey:key];

  // Send in notification project itself and project dictionary object key 
  // that was changed
  [notifObject setObject:self forKey:@"Project"];
  [notifObject setObject:key forKey:@"Attribute"];

  if (yn == YES)
    {
      [[NSNotificationCenter defaultCenter] 
	postNotificationName:PCProjectDictDidChangeNotification
                      object:notifObject];
    }
}

- (void)updateProjectDict
{
  Class        projClass = [self builderClass];
  NSString     *_file = nil;
  NSString     *key = nil;
  NSDictionary *origin = nil;
  NSArray      *keys = nil;
  NSEnumerator *enumerator = nil;

  _file = [[NSBundle bundleForClass:projClass] pathForResource:@"PC"
                                                        ofType:@"project"];

  origin = [NSMutableDictionary dictionaryWithContentsOfFile:_file];
  keys   = [origin allKeys];

  enumerator = [keys objectEnumerator];
  while ((key = [enumerator nextObject]))
    {
      if ([projectDict objectForKey:key] == nil)
	{
	  // Doesn't call setProjectDictObject:forKey for opimization
	  [projectDict setObject:[origin objectForKey:key] forKey:key];
	}
    }

  [self save];
}

- (NSDictionary *)projectDict
{
  return (NSDictionary *)projectDict;
}

// --- Name and path
- (NSString *)projectName
{
  return projectName;
}

- (void)setProjectName:(NSString *)aName
{
  if (projectName)
    {
      [projectName autorelease];
    }
  projectName = [aName copy];
//  [projectWindow setFileIconTitle:projectName];
}

- (NSString *)projectPath
{
    return projectPath;
}

- (void)setProjectPath:(NSString *)aPath
{
  if (projectPath)
    {
      [projectPath autorelease];
    }
  projectPath = [aPath copy];
}

// --- Saving
- (BOOL)isProjectChanged
{
  return [projectWindow isDocumentEdited];
}

// Saves backup file
- (BOOL)writeMakefile
{
  NSString *mf = [projectPath stringByAppendingPathComponent:@"GNUmakefile"];
  NSString *bu = [projectPath stringByAppendingPathComponent:@"GNUmakefile~"];
  NSFileManager *fm = [NSFileManager defaultManager];

  if ([fm isReadableFileAtPath:mf])
    {
      if ([fm isWritableFileAtPath:bu])
	{
	  [fm removeFileAtPath:bu handler:nil];
	}

      if (![fm copyPath:mf toPath:bu handler:nil])
	{
	  NSRunAlertPanel(@"Attention!",
			  @"Could not keep a backup of the GNUMakefile!",
			  @"OK",nil,nil);
	  return NO;
	}
    }

  return YES;
}

- (BOOL)saveProjectWindowsAndPanels
{
  NSMutableDictionary *windows = [NSMutableDictionary dictionary];
  NSString            *projectFile = nil;
  NSMutableDictionary *projectFileDict = nil;

  projectFile = [NSUserName() stringByAppendingPathExtension:@"project"];
  projectFileDict = [[NSMutableDictionary alloc] initWithCapacity:4];

  // Project Window
  [windows setObject:[projectWindow stringWithSavedFrame]
              forKey:@"ProjectWindow"];
  if ([projectWindow isToolbarVisible] == YES)
    {
      [windows setObject:@"YES"
	          forKey:@"ShowToolbar"];
    }
  else
    {
      [windows setObject:@"NO"
                  forKey:@"ShowToolbar"];
    }

  // ProjectBrowser
  [windows setObject:NSStringFromRect([[projectBrowser view] frame])
              forKey:@"ProjectBrowser"];

  // Write to file and exit if preferences wasn't set to save panels
  if (!rememberWindows)
    {
      [projectFileDict setObject:windows forKey:PCWindows];
      [projectFileDict writeToFile:projectFile atomically:YES];
      [projectFileDict release];
      return YES;
    }

  // Project Build
  if (projectBuilder && [[projectManager buildPanel] isVisible])
    {
      [windows setObject:[[projectManager buildPanel] stringWithSavedFrame]
	          forKey:@"ProjectBuild"];
    }
  else
    {
      [windows removeObjectForKey:@"ProjectBuild"];
    }

  // Project Launch
  if (projectLauncher && [[projectManager launchPanel] isVisible])
    {
      [windows setObject:[[projectManager launchPanel] stringWithSavedFrame]
                  forKey:@"ProjectLaunch"];
    }
  else
    {
      [windows removeObjectForKey:@"ProjectLaunch"];
    }

  // Loaded Files
  if (projectLoadedFiles && [[projectManager loadedFilesPanel] isVisible])
    {
      [windows 
	setObject:[[projectManager loadedFilesPanel] stringWithSavedFrame]
           forKey:@"LoadedFiles"];
    }
  else
    {
      [windows removeObjectForKey:@"LoadedFiles"];
    }

  // Set to project dict for case if project changed
  // Don't notify about projectDict changes
  [projectDict setObject:windows forKey:PCWindows];

  // Now save it directly to username.project file
  [projectFileDict setObject:windows forKey:PCWindows];

  [projectFileDict setObject: [[NSCalendarDate date] description]
	       forKey: PCLastEditing];

  // add the file and write the wrapper.
  [projectFileWrapper addRegularFileWithContents:
			[NSData dataWithBytes: [[projectFileDict description] cString]
				length: [[projectFileDict description] length]]
		      preferredFilename: projectFile];
  [projectFileWrapper writeToFile: wrapperPath 
		      atomically: YES 
		      updateFilenames: YES];
  
  // release
  [projectFileDict release];

  return YES;
}

- (BOOL)save
{
  NSFileManager  *fm = [NSFileManager defaultManager];
  NSUInteger      spCount = [loadedSubprojects count];
  int            i;
  NSString *wrapperFile;
  NSString *file = @"PC.project";
  NSString *backup;
  NSMutableDictionary *dict = [projectDict mutableCopy];
  NSData *dictData = nil;

  // remove key..
  [dict removeObjectForKey: PCWindows];
  [dict removeObjectForKey: PCLastEditing];

  // initialize the wrappers..
  wrapperFile = [projectName stringByAppendingPathExtension: @"pcproj"];
  projectFileWrapper = [[NSFileWrapper alloc] initDirectoryWithFileWrappers: 
						[NSMutableDictionary dictionaryWithCapacity: 3]];  
  wrapperPath = [projectPath stringByAppendingPathComponent: wrapperFile];
  backup = [wrapperPath stringByAppendingPathExtension:@"backup"];

  // load subprojects...
  for (i = 0; i < spCount; i++)
    {
      [[loadedSubprojects objectAtIndex:i] save];
    }

  // Remove backup file if exists
  if ([fm fileExistsAtPath:backup] && ![fm removeFileAtPath:backup handler:nil])
    {
      NSRunAlertPanel(@"Save Project",
		      @"Couldn't remove the old project backup file",
		      @"OK",nil,nil);
      [dict release];
      return NO;
    }

  // Save backup
  if ((keepBackup == YES) && [fm isReadableFileAtPath: wrapperPath]) 
    {
      if ([fm copyPath: wrapperPath 
	      toPath: backup 
	      handler:nil] == NO)
	{
	  NSRunAlertPanel(@"Save Project",
			  @"Couldn't save project backup file",
			  @"OK",nil,nil);
	  return NO;
	}
    }

  // Save project file
  dictData = [NSPropertyListSerialization dataFromPropertyList: dict
					  format: NSPropertyListOpenStepFormat
					  errorDescription: NULL];
  [projectFileWrapper addRegularFileWithContents: dictData
		      preferredFilename: file];
  if ([projectFileWrapper
	writeToFile:wrapperPath
	atomically:YES 
	updateFilenames: YES] == NO)
    {
      NSRunAlertPanel(@"Save Project",
		      @"Couldn't save project file",
		      @"OK",nil,nil,projectName);
      return NO;
    }

  [[NSNotificationCenter defaultCenter] 
    postNotificationName:PCProjectDictDidSaveNotification 
                  object:self];

  // Save GNUmakefile
  if ([self writeMakefile] == NO)
    {
      NSRunAlertPanel(@"Save Project",
		      @"Couldn't write GNUmakefile",
		      @"OK",nil,nil);
      return NO;
    }

  return YES;
}

- (BOOL)close:(id)sender
{
  PCLogInfo(self, @"Closing %@ project", projectName);
  
  // Save visible windows and panels positions to project dictionary
  if (isSubproject == NO)
    {
      [self saveProjectWindowsAndPanels];
      [projectBrowser setPath:@"/"];
      [projectManager setActiveProject:self];
    }
  
  // Project files (GNUmakefile, PC.project etc.)
  if (isSubproject == NO && [self isProjectChanged] == YES)
    {
      int ret;

      ret = NSRunAlertPanel(@"Close Project",
			    @"Project or subprojects are modified",
			    @"Save and Close",@"Don't save",@"Stop");
      switch (ret)
	{
	case NSAlertDefaultReturn:
	  if ([self save] == NO)
	    {
	      return NO;
	    }
	  break;
	  
	case NSAlertAlternateReturn:
	  break;

	case NSAlertOtherReturn:
	  return NO;
	  break;
	}
    }
    
  // Close subprojects
  while ([loadedSubprojects count])
    {
      [(PCProject *)[loadedSubprojects objectAtIndex:0] close:self];
      // We should release subproject here, because it retains us
      // and we never reach -dealloc in other case.
      [loadedSubprojects removeObjectAtIndex:0];
    }

  if (isSubproject == YES)
    {
      [projectManager closeProject:self];
      return YES;
    }

  // Editors
  // "Cancel" button on "Save Edited Files" panel selected
  if ([projectEditor closeAllEditors] == NO)
    {
      return NO;
    }

  // Project window
  if (sender != projectWindow)
    {
      [projectWindow close];
    }

  // Remove self from loaded projects
  [projectManager closeProject:self];

  return YES;
}

// ============================================================================
// ==== Accessory methods
// ============================================================================

- (PCProjectManager *)projectManager
{
  return projectManager;
}

- (void)setProjectManager:(PCProjectManager *)aManager
{
  projectManager = aManager;

  if (isSubproject)
    {
      return;
    }

  if (!projectBrowser)
    {
      projectBrowser = [[PCProjectBrowser alloc] initWithProject:self];
    }

  if (!projectLoadedFiles)
    {
      projectLoadedFiles = [[PCProjectLoadedFiles alloc] initWithProject:self];
    }

  if (!projectEditor)
    {
      projectEditor = [[PCProjectEditor alloc] init];
      [projectEditor setProject:self];
      [projectEditor setProjectManager:aManager];
    }

  if (!projectWindow)
    {
      projectWindow = [[PCProjectWindow alloc] initWithProject:self];
    }

  [[NSNotificationCenter defaultCenter]
    addObserver:self
       selector:@selector(loadPreferences:)
	   name:PCPreferencesDidChangeNotification
	 object:nil];
  [self loadPreferences:nil];
}

- (PCProjectWindow *)projectWindow
{
  return projectWindow;
}

- (PCProjectBrowser *)projectBrowser
{
  return projectBrowser;
}

- (PCProjectLoadedFiles *)projectLoadedFiles
{
  if (!projectLoadedFiles && !isSubproject)
    {
      projectLoadedFiles = [[PCProjectLoadedFiles alloc] initWithProject:self];
    }

  return projectLoadedFiles;
}

- (PCProjectBuilder *)projectBuilder
{
  if (!projectBuilder && !isSubproject)
    {
      projectBuilder = [[PCProjectBuilder alloc] initWithProject:self];
    }

  return projectBuilder;
}

- (PCProjectLauncher *)projectLauncher
{
  if (!projectLauncher && !isSubproject)
    {
      projectLauncher = [[PCProjectLauncher alloc] initWithProject:self];
    }

  return projectLauncher;
}

- (PCProjectEditor *)projectEditor
{
  return projectEditor;
}

// ============================================================================
// ==== Bundle methods
// ============================================================================

//--- Project Inspector's "Project Attributes"
- (NSView *)projectAttributesView
{
  return nil;
}

//--- Properties from Info.table
- (NSDictionary *)projectBundleInfoTable
{
  NSString *_file;
  Class    class = [self builderClass];

  _file = [[NSBundle bundleForClass:class] pathForResource:@"Info"
			     ofType:@"table"];
  return [NSMutableDictionary dictionaryWithContentsOfFile:_file];
}

- (NSString *)projectTypeName
{
  return [[self projectBundleInfoTable] objectForKey:@"Name"];
}

- (Class)builderClass
{
  return [[self projectBundleInfoTable] objectForKey:@"BuilderClassName"];
}

- (NSString *)projectDescription
{
  return [[self projectBundleInfoTable] objectForKey:@"Description"];
}

- (BOOL)isExecutable
{
  if ([[[self projectBundleInfoTable] 
      objectForKey:@"Executable"] isEqualToString:@"YES"])
    {
      return YES;
    }

  return NO;
}


- (NSArray *)buildTargets
{
  NSArray *buildTargets = [projectDict objectForKey:PCBuilderTargets];

  if (!buildTargets)
    {
      buildTargets = 
	[[self projectBundleInfoTable] objectForKey:@"BuildTargets"];
      [self setProjectDictObject:buildTargets
			  forKey:PCBuilderTargets
			  notify:NO];
    }

  return buildTargets;
}

- (NSArray *)sourceFileKeys
{
  return [[self projectBundleInfoTable] objectForKey:@"SourceFileKeys"];
}

- (NSArray *)resourceFileKeys
{
  return [[self projectBundleInfoTable] objectForKey:@"ResourceFileKeys"];
}

- (NSArray *)otherKeys
{
  return [[self projectBundleInfoTable] objectForKey:@"OtherFileKeys"];
}

- (NSArray *)allowableSubprojectTypes
{
  return [[self projectBundleInfoTable] 
    objectForKey:@"AllowableSubprojectTypes"];
}

- (NSArray *)localizableKeys
{
  return [[self projectBundleInfoTable] objectForKey:@"LocalizableCategories"];
}

//--- Public headers (for Library, Framework)
- (BOOL)canHavePublicHeaders
{
  if ([[[self projectBundleInfoTable] 
      objectForKey:@"CanHavePublicHeaders"] isEqualToString:@"YES"])
    {
      return YES;
    }

  return NO;
}

- (NSArray *)publicHeaders
{
  if ([self canHavePublicHeaders] == YES)
    {
      return [projectDict objectForKey:PCPublicHeaders];
    }
    
  return nil;
}

- (void)setHeaderFile:(NSString *)file public:(BOOL)yn
{
  NSMutableArray *publicHeaders = nil;

  if ((yn == YES && [[self publicHeaders] containsObject:file])
      || [self canHavePublicHeaders] == NO)
    {
      return;
    }

  publicHeaders = [[projectDict objectForKey:PCPublicHeaders] copy];

  if (yn)
    {
      [publicHeaders addObject:file];
    }
  else if ([publicHeaders count] > 0 && [publicHeaders containsObject:file])
    {
      [publicHeaders removeObject:file];
    }

  [self setProjectDictObject:publicHeaders 
		      forKey:PCPublicHeaders 
		      notify:YES];

  [publicHeaders release];
}

//--- Localization
- (NSArray *)localizedResources
{
  return [projectDict objectForKey:PCLocalizedResources];
}

- (NSString *)resourceDirForLanguage:(NSString *)language
{
  NSString *dir = nil;

  dir = [projectPath stringByAppendingPathComponent:language];
  dir = [dir stringByAppendingPathExtension:@"lproj"];

  return dir;
}

- (void)setResourceFile:(NSString *)file localizable:(BOOL)yn
{
  PCFileManager  *fileManager = [projectManager fileManager];
  NSArray        *userLanguages = nil;
  NSEnumerator   *enumerator = nil;
  NSString       *currentLanguage = nil;
  NSString       *resPath = nil;
  NSString       *resFilePath = nil;
  NSString       *langPath = nil;
  NSMutableArray *localizedResources = nil;

  if (yn == YES && [[self localizedResources] containsObject:file])
    {
      return;
    }
    
  resPath = [projectPath stringByAppendingPathComponent:@"Resources"];
  resFilePath = [resPath stringByAppendingPathComponent:file];
  localizedResources = [[self localizedResources] mutableCopy];

  userLanguages = [projectDict objectForKey:PCUserLanguages];
  enumerator = [userLanguages objectEnumerator];
  while ((currentLanguage = [enumerator nextObject]))
    {
      langPath = [self resourceDirForLanguage:currentLanguage];
      if (yn == YES)
	{
	  [fileManager copyFile:resFilePath intoDirectory:langPath];
	}
      else
	{
	  if ([currentLanguage isEqualToString:@"English"])
	    {
	      [fileManager copyFile:file 
		      fromDirectory:langPath
		      intoDirectory:resPath];
	    }
	  [fileManager removeFile:file 
		    fromDirectory:langPath
		removeDirsIfEmpty:YES];
	}
    }

  if (yn == YES)
    {
      [fileManager removeFileAtPath:resFilePath removeDirsIfEmpty:YES];
      [localizedResources addObject:file];
      [self setProjectDictObject:localizedResources
			  forKey:PCLocalizedResources
			  notify:YES];
    }
  else if ([localizedResources count] > 0 
	   && [localizedResources containsObject:file])
    {
      [localizedResources removeObject:file];
      [self setProjectDictObject:localizedResources
			  forKey:PCLocalizedResources
			  notify:YES];
    }

  [localizedResources release];
}
//---

// May files will be added to category?
- (BOOL)isEditableCategory:(NSString *)category
{
  NSString *key = [self keyForCategory:category];

  if ([key isEqualToString:PCSupportingFiles])
    {
      return NO;
    }

  return YES;
}

// May file will be edited in PC editor?
- (BOOL)isEditableFile:(NSString *)filePath
{
  NSString *key = [self keyForCategory:[projectBrowser nameOfSelectedCategory]];
  NSString *fileName = [filePath lastPathComponent];
  NSString *extension = [filePath pathExtension];

  if ([key isEqualToString:PCSupportingFiles]) 
    {
      if ([fileName isEqualToString:@"GNUmakefile"] ||
	  [extension isEqualToString:@"plist"])
	{
	  return NO;
	}
    }
    
  return YES;
}

- (NSArray *)fileTypesForCategoryKey:(NSString *)key 
{
  if ([key isEqualToString:PCClasses])
    {
      return [NSArray arrayWithObjects:@"m",@"mm",nil];
    }
  else if ([key isEqualToString:PCHeaders])
    {
      return [NSArray arrayWithObjects:@"h",nil];
    }
  else if ([key isEqualToString:PCOtherSources])
    {
      return [NSArray arrayWithObjects:@"c",@"C",@"m",nil];
    }
  else if ([key isEqualToString:PCInterfaces])
    {
      return [NSArray arrayWithObjects:@"gmodel",@"gorm", @"gsmarkup", @"nib", nil];
    }
  else if ([key isEqualToString:PCImages])
    {
      return [NSImage imageFileTypes];
    }
  else if ([key isEqualToString:PCSubprojects])
    {
      return [NSArray arrayWithObjects:@"subproj",nil];
    }
  else if ([key isEqualToString:PCLibraries])
    {
      return [NSArray arrayWithObjects:@"so",@"a",@"lib",@"dylib",nil];
    }

  return nil;
}

- (NSString *)categoryKeyForFileType:(NSString *)type
{
  NSEnumerator *keysEnum = [rootKeys objectEnumerator];
  NSString     *key = nil;

  while ((key = [keysEnum nextObject]))
    {
      if ([[self fileTypesForCategoryKey:key] containsObject:type])
	{
	  return key;
	}
    }

  return nil;
}

- (NSString *)dirForCategoryKey:(NSString *)key 
{
  if ([[self resourceFileKeys] containsObject:key])
    {
      return [projectPath stringByAppendingPathComponent:@"Resources"];
    }

  return projectPath;
}

- (NSString *)localizedDirForCategoryKey:(NSString *)key 
{
  NSString *language = nil;

  if ([[self resourceFileKeys] containsObject:key])
    {
      language = [projectDict objectForKey:PCLanguage];
      language = [language stringByAppendingPathExtension:@"lproj"];
      return [projectPath stringByAppendingPathComponent:language];
    }

  return projectPath;
}

- (NSString *)complementaryTypeForType:(NSString *)type
{
  if ([type isEqualToString:@"m"] || [type isEqualToString:@"c"])
    {
      return @"h";
    }
  else if ([type isEqualToString:@"h"])
    {
      return @"m";
    }

  return nil;
}

// ============================================================================
// ==== File Handling
// ============================================================================

- (NSString *)pathForFile:(NSString *)file forKey:(NSString *)key
{
  NSString *resPath = nil;

  if ([[self resourceFileKeys] containsObject:key])
    {
      if ([[projectDict objectForKey:PCLocalizedResources] containsObject:file])
	{
	  resPath = [self localizedDirForCategoryKey:key];
	  return [resPath stringByAppendingPathComponent:file];
	}
      else
	{
	  resPath = [self dirForCategoryKey:key];
	  return [resPath stringByAppendingPathComponent:file];
	}
    }
    
  return [projectPath stringByAppendingPathComponent:file];
}

- (NSString *)projectFileFromFile:(NSString *)file forKey:(NSString *)type
{
  NSString        *projectFile = nil;
  NSString        *_path = nil;
  NSMutableArray  *_pathComponents = nil;
  NSString        *_file = nil;
  NSArray         *subprojects = [projectDict objectForKey:PCSubprojects];
  NSRange         pathRange;
  NSString        *spDir = nil;

  _path = [file stringByDeletingLastPathComponent];
  _pathComponents = [[_path pathComponents] mutableCopy];
  _file = [file lastPathComponent];

  // Remove "lib" prefix from library name
  if ([type isEqualToString:PCLibraries])
    {
      _file = [_file stringByDeletingPathExtension];
      _file = [_file substringFromIndex:3];
    }

  pathRange = [_path rangeOfString:projectPath];

  // File is located in project's directory tree
  if (pathRange.length && ![type isEqualToString:PCLibraries])
    {
      unsigned i;

      for (i = 0; i < [subprojects count]; i++)
	{
	  spDir = [[subprojects objectAtIndex:i] 
	    stringByAppendingPathExtension:@"subproj"];
	  if ([_pathComponents containsObject:spDir])
	    {
	      break;
	    }
	  spDir = nil;
	}
    }

  if (spDir != nil)
    {
      while (![[_pathComponents objectAtIndex:0] isEqualToString:spDir])
	{
	  [_pathComponents removeObjectAtIndex:0];
	}
    }
  else
    {
      [_pathComponents removeAllObjects];
    }
  
  // Construct project file name
  if ([_pathComponents count])
    {
      projectFile = [NSString pathWithComponents:_pathComponents];
      projectFile = [projectFile stringByAppendingPathComponent:_file];
    }
  else
    {
      projectFile = [NSString stringWithString:_file];
    }

  RELEASE(_pathComponents);
    
  return projectFile;
}

- (BOOL)doesAcceptFile:(NSString *)file forKey:(NSString *)type
{
  NSString     *pFile = [self projectFileFromFile:file forKey:type];
  NSArray      *sourceKeys = [self sourceFileKeys];
  NSArray      *resourceKeys = [self resourceFileKeys];
  NSEnumerator *keyEnum = nil;
  NSString     *key = nil;
  NSArray      *projectFiles = nil;

  if ([sourceKeys containsObject:type])
    {
      keyEnum = [sourceKeys objectEnumerator];
    }
  else if ([resourceKeys containsObject:type])
    {
      keyEnum = [resourceKeys objectEnumerator];
    }
  else
    {
      return YES;
    }

  while ((key = [keyEnum nextObject]))
    {
      projectFiles = [projectDict objectForKey:key];
      if ([projectFiles containsObject:pFile])
	{
	  return NO;
	}
    }

  return YES;
}

- (BOOL)addAndCopyFiles:(NSArray *)files forKey:(NSString *)key
{
  NSEnumerator   *fileEnum = [files objectEnumerator];
  NSString       *file = nil;
  NSMutableArray *fileList = [[files mutableCopy] autorelease];
  NSString       *complementaryType = nil;
  NSString       *complementaryKey = nil;
  NSString       *complementaryDir = nil;
  NSMutableArray *complementaryFiles = [NSMutableArray array];
  PCFileManager  *fileManager = [projectManager fileManager];
  NSString       *directory = [self dirForCategoryKey:key];

  complementaryType = [self 
    complementaryTypeForType:[[files objectAtIndex:0] pathExtension]];
  if (complementaryType)
    {
      complementaryKey = [self categoryKeyForFileType:complementaryType];
      complementaryDir = [self dirForCategoryKey:complementaryKey];
    }
    
//  PCLogInfo(self, @"{%@} {addAndCopyFiles} %@", projectName, fileList);

  // Validate files
  while ((file = [fileEnum nextObject]))
    {
      if (![self doesAcceptFile:file forKey:key])
	{
	  [fileList removeObject:file];
	}
      else if (complementaryType != nil)
	{
	  NSString *compFile = nil;

	  compFile = [[file stringByDeletingPathExtension] 
	    stringByAppendingPathExtension:complementaryType];
	  if ([[NSFileManager defaultManager] fileExistsAtPath:compFile]
	      && [self doesAcceptFile:compFile forKey:complementaryKey])
	    {
	      [complementaryFiles addObject:compFile];
	    }
	}
    }

//  PCLogInfo(self, @"{addAndCopyFiles} %@", fileList);

  // Copy files
  if (![key isEqualToString:PCLibraries]) // Don't copy libraries
    {
      if (![fileManager copyFiles:fileList intoDirectory:directory])
	{
	  NSRunAlertPanel(@"Add File(s)",
			  @"Error adding files %@ to project %@!",
			  @"OK", nil, nil, fileList, projectName);
	  return NO;
	}

//      PCLogInfo(self, @"Complementary files: %@", complementaryFiles);
      // Complementaries
      if (![fileManager copyFiles:complementaryFiles 
	            intoDirectory:complementaryDir])
	{
	  NSRunAlertPanel(@"Add File(s)",
			  @"Error adding files %@ to project %@!",
			  @"OK", nil, nil, complementaryFiles, projectName);
	  return NO;
	}
    }

  if ([complementaryFiles count] > 0)
    {
      [self addFiles:complementaryFiles forKey:complementaryKey notify:NO];
    }
  // Add files to project
  [self addFiles:fileList forKey:key notify:YES];

  return YES;
}

- (void)addFiles:(NSArray *)files forKey:(NSString *)type notify:(BOOL)yn
{
  NSEnumerator   *enumerator = nil;
  NSString       *file = nil;
  NSString       *pFile = nil;
  NSArray        *types = [projectDict objectForKey:type];
  NSMutableArray *projectFiles = [NSMutableArray arrayWithArray:types];

  if ([type isEqualToString:PCLibraries])
    {
      NSMutableArray *searchLibs = [NSMutableArray arrayWithCapacity:1];
      NSString       *path = nil;

      path = [[files objectAtIndex:0] stringByDeletingLastPathComponent];
      [searchLibs setArray:[projectDict objectForKey:PCSearchLibs]];
      [searchLibs addObject:path];
      [self setProjectDictObject:searchLibs forKey:PCSearchLibs notify:yn];
    }

  enumerator = [files objectEnumerator];
  while ((file = [enumerator nextObject]))
    {
      pFile = [self projectFileFromFile:file forKey:type];
      [projectFiles addObject:pFile];
    }

  [self setProjectDictObject:projectFiles forKey:type notify:yn];
}

- (BOOL)removeFiles:(NSArray *)files forKey:(NSString *)key notify:(BOOL)yn
{
  NSEnumerator   *enumerator = nil;
  NSString       *filePath = nil;
  NSString       *file = nil;
  NSMutableArray *projectFiles = [[NSMutableArray alloc] initWithCapacity:1];
  NSArray        *localizedFiles = nil;

  // Check if file localizable. If yes, make it not localizable so file moved
  // to Resources dir.
  localizedFiles = [[self localizedResources] copy];
  enumerator = [files objectEnumerator];
  while ((file = [enumerator nextObject]))
    {
      if ([localizedFiles containsObject:file])
	{
	  [self setResourceFile:file localizable:NO];
	}
    }
  [localizedFiles release];

  // Remove files from project
//  projectFiles = [NSMutableArray arrayWithArray:[projectDict objectForKey:key]];
  [projectFiles setArray:[projectDict objectForKey:key]];
  NSLog(@"--- projectFiles: %@ forKey: %@", projectFiles, key);
  enumerator = [files objectEnumerator];
  while ((file = [enumerator nextObject]))
    {
      if ([key isEqualToString:PCSubprojects])
	{
	  NSLog(@"Removing subproject %@", file);
	  [self removeSubprojectWithName:file];
	}
      NSLog(@"Project %@ remove file %@", projectName, file);
      [projectFiles removeObject:file];

      // Close editor
      filePath = [projectPath stringByAppendingPathComponent:file];
      [projectEditor closeEditorForFile:filePath];
    }

  NSLog(@"projectFiles: %@", projectFiles);

  [self setProjectDictObject:projectFiles forKey:key notify:yn];

  [projectFiles release];

  return YES;
}

- (BOOL)renameFile:(NSString *)fromFile toFile:(NSString *)toFile
{
  NSFileManager       *fm = [NSFileManager defaultManager];
  NSString            *selectedCategory = nil;
  NSString            *selectedCategoryKey = nil;
  NSString            *fromPath = nil;
  NSString            *toPath = nil;
  NSMutableDictionary *_pDict = nil;
  NSString            *_file = nil;
  NSMutableArray      *_array = nil;
  BOOL                saveToFile = NO;
  int                 index = 0;
  id<CodeEditor>      _editor;
  NSString            *_editorPath = nil;
  NSMutableString     *_editorCategory = nil;
  
  selectedCategory = [projectBrowser nameOfSelectedCategory];
  selectedCategoryKey = [self keyForCategory:selectedCategory];

  fromPath = [[self dirForCategoryKey:selectedCategoryKey]
    stringByAppendingPathComponent:fromFile];
  toPath = [[self dirForCategoryKey:selectedCategoryKey]
    stringByAppendingPathComponent:toFile];

  if ([fm fileExistsAtPath:toPath])
    {
      switch (NSRunAlertPanel(@"Rename file",
       			      @"File \"%@\" already exist",
			      @"Overwrite file",@"Stop",nil, toFile))
	{
	case NSAlertDefaultReturn: // Overwrite
	  if ([fm removeFileAtPath:toPath handler:nil] == NO)
	    {
	      return NO;
	    }
	  break;
	case NSAlertAlternateReturn: // Stop rename
	  return NO;
	  break;

	}
    }

/*  PCLogInfo(self, @"{%@} move %@ to %@ category: %@", 
	    projectName, fromPath, toPath, selectedCategory);*/

  if ([[self localizedResources] containsObject:fromFile])
    {// Rename file in language dirs
      NSArray        *userLanguages;
      NSEnumerator   *enumerator;
      NSString       *lang;
      NSString       *langPath;
      NSMutableArray *localizedResources;

      localizedResources = 
	[NSMutableArray arrayWithArray:[self localizedResources]];
      userLanguages = [projectDict objectForKey:PCUserLanguages];
      enumerator = [userLanguages objectEnumerator];
      while ((lang = [enumerator nextObject]))
	{
	  langPath = [self resourceDirForLanguage:lang];
	  fromPath = [langPath stringByAppendingPathComponent:fromFile];
	  toPath = [langPath stringByAppendingPathComponent:toFile];
	  if ([fm movePath:fromPath toPath:toPath handler:nil] == NO)
	    {
	      return NO;
	    }
	}
      index = [localizedResources indexOfObject:fromFile];
      [localizedResources replaceObjectAtIndex:index withObject:toFile];
      [projectDict setObject:localizedResources
		      forKey:PCLocalizedResources];
    }
  else if ([fm movePath:fromPath toPath:toPath handler:nil] == NO)
    {
      return NO;
    }

  // TODO: Rewrite this when file operations history will be implemented
  if ([self isProjectChanged])
    {
      // Project already has changes
      saveToFile = YES;
    }

  // Make changes to projectDict
  _array = [projectDict objectForKey:selectedCategoryKey];
  index = [_array indexOfObject:fromFile];
  [_array replaceObjectAtIndex:index withObject:toFile];

  // Put only this change to project file, leaving 
  // other changes in memory(projectDict)
  if (saveToFile)
    {
      _file = [projectPath stringByAppendingPathComponent:@"PC.project"];
      _pDict = [NSMutableDictionary dictionaryWithContentsOfFile:_file];
      _array = [_pDict objectForKey:selectedCategoryKey];
      [_array removeObject:fromFile];
      [_array addObject:toFile];
      [_pDict setObject:_array forKey:selectedCategoryKey];
      [_pDict writeToFile:_file atomically:YES];
    }
  else
    {
      [self save];
    }

  // Handle editor(if any) information
  _editor = [projectEditor activeEditor];
  if (_editor)
    {
      NSRange range;

      _editorPath = [_editor path];
      _editorPath = [_editorPath stringByDeletingLastPathComponent];
      _editorPath = [_editorPath stringByAppendingPathComponent:toFile];
      [_editor setPath:_editorPath];

      _editorCategory = [[_editor categoryPath] mutableCopy];
      range = [_editorCategory rangeOfString:fromFile];
      [_editorCategory replaceCharactersInRange:range withString:toFile];
      
      [_editor setCategoryPath:_editorCategory];
      [projectBrowser setPath:_editorCategory];
      RELEASE(_editorCategory);
    }
  else
    {
      // Set browser path to new file name
      [projectBrowser reloadLastColumnAndSelectFile:toFile];

    }

  return YES;
}

// ============================================================================
// ==== Subprojects
// ============================================================================

- (NSArray *)loadedSubprojects
{
  return loadedSubprojects;
}

- (PCProject *)activeSubproject
{
  return activeSubproject;
}

- (BOOL)isSubproject
{
  return isSubproject;
}

- (void)setIsSubproject:(BOOL)yn
{
  isSubproject = yn;
}

- (PCProject *)superProject
{
  return superProject;
}

- (void)setSuperProject:(PCProject *)project
{
  if (superProject != nil)
    {
      return;
    }

  ASSIGN(superProject, project);

  // Assigning releases left part
  ASSIGN(projectBrowser,[project projectBrowser]);
  ASSIGN(projectLoadedFiles,[project projectLoadedFiles]);
  ASSIGN(projectEditor,[project projectEditor]);
  ASSIGN(projectWindow,[project projectWindow]);
}

- (PCProject *)subprojectWithName:(NSString *)name
{
  int       count = [loadedSubprojects count];
  int       i;
  PCProject *sp = nil;
  NSString  *spName = nil;
  NSString  *spPath = nil;

  // Subproject in project but not loaded
  if ([[projectDict objectForKey:PCSubprojects] containsObject:name])
    {
/*      PCLogInfo(self, @"{%@}Searching for loaded subproject: %@",
		projectName, name);*/
      // Search for subproject with name among loaded subprojects 
      for (i = 0; i < count; i++)
	{
	  sp = [loadedSubprojects objectAtIndex:i];
	  spName = [sp projectName];
	  if ([spName isEqualToString:name])
	    {
	      break;
	    }
	  sp = nil;
	}

      // Subproject not found in array, load it
      if (sp == nil)
	{
	  spPath = [projectPath stringByAppendingPathComponent:name];
	  spPath = [spPath stringByAppendingPathExtension:@"subproj"];

	  sp = [projectManager openProjectAt:spPath makeActive:NO];
	  if (sp)
	    {
	      [sp setIsSubproject:YES];
	      [sp setSuperProject:self];
	      [sp setProjectManager:projectManager];
	      [loadedSubprojects addObject:sp];
	    }
	}
    }
  
  return sp;
}

- (void)addSubproject:(PCProject *)aSubproject
{
  NSMutableArray *_subprojects;

  if (!aSubproject)
    {
      return;
    }

  _subprojects = [NSMutableArray 
    arrayWithArray:[projectDict objectForKey:PCSubprojects]];

  [_subprojects addObject:[aSubproject projectName]];
  [loadedSubprojects addObject:aSubproject];
  [self setProjectDictObject:_subprojects forKey:PCSubprojects notify:YES];
}

- (void)addSubprojectWithName:(NSString *)name
{
  NSMutableArray *_subprojects = nil;

  if (!name)
    {
      return;
    }

  _subprojects = [NSMutableArray 
    arrayWithArray:[projectDict objectForKey:PCSubprojects]];
  [_subprojects addObject:name];
  [self setProjectDictObject:_subprojects forKey:PCSubprojects notify:YES];
}

- (BOOL)removeSubprojectWithName:(NSString *)subprojectName
{
  NSString *extension = [subprojectName pathExtension];
  NSString *sName = subprojectName;
  
  if (extension && [extension isEqualToString:@"subproj"])
    {
      sName = [subprojectName stringByDeletingPathExtension];
    }

  return [self removeSubproject:[self subprojectWithName:sName]];
}

- (BOOL)removeSubproject:(PCProject *)aSubproject
{
  if ([loadedSubprojects containsObject:aSubproject])
    {
      [aSubproject close:self];
      [loadedSubprojects removeObject:aSubproject];
    }

  return YES;
}

@end

@implementation PCProject (ProjectBrowser)

// e.g. CLASS_FILES
- (NSArray *)rootKeys
{
  if (activeSubproject)
    {
      return [activeSubproject rootKeys];
    }

  return rootKeys;
}

// e.g. Classes
- (NSArray *)rootCategories
{
  if (activeSubproject)
    {
      return [activeSubproject rootCategories];
    }

  return rootCategories;
}

- (NSDictionary *)rootEntries
{
  if (activeSubproject)
    {
      return [activeSubproject rootEntries];
    }

  return rootEntries;
}

// Category - the name we see in project browser, e.g. "Classes"
// Key - the uppercase names located in PC.roject, e.g. "CLASS_FILES"
- (NSString *)keyForCategory:(NSString *)category
{
  int index = -1;

  if (activeSubproject)
    {
      return [activeSubproject keyForCategory:category];
    }

  if (![rootCategories containsObject:category])
    {
      return nil;
    }
    
  index = [rootCategories indexOfObject:category];
  return [rootKeys objectAtIndex:index];
}

- (NSString *)categoryForKey:(NSString *)key
{
  if (activeSubproject)
    {
      return [activeSubproject categoryForKey:key];
    }

  return [rootEntries objectForKey:key];
}

- (NSString *)rootCategoryForCategoryPath:(NSString *)categoryPath
{
  NSArray *pathComponents = nil;

  if ([categoryPath isEqualToString:@"/"] || [categoryPath isEqualToString:@""])
    {
      return nil;
    }
    
  pathComponents = [categoryPath componentsSeparatedByString:@"/"];

  return [pathComponents objectAtIndex:1];
}

- (NSString *)keyForRootCategoryInCategoryPath:(NSString *)categoryPath
{
  NSString *category = nil;
  NSString *key = nil;
  int      index = -1;

  if (categoryPath == nil 
      || [categoryPath isEqualToString:@""]
      || [categoryPath isEqualToString:@"/"])
    {
      return nil;
    }

  category = [self rootCategoryForCategoryPath:categoryPath];

  // Since keyForCategory subproject sensitive implement 
  // key searching here
  // TODO: revise all code in PCProject against subproject
  // sensitiveness
  // key = [self keyForCategory:category];
  if (![rootCategories containsObject:category])
    {
      return nil;
    }
    
  index = [rootCategories indexOfObject:category];
  key = [rootKeys objectAtIndex:index];

/*  PCLogInfo(self, @"{%@}(keyForRootCategoryInCategoryPath): %@ key:%@", 
	    projectName, categoryPath, key);*/

  return key;
}

// --- Requested by Project Browser

- (NSArray *)contentAtCategoryPath:(NSString *)categoryPath
{
  NSString *key = [self keyForRootCategoryInCategoryPath:categoryPath];
  NSArray  *pathArray = nil;
  NSString *listEntry = nil;

  pathArray = [categoryPath componentsSeparatedByString:@"/"];
  listEntry = [pathArray lastObject];

/*  PCLogInfo(self, @"{%@}{contentAtCategoryPath:} %@",
	    projectName, categoryPath);*/

  if ([categoryPath isEqualToString:@""] || [categoryPath isEqualToString:@"/"])
    {
      if ([projectManager activeProject] != self)
	{
	  [projectManager setActiveProject:self];
	}
      return rootCategories;
    }
  else if ([pathArray count] == 2)
    { // Click on /Category. [pathArray count] == 2 even in subprojects
      // because category path stripped from leading path components before 
      // going into subproject's code
//      NSLog(@"Click on Category");
      if ([projectManager activeProject] != self)
	{
	  [projectManager setActiveProject:self];
	}
      activeSubproject = nil;
      return [projectDict objectForKey:key];
    }
  else if ([key isEqualToString:PCSubprojects] && [pathArray count] > 2)
    { // Click on "/Subprojects/Name+"
      PCProject      *_subproject = nil;
      NSString       *spCategoryPath = nil;
      NSMutableArray *mCategoryPath = [NSMutableArray arrayWithArray:pathArray];

      _subproject = [self subprojectWithName:[pathArray objectAtIndex:2]];
      activeSubproject = _subproject;

      [mCategoryPath removeObjectAtIndex:1];
      [mCategoryPath removeObjectAtIndex:1];

      spCategoryPath = [mCategoryPath componentsJoinedByString:@"/"];

      return [_subproject contentAtCategoryPath:spCategoryPath];
    }
  else
    { // The file is selected, ask editor for browser items
      return [[projectEditor activeEditor] browserItemsForItem:listEntry];
    }
}

- (BOOL)hasChildrenAtCategoryPath:(NSString *)categoryPath
{
  NSString  *listEntry = nil;
  PCProject *activeProject = [projectManager activeProject];
  NSString  *category = [projectBrowser nameOfSelectedCategory];
  NSString  *categoryKey = [self keyForCategory:category];

  if (self != activeProject)
    {
      return [activeProject hasChildrenAtCategoryPath:categoryPath];
    }

  listEntry = [[categoryPath componentsSeparatedByString:@"/"] lastObject];
 
  // Categories
  if ([rootCategories containsObject:listEntry])
    {
      return YES;
    }
   
  // Subprojects
  if ([[projectDict objectForKey:PCSubprojects] containsObject:listEntry]
      && [category isEqualToString:@"Subprojects"])
    {
      return YES;
    }

  // Files. listEntry is file in category or contents of file
  if ([[projectDict objectForKey:categoryKey] containsObject:listEntry] ||
      [projectBrowser nameOfSelectedFile])
    {
      // TODO: Libraries
      if ([category isEqualToString:@"Libraries"])
	{
	  return NO;
	}

      if ([projectEditor editorProvidesBrowserItemsForItem:listEntry] == YES)
	{
	  return YES;
	}
    }
  
  return NO;
}

@end