summaryrefslogtreecommitdiffstats
path: root/src/libs/xpcom18a4/xpcom/obsolete/nsFileSpecMac.cpp
blob: fd208fb792ca9a65036e9727a4137052cb056a26 (plain)
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
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is mozilla.org code.
 *
 * The Initial Developer of the Original Code is
 * Netscape Communications Corporation.
 * Portions created by the Initial Developer are Copyright (C) 1998
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either of the GNU General Public License Version 2 or later (the "GPL"),
 * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */
 
//	  This file is included by nsFile.cp, and includes the Macintosh-specific
//	  implementations.


#include <string.h>

#include "prtypes.h"
#include "nscore.h"

#include "FullPath.h"
#include "FileCopy.h"
#include "MoreFilesExtras.h"

#include <Aliases.h>
#include <Folders.h>
#include <Math64.h>
#include <TextUtils.h>
#include <Processes.h>
#include <limits.h>		// ULONG_MAX

#include "nsFileSpec.h"
#include "nsEscape.h"
#include "nsXPIDLString.h"


const unsigned char* kAliasHavenFolderName = "\pnsAliasHaven";

//========================================================================================
namespace MacFileHelpers
//========================================================================================
{
	inline void						PLstrcpy(Str255 dst, ConstStr255Param src)
									{
										memcpy(dst, src, 1 + src[0]);
									}

	void							PLstrcpy(Str255 dst, const char* src, int inMaxLen=255);
	void							PLstrncpy(Str255 dst, const char* src, int inMaxLen);

	void							SwapSlashColon(char * s);
	OSErr							FSSpecFromUnixPath(
										const char * unixPath,
										FSSpec& ioSpec,
										Boolean hexDecode,
										Boolean resolveAlias,
										Boolean allowPartial = false,
										Boolean createDirs = false);
	char*							MacPathFromUnixPath(
										const char* unixPath,
										Boolean hexDecode);
	char*							EncodeMacPath(
										char* inPath, // NOT const - gets clobbered
										Boolean prependSlash,
										Boolean doEscape );
	OSErr							FSSpecFromPathname(
										const char* inPathNamePtr,
										FSSpec& ioSpec,
										Boolean inCreateDirs);
	char*							PathNameFromFSSpec(
										const FSSpec& inSpec );
	OSErr							CreateFolderInFolder(
										short				refNum,		// Parent directory/volume
										long				dirID,
										ConstStr255Param	folderName,	   // Name of the new folder
										short&				outRefNum,	  // Volume of the created folder
										long&				outDirID);	  // 

	// Some routines to support an "alias haven" directory.	 Aliases in this directory
	// are never resolved.	There is a ResolveAlias here that respects that.  This is
	// to support attaching of aliases in mail.
	void							EnsureAliasHaven();
	void							SetNoResolve(Boolean inResolve);
	PRBool							IsAliasSafe(const FSSpec& inSpec);
	OSErr							MakeAliasSafe(FSSpec& inOutSpec);
	OSErr							ResolveAliasFile(FSSpec& inOutSpec, Boolean& wasAliased);

	Boolean							sNoResolve = false;
	long							sAliasHavenDirID = 0;
	short							sAliasHavenVRefNum = 0;
} // namespace MacFileHelpers

//----------------------------------------------------------------------------------------
void MacFileHelpers::PLstrcpy(Str255 dst, const char* src, int inMax)
//----------------------------------------------------------------------------------------
{
	int srcLength = strlen(src);
	NS_ASSERTION(srcLength <= inMax, "Oops, string is too long!");
	if (srcLength > inMax)
		srcLength = inMax;
	dst[0] = srcLength;
	memcpy(&dst[1], src, srcLength);
}

//----------------------------------------------------------------------------------------
void MacFileHelpers::PLstrncpy(Str255 dst, const char* src, int inMax)
//----------------------------------------------------------------------------------------
{
	int srcLength = strlen(src);
	if (srcLength > inMax)
		srcLength = inMax;
	dst[0] = srcLength;
	memcpy(&dst[1], src, srcLength);
}

//-----------------------------------
void MacFileHelpers::SwapSlashColon(char * s)
//-----------------------------------

{
	while (*s)
	{
		if (*s == '/')
			*s++ = ':';
		else if (*s == ':')
			*s++ = '/';
		else
			*s++;
	}
} // MacFileHelpers::SwapSlashColon

//-----------------------------------
char* MacFileHelpers::EncodeMacPath(
	char* inPath, // NOT const, gets clobbered
	Boolean prependSlash,
	Boolean doEscape )
//	  Transforms Macintosh style path into Unix one
//	  Method: Swap ':' and '/', hex escape the result
//-----------------------------------
{
	if (inPath == nsnull)
		return nsnull;
	int pathSize = strlen(inPath);
	
	// XP code sometimes chokes if there's a final slash in the unix path.
	// Since correct mac paths to folders and volumes will end in ':', strip this
	// first.
	char* c = inPath + pathSize - 1;
	if (*c == ':')
	{
		*c = 0;
		pathSize--;
	}

	char * newPath = nsnull;
	char * finalPath = nsnull;
	
	if (prependSlash)
	{
		newPath = new char[pathSize + 2];
		newPath[0] = ':';	 // It will be converted to '/'
		memcpy(&newPath[1], inPath, pathSize + 1);
	}
	else
	{
		newPath = new char[pathSize + 1];
		strcpy(newPath, inPath);
	}
	if (newPath)
	{
		SwapSlashColon( newPath );
		if (doEscape)
		{
			finalPath = nsEscape(newPath, url_Path);
			delete [] newPath;
		}
		else
			finalPath = newPath;
	}
	delete [] inPath;
	return finalPath;
} // MacFileHelpers::EncodeMacPath

//----------------------------------------------------------------------------------------
inline void MacFileHelpers::SetNoResolve(Boolean inResolve)
//----------------------------------------------------------------------------------------
{
	sNoResolve = inResolve;
} // MacFileHelpers::SetNoResolve

