1// Copyright 2014 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/bitmap_fetcher/bitmap_fetcher.h"
6
7#include "content/public/browser/browser_thread.h"
8#include "net/url_request/url_fetcher.h"
9#include "net/url_request/url_request_context_getter.h"
10#include "net/url_request/url_request_status.h"
11
12namespace chrome {
13
14BitmapFetcher::BitmapFetcher(const GURL& url, BitmapFetcherDelegate* delegate)
15    : url_(url), delegate_(delegate) {
16}
17
18BitmapFetcher::~BitmapFetcher() {
19}
20
21void BitmapFetcher::Start(net::URLRequestContextGetter* request_context,
22                          const std::string& referrer,
23                          net::URLRequest::ReferrerPolicy referrer_policy,
24                          int load_flags) {
25  if (url_fetcher_ != NULL)
26    return;
27
28  url_fetcher_.reset(net::URLFetcher::Create(url_, net::URLFetcher::GET, this));
29  url_fetcher_->SetRequestContext(request_context);
30  url_fetcher_->SetReferrer(referrer);
31  url_fetcher_->SetReferrerPolicy(referrer_policy);
32  url_fetcher_->SetLoadFlags(load_flags);
33  url_fetcher_->Start();
34}
35
36// Methods inherited from URLFetcherDelegate.
37
38void BitmapFetcher::OnURLFetchComplete(const net::URLFetcher* source) {
39  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
40
41  if (source->GetStatus().status() != net::URLRequestStatus::SUCCESS) {
42    ReportFailure();
43    return;
44  }
45
46  std::string image_data;
47  source->GetResponseAsString(&image_data);
48  image_decoder_ =
49      new ImageDecoder(this, image_data, ImageDecoder::DEFAULT_CODEC);
50
51  // Call start to begin decoding.  The ImageDecoder will call OnImageDecoded
52  // with the data when it is done.
53  scoped_refptr<base::MessageLoopProxy> task_runner =
54      content::BrowserThread::GetMessageLoopProxyForThread(
55          content::BrowserThread::UI);
56  image_decoder_->Start(task_runner);
57}
58
59void BitmapFetcher::OnURLFetchDownloadProgress(const net::URLFetcher* source,
60                                               int64 current,
61                                               int64 total) {
62  // Do nothing here.
63}
64
65// Methods inherited from ImageDecoder::Delegate.
66
67void BitmapFetcher::OnImageDecoded(const ImageDecoder* decoder,
68                                   const SkBitmap& decoded_image) {
69  // Report success.
70  delegate_->OnFetchComplete(url_, &decoded_image);
71}
72
73void BitmapFetcher::OnDecodeImageFailed(const ImageDecoder* decoder) {
74  ReportFailure();
75}
76
77void BitmapFetcher::ReportFailure() {
78  delegate_->OnFetchComplete(url_, NULL);
79}
80
81}  // namespace chrome
82