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.
5 #include "content/child/notifications/notification_image_loader.h"
7 #include "base/logging.h"
8 #include "base/thread_task_runner_handle.h"
9 #include "content/child/child_thread_impl.h"
10 #include "content/child/image_decoder.h"
11 #include "third_party/WebKit/public/platform/Platform.h"
12 #include "third_party/WebKit/public/platform/WebURL.h"
13 #include "third_party/WebKit/public/platform/WebURLLoader.h"
14 #include "third_party/WebKit/public/platform/WebURLRequest.h"
15 #include "third_party/skia/include/core/SkBitmap.h"
18 using blink::WebURLError
;
19 using blink::WebURLLoader
;
20 using blink::WebURLRequest
;
24 NotificationImageLoader::NotificationImageLoader(
25 const ImageLoadCompletedCallback
& callback
,
26 const scoped_refptr
<base::SingleThreadTaskRunner
>& worker_task_runner
)
27 : callback_(callback
),
28 worker_task_runner_(worker_task_runner
),
32 NotificationImageLoader::~NotificationImageLoader() {
33 if (main_thread_task_runner_
)
34 DCHECK(main_thread_task_runner_
->BelongsToCurrentThread());
37 void NotificationImageLoader::StartOnMainThread(int notification_id
,
38 const GURL
& image_url
) {
39 DCHECK(ChildThreadImpl::current());
42 main_thread_task_runner_
= base::ThreadTaskRunnerHandle::Get();
43 notification_id_
= notification_id
;
45 WebURL
image_web_url(image_url
);
46 WebURLRequest
request(image_web_url
);
47 request
.setRequestContext(WebURLRequest::RequestContextImage
);
49 url_loader_
.reset(blink::Platform::current()->createURLLoader());
50 url_loader_
->loadAsynchronously(request
, this);
53 void NotificationImageLoader::didReceiveData(
57 int encoded_data_length
) {
59 DCHECK_GT(data_length
, 0);
61 buffer_
.insert(buffer_
.end(), data
, data
+ data_length
);
64 void NotificationImageLoader::didFinishLoading(
67 int64_t total_encoded_data_length
) {
70 RunCallbackOnWorkerThread();
73 void NotificationImageLoader::didFail(WebURLLoader
* loader
,
74 const WebURLError
& error
) {
78 RunCallbackOnWorkerThread();
81 void NotificationImageLoader::RunCallbackOnWorkerThread() {
85 SkBitmap icon
= GetDecodedImage();
87 if (worker_task_runner_
->BelongsToCurrentThread()) {
88 callback_
.Run(notification_id_
, icon
);
90 worker_task_runner_
->PostTask(
91 FROM_HERE
, base::Bind(callback_
, notification_id_
, icon
));
95 SkBitmap
NotificationImageLoader::GetDecodedImage() const {
100 ImageDecoder decoder
;
101 return decoder
.Decode(&buffer_
[0], buffer_
.size());
104 void NotificationImageLoader::DeleteOnCorrectThread() const {
105 if (!ChildThreadImpl::current()) {
106 main_thread_task_runner_
->DeleteSoon(FROM_HERE
, this);
113 } // namespace content