//----------------------------------------------------------------------------------------
OSErr MacFileHelpers::MakeAliasSafe(FSSpec& inOutSpec)
// Pass in the spec of an alias.  This copies the file to the safe haven folder, and
// returns the spec of the copy to the caller
//----------------------------------------------------------------------------------------
{
	EnsureAliasHaven();
	nsFileSpec dstDirSpec(sAliasHavenVRefNum, sAliasHavenDirID, "\p");

	// Make sure its name is unique
	nsFileSpec havenSpec(sAliasHavenVRefNum, sAliasHavenDirID, "\pG'day");
	if (havenSpec.Valid())
		havenSpec.MakeUnique(inOutSpec.name);
	// Copy the file into the haven directory
	if (havenSpec.Valid())
	{
		OSErr err = ::FSpFileCopy(
						&inOutSpec,
						dstDirSpec,
						havenSpec.GetLeafPName(),
						nil, 0, true);
		// Return the spec of the copy to the caller.
		if (err != noErr)
			return err;
		inOutSpec = havenSpec;
	}
	return noErr;
} // MacFileHelpers::MakeAliasSafe

//----------------------------------------------------------------------------------------
char* MacFileHelpers::MacPathFromUnixPath(const char* unixPath, Boolean hexDecode)
//----------------------------------------------------------------------------------------
{
	// Relying on the fact that the unix path is always longer than the mac path:
	size_t len = strlen(unixPath);
	char* result = new char[len + 2]; // ... but allow for the initial colon in a partial name
	// REMEMBER: at the end we call SwapSlashColon, so bear that in mind when you see
	// this code using '/' as a separator in what is supposed to be a Macintosh path!
	if (result)
	{
		char* dst = result;
		const char* src = unixPath;
		if (*src == '/')			 // * full path
			src++;
		else if (strchr(src, '/') && *src != '.')
		{
			// * partial path, and not just a leaf name. The '.' test is there because
			// the loop below will add sufficient colons in that case.
			*dst++ = '/';
		}
		// Copy src to dst, but watch out for .. and .
		char c = '/';
		do
		{
			char cprev = c; // remember the previous char (initially /)
			c = *src++;
			if (c == '.' && cprev == '/')
			{
				char* dstSaved = dst;
				// Special cases: "." and "..". Convert to ':' and '::'
				*dst++ = '/';  // . becomes :
				c = *src++;
				if (c == '.')
				{
					*dst++ = '/'; // .. becomes ::
					c = *src++;
				}
				if (c == '/')
				{
					// ../	  becomes	:: so just skip the slash
					// ./	  becomes	:  "  "	   "	"	"
					src++;
				}
				else if (c)
				{
					// Oh. A file called ".foo" or "..foo"
					// Back up and just do the normal thing.
					src -= (dst - dstSaved);
					dst = dstSaved;
					// Since c is not '/', we won't do this stuff on the
					// next iteration.
				}
				continue;
			}
			else if (c == '/' && cprev == '/')
			{
				// Hmm. A 'run on' path with two slashes right next to each other.
				// This is an illegal path, but, hey, we'll be tough and try to
				// deal with it (especially since '::' has loaded semantics in
				// a Mac path)
				continue;
			}
			*dst++ = c;
		} while (c);
		if (hexDecode)
			nsUnescape(result);	   // Hex Decode
		MacFileHelpers::SwapSlashColon(result);
	}
	return result;
} // MacFileHelpers::MacPathFromUnixPath

//----------------------------------------------------------------------------------------
OSErr MacFileHelpers::FSSpecFromPathname(
	const char* inPathNamePtr,
	FSSpec& ioSpec, // used as in-parameter for a relative path.
	Boolean inCreateDirs)
// FSSpecFromPathname reverses PathNameFromFSSpec.
// It returns a FSSpec given a c string which is a mac pathname.
//----------------------------------------------------------------------------------------
{
	OSErr err;
	// Simplify this routine to use FSMakeFSSpec if length < 255. Otherwise use the MoreFiles
	// routine FSpLocationFromFullPath, which allocates memory, to handle longer pathnames. 
	
	short inVRefNum = ioSpec.vRefNum;
	long inParID = ioSpec.parID;
	
	size_t inLength = strlen(inPathNamePtr);
	bool isRelative = (strchr(inPathNamePtr, ':') == 0 || *inPathNamePtr == ':');
#ifdef NS_DEBUG
	// Attempt to catch people sending unix paths in to routines that expect native ones.
	NS_ASSERTION(strchr(inPathNamePtr, '/') == 0,
			"Possible unix path where native path is required");
#endif
	if (inLength < 255)
	{
		Str255 pascalpath;
		MacFileHelpers::PLstrcpy(pascalpath, inPathNamePtr);
		if (isRelative)
			err = ::FSMakeFSSpec(inVRefNum, inParID, pascalpath, &ioSpec);
		else
			err = ::FSMakeFSSpec(0, 0, pascalpath, &ioSpec);
	}
	else if (!isRelative)
		err = FSpLocationFromFullPath(inLength, inPathNamePtr, &ioSpec);
	else
		err = bdNamErr;

	if ((err == dirNFErr || err == bdNamErr) && inCreateDirs)
	{
		const char* path = inPathNamePtr;
		if (isRelative)
		{
			ioSpec.vRefNum = inVRefNum;
			ioSpec.parID = inParID;
		}
		else
		{
			ioSpec.vRefNum = 0;
			ioSpec.parID = 0;
		}
		do {
			// Locate the colon that terminates the node.
			// But if we've a partial path (starting with a colon), find the second one.
			const char* nextColon = strchr(path + (*path == ':'), ':');
			// Well, if there are no more colons, point to the end of the string.
			if (!nextColon)
				nextColon = path + strlen(path);

			// Make a pascal string out of this node.  Include initial
			// and final colon, if any!
			Str255 ppath;
			MacFileHelpers::PLstrncpy(ppath, path, nextColon - path + 1);
			
			// Use this string as a relative path using the directory created
			// on the previous round (or directory 0,0 on the first round).
			err = ::FSMakeFSSpec(ioSpec.vRefNum, ioSpec.parID, ppath, &ioSpec);

			// If this was the leaf node, then we are done.
			if (!*nextColon)
				break;

			// Since there's more to go, we have to get the directory ID, which becomes
			// the parID for the next round.
			if (err == noErr)
			{
				// The directory (or perhaps a file) exists. Find its dirID.
				long dirID;
				Boolean isDirectory;
				err = ::FSpGetDirectoryID(&ioSpec, &dirID, &isDirectory);
				if (!isDirectory)
					return dupFNErr; // oops! a file exists with that name.
				if (err)
					return err;
				ioSpec.parID = dirID;
			}
			else if (err == fnfErr)
			{
				// If we got "file not found", then
				// we need to create a directory.
				err = ::FSpDirCreate(&ioSpec, smCurrentScript, &ioSpec.parID);
				// For some reason, this usually returns fnfErr, even though it works.
				if (err == fnfErr)
					err = noErr;
			}
			if (err != noErr)
				return err;
			path = nextColon; // next round
		} while (1);
	}
	return err;
} // MacFileHelpers::FSSpecFromPathname

