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.
5 #include "base/mime_util.h"
16 #include "base/file_util.h"
17 #include "base/logging.h"
18 #include "base/message_loop.h"
19 #include "base/scoped_ptr.h"
20 #include "base/singleton.h"
21 #include "base/string_util.h"
22 #include "base/third_party/xdg_mime/xdgmime.h"
28 class MimeUtilConstants
{
31 // In seconds, specified by icon theme specs.
32 const int kUpdateInterval
;
34 // Store icon directories and their mtimes.
35 std::map
<FilePath
, int>* icon_dirs_
;
37 // Store icon formats.
38 std::vector
<std::string
> icon_formats_
;
40 // Store loaded icon_theme.
41 std::map
<std::string
, IconTheme
*>* icon_themes_
;
43 static const size_t kDefaultThemeNum
= 4;
46 IconTheme
* default_themes_
[kDefaultThemeNum
];
48 time_t last_check_time_
;
50 // This is set by DetectGtkTheme(). We cache it so that we can access the
51 // theme name from threads that aren't allowed to call
52 // gtk_settings_get_default().
53 std::string gtk_theme_name_
;
61 icon_formats_
.push_back(".png");
62 icon_formats_
.push_back(".svg");
63 icon_formats_
.push_back(".xpm");
65 for (size_t i
= 0; i
< kDefaultThemeNum
; ++i
)
66 default_themes_
[i
] = NULL
;
70 friend struct DefaultSingletonTraits
<MimeUtilConstants
>;
72 DISALLOW_COPY_AND_ASSIGN(MimeUtilConstants
);
75 // IconTheme represents an icon theme as defined by the xdg icon theme spec.
76 // Example themes on GNOME include 'Human' and 'Mist'.
77 // Example themes on KDE include 'crystalsvg' and 'kdeclassic'.
80 // A theme consists of multiple sub-directories, like '32x32' and 'scalable'.
83 // See spec for details.
96 size_t size
; // Nominal size of the icons in this directory.
97 Type type
; // Type of the icon size.
98 size_t max_size
; // Maximum size that the icons can be scaled to.
99 size_t min_size
; // Minimum size that the icons can be scaled to.
100 size_t threshold
; // Maximum difference from desired size. 2 by default.
103 explicit IconTheme(const std::string
& name
);
106 delete[] info_array_
;
109 // Returns the path to an icon with the name |icon_name| and a size of |size|
110 // pixels. If the icon does not exist, but |inherits| is true, then look for
111 // the icon in the parent theme.
112 FilePath
GetIconPath(const std::string
& icon_name
, int size
, bool inherits
);
114 // Load a theme with the name |theme_name| into memory. Returns null if theme
116 static IconTheme
* LoadTheme(const std::string
& theme_name
);
119 // Returns the path to an icon with the name |icon_name| in |subdir|.
120 FilePath
GetIconPathUnderSubdir(const std::string
& icon_name
,
121 const std::string
& subdir
);
123 // Whether the theme loaded properly.
125 return index_theme_loaded_
;
128 // Read and parse |file| which is usually named 'index.theme' per theme spec.
129 bool LoadIndexTheme(const FilePath
& file
);
131 // Checks to see if the icons in |info| matches |size| (in pixels). Returns
132 // 0 if they match, or the size difference in pixels.
133 size_t MatchesSize(SubDirInfo
* info
, size_t size
);
135 // Yet another function to read a line.
136 std::string
ReadLine(FILE* fp
);
138 // Set directories to search for icons to the comma-separated list |dirs|.
139 bool SetDirectories(const std::string
& dirs
);
141 bool index_theme_loaded_
; // True if an instance is properly loaded.
142 // store the scattered directories of this theme.
143 std::list
<FilePath
> dirs_
;
145 // store the subdirs of this theme and array index of |info_array_|.
146 std::map
<std::string
, int> subdirs_
;
147 SubDirInfo
* info_array_
; // List of sub-directories.
148 std::string inherits_
; // Name of the theme this one inherits from.
151 IconTheme::IconTheme(const std::string
& name
)
152 : index_theme_loaded_(false),
154 // Iterate on all icon directories to find directories of the specified
155 // theme and load the first encountered index.theme.
156 std::map
<FilePath
, int>::iterator iter
;
158 std::map
<FilePath
, int>* icon_dirs
=
159 Singleton
<MimeUtilConstants
>::get()->icon_dirs_
;
160 for (iter
= icon_dirs
->begin(); iter
!= icon_dirs
->end(); ++iter
) {
161 theme_path
= iter
->first
.Append(name
);
162 if (!file_util::DirectoryExists(theme_path
))
164 FilePath theme_index
= theme_path
.Append("index.theme");
165 if (!index_theme_loaded_
&& file_util::PathExists(theme_index
)) {
166 if (!LoadIndexTheme(theme_index
))
168 index_theme_loaded_
= true;
170 dirs_
.push_back(theme_path
);
174 FilePath
IconTheme::GetIconPath(const std::string
& icon_name
, int size
,
176 std::map
<std::string
, int>::iterator subdir_iter
;
179 for (subdir_iter
= subdirs_
.begin();
180 subdir_iter
!= subdirs_
.end();
182 SubDirInfo
* info
= &info_array_
[subdir_iter
->second
];
183 if (MatchesSize(info
, size
) == 0) {
184 icon_path
= GetIconPathUnderSubdir(icon_name
, subdir_iter
->first
);
185 if (!icon_path
.empty())
189 // Now looking for the mostly matched.
190 int min_delta_seen
= 9999;
192 for (subdir_iter
= subdirs_
.begin();
193 subdir_iter
!= subdirs_
.end();
195 SubDirInfo
* info
= &info_array_
[subdir_iter
->second
];
196 int delta
= abs(MatchesSize(info
, size
));
197 if (delta
< min_delta_seen
) {
198 FilePath path
= GetIconPathUnderSubdir(icon_name
, subdir_iter
->first
);
200 min_delta_seen
= delta
;
206 if (!icon_path
.empty() || !inherits
|| inherits_
== "")
209 IconTheme
* theme
= LoadTheme(inherits_
);
211 return theme
->GetIconPath(icon_name
, size
, inherits
);
216 IconTheme
* IconTheme::LoadTheme(const std::string
& theme_name
) {
217 scoped_ptr
<IconTheme
> theme
;
218 std::map
<std::string
, IconTheme
*>* icon_themes
=
219 Singleton
<MimeUtilConstants
>::get()->icon_themes_
;
220 if (icon_themes
->find(theme_name
) != icon_themes
->end()) {
221 theme
.reset((*icon_themes
)[theme_name
]);
223 theme
.reset(new IconTheme(theme_name
));
224 if (!theme
->IsValid())
226 (*icon_themes
)[theme_name
] = theme
.get();
228 return theme
.release();
231 FilePath
IconTheme::GetIconPathUnderSubdir(const std::string
& icon_name
,
232 const std::string
& subdir
) {
234 std::list
<FilePath
>::iterator dir_iter
;
235 std::vector
<std::string
>* icon_formats
=
236 &Singleton
<MimeUtilConstants
>::get()->icon_formats_
;
237 for (dir_iter
= dirs_
.begin(); dir_iter
!= dirs_
.end(); ++dir_iter
) {
238 for (size_t i
= 0; i
< icon_formats
->size(); ++i
) {
239 icon_path
= dir_iter
->Append(subdir
);
240 icon_path
= icon_path
.Append(icon_name
+ (*icon_formats
)[i
]);
241 if (file_util::PathExists(icon_path
))
248 bool IconTheme::LoadIndexTheme(const FilePath
& file
) {
249 FILE* fp
= file_util::OpenFile(file
, "r");
250 SubDirInfo
* current_info
= NULL
;
255 while (!feof(fp
) && !ferror(fp
)) {
256 std::string buf
= ReadLine(fp
);
261 TrimWhitespaceASCII(buf
, TRIM_ALL
, &entry
);
262 if (entry
.length() == 0 || entry
[0] == '#') {
263 // Blank line or Comment.
265 } else if (entry
[0] == '[' && info_array_
) {
267 std::string subdir
= entry
.substr(1, entry
.length() - 2);
268 if (subdirs_
.find(subdir
) != subdirs_
.end())
269 current_info
= &info_array_
[subdirs_
[subdir
]];
272 std::string key
, value
;
273 std::vector
<std::string
> r
;
274 SplitStringDontTrim(entry
, '=', &r
);
278 TrimWhitespaceASCII(r
[0], TRIM_ALL
, &key
);
279 for (size_t i
= 1; i
< r
.size(); i
++)
281 TrimWhitespaceASCII(value
, TRIM_ALL
, &value
);
285 current_info
->size
= atoi(value
.c_str());
286 } else if (key
== "Type") {
287 if (value
== "Fixed")
288 current_info
->type
= SubDirInfo::Fixed
;
289 else if (value
== "Scalable")
290 current_info
->type
= SubDirInfo::Scalable
;
291 else if (value
== "Threshold")
292 current_info
->type
= SubDirInfo::Threshold
;
293 } else if (key
== "MaxSize") {
294 current_info
->max_size
= atoi(value
.c_str());
295 } else if (key
== "MinSize") {
296 current_info
->min_size
= atoi(value
.c_str());
297 } else if (key
== "Threshold") {
298 current_info
->threshold
= atoi(value
.c_str());
301 if (key
.compare("Directories") == 0 && !info_array_
) {
302 if (!SetDirectories(value
)) break;
303 } else if (key
.compare("Inherits") == 0) {
304 if (value
!= "hicolor")
310 file_util::CloseFile(fp
);
311 return info_array_
!= NULL
;
314 size_t IconTheme::MatchesSize(SubDirInfo
* info
, size_t size
) {
315 if (info
->type
== SubDirInfo::Fixed
) {
316 return size
- info
->size
;
317 } else if (info
->type
== SubDirInfo::Scalable
) {
318 if (size
>= info
->min_size
&& size
<= info
->max_size
) {
321 return abs(size
- info
->min_size
) < abs(size
- info
->max_size
) ?
322 (size
- info
->min_size
) : (size
- info
->max_size
);
325 if (size
>= info
->size
- info
->threshold
&&
326 size
<= info
->size
+ info
->threshold
) {
329 return abs(size
- info
->size
- info
->threshold
) <
330 abs(size
- info
->size
+ info
->threshold
)
331 ? size
- info
->size
- info
->threshold
332 : size
- info
->size
+ info
->threshold
;
337 std::string
IconTheme::ReadLine(FILE* fp
) {
341 std::string result
= "";
342 const size_t kBufferSize
= 100;
343 char buffer
[kBufferSize
];
344 while ((fgets(buffer
, kBufferSize
- 1, fp
)) != NULL
) {
346 size_t len
= result
.length();
349 char end
= result
[len
- 1];
350 if (end
== '\n' || end
== '\0')
357 bool IconTheme::SetDirectories(const std::string
& dirs
) {
359 std::string::size_type pos
= 0, epos
;
361 while ((epos
= dirs
.find(',', pos
)) != std::string::npos
) {
362 TrimWhitespaceASCII(dirs
.substr(pos
, epos
- pos
), TRIM_ALL
, &dir
);
363 if (dir
.length() == 0) {
364 LOG(WARNING
) << "Invalid index.theme: blank subdir";
367 subdirs_
[dir
] = num
++;
370 TrimWhitespaceASCII(dirs
.substr(pos
), TRIM_ALL
, &dir
);
371 if (dir
.length() == 0) {
372 LOG(WARNING
) << "Invalid index.theme: blank subdir";
375 subdirs_
[dir
] = num
++;
376 info_array_
= new SubDirInfo
[num
];
380 // Make sure |dir| exists and add it to the list of icon directories.
381 void TryAddIconDir(const FilePath
& dir
) {
382 if (!file_util::DirectoryExists(dir
))
384 (*Singleton
<MimeUtilConstants
>::get()->icon_dirs_
)[dir
] = 0;
387 // For a xdg directory |dir|, add the appropriate icon sub-directories.
388 void AddXDGDataDir(const FilePath
& dir
) {
389 if (!file_util::DirectoryExists(dir
))
391 TryAddIconDir(dir
.Append("icons"));
392 TryAddIconDir(dir
.Append("pixmaps"));
395 // Add all the xdg icon directories.
397 Singleton
<MimeUtilConstants
>::get()->icon_dirs_
->clear();
398 const char* home
= getenv("HOME");
400 FilePath
legacy_data_dir(home
);
401 legacy_data_dir
= legacy_data_dir
.AppendASCII(".icons");
402 if (file_util::DirectoryExists(legacy_data_dir
))
403 TryAddIconDir(legacy_data_dir
);
405 const char* env
= getenv("XDG_DATA_HOME");
407 AddXDGDataDir(FilePath(env
));
409 FilePath
local_data_dir(home
);
410 local_data_dir
= local_data_dir
.AppendASCII(".local");
411 local_data_dir
= local_data_dir
.AppendASCII("share");
412 AddXDGDataDir(local_data_dir
);
415 env
= getenv("XDG_DATA_DIRS");
417 AddXDGDataDir(FilePath("/usr/local/share"));
418 AddXDGDataDir(FilePath("/usr/share"));
420 std::string xdg_data_dirs
= env
;
421 std::string::size_type pos
= 0, epos
;
422 while ((epos
= xdg_data_dirs
.find(':', pos
)) != std::string::npos
) {
423 AddXDGDataDir(FilePath(xdg_data_dirs
.substr(pos
, epos
- pos
)));
426 AddXDGDataDir(FilePath(xdg_data_dirs
.substr(pos
)));
430 // Per xdg theme spec, we should check the icon directories every so often for
431 // newly added icons. This isn't quite right.
432 void EnsureUpdated() {
434 gettimeofday(&t
, NULL
);
435 time_t now
= t
.tv_sec
;
436 MimeUtilConstants
* constants
= Singleton
<MimeUtilConstants
>::get();
438 if (constants
->last_check_time_
== 0) {
439 constants
->icon_dirs_
= new std::map
<FilePath
, int>;
440 constants
->icon_themes_
= new std::map
<std::string
, IconTheme
*>;
442 constants
->last_check_time_
= now
;
444 // TODO(thestig): something changed. start over. Upstream fix to Google
445 // Gadgets for Linux.
446 if (now
> constants
->last_check_time_
+ constants
->kUpdateInterval
) {
451 // Find a fallback icon if we cannot find it in the default theme.
452 FilePath
LookupFallbackIcon(const std::string
& icon_name
) {
454 MimeUtilConstants
* constants
= Singleton
<MimeUtilConstants
>::get();
455 std::map
<FilePath
, int>::iterator iter
;
456 std::map
<FilePath
, int>* icon_dirs
= constants
->icon_dirs_
;
457 std::vector
<std::string
>* icon_formats
= &constants
->icon_formats_
;
458 for (iter
= icon_dirs
->begin(); iter
!= icon_dirs
->end(); ++iter
) {
459 for (size_t i
= 0; i
< icon_formats
->size(); ++i
) {
460 icon
= iter
->first
.Append(icon_name
+ (*icon_formats
)[i
]);
461 if (file_util::PathExists(icon
))
468 // Initialize the list of default themes.
469 void InitDefaultThemes() {
470 IconTheme
** default_themes
=
471 Singleton
<MimeUtilConstants
>::get()->default_themes_
;
473 char* env
= getenv("KDE_FULL_SESSION");
476 std::string kde_default_theme
;
477 std::string kde_fallback_theme
;
479 // TODO(thestig): Figure out how to get the current icon theme on KDE.
480 // Setting stored in ~/.kde/share/config/kdeglobals under Icons -> Theme.
481 default_themes
[0] = NULL
;
483 // Try some reasonable defaults for KDE.
484 env
= getenv("KDE_SESSION_VERSION");
485 if (!env
|| env
[0] != '4') {
487 kde_default_theme
= "default.kde";
488 kde_fallback_theme
= "crystalsvg";
491 kde_default_theme
= "default.kde4";
492 kde_fallback_theme
= "oxygen";
494 default_themes
[1] = IconTheme::LoadTheme(kde_default_theme
);
495 default_themes
[2] = IconTheme::LoadTheme(kde_fallback_theme
);
497 // Assume it's Gnome and use GTK to figure out the theme.
498 default_themes
[1] = IconTheme::LoadTheme(
499 Singleton
<MimeUtilConstants
>::get()->gtk_theme_name_
);
500 default_themes
[2] = IconTheme::LoadTheme("gnome");
502 // hicolor needs to be last per icon theme spec.
503 default_themes
[3] = IconTheme::LoadTheme("hicolor");
505 for (size_t i
= 0; i
< MimeUtilConstants::kDefaultThemeNum
; i
++) {
506 if (default_themes
[i
] == NULL
)
508 // NULL out duplicate pointers.
509 for (size_t j
= i
+ 1; j
< MimeUtilConstants::kDefaultThemeNum
; j
++) {
510 if (default_themes
[j
] == default_themes
[i
])
511 default_themes
[j
] = NULL
;
516 // Try to find an icon with the name |icon_name| that's |size| pixels.
517 FilePath
LookupIconInDefaultTheme(const std::string
& icon_name
, int size
) {
519 MimeUtilConstants
* constants
= Singleton
<MimeUtilConstants
>::get();
520 std::map
<std::string
, IconTheme
*>* icon_themes
= constants
->icon_themes_
;
521 if (icon_themes
->size() == 0)
525 IconTheme
** default_themes
= constants
->default_themes_
;
526 for (size_t i
= 0; i
< MimeUtilConstants::kDefaultThemeNum
; i
++) {
527 if (default_themes
[i
]) {
528 icon_path
= default_themes
[i
]->GetIconPath(icon_name
, size
, true);
529 if (!icon_path
.empty())
533 return LookupFallbackIcon(icon_name
);
536 MimeUtilConstants::~MimeUtilConstants() {
539 for (size_t i
= 0; i
< kDefaultThemeNum
; i
++)
540 delete default_themes_
[i
];
545 namespace mime_util
{
547 std::string
GetFileMimeType(const FilePath
& filepath
) {
548 return xdg_mime_get_mime_type_from_file_name(filepath
.value().c_str());
551 std::string
GetDataMimeType(const std::string
& data
) {
552 return xdg_mime_get_mime_type_for_data(data
.data(), data
.length(), NULL
);
555 void DetectGtkTheme() {
556 // If the theme name is already loaded, do nothing. Chrome doesn't respond
557 // to changes in the system theme, so we never need to set this more than
559 if (!Singleton
<MimeUtilConstants
>::get()->gtk_theme_name_
.empty())
562 // We should only be called on the UI thread.
563 DCHECK_EQ(MessageLoop::TYPE_UI
, MessageLoop::current()->type());
565 gchar
* gtk_theme_name
;
566 g_object_get(gtk_settings_get_default(),
567 "gtk-icon-theme-name",
568 >k_theme_name
, NULL
);
569 Singleton
<MimeUtilConstants
>::get()->gtk_theme_name_
.assign(gtk_theme_name
);
570 g_free(gtk_theme_name
);
573 FilePath
GetMimeIcon(const std::string
& mime_type
, size_t size
) {
574 std::vector
<std::string
> icon_names
;
575 std::string icon_name
;
578 const char* icon
= xdg_mime_get_icon(mime_type
.c_str());
579 icon_name
= std::string(icon
? icon
: "");
580 if (icon_name
.length())
581 icon_names
.push_back(icon_name
);
583 // For text/plain, try text-plain.
584 icon_name
= mime_type
;
585 for (size_t i
= icon_name
.find('/', 0); i
!= std::string::npos
;
586 i
= icon_name
.find('/', i
+ 1)) {
589 icon_names
.push_back(icon_name
);
590 // Also try gnome-mime-text-plain.
591 icon_names
.push_back("gnome-mime-" + icon_name
);
593 // Try "deb" for "application/x-deb" in KDE 3.
594 icon_name
= mime_type
.substr(mime_type
.find("/x-") + 3);
595 icon_names
.push_back(icon_name
);
597 // Try generic name like text-x-generic.
598 icon_name
= mime_type
.substr(0, mime_type
.find('/')) + "-x-generic";
599 icon_names
.push_back(icon_name
);
602 icon_names
.push_back("unknown");
604 for (size_t i
= 0; i
< icon_names
.size(); i
++) {
605 if (icon_names
[i
][0] == '/') {
606 icon_file
= FilePath(icon_names
[i
]);
607 if (file_util::PathExists(icon_file
))
610 icon_file
= LookupIconInDefaultTheme(icon_names
[i
], size
);
611 if (!icon_file
.empty())
618 } // namespace mime_util