1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* ***** BEGIN LICENSE BLOCK *****
3 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
5 * The contents of this file are subject to the Mozilla Public License Version
6 * 1.1 (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 * http://www.mozilla.org/MPL/
10 * Software distributed under the License is distributed on an "AS IS" basis,
11 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
12 * for the specific language governing rights and limitations under the
15 * The Original Code is mozilla.org code.
17 * The Initial Developer of the Original Code is
18 * Netscape Communications Corporation.
19 * Portions created by the Initial Developer are Copyright (C) 1998
20 * the Initial Developer. All Rights Reserved.
24 * Alternatively, the contents of this file may be used under the terms of
25 * either of the GNU General Public License Version 2 or later (the "GPL"),
26 * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
27 * in which case the provisions of the GPL or the LGPL are applicable instead
28 * of those above. If you wish to allow use of your version of this file only
29 * under the terms of either the GPL or the LGPL, and not to allow others to
30 * use your version of this file under the terms of the MPL, indicate your
31 * decision by deleting the provisions above and replace them with the notice
32 * and other provisions required by the GPL or the LGPL. If you do not delete
33 * the provisions above, a recipient may use your version of this file under
34 * the terms of any one of the MPL, the GPL or the LGPL.
36 * ***** END LICENSE BLOCK ***** */
41 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
42 THESE CLASSES ARE DEPRECATED AND UNSUPPORTED! USE |nsIFile| and |nsILocalFile|.
43 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
54 // First checked in on 98/11/20 by John R. McMullen in the wrong directory.
55 // Checked in again 98/12/04.
56 // Polished version 98/12/08.
58 //========================================================================================
62 // nsFilePath, nsFileURL, nsFileSpec, nsPersistentFileDescriptor
63 // nsDirectoryIterator.
65 // Q. How should I represent files at run time?
66 // A. Use nsFileSpec. Using char* will lose information on some platforms.
68 // Q. Then what are nsFilePath and nsFileURL for?
69 // A. Only when you need a char* parameter for legacy code.
71 // Q. How should I represent files in a persistent way (eg, in a disk file)?
72 // A. Use nsPersistentFileDescriptor. Convert to and from nsFileSpec at run time.
74 // This suite provides the following services:
76 // 1. Encapsulates all platform-specific file details, so that files can be
77 // described correctly without any platform #ifdefs
79 // 2. Type safety. This will fix the problems that used to occur because people
80 // confused file paths. They used to use const char*, which could mean three
81 // or four different things. Bugs were introduced as people coded, right up
82 // to the moment Communicator 4.5 shipped.
84 // 3. Used in conjunction with nsFileStream.h (q.v.), this supports all the power
85 // and readability of the ansi stream syntax.
89 // nsFilePath myPath("/Development/iotest.txt");
91 // nsOutputFileStream testStream(nsFileSpec(myPath));
92 // testStream << "Hello World" << nsEndl;
94 // 4. Handy methods for manipulating file specifiers safely, e.g. MakeUnique(),
95 // SetLeafName(), Exists().
97 // 5. Easy cross-conversion.
101 // Initialize a URL from a string
103 // nsFileURL fileURL("file:///Development/MPW/MPW%20Shell");
105 // Initialize a Unix-style path from a URL
107 // nsFilePath filePath(fileURL);
109 // Initialize a file spec from a URL
111 // nsFileSpec fileSpec(fileURL);
113 // Make the spec unique.
115 // fileSpec.MakeUnique();
117 // Assign the spec to a URL (causing conversion)
119 // fileURL = fileSpec;
121 // Assign a unix path using a string
123 // filePath = "/Development/MPW/SysErrs.err";
125 // Assign to a file spec using a unix path (causing conversion).
127 // fileSpec = filePath;
131 // fileSpec.MakeUnique();
133 // 6. Fixes a bug that have been there for a long time, and
134 // is inevitable if you use NSPR alone, where files are described as paths.
136 // The problem affects platforms (Macintosh) in which a path does not fully
137 // specify a file, because two volumes can have the same name. This
138 // is solved by holding a "private" native file spec inside the
139 // nsFilePath and nsFileURL classes, which is used when appropriate.
141 //========================================================================================
146 #include "xpcomobsolete.h"
148 #include "nsString.h"
149 #include "nsReadableUtils.h"
153 //========================================================================================
154 // Compiler-specific macros, as needed
155 //========================================================================================
156 #if !defined(NS_USING_NAMESPACE) && (defined(__MWERKS__) || defined(_MSC_VER))
157 #define NS_USING_NAMESPACE
160 #ifdef NS_USING_NAMESPACE
162 #define NS_NAMESPACE_PROTOTYPE
163 #define NS_NAMESPACE namespace
164 #define NS_NAMESPACE_END
165 #define NS_EXPLICIT explicit
168 #define NS_NAMESPACE_PROTOTYPE static
169 #define NS_NAMESPACE struct
170 #define NS_NAMESPACE_END ;
174 //=========================== End Compiler-specific macros ===============================
176 #include "nsILocalFile.h"
177 #include "nsCOMPtr.h"
179 #if defined(XP_UNIX) || defined(XP_BEOS)
181 #elif defined(XP_WIN)
183 // This clashes with some of the Win32 system headers (specifically,
184 // winbase.h). Hopefully they'll have been included first; else we may
185 // have problems. We could include winbase.h before doing this;
186 // unfortunately, it's bring in too much crap and'd slow stuff down
187 // more than it's worth doing.
188 #ifdef CreateDirectory
189 #undef CreateDirectory
193 #elif defined(XP_OS2)
195 #define INCL_DOSERRORS
202 //========================================================================================
203 // Here are the allowable ways to describe a file.
204 //========================================================================================
206 class nsFileSpec
; // Preferred. For i/o use nsInputFileStream, nsOutputFileStream
209 class nsNSPRPath
; // This can be passed to NSPR file I/O routines, if you must.
210 class nsPersistentFileDescriptor
; // Used for storage across program launches.
212 #define kFileURLPrefix "file://"
213 #define kFileURLPrefixLength (7)
215 class nsOutputStream
;
217 class nsIOutputStream
;
218 class nsIInputStream
;
219 class nsOutputFileStream
;
220 class nsInputFileStream
;
221 class nsOutputConsoleStream
;
223 class nsIUnicodeEncoder
;
224 class nsIUnicodeDecoder
;
226 //========================================================================================
227 // Conversion of native file errors to nsresult values. These are really only for use
228 // in the file module, clients of this interface shouldn't really need them.
229 // Error results returned from this interface have, in the low-order 16 bits,
230 // native errors that are masked to 16 bits. Assumption: a native error of 0 is success
231 // on all platforms. Note the way we define this using an inline function. This
232 // avoids multiple evaluation if people go NS_FILE_RESULT(function_call()).
233 #define NS_FILE_RESULT(x) ns_file_convert_result((PRInt32)x)
234 nsresult
ns_file_convert_result(PRInt32 nativeErr
);
235 #define NS_FILE_FAILURE NS_FILE_RESULT(-1)
237 //========================================================================================
238 class nsSimpleCharString
239 // An envelope for char*: reference counted. Used internally by all the nsFileSpec
241 //========================================================================================
244 nsSimpleCharString();
245 nsSimpleCharString(const char*);
246 nsSimpleCharString(const nsString
&);
247 nsSimpleCharString(const nsSimpleCharString
&);
248 nsSimpleCharString(const char* inData
, PRUint32 inLength
);
250 ~nsSimpleCharString();
252 void operator = (const char*);
253 void operator = (const nsString
&);
254 void operator = (const nsSimpleCharString
&);
256 operator const char*() const { return mData
? mData
->mString
: 0; }
259 ReallocData(Length()); // requires detaching if shared...
260 return mData
? mData
->mString
: 0;
262 PRBool
operator == (const char*);
263 PRBool
operator == (const nsString
&);
264 PRBool
operator == (const nsSimpleCharString
&);
266 void operator += (const char* inString
);
267 nsSimpleCharString
operator + (const char* inString
) const;
269 char operator [](int i
) const { return mData
? mData
->mString
[i
] : '\0'; }
270 char& operator [](int i
)
272 if (i
>= (int)Length())
273 ReallocData((PRUint32
)i
+ 1);
274 return mData
->mString
[i
]; // caveat appelator
276 char& operator [](unsigned int i
) { return (*this)[(int)i
]; }
278 void Catenate(const char* inString1
, const char* inString2
);
281 PRBool
IsEmpty() const { return Length() == 0; }
283 PRUint32
Length() const { return mData
? mData
->mLength
: 0; }
284 void SetLength(PRUint32 inLength
) { ReallocData(inLength
); }
285 void CopyFrom(const char* inData
, PRUint32 inLength
);
286 void LeafReplace(char inSeparator
, const char* inLeafName
);
287 char* GetLeaf(char inSeparator
) const; // use PR_Free()
294 void ReallocData(PRUint32 inLength
);
296 //--------------------------------------------------
298 //--------------------------------------------------
308 }; // class nsSimpleCharString
310 //========================================================================================
311 class NS_COM_OBSOLETE nsFileSpec
312 // This is whatever each platform really prefers to describe files as. Declared first
313 // because the other two types have an embedded nsFileSpec object.
314 //========================================================================================
319 // These two meathods take *native* file paths.
320 NS_EXPLICIT
nsFileSpec(const char* inNativePath
, PRBool inCreateDirs
= PR_FALSE
);
321 NS_EXPLICIT
nsFileSpec(const nsString
& inNativePath
, PRBool inCreateDirs
= PR_FALSE
);
324 NS_EXPLICIT
nsFileSpec(const nsFilePath
& inPath
);
325 NS_EXPLICIT
nsFileSpec(const nsFileURL
& inURL
);
326 nsFileSpec(const nsFileSpec
& inPath
);
327 virtual ~nsFileSpec();
329 // These two operands take *native* file paths.
330 void operator = (const char* inNativePath
);
332 void operator = (const nsFilePath
& inPath
);
333 void operator = (const nsFileURL
& inURL
);
334 void operator = (const nsFileSpec
& inOther
);
335 void operator = (const nsPersistentFileDescriptor
& inOther
);
337 PRBool
operator ==(const nsFileSpec
& inOther
) const;
338 PRBool
operator !=(const nsFileSpec
& inOther
) const;
341 // Returns a native path, and allows the
342 // path to be "passed" to legacy code. This practice
343 // is VERY EVIL and should only be used to support legacy
344 // code. Using it guarantees bugs on Macintosh.
345 // The path is cached and freed by the nsFileSpec destructor
346 // so do not delete (or free) it. See also nsNSPRPath below,
347 // if you really must pass a string to PR_OpenFile().
348 // Doing so will introduce two automatic bugs.
349 const char* GetCString() const;
351 // Same as GetCString (please read the comments).
352 // Do not try to free this!
353 operator const char* () const { return GetCString(); }
355 // Same as GetCString (please read the comments).
356 // Do not try to free this!
357 const char* GetNativePathCString() const { return GetCString(); }
359 PRBool
IsChildOf(nsFileSpec
&possibleParent
);
361 PRBool
Valid() const { return NS_SUCCEEDED(Error()); }
362 nsresult
Error() const
364 if (mPath
.IsEmpty() && NS_SUCCEEDED(mError
))
365 ((nsFileSpec
*)this)->mError
= NS_ERROR_NOT_INITIALIZED
;
368 PRBool
Failed() const { return (PRBool
)NS_FAILED(Error()); }
370 //--------------------------------------------------
371 // Queries and path algebra. These do not modify the disk.
372 //--------------------------------------------------
374 char* GetLeafName() const; // Allocated. Use nsCRT::free().
375 // inLeafName can be a relative path, so this allows
376 // one kind of concatenation of "paths".
377 void SetLeafName(const char* inLeafName
);
379 // Return the filespec of the parent directory. Used
380 // in conjunction with GetLeafName(), this lets you
381 // parse a path into a list of node names. Beware,
382 // however, that the top node is still not a name,
383 // but a spec. Volumes on Macintosh can have identical
384 // names. Perhaps could be used for an operator --() ?
385 void GetParent(nsFileSpec
& outSpec
) const;
388 // ie nsFileSpec::TimeStamp. This is 32 bits now,
389 // but might change, eg, to a 64-bit class. So use the
390 // typedef, and use a streaming operator to convert
391 // to a string, so that your code won't break. It's
392 // none of your business what the number means. Don't
393 // rely on the implementation.
394 typedef PRUint32 TimeStamp
;
396 // This will return different values on different
397 // platforms, even for the same file (eg, on a server).
398 // But if the platform is constant, it will increase after
399 // every file modification.
400 void GetModDate(TimeStamp
& outStamp
) const;
402 PRBool
ModDateChanged(const TimeStamp
& oldStamp
) const
405 GetModDate(newStamp
);
406 return newStamp
!= oldStamp
;
409 PRUint32
GetFileSize() const;
410 PRInt64
GetDiskSpaceAvailable() const;
412 nsFileSpec
operator + (const char* inRelativeUnixPath
) const;
414 // Concatenate the relative path to this directory.
415 // Used for constructing the filespec of a descendant.
416 // This must be a directory for this to work. This differs
417 // from SetLeafName(), since the latter will work
418 // starting with a sibling of the directory and throws
419 // away its leaf information, whereas this one assumes
420 // this is a directory, and the relative path starts
422 void operator += (const char* inRelativeUnixPath
);
426 PRBool
IsDirectory() const; // More stringent than Exists()
427 PRBool
IsFile() const; // More stringent than Exists()
428 PRBool
Exists() const;
430 PRBool
IsHidden() const;
432 PRBool
IsSymlink() const;
434 //--------------------------------------------------
435 // Creation and deletion of objects. These can modify the disk.
436 //--------------------------------------------------
438 // For security reasons, these create the file.
439 void MakeUnique(PRBool inCreateFile
= PR_TRUE
);
440 void MakeUnique(const char* inSuggestedLeafName
, PRBool inCreateFile
= PR_TRUE
);
442 // Called for the spec of an alias. Modifies the spec to
443 // point to the original. Sets mError.
444 nsresult
ResolveSymlink(PRBool
& wasSymlink
);
446 void CreateDirectory(int mode
= 0775 /* for unix */);
447 void CreateDir(int mode
= 0775) { CreateDirectory(mode
); }
448 // workaround for yet another VC++ bug with long identifiers.
449 void Delete(PRBool inRecursive
) const;
450 nsresult
Truncate(PRInt32 aNewLength
) const;
451 void RecursiveCopy(nsFileSpec newDir
) const;
453 nsresult
Rename(const char* inNewName
); // not const: gets updated
454 nsresult
CopyToDir(const nsFileSpec
& inNewParentDirectory
) const;
455 nsresult
MoveToDir(const nsFileSpec
& inNewParentDirectory
);
456 nsresult
Execute(const char* args
) const;
460 //--------------------------------------------------
462 //--------------------------------------------------
466 // Clear the nsFileSpec contents, resetting it
467 // to the uninitialized state;
470 friend class nsFilePath
;
471 friend class nsFileURL
;
472 friend class nsDirectoryIterator
;
474 nsSimpleCharString mPath
;
478 NS_EXPLICIT
nsFileSpec(const nsPersistentFileDescriptor
& inURL
);
480 }; // class nsFileSpec
482 // FOR HISTORICAL REASONS:
484 typedef nsFileSpec nsNativeFileSpec
;
486 //========================================================================================
487 class NS_COM_OBSOLETE nsFileURL
488 // This is an escaped string that looks like "file:///foo/bar/mumble%20fish". Since URLs
489 // are the standard way of doing things in mozilla, this allows a string constructor,
490 // which just stashes the string with no conversion.
491 //========================================================================================
494 nsFileURL(const nsFileURL
& inURL
);
495 NS_EXPLICIT
nsFileURL(const char* inURLString
, PRBool inCreateDirs
= PR_FALSE
);
496 NS_EXPLICIT
nsFileURL(const nsString
& inURLString
, PRBool inCreateDirs
= PR_FALSE
);
497 NS_EXPLICIT
nsFileURL(const nsFilePath
& inPath
);
498 NS_EXPLICIT
nsFileURL(const nsFileSpec
& inPath
);
499 virtual ~nsFileURL();
501 // nsString GetString() const { return mPath; }
502 // may be needed for implementation reasons,
503 // but should not provide a conversion constructor.
505 void operator = (const nsFileURL
& inURL
);
506 void operator = (const char* inURLString
);
507 void operator = (const nsString
& inURLString
)
509 *this = NS_LossyConvertUTF16toASCII(inURLString
).get();
511 void operator = (const nsFilePath
& inOther
);
512 void operator = (const nsFileSpec
& inOther
);
514 void operator +=(const char* inRelativeUnixPath
);
515 nsFileURL
operator +(const char* inRelativeUnixPath
) const;
516 operator const char* () const { return (const char*)mURL
; } // deprecated.
517 const char* GetURLString() const { return (const char*)mURL
; }
518 // Not allocated, so don't free it.
519 const char* GetAsString() const { return (const char*)mURL
; }
520 // Not allocated, so don't free it.
522 //--------------------------------------------------
524 //--------------------------------------------------
527 friend class nsFilePath
; // to allow construction of nsFilePath
528 nsSimpleCharString mURL
;
529 }; // class nsFileURL
531 //========================================================================================
532 class NS_COM_OBSOLETE nsFilePath
533 // This is a string that looks like "/foo/bar/mumble fish". Same as nsFileURL, but
534 // without the "file:// prefix", and NOT %20 ENCODED! Strings passed in must be
535 // valid unix-style paths in this format.
536 //========================================================================================
539 nsFilePath(const nsFilePath
& inPath
);
540 NS_EXPLICIT
nsFilePath(const char* inUnixPathString
, PRBool inCreateDirs
= PR_FALSE
);
541 NS_EXPLICIT
nsFilePath(const nsString
& inUnixPathString
, PRBool inCreateDirs
= PR_FALSE
);
542 NS_EXPLICIT
nsFilePath(const nsFileURL
& inURL
);
543 NS_EXPLICIT
nsFilePath(const nsFileSpec
& inPath
);
544 virtual ~nsFilePath();
547 operator const char* () const { return mPath
; }
548 // This will return a UNIX string. If you
549 // need a string that can be passed into
550 // NSPR, take a look at the nsNSPRPath class.
552 void operator = (const nsFilePath
& inPath
);
553 void operator = (const char* inUnixPathString
);
554 void operator = (const nsString
& inUnixPathString
)
556 *this = NS_LossyConvertUTF16toASCII(inUnixPathString
).get();
558 void operator = (const nsFileURL
& inURL
);
559 void operator = (const nsFileSpec
& inOther
);
561 void operator +=(const char* inRelativeUnixPath
);
562 nsFilePath
operator +(const char* inRelativeUnixPath
) const;
564 //--------------------------------------------------
566 //--------------------------------------------------
570 nsSimpleCharString mPath
;
571 }; // class nsFilePath
573 //========================================================================================
574 class nsPersistentFileDescriptor
575 // To save information about a file's location in another file, initialize
576 // one of these from your nsFileSpec, and then write this out to your output stream.
577 // To retrieve the info, create one of these, read its value from an input stream.
578 // and then make an nsFileSpec from it.
579 //========================================================================================
582 nsPersistentFileDescriptor() {}
583 // For use prior to reading in from a stream
584 nsPersistentFileDescriptor(const nsPersistentFileDescriptor
& inEncodedData
);
585 virtual ~nsPersistentFileDescriptor();
586 void operator = (const nsPersistentFileDescriptor
& inEncodedData
);
589 NS_EXPLICIT
nsPersistentFileDescriptor(const nsFileSpec
& inSpec
);
590 void operator = (const nsFileSpec
& inSpec
);
592 // The following four functions are declared here (as friends). Their implementations
593 // are in mozilla/base/src/nsFileSpecStreaming.cpp.
595 friend nsresult
Read(nsIInputStream
* aStream
, nsPersistentFileDescriptor
&);
596 friend nsresult
Write(nsIOutputStream
* aStream
, const nsPersistentFileDescriptor
&);
597 // writes the data to a file
598 friend NS_COM_OBSOLETE nsInputStream
& operator >> (nsInputStream
&, nsPersistentFileDescriptor
&);
599 // reads the data from a file
600 friend NS_COM_OBSOLETE nsOutputStream
& operator << (nsOutputStream
&, const nsPersistentFileDescriptor
&);
601 // writes the data to a file
602 friend class nsFileSpec
;
604 void GetData(nsAFlatCString
& outData
) const;
605 void SetData(const nsAFlatCString
& inData
);
606 void SetData(const char* inData
, PRInt32 inSize
);
608 //--------------------------------------------------
610 //--------------------------------------------------
614 nsSimpleCharString mDescriptorString
;
616 }; // class nsPersistentFileDescriptor
618 //========================================================================================
619 class NS_COM_OBSOLETE nsDirectoryIterator
622 // nsFileSpec parentDir(...); // directory over whose children we shall iterate
623 // for (nsDirectoryIterator i(parentDir, PR_FALSE); i.Exists(); i++)
625 // // do something with i.Spec()
630 // for (nsDirectoryIterator i(parentDir, PR_TRUE); i.Exists(); i--)
632 // // do something with i.Spec()
634 // This one passed the PR_TRUE flag which will resolve any symlink encountered.
635 //========================================================================================
638 nsDirectoryIterator( const nsFileSpec
& parent
,
639 PRBool resoveSymLinks
);
640 virtual ~nsDirectoryIterator();
641 PRBool
Exists() const { return mExists
; }
642 nsDirectoryIterator
& operator ++(); // moves to the next item, if any.
643 nsDirectoryIterator
& operator ++(int) { return ++(*this); } // post-increment.
644 nsDirectoryIterator
& operator --(); // moves to the previous item, if any.
645 nsDirectoryIterator
& operator --(int) { return --(*this); } // post-decrement.
646 operator nsFileSpec
&() { return mCurrent
; }
648 nsFileSpec
& Spec() { return mCurrent
; }
650 //--------------------------------------------------
652 //--------------------------------------------------
658 PRBool mResoveSymLinks
;
660 #if (defined(XP_UNIX) || defined(XP_BEOS) || defined (XP_WIN) || defined(XP_OS2))
661 nsFileSpec mStarting
;
664 #if defined(XP_UNIX) || defined(XP_BEOS)
666 #elif defined(XP_WIN) || defined(XP_OS2)
667 PRDir
* mDir
; // XXX why not use PRDir for Unix too?
669 }; // class nsDirectoryIterator
671 //========================================================================================
672 class NS_COM_OBSOLETE nsNSPRPath
673 // This class will allow you to pass any one of the nsFile* classes directly into NSPR
674 // without the need to worry about whether you have the right kind of filepath or not.
675 // It will also take care of cleaning up any allocated memory.
676 //========================================================================================
679 NS_EXPLICIT
nsNSPRPath(const nsFileSpec
& inSpec
)
680 : mFilePath(inSpec
), modifiedNSPRPath(nsnull
) {}
681 NS_EXPLICIT
nsNSPRPath(const nsFileURL
& inURL
)
682 : mFilePath(inURL
), modifiedNSPRPath(nsnull
) {}
683 NS_EXPLICIT
nsNSPRPath(const nsFilePath
& inUnixPath
)
684 : mFilePath(inUnixPath
), modifiedNSPRPath(nsnull
) {}
686 virtual ~nsNSPRPath();
688 operator const char*() const;
690 // that NSPR file routines expect on each platform.
691 // Concerning constness, this can modify
692 // modifiedNSPRPath, but it's really just "mutable".
694 //--------------------------------------------------
696 //--------------------------------------------------
700 nsFilePath mFilePath
;
701 char* modifiedNSPRPath
; // Currently used only on XP_WIN,XP_OS2
702 }; // class nsNSPRPath
705 NS_COM_OBSOLETE nsresult
NS_FileSpecToIFile(nsFileSpec
* fileSpec
, nsILocalFile
* *result
);
707 #endif // _FILESPEC_H_