//----------------------------------------------------------------------------------------
OSErr MacFileHelpers::CreateFolderInFolder(
	short				 refNum,	 // Parent directory/volume
	long				dirID,
	ConstStr255Param	folderName,	   // Name of the new folder
	short&				  outRefNum,	// Volume of the created folder
	long&				 outDirID)	  // 
// Creates a folder named 'folderName' inside a folder.
// The errors returned are same as PBDirCreate
//----------------------------------------------------------------------------------------
{
	HFileParam hpb;
	hpb.ioVRefNum = refNum;
	hpb.ioDirID = dirID;
	hpb.ioNamePtr = (StringPtr)&folderName;

	OSErr err = PBDirCreateSync((HParmBlkPtr)&hpb);
	if (err == noErr)
	{
		outRefNum = hpb.ioVRefNum;
		outDirID = hpb.ioDirID;
	}
	else
	{
		outRefNum = 0;
		outDirID = 0;
	}
	return err;
} // MacFileHelpers::CreateFolderInFolder

//----------------------------------------------------------------------------------------
void MacFileHelpers::EnsureAliasHaven()
//----------------------------------------------------------------------------------------
{
	// Alias Haven is a directory in which we never resolve aliases.
	if (sAliasHavenVRefNum != 0)
		return;

	
	FSSpec temp;
	if (FindFolder(0, kTemporaryFolderType, true, & temp.vRefNum, &temp.parID) == noErr)
	{
		CreateFolderInFolder(
			temp.vRefNum,				  // Parent directory/volume
			temp.parID,
			kAliasHavenFolderName,		  // Name of the new folder
			sAliasHavenVRefNum,		   // Volume of the created folder
			sAliasHavenDirID);		  
	}
} // MacFileHelpers::EnsureAliasHaven

//----------------------------------------------------------------------------------------
PRBool MacFileHelpers::IsAliasSafe(const FSSpec& inSpec)
// Returns true if the alias is in the alias haven directory, or if alias resolution
// has been turned off.
//----------------------------------------------------------------------------------------
{
	return sNoResolve
		|| (inSpec.parID == sAliasHavenDirID && inSpec.vRefNum == sAliasHavenVRefNum);
} // MacFileHelpers::IsAliasSafe

//----------------------------------------------------------------------------------------
OSErr MacFileHelpers::ResolveAliasFile(FSSpec& inOutSpec, Boolean& wasAliased)
//----------------------------------------------------------------------------------------
{
	wasAliased = false;
	if (IsAliasSafe(inOutSpec))
		return noErr;
	Boolean dummy;	  
	return ::ResolveAliasFile(&inOutSpec, TRUE, &dummy, &wasAliased);
} // MacFileHelpers::ResolveAliasFile

//-----------------------------------
OSErr MacFileHelpers::FSSpecFromUnixPath(
	const char * unixPath,
	FSSpec& ioSpec,
	Boolean hexDecode,
	Boolean resolveAlias,
	Boolean allowPartial,
	Boolean createDirs)
// File spec from URL. Reverses GetURLFromFileSpec 
// Its input is only the <path> part of the URL
// JRM 97/01/08 changed this so that if it's a partial path (doesn't start with '/'),
// then it is combined with inOutSpec's vRefNum and parID to form a new spec.
//-----------------------------------
{
	if (unixPath == nsnull)
		return badFidErr;
	char* macPath = MacPathFromUnixPath(unixPath, hexDecode);
	if (!macPath)
		return memFullErr;

	OSErr err = noErr;
	if (!allowPartial)
	{
		NS_ASSERTION(*unixPath == '/' /*full path*/, "Not a full Unix path!");
	}
	err = FSSpecFromPathname(macPath, ioSpec, createDirs);
	if (err == fnfErr)
		err = noErr;
	Boolean dummy;	  
	if (err == noErr && resolveAlias)	 // Added 
		err = MacFileHelpers::ResolveAliasFile(ioSpec, dummy);
	delete [] macPath;
	NS_ASSERTION(err==noErr||err==fnfErr||err==dirNFErr||err==nsvErr, "Not a path!");
	return err;
} // MacFileHelpers::FSSpecFromLocalUnixPath

//-----------------------------------
char* MacFileHelpers::PathNameFromFSSpec( const FSSpec& inSpec )
// Returns a full pathname to the given file
// Returned value is allocated with new [], and must be freed with delete []
// For consistency and to work under OS X this creates an nsILocalFileMac and has it do the work.
//-----------------------------------
{
	char* result = nil;
	nsresult rv;

    FSSpec nonConstSpec = inSpec;
    nsCAutoString path;	
    nsCOMPtr<nsILocalFileMac> macFile;
    
    rv = NS_NewLocalFileWithFSSpec(&nonConstSpec, PR_TRUE, getter_AddRefs(macFile));
    if (NS_FAILED(rv)) return nsnull;
    nsCOMPtr<nsILocalFile> localFile(do_QueryInterface(macFile, &rv));
    if (NS_FAILED(rv)) return nsnull;
    rv = localFile->GetNativePath(path);
    if (NS_FAILED(rv)) return nsnull;
    PRInt32 strLen = path.Length();
    result = new char [strLen + 1];
    if (!result) return nsnull;
	memcpy(result, path.get(), strLen);
	result[ strLen ] = 0;

	return result;
} // MacFileHelpers::PathNameFromFSSpec


#pragma mark -

//========================================================================================
//					  Macintosh nsFileSpec implementation
//========================================================================================

//----------------------------------------------------------------------------------------
nsFileSpec::nsFileSpec()
//----------------------------------------------------------------------------------------
{
//    NS_ASSERTION(0, "nsFileSpec is unsupported - use nsIFile!");
	Clear();
}

//----------------------------------------------------------------------------------------
nsFileSpec::nsFileSpec(const FSSpec& inSpec, PRBool resolveAlias)
//----------------------------------------------------------------------------------------
: mSpec(inSpec)
, mError(NS_OK)
{
//    NS_ASSERTION(0, "nsFileSpec is unsupported - use nsIFile!");
	if (resolveAlias)
	{
		PRBool dummy;
		ResolveSymlink(dummy);
	}
}

