1// Copyright (c) 2012 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5// FilePath is a container for pathnames stored in a platform's native string
6// type, providing containers for manipulation in according with the
7// platform's conventions for pathnames.  It supports the following path
8// types:
9//
10//                   POSIX            Windows
11//                   ---------------  ----------------------------------
12// Fundamental type  char[]           wchar_t[]
13// Encoding          unspecified*     UTF-16
14// Separator         /                \, tolerant of /
15// Drive letters     no               case-insensitive A-Z followed by :
16// Alternate root    // (surprise!)   \\, for UNC paths
17//
18// * The encoding need not be specified on POSIX systems, although some
19//   POSIX-compliant systems do specify an encoding.  Mac OS X uses UTF-8.
20//   Chrome OS also uses UTF-8.
21//   Linux does not specify an encoding, but in practice, the locale's
22//   character set may be used.
23//
24// For more arcane bits of path trivia, see below.
25//
26// FilePath objects are intended to be used anywhere paths are.  An
27// application may pass FilePath objects around internally, masking the
28// underlying differences between systems, only differing in implementation
29// where interfacing directly with the system.  For example, a single
30// OpenFile(const FilePath &) function may be made available, allowing all
31// callers to operate without regard to the underlying implementation.  On
32// POSIX-like platforms, OpenFile might wrap fopen, and on Windows, it might
33// wrap _wfopen_s, perhaps both by calling file_path.value().c_str().  This
34// allows each platform to pass pathnames around without requiring conversions
35// between encodings, which has an impact on performance, but more imporantly,
36// has an impact on correctness on platforms that do not have well-defined
37// encodings for pathnames.
38//
39// Several methods are available to perform common operations on a FilePath
40// object, such as determining the parent directory (DirName), isolating the
41// final path component (BaseName), and appending a relative pathname string
42// to an existing FilePath object (Append).  These methods are highly
43// recommended over attempting to split and concatenate strings directly.
44// These methods are based purely on string manipulation and knowledge of
45// platform-specific pathname conventions, and do not consult the filesystem
46// at all, making them safe to use without fear of blocking on I/O operations.
47// These methods do not function as mutators but instead return distinct
48// instances of FilePath objects, and are therefore safe to use on const
49// objects.  The objects themselves are safe to share between threads.
50//
51// To aid in initialization of FilePath objects from string literals, a
52// FILE_PATH_LITERAL macro is provided, which accounts for the difference
53// between char[]-based pathnames on POSIX systems and wchar_t[]-based
54// pathnames on Windows.
55//
56// Paths can't contain NULs as a precaution agaist premature truncation.
57//
58// Because a FilePath object should not be instantiated at the global scope,
59// instead, use a FilePath::CharType[] and initialize it with
60// FILE_PATH_LITERAL.  At runtime, a FilePath object can be created from the
61// character array.  Example:
62//
63// | const FilePath::CharType kLogFileName[] = FILE_PATH_LITERAL("log.txt");
64// |
65// | void Function() {
66// |   FilePath log_file_path(kLogFileName);
67// |   [...]
68// | }
69//
70// WARNING: FilePaths should ALWAYS be displayed with LTR directionality, even
71// when the UI language is RTL. This means you always need to pass filepaths
72// through base::i18n::WrapPathWithLTRFormatting() before displaying it in the
73// RTL UI.
74//
75// This is a very common source of bugs, please try to keep this in mind.
76//
77// ARCANE BITS OF PATH TRIVIA
78//
79//  - A double leading slash is actually part of the POSIX standard.  Systems
80//    are allowed to treat // as an alternate root, as Windows does for UNC
81//    (network share) paths.  Most POSIX systems don't do anything special
82//    with two leading slashes, but FilePath handles this case properly
83//    in case it ever comes across such a system.  FilePath needs this support
84//    for Windows UNC paths, anyway.
85//    References:
86//    The Open Group Base Specifications Issue 7, sections 3.266 ("Pathname")
87//    and 4.12 ("Pathname Resolution"), available at:
88//    http://www.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_266
89//    http://www.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_12
90//
91//  - Windows treats c:\\ the same way it treats \\.  This was intended to
92//    allow older applications that require drive letters to support UNC paths
93//    like \\server\share\path, by permitting c:\\server\share\path as an
94//    equivalent.  Since the OS treats these paths specially, FilePath needs
95//    to do the same.  Since Windows can use either / or \ as the separator,
96//    FilePath treats c://, c:\\, //, and \\ all equivalently.
97//    Reference:
98//    The Old New Thing, "Why is a drive letter permitted in front of UNC
99//    paths (sometimes)?", available at:
100//    http://blogs.msdn.com/oldnewthing/archive/2005/11/22/495740.aspx
101
102#ifndef BASE_FILES_FILE_PATH_H_
103#define BASE_FILES_FILE_PATH_H_
104
105#include <stddef.h>
106#include <string>
107#include <vector>
108
109#include "base/base_export.h"
110#include "base/compiler_specific.h"
111#include "base/containers/hash_tables.h"
112#include "base/strings/string16.h"
113#include "base/strings/string_piece.h"  // For implicit conversions.
114#include "build/build_config.h"
115
116// Windows-style drive letter support and pathname separator characters can be
117// enabled and disabled independently, to aid testing.  These #defines are
118// here so that the same setting can be used in both the implementation and
119// in the unit test.
120#if defined(OS_WIN)
121#define FILE_PATH_USES_DRIVE_LETTERS
122#define FILE_PATH_USES_WIN_SEPARATORS
123#endif  // OS_WIN
124
125class Pickle;
126class PickleIterator;
127
128namespace base {
129
130// An abstraction to isolate users from the differences between native
131// pathnames on different platforms.
132class BASE_EXPORT FilePath {
133 public:
134#if defined(OS_POSIX)
135  // On most platforms, native pathnames are char arrays, and the encoding
136  // may or may not be specified.  On Mac OS X, native pathnames are encoded
137  // in UTF-8.
138  typedef std::string StringType;
139#elif defined(OS_WIN)
140  // On Windows, for Unicode-aware applications, native pathnames are wchar_t
141  // arrays encoded in UTF-16.
142  typedef std::wstring StringType;
143#endif  // OS_WIN
144
145  typedef StringType::value_type CharType;
146
147  // Null-terminated array of separators used to separate components in
148  // hierarchical paths.  Each character in this array is a valid separator,
149  // but kSeparators[0] is treated as the canonical separator and will be used
150  // when composing pathnames.
151  static const CharType kSeparators[];
152
153  // arraysize(kSeparators).
154  static const size_t kSeparatorsLength;
155
156  // A special path component meaning "this directory."
157  static const CharType kCurrentDirectory[];
158
159  // A special path component meaning "the parent directory."
160  static const CharType kParentDirectory[];
161
162  // The character used to identify a file extension.
163  static const CharType kExtensionSeparator;
164
165  FilePath();
166  FilePath(const FilePath& that);
167  explicit FilePath(const StringType& path);
168  ~FilePath();
169  FilePath& operator=(const FilePath& that);
170
171  bool operator==(const FilePath& that) const;
172
173  bool operator!=(const FilePath& that) const;
174
175  // Required for some STL containers and operations
176  bool operator<(const FilePath& that) const {
177    return path_ < that.path_;
178  }
179
180  const StringType& value() const { return path_; }
181
182  bool empty() const { return path_.empty(); }
183
184  void clear() { path_.clear(); }
185
186  // Returns true if |character| is in kSeparators.
187  static bool IsSeparator(CharType character);
188
189  // Returns a vector of all of the components of the provided path. It is
190  // equivalent to calling DirName().value() on the path's root component,
191  // and BaseName().value() on each child component.
192  void GetComponents(std::vector<FilePath::StringType>* components) const;
193
194  // Returns true if this FilePath is a strict parent of the |child|. Absolute
195  // and relative paths are accepted i.e. is /foo parent to /foo/bar and
196  // is foo parent to foo/bar. Does not convert paths to absolute, follow
197  // symlinks or directory navigation (e.g. ".."). A path is *NOT* its own
198  // parent.
199  bool IsParent(const FilePath& child) const;
200
201  // If IsParent(child) holds, appends to path (if non-NULL) the
202  // relative path to child and returns true.  For example, if parent
203  // holds "/Users/johndoe/Library/Application Support", child holds
204  // "/Users/johndoe/Library/Application Support/Google/Chrome/Default", and
205  // *path holds "/Users/johndoe/Library/Caches", then after
206  // parent.AppendRelativePath(child, path) is called *path will hold
207  // "/Users/johndoe/Library/Caches/Google/Chrome/Default".  Otherwise,
208  // returns false.
209  bool AppendRelativePath(const FilePath& child, FilePath* path) const;
210
211  // Returns a FilePath corresponding to the directory containing the path
212  // named by this object, stripping away the file component.  If this object
213  // only contains one component, returns a FilePath identifying
214  // kCurrentDirectory.  If this object already refers to the root directory,
215  // returns a FilePath identifying the root directory.
216  FilePath DirName() const WARN_UNUSED_RESULT;
217
218  // Returns a FilePath corresponding to the last path component of this
219  // object, either a file or a directory.  If this object already refers to
220  // the root directory, returns a FilePath identifying the root directory;
221  // this is the only situation in which BaseName will return an absolute path.
222  FilePath BaseName() const WARN_UNUSED_RESULT;
223
224  // Returns ".jpg" for path "C:\pics\jojo.jpg", or an empty string if
225  // the file has no extension.  If non-empty, Extension() will always start
226  // with precisely one ".".  The following code should always work regardless
227  // of the value of path.
228  // new_path = path.RemoveExtension().value().append(path.Extension());
229  // ASSERT(new_path == path.value());
230  // NOTE: this is different from the original file_util implementation which
231  // returned the extension without a leading "." ("jpg" instead of ".jpg")
232  StringType Extension() const;
233
234  // Returns "C:\pics\jojo" for path "C:\pics\jojo.jpg"
235  // NOTE: this is slightly different from the similar file_util implementation
236  // which returned simply 'jojo'.
237  FilePath RemoveExtension() const WARN_UNUSED_RESULT;
238
239  // Inserts |suffix| after the file name portion of |path| but before the
240  // extension.  Returns "" if BaseName() == "." or "..".
241  // Examples:
242  // path == "C:\pics\jojo.jpg" suffix == " (1)", returns "C:\pics\jojo (1).jpg"
243  // path == "jojo.jpg"         suffix == " (1)", returns "jojo (1).jpg"
244  // path == "C:\pics\jojo"     suffix == " (1)", returns "C:\pics\jojo (1)"
245  // path == "C:\pics.old\jojo" suffix == " (1)", returns "C:\pics.old\jojo (1)"
246  FilePath InsertBeforeExtension(
247      const StringType& suffix) const WARN_UNUSED_RESULT;
248  FilePath InsertBeforeExtensionASCII(
249      const base::StringPiece& suffix) const WARN_UNUSED_RESULT;
250
251  // Adds |extension| to |file_name|. Returns the current FilePath if
252  // |extension| is empty. Returns "" if BaseName() == "." or "..".
253  FilePath AddExtension(
254      const StringType& extension) const WARN_UNUSED_RESULT;
255
256  // Replaces the extension of |file_name| with |extension|.  If |file_name|
257  // does not have an extension, then |extension| is added.  If |extension| is
258  // empty, then the extension is removed from |file_name|.
259  // Returns "" if BaseName() == "." or "..".
260  FilePath ReplaceExtension(
261      const StringType& extension) const WARN_UNUSED_RESULT;
262
263  // Returns true if the file path matches the specified extension. The test is
264  // case insensitive. Don't forget the leading period if appropriate.
265  bool MatchesExtension(const StringType& extension) const;
266
267  // Returns a FilePath by appending a separator and the supplied path
268  // component to this object's path.  Append takes care to avoid adding
269  // excessive separators if this object's path already ends with a separator.
270  // If this object's path is kCurrentDirectory, a new FilePath corresponding
271  // only to |component| is returned.  |component| must be a relative path;
272  // it is an error to pass an absolute path.
273  FilePath Append(const StringType& component) const WARN_UNUSED_RESULT;
274  FilePath Append(const FilePath& component) const WARN_UNUSED_RESULT;
275
276  // Although Windows StringType is std::wstring, since the encoding it uses for
277  // paths is well defined, it can handle ASCII path components as well.
278  // Mac uses UTF8, and since ASCII is a subset of that, it works there as well.
279  // On Linux, although it can use any 8-bit encoding for paths, we assume that
280  // ASCII is a valid subset, regardless of the encoding, since many operating
281  // system paths will always be ASCII.
282  FilePath AppendASCII(const base::StringPiece& component)
283      const WARN_UNUSED_RESULT;
284
285  // Returns true if this FilePath contains an absolute path.  On Windows, an
286  // absolute path begins with either a drive letter specification followed by
287  // a separator character, or with two separator characters.  On POSIX
288  // platforms, an absolute path begins with a separator character.
289  bool IsAbsolute() const;
290
291  // Returns true if the patch ends with a path separator character.
292  bool EndsWithSeparator() const WARN_UNUSED_RESULT;
293
294  // Returns a copy of this FilePath that ends with a trailing separator. If
295  // the input path is empty, an empty FilePath will be returned.
296  FilePath AsEndingWithSeparator() const WARN_UNUSED_RESULT;
297
298  // Returns a copy of this FilePath that does not end with a trailing
299  // separator.
300  FilePath StripTrailingSeparators() const WARN_UNUSED_RESULT;
301
302  // Returns true if this FilePath contains any attempt to reference a parent
303  // directory (i.e. has a path component that is ".."
304  bool ReferencesParent() const;
305
306  // Return a Unicode human-readable version of this path.
307  // Warning: you can *not*, in general, go from a display name back to a real
308  // path.  Only use this when displaying paths to users, not just when you
309  // want to stuff a string16 into some other API.
310  string16 LossyDisplayName() const;
311
312  // Return the path as ASCII, or the empty string if the path is not ASCII.
313  // This should only be used for cases where the FilePath is representing a
314  // known-ASCII filename.
315  std::string MaybeAsASCII() const;
316
317  // Return the path as UTF-8.
318  //
319  // This function is *unsafe* as there is no way to tell what encoding is
320  // used in file names on POSIX systems other than Mac and Chrome OS,
321  // although UTF-8 is practically used everywhere these days. To mitigate
322  // the encoding issue, this function internally calls
323  // SysNativeMBToWide() on POSIX systems other than Mac and Chrome OS,
324  // per assumption that the current locale's encoding is used in file
325  // names, but this isn't a perfect solution.
326  //
327  // Once it becomes safe to to stop caring about non-UTF-8 file names,
328  // the SysNativeMBToWide() hack will be removed from the code, along
329  // with "Unsafe" in the function name.
330  std::string AsUTF8Unsafe() const;
331
332  // Similar to AsUTF8Unsafe, but returns UTF-16 instead.
333  string16 AsUTF16Unsafe() const;
334
335  // Older Chromium code assumes that paths are always wstrings.
336  // This function converts wstrings to FilePaths, and is
337  // useful to smooth porting that old code to the FilePath API.
338  // It has "Hack" its name so people feel bad about using it.
339  // http://code.google.com/p/chromium/issues/detail?id=24672
340  //
341  // If you are trying to be a good citizen and remove these, ask yourself:
342  // - Am I interacting with other Chrome code that deals with files?  Then
343  //   try to convert the API into using FilePath.
344  // - Am I interacting with OS-native calls?  Then use value() to get at an
345  //   OS-native string format.
346  // - Am I using well-known file names, like "config.ini"?  Then use the
347  //   ASCII functions (we require paths to always be supersets of ASCII).
348  // - Am I displaying a string to the user in some UI?  Then use the
349  //   LossyDisplayName() function, but keep in mind that you can't
350  //   ever use the result of that again as a path.
351  static FilePath FromWStringHack(const std::wstring& wstring);
352
353  // Returns a FilePath object from a path name in UTF-8. This function
354  // should only be used for cases where you are sure that the input
355  // string is UTF-8.
356  //
357  // Like AsUTF8Unsafe(), this function is unsafe. This function
358  // internally calls SysWideToNativeMB() on POSIX systems other than Mac
359  // and Chrome OS, to mitigate the encoding issue. See the comment at
360  // AsUTF8Unsafe() for details.
361  static FilePath FromUTF8Unsafe(const std::string& utf8);
362
363  // Similar to FromUTF8Unsafe, but accepts UTF-16 instead.
364  static FilePath FromUTF16Unsafe(const string16& utf16);
365
366  void WriteToPickle(Pickle* pickle) const;
367  bool ReadFromPickle(PickleIterator* iter);
368
369  // Normalize all path separators to backslash on Windows
370  // (if FILE_PATH_USES_WIN_SEPARATORS is true), or do nothing on POSIX systems.
371  FilePath NormalizePathSeparators() const;
372
373  // Compare two strings in the same way the file system does.
374  // Note that these always ignore case, even on file systems that are case-
375  // sensitive. If case-sensitive comparison is ever needed, add corresponding
376  // methods here.
377  // The methods are written as a static method so that they can also be used
378  // on parts of a file path, e.g., just the extension.
379  // CompareIgnoreCase() returns -1, 0 or 1 for less-than, equal-to and
380  // greater-than respectively.
381  static int CompareIgnoreCase(const StringType& string1,
382                               const StringType& string2);
383  static bool CompareEqualIgnoreCase(const StringType& string1,
384                                     const StringType& string2) {
385    return CompareIgnoreCase(string1, string2) == 0;
386  }
387  static bool CompareLessIgnoreCase(const StringType& string1,
388                                    const StringType& string2) {
389    return CompareIgnoreCase(string1, string2) < 0;
390  }
391
392#if defined(OS_MACOSX)
393  // Returns the string in the special canonical decomposed form as defined for
394  // HFS, which is close to, but not quite, decomposition form D. See
395  // http://developer.apple.com/mac/library/technotes/tn/tn1150.html#UnicodeSubtleties
396  // for further comments.
397  // Returns the epmty string if the conversion failed.
398  static StringType GetHFSDecomposedForm(const FilePath::StringType& string);
399
400  // Special UTF-8 version of FastUnicodeCompare. Cf:
401  // http://developer.apple.com/mac/library/technotes/tn/tn1150.html#StringComparisonAlgorithm
402  // IMPORTANT: The input strings must be in the special HFS decomposed form!
403  // (cf. above GetHFSDecomposedForm method)
404  static int HFSFastUnicodeCompare(const StringType& string1,
405                                   const StringType& string2);
406#endif
407
408 private:
409  // Remove trailing separators from this object.  If the path is absolute, it
410  // will never be stripped any more than to refer to the absolute root
411  // directory, so "////" will become "/", not "".  A leading pair of
412  // separators is never stripped, to support alternate roots.  This is used to
413  // support UNC paths on Windows.
414  void StripTrailingSeparatorsInternal();
415
416  StringType path_;
417};
418
419}  // namespace base
420
421// This is required by googletest to print a readable output on test failures.
422BASE_EXPORT extern void PrintTo(const base::FilePath& path, std::ostream* out);
423
424// Macros for string literal initialization of FilePath::CharType[], and for
425// using a FilePath::CharType[] in a printf-style format string.
426#if defined(OS_POSIX)
427#define FILE_PATH_LITERAL(x) x
428#define PRFilePath "s"
429#define PRFilePathLiteral "%s"
430#elif defined(OS_WIN)
431#define FILE_PATH_LITERAL(x) L ## x
432#define PRFilePath "ls"
433#define PRFilePathLiteral L"%ls"
434#endif  // OS_WIN
435
436// Provide a hash function so that hash_sets and maps can contain FilePath
437// objects.
438namespace BASE_HASH_NAMESPACE {
439#if defined(COMPILER_GCC)
440
441template<>
442struct hash<base::FilePath> {
443  size_t operator()(const base::FilePath& f) const {
444    return hash<base::FilePath::StringType>()(f.value());
445  }
446};
447
448#elif defined(COMPILER_MSVC)
449
450inline size_t hash_value(const base::FilePath& f) {
451  return hash_value(f.value());
452}
453
454#endif  // COMPILER
455
456}  // namespace BASE_HASH_NAMESPACE
457
458#endif  // BASE_FILES_FILE_PATH_H_
459