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#include "chrome/browser/icon_loader.h"
6
7#include <windows.h>
8#include <shellapi.h>
9
10#include "base/bind.h"
11#include "base/message_loop/message_loop.h"
12#include "base/threading/thread.h"
13#include "third_party/skia/include/core/SkBitmap.h"
14#include "ui/gfx/icon_util.h"
15#include "ui/gfx/image/image_skia.h"
16#include "ui/gfx/size.h"
17
18// static
19IconGroupID IconLoader::ReadGroupIDFromFilepath(
20    const base::FilePath& filepath) {
21  if (!IsIconMutableFromFilepath(filepath))
22    return filepath.Extension();
23  return filepath.value();
24}
25
26bool IconLoader::IsIconMutableFromFilepath(const base::FilePath& filepath) {
27  return filepath.MatchesExtension(L".exe") ||
28         filepath.MatchesExtension(L".dll") ||
29         filepath.MatchesExtension(L".ico");
30}
31
32void IconLoader::ReadIcon() {
33  int size = 0;
34  switch (icon_size_) {
35    case IconLoader::SMALL:
36      size = SHGFI_SMALLICON;
37      break;
38    case IconLoader::NORMAL:
39      size = 0;
40      break;
41    case IconLoader::LARGE:
42      size = SHGFI_LARGEICON;
43      break;
44    default:
45      NOTREACHED();
46  }
47
48  image_.reset();
49
50  SHFILEINFO file_info = { 0 };
51  if (SHGetFileInfo(group_.c_str(), FILE_ATTRIBUTE_NORMAL, &file_info,
52                     sizeof(SHFILEINFO),
53                     SHGFI_ICON | size | SHGFI_USEFILEATTRIBUTES)) {
54    scoped_ptr<SkBitmap> bitmap(IconUtil::CreateSkBitmapFromHICON(
55        file_info.hIcon));
56    if (bitmap.get()) {
57      gfx::ImageSkia image_skia = gfx::ImageSkia::CreateFrom1xBitmap(*bitmap);
58      image_skia.MakeThreadSafe();
59      image_.reset(new gfx::Image(image_skia));
60      DestroyIcon(file_info.hIcon);
61    }
62  }
63
64  // Always notify the delegate, regardless of success.
65  target_message_loop_->PostTask(FROM_HERE,
66      base::Bind(&IconLoader::NotifyDelegate, this));
67}
68