//----------------------------------------------------------------------------------------
void nsFileSpec::operator = (const FSSpec& inSpec)
//----------------------------------------------------------------------------------------
{
	mSpec = inSpec;
	mError = NS_OK;
}

//----------------------------------------------------------------------------------------
nsFileSpec::nsFileSpec(const nsFileSpec& inSpec)
//----------------------------------------------------------------------------------------
:	 mSpec(inSpec.mSpec)
,	 mError(inSpec.Error())
{
//    NS_ASSERTION(0, "nsFileSpec is unsupported - use nsIFile!");
}

//----------------------------------------------------------------------------------------
nsFileSpec::nsFileSpec(const char* inNativePathString, PRBool inCreateDirs)
//----------------------------------------------------------------------------------------
{
//  NS_ASSERTION(0, "nsFileSpec is unsupported - use nsIFile!");
    Clear();		// this sets mError to NS_ERROR_NOT_INITIALIZED

	if (inNativePathString)
	{
		mError = NS_FILE_RESULT(MacFileHelpers::FSSpecFromPathname(
				  inNativePathString, mSpec, inCreateDirs));
		if (mError == NS_FILE_RESULT(fnfErr))
			mError = NS_OK;
	}

} // nsFileSpec::nsFileSpec

//----------------------------------------------------------------------------------------
nsFileSpec::nsFileSpec(const nsString& inNativePathString, PRBool inCreateDirs)
//----------------------------------------------------------------------------------------
{
//    NS_ASSERTION(0, "nsFileSpec is unsupported - use nsIFile!");
	Clear();		// this sets mError to NS_ERROR_NOT_INITIALIZED

	mError = NS_FILE_RESULT(
		MacFileHelpers::FSSpecFromPathname(
			NS_LossyConvertUCS2toASCII(inNativePathString).get(),
			mSpec, inCreateDirs));
	if (mError == NS_FILE_RESULT(fnfErr))
		mError = NS_OK;

} // nsFileSpec::nsFileSpec

//----------------------------------------------------------------------------------------
nsFileSpec::nsFileSpec(short vRefNum, long parID, ConstStr255Param fileName,  PRBool resolveAlias)
//----------------------------------------------------------------------------------------
{
//    NS_ASSERTION(0, "nsFileSpec is unsupported - use nsIFile!");
	mError = NS_FILE_RESULT(::FSMakeFSSpec(vRefNum, parID, fileName, &mSpec));
	if (mError == NS_FILE_RESULT(fnfErr))
		mError = NS_OK;
 
	if (resolveAlias)
	{
		PRBool dummy;
		ResolveSymlink(dummy);
	}
}

//----------------------------------------------------------------------------------------
nsFileSpec::nsFileSpec(const nsFilePath& inPath)
//----------------------------------------------------------------------------------------
{
//    NS_ASSERTION(0, "nsFileSpec is unsupported - use nsIFile!");
	*this = inPath.GetFileSpec();
}

//----------------------------------------------------------------------------------------
void nsFileSpec::operator = (const char* inString)
//----------------------------------------------------------------------------------------
{
	Clear();		// this sets mError to NS_ERROR_NOT_INITIALIZED

	if (inString)
	{
		mError = NS_FILE_RESULT(MacFileHelpers::FSSpecFromPathname(inString, mSpec, true));
		if (mError == NS_FILE_RESULT(fnfErr))
			mError = NS_OK;
	}
	
} // nsFileSpec::operator =

//----------------------------------------------------------------------------------------
void nsFileSpec::operator = (const nsFileSpec& inSpec)
//----------------------------------------------------------------------------------------
{
	mPath.SetToEmpty();
	mSpec.vRefNum = inSpec.mSpec.vRefNum;
	mSpec.parID = inSpec.mSpec.parID;

	PRInt32 copySize = inSpec.mSpec.name[0] + 1;
	if (copySize > sizeof(inSpec.mSpec.name))
		copySize = sizeof(inSpec.mSpec.name);
	memcpy(mSpec.name, inSpec.mSpec.name, copySize);
	mError = inSpec.Error();	// note that the error is propagated
} // nsFileSpec::operator =

//----------------------------------------------------------------------------------------
void nsFileSpec::operator = (const nsFilePath& inPath)
//----------------------------------------------------------------------------------------
{
	*this = inPath.GetFileSpec();
} // nsFileSpec::operator =

//----------------------------------------------------------------------------------------
inline void nsFileSpec::Clear()
//----------------------------------------------------------------------------------------
{
	mPath.SetToEmpty();
	mSpec.vRefNum = 0;
	mSpec.parID = 0;
	mSpec.name[0] = 0;
	mError = NS_ERROR_NOT_INITIALIZED;
}

//----------------------------------------------------------------------------------------
PRBool nsFileSpec::Exists() const
//----------------------------------------------------------------------------------------
{
  if (NS_FAILED(mError)) return PR_FALSE;
	FSSpec temp;
	return ::FSMakeFSSpec(mSpec.vRefNum, mSpec.parID, mSpec.name, &temp) == noErr;
} // nsFileSpec::Exists()

//----------------------------------------------------------------------------------------
void nsFileSpec::GetModDate(TimeStamp& outStamp) const
//----------------------------------------------------------------------------------------
{
	CInfoPBRec pb;
	if (GetCatInfo(pb) == noErr)
		outStamp = ((DirInfo*)&pb)->ioDrMdDat; // The mod date is in the same spot for files and dirs.
	else
		outStamp = 0;
} // nsFileSpec::GetModDate

//----------------------------------------------------------------------------------------
PRUint32 nsFileSpec::GetFileSize() const
//----------------------------------------------------------------------------------------
{
	CInfoPBRec pb;
	if (noErr == GetCatInfo(pb))
		return (PRUint32)((HFileInfo*)&pb)->ioFlLgLen;
	return 0;
} // nsFileSpec::GetFileSize

//----------------------------------------------------------------------------------------
void nsFileSpec::SetLeafName(const char* inLeafName)
// In leaf name can actually be a partial path...
//----------------------------------------------------------------------------------------
{
	NS_ASSERTION(inLeafName, "Attempt to set leaf name with a null string");
	
	mPath.SetToEmpty();

	if (inLeafName)
	{
		// what about long relative paths?	Hmm?  We don't have a routine for this anywhere.
		Str255 partialPath;
		MacFileHelpers::PLstrcpy(partialPath, inLeafName);
		mError = NS_FILE_RESULT(
			::FSMakeFSSpec(mSpec.vRefNum, mSpec.parID, partialPath, &mSpec));
		if (mError == NS_FILE_RESULT(fnfErr))
			mError = NS_OK;
	}
	
} // nsFileSpec::SetLeafName

