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// As a precaution against premature truncation, paths can't contain NULs.
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.267 ("Pathname")
87//    and 4.12 ("Pathname Resolution"), available at:
88//    http://www.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_267
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
107#include <iosfwd>
108#include <string>
109#include <vector>
110
111#include "base/base_export.h"
112#include "base/compiler_specific.h"
113#include "base/containers/hash_tables.h"
114#include "base/macros.h"
115#include "base/strings/string16.h"
116#include "base/strings/string_piece.h"
117#include "build/build_config.h"
118
119// Windows-style drive letter support and pathname separator characters can be
120// enabled and disabled independently, to aid testing.  These #defines are
121// here so that the same setting can be used in both the implementation and
122// in the unit test.
123#if defined(OS_WIN)
124#define FILE_PATH_USES_DRIVE_LETTERS
125#define FILE_PATH_USES_WIN_SEPARATORS
126#endif  // OS_WIN
127
128// To print path names portably use PRIsFP (based on PRIuS and friends from
129// C99 and format_macros.h) like this:
130// base::StringPrintf("Path is %" PRIsFP ".\n", path.value().c_str());
131#if defined(OS_POSIX)
132#define PRIsFP "s"
133#elif defined(OS_WIN)
134#define PRIsFP "ls"
135#endif  // OS_WIN
136
137namespace base {
138
139class Pickle;
140class PickleIterator;
141
142// An abstraction to isolate users from the differences between native
143// pathnames on different platforms.
144class BASE_EXPORT FilePath {
145 public:
146#if defined(OS_POSIX)
147  // On most platforms, native pathnames are char arrays, and the encoding
148  // may or may not be specified.  On Mac OS X, native pathnames are encoded
149  // in UTF-8.
150  typedef std::string StringType;
151#elif defined(OS_WIN)
152  // On Windows, for Unicode-aware applications, native pathnames are wchar_t
153  // arrays encoded in UTF-16.
154  typedef std::wstring StringType;
155#endif  // OS_WIN
156
157  typedef BasicStringPiece<StringType> StringPieceType;
158  typedef StringType::value_type CharType;
159
160  // Null-terminated array of separators used to separate components in
161  // hierarchical paths.  Each character in this array is a valid separator,
162  // but kSeparators[0] is treated as the canonical separator and will be used
163  // when composing pathnames.
164  static const CharType kSeparators[];
165
166  // arraysize(kSeparators).
167  static const size_t kSeparatorsLength;
168
169  // A special path component meaning "this directory."
170  static const CharType kCurrentDirectory[];
171
172  // A special path component meaning "the parent directory."
173  static const CharType kParentDirectory[];
174
175  // The character used to identify a file extension.
176  static const CharType kExtensionSeparator;
177
178  FilePath();
179  FilePath(const FilePath& that);
180  explicit FilePath(StringPieceType path);
181  ~FilePath();
182  FilePath& operator=(const FilePath& that);
183
184  bool operator==(const FilePath& that) const;
185
186  bool operator!=(const FilePath& that) const;
187
188  // Required for some STL containers and operations
189  bool operator<(const FilePath& that) const {
190    return path_ < that.path_;
191  }
192
193  const StringType& value() const { return path_; }
194
195  bool empty() const { return path_.empty(); }
196
197  void clear() { path_.clear(); }
198
199  // Returns true if |character| is in kSeparators.
200  static bool IsSeparator(CharType character);
201
202  // Returns a vector of all of the components of the provided path. It is
203  // equivalent to calling DirName().value() on the path's root component,
204  // and BaseName().value() on each child component.
205  //
206  // To make sure this is lossless so we can differentiate absolute and
207  // relative paths, the root slash will be included even though no other
208  // slashes will be. The precise behavior is:
209  //
210  // Posix:  "/foo/bar"  ->  [ "/", "foo", "bar" ]
211  // Windows:  "C:\foo\bar"  ->  [ "C:", "\\", "foo", "bar" ]
212  void GetComponents(std::vector<FilePath::StringType>* components) const;
213
214  // Returns true if this FilePath is a strict parent of the |child|. Absolute
215  // and relative paths are accepted i.e. is /foo parent to /foo/bar and
216  // is foo parent to foo/bar. Does not convert paths to absolute, follow
217  // symlinks or directory navigation (e.g. ".."). A path is *NOT* its own
218  // parent.
219  bool IsParent(const FilePath& child) const;
220
221  // If IsParent(child) holds, appends to path (if non-NULL) the
222  // relative path to child and returns true.  For example, if parent
223  // holds "/Users/johndoe/Library/Application Support", child holds
224  // "/Users/johndoe/Library/Application Support/Google/Chrome/Default", and
225  // *path holds "/Users/johndoe/Library/Caches", then after
226  // parent.AppendRelativePath(child, path) is called *path will hold
227  // "/Users/johndoe/Library/Caches/Google/Chrome/Default".  Otherwise,
228  // returns false.
229  bool AppendRelativePath(const FilePath& child, FilePath* path) const;
230
231  // Returns a FilePath corresponding to the directory containing the path
232  // named by this object, stripping away the file component.  If this object
233  // only contains one component, returns a FilePath identifying
234  // kCurrentDirectory.  If this object already refers to the root directory,
235  // returns a FilePath identifying the root directory.
236  FilePath DirName() const WARN_UNUSED_RESULT;
237
238  // Returns a FilePath corresponding to the last path component of this
239  // object, either a file or a directory.  If this object already refers to
240  // the root directory, returns a FilePath identifying the root directory;
241  // this is the only situation in which BaseName will return an absolute path.
242  FilePath BaseName() const WARN_UNUSED_RESULT;
243
244  // Returns ".jpg" for path "C:\pics\jojo.jpg", or an empty string if
245  // the file has no extension.  If non-empty, Extension() will always start
246  // with precisely one ".".  The following code should always work regardless
247  // of the value of path.  For common double-extensions like .tar.gz and
248  // .user.js, this method returns the combined extension.  For a single
249  // component, use FinalExtension().
250  // new_path = path.RemoveExtension().value().append(path.Extension());
251  // ASSERT(new_path == path.value());
252  // NOTE: this is different from the original file_util implementation which
253  // returned the extension without a leading "." ("jpg" instead of ".jpg")
254  StringType Extension() const WARN_UNUSED_RESULT;
255
256  // Returns the path's file extension, as in Extension(), but will
257  // never return a double extension.
258  //
259  // TODO(davidben): Check all our extension-sensitive code to see if
260  // we can rename this to Extension() and the other to something like
261  // LongExtension(), defaulting to short extensions and leaving the
262  // long "extensions" to logic like base::GetUniquePathNumber().
263  StringType FinalExtension() const WARN_UNUSED_RESULT;
264
265  // Returns "C:\pics\jojo" for path "C:\pics\jojo.jpg"
266  // NOTE: this is slightly different from the similar file_util implementation
267  // which returned simply 'jojo'.
268  FilePath RemoveExtension() const WARN_UNUSED_RESULT;
269
270  // Removes the path's file extension, as in RemoveExtension(), but
271  // ignores double extensions.
272  FilePath RemoveFinalExtension() const WARN_UNUSED_RESULT;
273
274  // Inserts |suffix| after the file name portion of |path| but before the
275  // extension.  Returns "" if BaseName() == "." or "..".
276  // Examples:
277  // path == "C:\pics\jojo.jpg" suffix == " (1)", returns "C:\pics\jojo (1).jpg"
278  // path == "jojo.jpg"         suffix == " (1)", returns "jojo (1).jpg"
279  // path == "C:\pics\jojo"     suffix == " (1)", returns "C:\pics\jojo (1)"
280  // path == "C:\pics.old\jojo" suffix == " (1)", returns "C:\pics.old\jojo (1)"
281  FilePath InsertBeforeExtension(
282      StringPieceType suffix) const WARN_UNUSED_RESULT;
283  FilePath InsertBeforeExtensionASCII(
284      StringPiece suffix) const WARN_UNUSED_RESULT;
285
286  // Adds |extension| to |file_name|. Returns the current FilePath if
287  // |extension| is empty. Returns "" if BaseName() == "." or "..".
288  FilePath AddExtension(StringPieceType extension) const WARN_UNUSED_RESULT;
289
290  // Replaces the extension of |file_name| with |extension|.  If |file_name|
291  // does not have an extension, then |extension| is added.  If |extension| is
292  // empty, then the extension is removed from |file_name|.
293  // Returns "" if BaseName() == "." or "..".
294  FilePath ReplaceExtension(StringPieceType extension) const WARN_UNUSED_RESULT;
295
296  // Returns true if the file path matches the specified extension. The test is
297  // case insensitive. Don't forget the leading period if appropriate.
298  bool MatchesExtension(StringPieceType extension) const;
299
300  // Returns a FilePath by appending a separator and the supplied path
301  // component to this object's path.  Append takes care to avoid adding
302  // excessive separators if this object's path already ends with a separator.
303  // If this object's path is kCurrentDirectory, a new FilePath corresponding
304  // only to |component| is returned.  |component| must be a relative path;
305  // it is an error to pass an absolute path.
306  FilePath Append(StringPieceType component) const WARN_UNUSED_RESULT;
307  FilePath Append(const FilePath& component) const WARN_UNUSED_RESULT;
308
309  // Although Windows StringType is std::wstring, since the encoding it uses for
310  // paths is well defined, it can handle ASCII path components as well.
311  // Mac uses UTF8, and since ASCII is a subset of that, it works there as well.
312  // On Linux, although it can use any 8-bit encoding for paths, we assume that
313  // ASCII is a valid subset, regardless of the encoding, since many operating
314  // system paths will always be ASCII.
315  FilePath AppendASCII(StringPiece component) const WARN_UNUSED_RESULT;
316
317  // Returns true if this FilePath contains an absolute path.  On Windows, an
318  // absolute path begins with either a drive letter specification followed by
319  // a separator character, or with two separator characters.  On POSIX
320  // platforms, an absolute path begins with a separator character.
321  bool IsAbsolute() const;
322
323  // Returns true if the patch ends with a path separator character.
324  bool EndsWithSeparator() const WARN_UNUSED_RESULT;
325
326  // Returns a copy of this FilePath that ends with a trailing separator. If
327  // the input path is empty, an empty FilePath will be returned.
328  FilePath AsEndingWithSeparator() const WARN_UNUSED_RESULT;
329
330  // Returns a copy of this FilePath that does not end with a trailing
331  // separator.
332  FilePath StripTrailingSeparators() const WARN_UNUSED_RESULT;
333
334  // Returns true if this FilePath contains an attempt to reference a parent
335  // directory (e.g. has a path component that is "..").
336  bool ReferencesParent() const;
337
338  // Return a Unicode human-readable version of this path.
339  // Warning: you can *not*, in general, go from a display name back to a real
340  // path.  Only use this when displaying paths to users, not just when you
341  // want to stuff a string16 into some other API.
342  string16 LossyDisplayName() const;
343
344  // Return the path as ASCII, or the empty string if the path is not ASCII.
345  // This should only be used for cases where the FilePath is representing a
346  // known-ASCII filename.
347  std::string MaybeAsASCII() const;
348
349  // Return the path as UTF-8.
350  //
351  // This function is *unsafe* as there is no way to tell what encoding is
352  // used in file names on POSIX systems other than Mac and Chrome OS,
353  // although UTF-8 is practically used everywhere these days. To mitigate
354  // the encoding issue, this function internally calls
355  // SysNativeMBToWide() on POSIX systems other than Mac and Chrome OS,
356  // per assumption that the current locale's encoding is used in file
357  // names, but this isn't a perfect solution.
358  //
359  // Once it becomes safe to to stop caring about non-UTF-8 file names,
360  // the SysNativeMBToWide() hack will be removed from the code, along
361  // with "Unsafe" in the function name.
362  std::string AsUTF8Unsafe() const;
363
364  // Similar to AsUTF8Unsafe, but returns UTF-16 instead.
365  string16 AsUTF16Unsafe() const;
366
367  // Returns a FilePath object from a path name in UTF-8. This function
368  // should only be used for cases where you are sure that the input
369  // string is UTF-8.
370  //
371  // Like AsUTF8Unsafe(), this function is unsafe. This function
372  // internally calls SysWideToNativeMB() on POSIX systems other than Mac
373  // and Chrome OS, to mitigate the encoding issue. See the comment at
374  // AsUTF8Unsafe() for details.
375  static FilePath FromUTF8Unsafe(const std::string& utf8);
376
377  // Similar to FromUTF8Unsafe, but accepts UTF-16 instead.
378  static FilePath FromUTF16Unsafe(const string16& utf16);
379
380  void WriteToPickle(Pickle* pickle) const;
381  bool ReadFromPickle(PickleIterator* iter);
382
383  // Normalize all path separators to backslash on Windows
384  // (if FILE_PATH_USES_WIN_SEPARATORS is true), or do nothing on POSIX systems.
385  FilePath NormalizePathSeparators() const;
386
387  // Normalize all path separattors to given type on Windows
388  // (if FILE_PATH_USES_WIN_SEPARATORS is true), or do nothing on POSIX systems.
389  FilePath NormalizePathSeparatorsTo(CharType separator) const;
390
391  // Compare two strings in the same way the file system does.
392  // Note that these always ignore case, even on file systems that are case-
393  // sensitive. If case-sensitive comparison is ever needed, add corresponding
394  // methods here.
395  // The methods are written as a static method so that they can also be used
396  // on parts of a file path, e.g., just the extension.
397  // CompareIgnoreCase() returns -1, 0 or 1 for less-than, equal-to and
398  // greater-than respectively.
399  static int CompareIgnoreCase(StringPieceType string1,
400                               StringPieceType string2);
401  static bool CompareEqualIgnoreCase(StringPieceType string1,
402                                     StringPieceType string2) {
403    return CompareIgnoreCase(string1, string2) == 0;
404  }
405  static bool CompareLessIgnoreCase(StringPieceType string1,
406                                    StringPieceType string2) {
407    return CompareIgnoreCase(string1, string2) < 0;
408  }
409
410#if defined(OS_MACOSX)
411  // Returns the string in the special canonical decomposed form as defined for
412  // HFS, which is close to, but not quite, decomposition form D. See
413  // http://developer.apple.com/mac/library/technotes/tn/tn1150.html#UnicodeSubtleties
414  // for further comments.
415  // Returns the epmty string if the conversion failed.
416  static StringType GetHFSDecomposedForm(StringPieceType string);
417
418  // Special UTF-8 version of FastUnicodeCompare. Cf:
419  // http://developer.apple.com/mac/library/technotes/tn/tn1150.html#StringComparisonAlgorithm
420  // IMPORTANT: The input strings must be in the special HFS decomposed form!
421  // (cf. above GetHFSDecomposedForm method)
422  static int HFSFastUnicodeCompare(StringPieceType string1,
423                                   StringPieceType string2);
424#endif
425
426#if defined(OS_ANDROID)
427  // On android, file selection dialog can return a file with content uri
428  // scheme(starting with content://). Content uri needs to be opened with
429  // ContentResolver to guarantee that the app has appropriate permissions
430  // to access it.
431  // Returns true if the path is a content uri, or false otherwise.
432  bool IsContentUri() const;
433#endif
434
435 private:
436  // Remove trailing separators from this object.  If the path is absolute, it
437  // will never be stripped any more than to refer to the absolute root
438  // directory, so "////" will become "/", not "".  A leading pair of
439  // separators is never stripped, to support alternate roots.  This is used to
440  // support UNC paths on Windows.
441  void StripTrailingSeparatorsInternal();
442
443  StringType path_;
444};
445
446// This is required by googletest to print a readable output on test failures.
447// This is declared here for use in gtest-based unit tests but is defined in
448// the test_support_base target. Depend on that to use this in your unit test.
449// This should not be used in production code - call ToString() instead.
450void PrintTo(const FilePath& path, std::ostream* out);
451
452}  // namespace base
453
454// Macros for string literal initialization of FilePath::CharType[], and for
455// using a FilePath::CharType[] in a printf-style format string.
456#if defined(OS_POSIX)
457#define FILE_PATH_LITERAL(x) x
458#define PRFilePath "s"
459#elif defined(OS_WIN)
460#define FILE_PATH_LITERAL(x) L ## x
461#define PRFilePath "ls"
462#endif  // OS_WIN
463
464// Provide a hash function so that hash_sets and maps can contain FilePath
465// objects.
466namespace BASE_HASH_NAMESPACE {
467
468template<>
469struct hash<base::FilePath> {
470  size_t operator()(const base::FilePath& f) const {
471    return hash<base::FilePath::StringType>()(f.value());
472  }
473};
474
475}  // namespace BASE_HASH_NAMESPACE
476
477#endif  // BASE_FILES_FILE_PATH_H_
478