file_util_icu.cc revision c7f5f8508d98d5952d42ed7648c2a8f30a4da156
1// Copyright (c) 2009 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// File utilities that use the ICU library go in this file.
6
7#include "base/i18n/file_util_icu.h"
8
9#include "base/file_path.h"
10#include "base/scoped_ptr.h"
11#include "base/singleton.h"
12#include "base/string_util.h"
13#include "base/sys_string_conversions.h"
14#include "build/build_config.h"
15#include "unicode/coll.h"
16#include "unicode/uniset.h"
17
18namespace {
19
20class IllegalCharacters {
21 public:
22  bool contains(UChar32 ucs4) {
23    return !!set->contains(ucs4);
24  }
25
26  bool containsNone(const string16 &s) {
27    return !!set->containsNone(icu::UnicodeString(s.c_str(), s.size()));
28  }
29
30 private:
31  friend class Singleton<IllegalCharacters>;
32  friend struct DefaultSingletonTraits<IllegalCharacters>;
33
34  IllegalCharacters();
35  ~IllegalCharacters() { }
36
37  scoped_ptr<icu::UnicodeSet> set;
38
39  DISALLOW_COPY_AND_ASSIGN(IllegalCharacters);
40};
41
42IllegalCharacters::IllegalCharacters() {
43  UErrorCode status = U_ZERO_ERROR;
44  // Control characters, formatting characters, non-characters, and
45  // some printable ASCII characters regarded as dangerous ('"*/:<>?\\').
46  // See  http://blogs.msdn.com/michkap/archive/2006/11/03/941420.aspx
47  // and http://msdn2.microsoft.com/en-us/library/Aa365247.aspx
48  // TODO(jungshik): Revisit the set. ZWJ and ZWNJ are excluded because they
49  // are legitimate in Arabic and some S/SE Asian scripts. However, when used
50  // elsewhere, they can be confusing/problematic.
51  // Also, consider wrapping the set with our Singleton class to create and
52  // freeze it only once. Note that there's a trade-off between memory and
53  // speed.
54#if defined(WCHAR_T_IS_UTF16)
55  set.reset(new icu::UnicodeSet(icu::UnicodeString(
56      L"[[\"*/:<>?\\\\|][:Cc:][:Cf:] - [\u200c\u200d]]"), status));
57#else
58  set.reset(new icu::UnicodeSet(UNICODE_STRING_SIMPLE(
59      "[[\"*/:<>?\\\\|][:Cc:][:Cf:] - [\\u200c\\u200d]]").unescape(),
60      status));
61#endif
62  DCHECK(U_SUCCESS(status));
63  // Add non-characters. If this becomes a performance bottleneck by
64  // any chance, do not add these to |set| and change IsFilenameLegal()
65  // to check |ucs4 & 0xFFFEu == 0xFFFEu|, in addiition to calling
66  // containsNone().
67  set->add(0xFDD0, 0xFDEF);
68  for (int i = 0; i <= 0x10; ++i) {
69    int plane_base = 0x10000 * i;
70    set->add(plane_base + 0xFFFE, plane_base + 0xFFFF);
71  }
72  set->freeze();
73}
74
75class LocaleAwareComparator {
76 public:
77  LocaleAwareComparator() {
78    UErrorCode error_code = U_ZERO_ERROR;
79    // Use the default collator. The default locale should have been properly
80    // set by the time this constructor is called.
81    collator_.reset(icu::Collator::createInstance(error_code));
82    DCHECK(U_SUCCESS(error_code));
83    // Make it case-sensitive.
84    collator_->setStrength(icu::Collator::TERTIARY);
85    // Note: We do not set UCOL_NORMALIZATION_MODE attribute. In other words, we
86    // do not pay performance penalty to guarantee sort order correctness for
87    // non-FCD (http://unicode.org/notes/tn5/#FCD) file names. This should be a
88    // reasonable tradeoff because such file names should be rare and the sort
89    // order doesn't change much anyway.
90  }
91
92  // Note: A similar function is available in l10n_util.
93  // We cannot use it because base should not depend on l10n_util.
94  // TODO(yuzo): Move some of l10n_util to base.
95  int Compare(const string16& a, const string16& b) {
96    // We are not sure if Collator::compare is thread-safe.
97    // Use an AutoLock just in case.
98    AutoLock auto_lock(lock_);
99
100    UErrorCode error_code = U_ZERO_ERROR;
101    UCollationResult result = collator_->compare(
102        static_cast<const UChar*>(a.c_str()),
103        static_cast<int>(a.length()),
104        static_cast<const UChar*>(b.c_str()),
105        static_cast<int>(b.length()),
106        error_code);
107    DCHECK(U_SUCCESS(error_code));
108    return result;
109  }
110
111 private:
112  scoped_ptr<icu::Collator> collator_;
113  Lock lock_;
114  friend struct DefaultSingletonTraits<LocaleAwareComparator>;
115
116  DISALLOW_COPY_AND_ASSIGN(LocaleAwareComparator);
117};
118
119}  // namespace
120
121namespace file_util {
122
123bool IsFilenameLegal(const string16& file_name) {
124  return Singleton<IllegalCharacters>()->containsNone(file_name);
125}
126
127void ReplaceIllegalCharactersInPath(FilePath::StringType* file_name,
128                                    char replace_char) {
129  DCHECK(file_name);
130
131  DCHECK(!(Singleton<IllegalCharacters>()->contains(replace_char)));
132
133  // Remove leading and trailing whitespace.
134  TrimWhitespace(*file_name, TRIM_ALL, file_name);
135
136  IllegalCharacters* illegal = Singleton<IllegalCharacters>::get();
137  int cursor = 0;  // The ICU macros expect an int.
138  while (cursor < static_cast<int>(file_name->size())) {
139    int char_begin = cursor;
140    uint32 code_point;
141#if defined(OS_MACOSX)
142    // Mac uses UTF-8 encoding for filenames.
143    U8_NEXT(file_name->data(), cursor, static_cast<int>(file_name->length()),
144            code_point);
145#elif defined(OS_WIN)
146    // Windows uses UTF-16 encoding for filenames.
147    U16_NEXT(file_name->data(), cursor, static_cast<int>(file_name->length()),
148             code_point);
149#elif defined(OS_POSIX)
150    // Linux doesn't actually define an encoding. It basically allows anything
151    // except for a few special ASCII characters.
152    unsigned char cur_char = static_cast<unsigned char>((*file_name)[cursor++]);
153    if (cur_char >= 0x80)
154      continue;
155    code_point = cur_char;
156#else
157    NOTREACHED();
158#endif
159
160    if (illegal->contains(code_point)) {
161      file_name->replace(char_begin, cursor - char_begin, 1, replace_char);
162      // We just made the potentially multi-byte/word char into one that only
163      // takes one byte/word, so need to adjust the cursor to point to the next
164      // character again.
165      cursor = char_begin + 1;
166    }
167  }
168}
169
170bool LocaleAwareCompareFilenames(const FilePath& a, const FilePath& b) {
171#if defined(OS_WIN)
172  return Singleton<LocaleAwareComparator>()->Compare(a.value().c_str(),
173                                                     b.value().c_str()) < 0;
174
175#elif defined(OS_POSIX)
176  // On linux, the file system encoding is not defined. We assume
177  // SysNativeMBToWide takes care of it.
178  //
179  // ICU's collator can take strings in OS native encoding. But we convert the
180  // strings to UTF-16 ourselves to ensure conversion consistency.
181  // TODO(yuzo): Perhaps we should define SysNativeMBToUTF16?
182  return Singleton<LocaleAwareComparator>()->Compare(
183      WideToUTF16(base::SysNativeMBToWide(a.value().c_str())),
184      WideToUTF16(base::SysNativeMBToWide(b.value().c_str()))) < 0;
185#else
186  #error Not implemented on your system
187#endif
188}
189
190}  // namespace
191