//----------------------------------------------------------------------------------------
char* nsFileSpec::GetLeafName() const
// Result needs to be nsCRT::free()ed.
//----------------------------------------------------------------------------------------
{
	char leaf[sizeof(mSpec.name)];
	memcpy(leaf, &mSpec.name[1], mSpec.name[0]);
	leaf[mSpec.name[0]] = '\0';
	return nsCRT::strdup(leaf);
} // nsFileSpec::GetLeafName

//----------------------------------------------------------------------------------------
void nsFileSpec::MakeAliasSafe()
//----------------------------------------------------------------------------------------
{
	mPath.SetToEmpty();
	mError = NS_FILE_RESULT(MacFileHelpers::MakeAliasSafe(mSpec));
} // nsFileSpec::MakeAliasSafe

//----------------------------------------------------------------------------------------
void nsFileSpec::MakeUnique(ConstStr255Param inSuggestedLeafName)
//----------------------------------------------------------------------------------------
{
	mPath.SetToEmpty();
	if (inSuggestedLeafName[0] > 0)
		MacFileHelpers::PLstrcpy(mSpec.name, inSuggestedLeafName);

	MakeUnique();
} // nsFileSpec::MakeUnique

//----------------------------------------------------------------------------------------
PRBool nsFileSpec::IsFile() const
//----------------------------------------------------------------------------------------
{
	long dirID;
	Boolean isDirectory;
	return (noErr == ::FSpGetDirectoryID(&mSpec, &dirID, &isDirectory) && !isDirectory);
} // nsFileSpec::IsFile

//----------------------------------------------------------------------------------------
PRBool nsFileSpec::IsDirectory() const
//----------------------------------------------------------------------------------------
{
	long dirID;
	Boolean isDirectory;
	return (noErr == ::FSpGetDirectoryID(&mSpec, &dirID, &isDirectory) && isDirectory);
} // nsFileSpec::IsDirectory

//----------------------------------------------------------------------------------------
PRBool nsFileSpec::IsHidden() const
//----------------------------------------------------------------------------------------
{
	CInfoPBRec		cInfo;
	PRBool			hidden = PR_FALSE;

	if (noErr == GetCatInfo(cInfo))
		if (cInfo.hFileInfo.ioFlFndrInfo.fdFlags & kIsInvisible)
			hidden = PR_TRUE;
	
	return hidden;
} // nsFileSpec::IsHidden

//----------------------------------------------------------------------------------------
PRBool nsFileSpec::IsSymlink() const
//----------------------------------------------------------------------------------------
{
	CInfoPBRec		cInfo;
	PRBool			hidden = PR_FALSE;

	if (noErr == GetCatInfo(cInfo))
		if (cInfo.hFileInfo.ioFlFndrInfo.fdFlags & kIsAlias)
			hidden = PR_TRUE;
	
	return hidden;
} // nsFileSpec::IsSymlink

//----------------------------------------------------------------------------------------
nsresult nsFileSpec::ResolveSymlink(PRBool& wasAliased)
//----------------------------------------------------------------------------------------
{
	Boolean wasAliased2; // Type conversion Boolean <--> PRBool 
	OSErr err = MacFileHelpers::ResolveAliasFile(mSpec, wasAliased2); 
	if (wasAliased2) 
	{ 
		mError = NS_FILE_RESULT(err); 
		wasAliased = PR_TRUE; 
	} 
	else 
		wasAliased = PR_FALSE; 

	return mError;
} // nsFileSpec::ResolveSymlink

//----------------------------------------------------------------------------------------
void nsFileSpec::GetParent(nsFileSpec& outSpec) const
//----------------------------------------------------------------------------------------
{
	if (NS_SUCCEEDED(mError))
		outSpec.mError = NS_FILE_RESULT(::FSMakeFSSpec(mSpec.vRefNum, mSpec.parID, nsnull, outSpec));
} // nsFileSpec::GetParent

//----------------------------------------------------------------------------------------
void nsFileSpec::operator += (const char* inRelativePath)
//----------------------------------------------------------------------------------------
{
	NS_ASSERTION(inRelativePath, "Attempt to append relative path with null path");

	// Invalidate the path cache string, since we're changing ourselves.
	mPath.SetToEmpty();

	// if we are already bad, don't allow appendage
	if (NS_FAILED(Error()))
	{
	  NS_WARNING("trying to append to a bad nsFileSpec");
	  return;
	}
	
	// Find the dirID of the directory described by this spec
	long dirID;
	Boolean isDirectory;
	mError = NS_FILE_RESULT(::FSpGetDirectoryID(&mSpec, &dirID, &isDirectory));
	if (NS_FAILED(mError) || !isDirectory || !inRelativePath)
		return;
   // mSpec.vRefNum is already correct.
	mSpec.parID = dirID;

	// Next, determine if it is a UNIX or Mac style path. Now, Macintosh relative paths
	// are either leaf names (in which the distinction between unix and macintosh
	// relative paths disappears) or they start with a colon. If we find an initial colon,
	// then assume it's a macintosh path.
	// If it is a UNIX path (including just a leaf name), we will also look for ':' and
	// assert if we find one.
	if (*inRelativePath != ':')
	{
		// Looks like a UNIX path (including possibly just a leaf name)
		NS_ASSERTION(strchr(inRelativePath, ':') == nsnull, "Can not determine path type");
	   // Convert unix path (which is unencoded) to a spec
		mError = NS_FILE_RESULT(
			MacFileHelpers::FSSpecFromUnixPath(inRelativePath, mSpec, false, false, true, true));
	}
	else
	{
		// We must be a mac path!				 
		mError = NS_FILE_RESULT(MacFileHelpers::FSSpecFromPathname(inRelativePath, mSpec, true));
	}
	if (mError == NS_FILE_RESULT(fnfErr))
		mError = NS_OK;
	
} // nsFileSpec::operator +=

//----------------------------------------------------------------------------------------
void nsFileSpec::CreateDirectory(int /* unix mode */)
//----------------------------------------------------------------------------------------
{
	long ignoredDirID;
	OSErr	err = ::FSpDirCreate(&mSpec, smCurrentScript, &ignoredDirID);
	// it's OK if the dir already exists
	if (err != noErr && IsDirectory())
		err = noErr;
		
	mError = NS_FILE_RESULT(err);
	
} // nsFileSpec::CreateDirectory

//----------------------------------------------------------------------------------------
void nsFileSpec::Delete(PRBool inRecursive) const
//----------------------------------------------------------------------------------------
{
	OSErr anErr;

	nsresult& mutableError = const_cast<nsFileSpec*>(this)->mError;
	if (inRecursive)
	{
		// MoreFilesExtras
		anErr = ::DeleteDirectory(
					mSpec.vRefNum,
					mSpec.parID,
					const_cast<unsigned char*>(mSpec.name));
	}
	else
		anErr = ::FSpDelete(&mSpec);
	
	if (anErr == fnfErr) // deleting a file that doesn't exist isn't an error!
		anErr = noErr;
	
	mutableError = NS_FILE_RESULT(anErr);
   
} // nsFileSpec::Delete

//----------------------------------------------------------------------------------------
void nsFileSpec::RecursiveCopy(nsFileSpec newDir) const
//----------------------------------------------------------------------------------------
{
	if (IsDirectory())
	{
		if (!(newDir.Exists()))
		{
			newDir.CreateDirectory();
		}

		for (nsDirectoryIterator i(*this, PR_FALSE); i.Exists(); i++)
		{
			nsFileSpec& child = (nsFileSpec&)i;

			if (child.IsDirectory())
			{
				nsFileSpec tmpDirSpec(newDir);

				char *leafname = child.GetLeafName();
				tmpDirSpec += leafname;
				nsCRT::free(leafname);

				child.RecursiveCopy(tmpDirSpec);
			}
			else
			{
				child.RecursiveCopy(newDir);
			}
		}
	}
	else
	{
		nsFileSpec& filePath = (nsFileSpec&) *this;

		if (!(newDir.Exists()))
		{
			newDir.CreateDirectory();
		}

		filePath.CopyToDir(newDir);
	}
} // nsFileSpec::RecursiveCopy

//----------------------------------------------------------------------------------------
nsresult nsFileSpec::Truncate(PRInt32 aNewLength) const
//----------------------------------------------------------------------------------------
{
    short   refNum;
    OSErr   err;
        
    // First see if we have an internal error set
    if (NS_FAILED(mError))
        return mError;
        
    // Need to open the file to trunc
    if (::FSpOpenDF(&mSpec, fsWrPerm, &refNum) != noErr)
        return NS_FILE_FAILURE;

    err = ::SetEOF(refNum, aNewLength);
        
    // Close the file unless we got an error that it was already closed
    if (err != fnOpnErr)
        (void)::FSClose(refNum);
        
    if (err != noErr)
        return NS_FILE_FAILURE;
        
    return NS_OK;
} // nsFileSpec::Truncate

//----------------------------------------------------------------------------------------
nsresult nsFileSpec::Rename(const char* inNewName)
//----------------------------------------------------------------------------------------
{
	NS_ASSERTION(inNewName, "Attempt to rename with null new name");

	if (strchr(inNewName, '/'))
		return NS_FILE_FAILURE; // no relative paths here!
	
	Str255 pName;
	MacFileHelpers::PLstrcpy(pName, inNewName);
	if (::FSpRename(&mSpec, pName) != noErr)
		return NS_FILE_FAILURE;
	SetLeafName(inNewName);
	return NS_OK;
} // nsFileSpec::Rename

//----------------------------------------------------------------------------------------
nsresult nsFileSpec::CopyToDir(const nsFileSpec& newParentDir) const
//----------------------------------------------------------------------------------------
{
	// We can only copy into a directory, and (for now) can not copy entire directories

	if (!newParentDir.IsDirectory() || (IsDirectory() ) )
		return NS_FILE_FAILURE;
	
	nsresult rv = NS_FILE_RESULT(::FSpFileCopy(&mSpec,
							&newParentDir.mSpec,
							const_cast<StringPtr>(GetLeafPName()),
							nsnull,
							0,
							true));

	return rv;

} // nsFileSpec::CopyToDir

//----------------------------------------------------------------------------------------
nsresult nsFileSpec::MoveToDir(const nsFileSpec& newParentDir) 
//----------------------------------------------------------------------------------------
{
	// We can only move into a directory
	
	if (!newParentDir.IsDirectory())
		return NS_FILE_FAILURE;
 
	nsresult result = NS_FILE_RESULT(::FSpMoveRenameCompat(&mSpec,
									&newParentDir.mSpec,
									const_cast<StringPtr>(GetLeafPName())));

	if ( NS_SUCCEEDED(result) )
	{
		char* leafName = GetLeafName();
		*this = newParentDir + leafName;
		nsCRT::free(leafName);
	}
	return result;
} // nsFileSpec::MoveToDir

//----------------------------------------------------------------------------------------
nsresult nsFileSpec::Execute(const char* /*args - how can this be cross-platform?  problem! */ ) const
//----------------------------------------------------------------------------------------
{
	if (IsDirectory())
		return NS_FILE_FAILURE;

	LaunchParamBlockRec launchThis;
	launchThis.launchAppSpec = const_cast<FSSpec*>(&mSpec);
	launchThis.launchAppParameters = nsnull; // args;
	/* launch the thing */
	launchThis.launchBlockID	= extendedBlock;
	launchThis.launchEPBLength	= extendedBlockLen;
	launchThis.launchFileFlags	= nsnull;
	launchThis.launchControlFlags = launchContinue + launchNoFileFlags + launchUseMinimum;
	launchThis.launchControlFlags += launchDontSwitch;

	nsresult result = NS_FILE_RESULT(::LaunchApplication(&launchThis));
	return result;
  
} // nsFileSpec::Execute

//----------------------------------------------------------------------------------------
OSErr nsFileSpec::GetCatInfo(CInfoPBRec& outInfo) const
//----------------------------------------------------------------------------------------
{
	DirInfo	   *dipb=(DirInfo *)&outInfo;
	dipb->ioCompletion = nsnull;
	dipb->ioFDirIndex = 0; // use dirID and name
	dipb->ioVRefNum = mSpec.vRefNum;
	dipb->ioDrDirID = mSpec.parID;
	dipb->ioNamePtr = const_cast<nsFileSpec*>(this)->mSpec.name;
	return PBGetCatInfoSync(&outInfo);
} // nsFileSpec::GetCatInfo()

//----------------------------------------------------------------------------------------
OSErr nsFileSpec::SetFileTypeAndCreator(OSType type, OSType creator)
//----------------------------------------------------------------------------------------
{
	FInfo info;
	OSErr err = ::FSpGetFInfo(&mSpec, &info);
	if (err != noErr)
		return err;
	info.fdType = type;
	info.fdCreator = creator;
	err = ::FSpSetFInfo(&mSpec, &info);
	return err;
}

//----------------------------------------------------------------------------------------
OSErr nsFileSpec::GetFileTypeAndCreator(OSType* type, OSType* creator)
//----------------------------------------------------------------------------------------
{
	FInfo info;
	OSErr err = ::FSpGetFInfo(&mSpec, &info);
	if (err != noErr)
		return err;
	*type = info.fdType;
	*creator = info.fdCreator;	
	return noErr;
}

//----------------------------------------------------------------------------------------
PRInt64 nsFileSpec::GetDiskSpaceAvailable() const
//----------------------------------------------------------------------------------------
{
	PRInt64 space64Bits;

	LL_I2L(space64Bits , LONG_MAX);

	XVolumeParam	pb;
	pb.ioCompletion = nsnull;
	pb.ioVolIndex = 0;
	pb.ioNamePtr = nsnull;
	pb.ioVRefNum = mSpec.vRefNum;
	
	// PBXGetVolInfoSync works on HFS+ volumes too!
	OSErr err = ::PBXGetVolInfoSync(&pb);
	
	if (err == noErr)
	{
#ifdef HAVE_LONG_LONG
		space64Bits = pb.ioVFreeBytes;
#else
		const UnsignedWide& freeBytes = UInt64ToUnsignedWide(pb.ioVFreeBytes);
		space64Bits.lo = freeBytes.lo;
		space64Bits.hi = freeBytes.hi;
#endif
	}
		
	return space64Bits;
} // nsFileSpec::GetDiskSpace()

//----------------------------------------------------------------------------------------
const char* nsFileSpec::GetCString() const
// This is the only conversion to const char* that is provided, and it allows the
// path to be "passed" to NSPR file routines.  This practice is VERY EVIL and should only
// be used to support legacy code.	Using it guarantees bugs on Macintosh. The string is
// cached and freed by the nsFileSpec destructor, so do not delete (or free) it.
//----------------------------------------------------------------------------------------
{
	if (mPath.IsEmpty())
	{
		char* path = MacFileHelpers::PathNameFromFSSpec(mSpec);
		if (path != NULL) {
			const_cast<nsFileSpec*>(this)->mPath = path;	// operator =() copies the string!!!
			delete[] path;
		} else {
			const_cast<nsFileSpec*>(this)->mError = NS_ERROR_OUT_OF_MEMORY;
		}
	}
	return mPath;
}

#pragma mark -

//========================================================================================
//					  Macintosh nsFilePath implementation
//========================================================================================

//----------------------------------------------------------------------------------------
static void AssignFromPath(nsFilePath& ioPath, const char* inString, PRBool inCreateDirs)
//----------------------------------------------------------------------------------------
{
	NS_ASSERTION(inString, "AssignFromPath called with null inString");
	NS_ASSERTION(strstr(inString, kFileURLPrefix) != inString, "URL passed as path");

	FSSpec spec;
	spec.vRefNum = 0;
	spec.parID = 0;
	spec.name[0] = 0;
	MacFileHelpers::FSSpecFromUnixPath(
		inString,
		spec,
		false,
		true, // resolve alias
		true,
		inCreateDirs);
	// Now we have a spec,
	// Invoke operator = (const nsFileSpec&) to do the rest.
	// Why didn't we just say mPath = inString to get the path? Well, we want it to be
	// canonical and absolute.
	ioPath = spec;
}

//----------------------------------------------------------------------------------------
nsFilePath::nsFilePath(const char* inString, PRBool inCreateDirs)
//----------------------------------------------------------------------------------------
{
	AssignFromPath(*this, inString, inCreateDirs);
} //nsFilePath::nsFilePath

//----------------------------------------------------------------------------------------
nsFilePath::nsFilePath(const nsString& inString, PRBool inCreateDirs)
//----------------------------------------------------------------------------------------
{
	AssignFromPath(*this, NS_LossyConvertUCS2toASCII(inString).get(),
	               inCreateDirs);
}

//----------------------------------------------------------------------------------------
void nsFilePath::operator = (const char* inString)
//----------------------------------------------------------------------------------------
{
	AssignFromPath(*this, inString, PR_FALSE);
}

//----------------------------------------------------------------------------------------
nsFilePath::nsFilePath(const nsFileSpec& inSpec)
//----------------------------------------------------------------------------------------
{
	*this = inSpec;
}

//----------------------------------------------------------------------------------------
nsFilePath::nsFilePath(const nsFileURL& inOther)
//----------------------------------------------------------------------------------------
{
	*this = inOther;
}

//----------------------------------------------------------------------------------------
void nsFilePath::operator = (const nsFileSpec& inSpec)
//----------------------------------------------------------------------------------------
{
	char * path = MacFileHelpers::PathNameFromFSSpec(inSpec);
	path = MacFileHelpers::EncodeMacPath(path, true, false);
	mPath = path;
	nsCRT::free(path);
	mFileSpec = inSpec;
} // nsFilePath::operator =

//----------------------------------------------------------------------------------------
void nsFilePath::operator = (const nsFileURL& inOther)
//----------------------------------------------------------------------------------------
{
	char * path = MacFileHelpers::PathNameFromFSSpec(inOther.mFileSpec);
	path = MacFileHelpers::EncodeMacPath(path, true, false);
	mPath = path;
	nsCRT::free(path);
	mFileSpec = inOther.GetFileSpec();
}

#pragma mark -

//========================================================================================
//								  nsFileURL implementation
//========================================================================================

//----------------------------------------------------------------------------------------
nsFileURL::nsFileURL(const char* inString, PRBool inCreateDirs)
//----------------------------------------------------------------------------------------
:	 mURL(inString)
{	 
	NS_ASSERTION(inString, "nsFileURL constructed with null inString");
	NS_ASSERTION(strstr(inString, kFileURLPrefix) == inString, "Not a URL!");
	mFileSpec.mError = NS_FILE_RESULT(MacFileHelpers::FSSpecFromUnixPath(
		inString + kFileURLPrefixLength,
		mFileSpec.mSpec,
		true, // need to decode
		false, // resolve alias
		false, // must be a full path
		inCreateDirs));
	if (mFileSpec.mError == NS_FILE_RESULT(fnfErr))
		mFileSpec.mError = NS_OK;
} // nsFileURL::nsFileURL

//----------------------------------------------------------------------------------------
nsFileURL::nsFileURL(const nsString& inString, PRBool inCreateDirs)
//----------------------------------------------------------------------------------------
:	 mURL(nsnull)
{
	NS_LossyConvertUCS2toASCII cstring(inString);
	mURL = cstring.get();
	NS_ASSERTION(strstr(cstring.get(), kFileURLPrefix) == cstring.get(),
	             "Not a URL!");
	mFileSpec.mError = NS_FILE_RESULT(MacFileHelpers::FSSpecFromUnixPath(
		cstring.get() + kFileURLPrefixLength,
		mFileSpec.mSpec,
		true, // need to decode
		false, // resolve alias
		false, // must be a full path
		inCreateDirs));
	if (mFileSpec.mError == NS_FILE_RESULT(fnfErr))
		mFileSpec.mError = NS_OK;
} // nsFileURL::nsFileURL

//----------------------------------------------------------------------------------------
nsFileURL::nsFileURL(const nsFilePath& inOther)
//----------------------------------------------------------------------------------------
{
	*this = inOther.GetFileSpec();
} // nsFileURL::nsFileURL

//----------------------------------------------------------------------------------------
nsFileURL::nsFileURL(const nsFileSpec& inOther)
//----------------------------------------------------------------------------------------
{
	*this = inOther;
} // nsFileURL::nsFileURL

//----------------------------------------------------------------------------------------
void nsFileURL::operator = (const nsFilePath& inOther)
//----------------------------------------------------------------------------------------
{
	*this = inOther.GetFileSpec();
} // nsFileURL::operator =

//----------------------------------------------------------------------------------------
void nsFileURL::operator = (const nsFileSpec& inOther)
//----------------------------------------------------------------------------------------
{
	mFileSpec  = inOther;
	char* path = MacFileHelpers::PathNameFromFSSpec( mFileSpec );
	char* encodedPath = MacFileHelpers::EncodeMacPath(path, true, true);
	nsSimpleCharString encodedURL(kFileURLPrefix);
	encodedURL += encodedPath;
	nsCRT::free(encodedPath);
	mURL = encodedURL;
	if (encodedURL[encodedURL.Length() - 1] != '/' && inOther.IsDirectory())
		mURL += "/";
} // nsFileURL::operator =

//----------------------------------------------------------------------------------------
void nsFileURL::operator = (const char* inString)
//----------------------------------------------------------------------------------------
{
	NS_ASSERTION(inString, "nsFileURL operator= constructed with null inString");

	mURL = inString;
	NS_ASSERTION(strstr(inString, kFileURLPrefix) == inString, "Not a URL!");
	mFileSpec.mError = NS_FILE_RESULT(MacFileHelpers::FSSpecFromUnixPath(
		inString + kFileURLPrefixLength,
		mFileSpec.mSpec,
		true, // need to decode
		true, // resolve alias
		false, // must be a full path
		false)); // don't create dirs.
	if (mFileSpec.mError == NS_FILE_RESULT(fnfErr))
		mFileSpec.mError = NS_OK;
} // nsFileURL::operator =

#pragma mark -

//========================================================================================
//								  nsDirectoryIterator
//========================================================================================

//----------------------------------------------------------------------------------------
nsDirectoryIterator::nsDirectoryIterator(
	const nsFileSpec& inDirectory
,	PRBool resolveSymLinks)
//----------------------------------------------------------------------------------------
	: mCurrent(inDirectory)
	, mExists(false)
	, mResoveSymLinks(resolveSymLinks)
	, mIndex(-1)
{
	CInfoPBRec pb;
	OSErr err = inDirectory.GetCatInfo(pb);
	
	// test that we have got a directory back, not a file
	DirInfo* dipb = (DirInfo*)&pb;
	if (err != noErr  || !( dipb->ioFlAttrib & 0x0010))
		return;
	// Sorry about this, there seems to be a bug in CWPro 4:
	FSSpec& currentSpec = mCurrent.nsFileSpec::operator FSSpec&();
	mVRefNum = currentSpec.vRefNum;
	mParID = dipb->ioDrDirID;
	mMaxIndex = pb.dirInfo.ioDrNmFls;
	mIndex = 0; // ready to increment
	++(*this); // the pre-increment operator
	
} // nsDirectoryIterator::nsDirectoryIterator

//----------------------------------------------------------------------------------------
OSErr nsDirectoryIterator::SetToIndex()
//----------------------------------------------------------------------------------------
{
	CInfoPBRec cipb;
	DirInfo	   *dipb=(DirInfo *)&cipb;
	Str255 objectName;
	dipb->ioCompletion = nsnull;
	dipb->ioFDirIndex = mIndex;
	// Sorry about this, there seems to be a bug in CWPro 4:
	FSSpec& currentSpec = mCurrent.nsFileSpec::operator FSSpec&();
	dipb->ioVRefNum = mVRefNum; /* Might need to use vRefNum, not sure*/
	dipb->ioDrDirID = mParID;
	dipb->ioNamePtr = objectName;
	OSErr err = PBGetCatInfoSync(&cipb);
	FSSpec temp;
	if (err == noErr)
		err = FSMakeFSSpec(mVRefNum, mParID, objectName, &temp);
	mCurrent = temp; // use the operator: it clears the string cache.
	mExists = err == noErr;

	if (mExists && mResoveSymLinks)
	{	
		PRBool ignore;
		mCurrent.ResolveSymlink(ignore);
	}
	return err;
} // nsDirectoryIterator::SetToIndex()

//----------------------------------------------------------------------------------------
nsDirectoryIterator& nsDirectoryIterator::operator -- ()
//----------------------------------------------------------------------------------------
{
	mExists = false;
	while (--mIndex > 0)
	{
		OSErr err = SetToIndex();
		if (err == noErr)
			break;
	}
	return *this;
} // nsDirectoryIterator::operator --

//----------------------------------------------------------------------------------------
nsDirectoryIterator& nsDirectoryIterator::operator ++ ()
//----------------------------------------------------------------------------------------
{
	mExists = false;
	if (mIndex >= 0) // probably trying to use a file as a directory!
		while (++mIndex <= mMaxIndex)
		{
			OSErr err = SetToIndex();
			if (err == noErr)
				break;
		}
	return *this;
} // nsDirectoryIterator::operator ++