Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(451)

Side by Side Diff: pdf/url_loader_wrapper_impl.cc

Issue 2455403002: Reland of Improve linearized pdf load/show time. (Closed)
Patch Set: Fix memory leaks Created 4 years, 1 month ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 // Copyright 2016 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 "pdf/url_loader_wrapper_impl.h"
6
7 #include "base/logging.h"
8 #include "base/memory/ptr_util.h"
9 #include "base/strings/string_util.h"
10 #include "base/strings/stringprintf.h"
11 #include "net/http/http_util.h"
12 #include "pdf/timer.h"
13 #include "ppapi/c/pp_errors.h"
14 #include "ppapi/cpp/logging.h"
15 #include "ppapi/cpp/url_request_info.h"
16 #include "ppapi/cpp/url_response_info.h"
17
18 namespace chrome_pdf {
19
20 namespace {
21 // We should read with delay to prevent block UI thread, and reduce CPU usage.
22 const int kReadDelayMs = 2;
23
24 pp::URLRequestInfo MakeRangeRequest(pp::Instance* plugin_instance,
25 const std::string& url,
26 const std::string& referrer_url,
27 uint32_t position,
28 uint32_t size) {
29 pp::URLRequestInfo request(plugin_instance);
30 request.SetURL(url);
31 request.SetMethod("GET");
32 request.SetFollowRedirects(false);
33 request.SetCustomReferrerURL(referrer_url);
34
35 // According to rfc2616, byte range specifies position of the first and last
36 // bytes in the requested range inclusively. Therefore we should subtract 1
37 // from the position + size, to get index of the last byte that needs to be
38 // downloaded.
39 std::string str_header =
40 base::StringPrintf("Range: bytes=%d-%d", position, position + size - 1);
41 pp::Var header(str_header.c_str());
42 request.SetHeaders(header);
43
44 return request;
45 }
46
47 bool GetByteRangeFromStr(const std::string& content_range_str,
48 int* start,
49 int* end) {
50 std::string range = content_range_str;
51 if (!base::StartsWith(range, "bytes", base::CompareCase::INSENSITIVE_ASCII))
52 return false;
53
54 range = range.substr(strlen("bytes"));
55 std::string::size_type pos = range.find('-');
56 std::string range_end;
57 if (pos != std::string::npos)
58 range_end = range.substr(pos + 1);
59 base::TrimWhitespaceASCII(range, base::TRIM_LEADING, &range);
60 base::TrimWhitespaceASCII(range_end, base::TRIM_LEADING, &range_end);
61 *start = atoi(range.c_str());
62 *end = atoi(range_end.c_str());
63 return true;
64 }
65
66 // If the headers have a byte-range response, writes the start and end
67 // positions and returns true if at least the start position was parsed.
68 // The end position will be set to 0 if it was not found or parsed from the
69 // response.
70 // Returns false if not even a start position could be parsed.
71 bool GetByteRangeFromHeaders(const std::string& headers, int* start, int* end) {
72 net::HttpUtil::HeadersIterator it(headers.begin(), headers.end(), "\n");
73 while (it.GetNext()) {
74 if (base::LowerCaseEqualsASCII(it.name(), "content-range")) {
75 if (GetByteRangeFromStr(it.values().c_str(), start, end))
76 return true;
77 }
78 }
79 return false;
80 }
81
82 bool IsDoubleEndLineAtEnd(const char* buffer, int size) {
83 if (size < 2)
84 return false;
85
86 if (buffer[size - 1] == '\n' && buffer[size - 2] == '\n')
87 return true;
88
89 if (size < 4)
90 return false;
91
92 return buffer[size - 1] == '\n' && buffer[size - 2] == '\r' &&
93 buffer[size - 3] == '\n' && buffer[size - 4] == '\r';
94 }
95
96 } // namespace
97
98 class URLLoaderWrapperImpl::ReadStarter : public Timer {
99 public:
100 explicit ReadStarter(URLLoaderWrapperImpl* owner)
101 : Timer(kReadDelayMs), owner_(owner) {}
102 ~ReadStarter() override {}
103
104 // Timer overrides:
105 void OnTimer() override { owner_->ReadResponseBodyImpl(); }
106
107 private:
108 URLLoaderWrapperImpl* owner_;
109 };
110
111 URLLoaderWrapperImpl::URLLoaderWrapperImpl(pp::Instance* plugin_instance,
112 const pp::URLLoader& url_loader)
113 : plugin_instance_(plugin_instance),
114 url_loader_(url_loader),
115 callback_factory_(this) {
116 SetHeadersFromLoader();
117 }
118
119 URLLoaderWrapperImpl::~URLLoaderWrapperImpl() {
120 Close();
121 // We should call callbacks to prevent memory leaks.
122 // The objects, which create its, should be destroyed at this moments.
123 if (!did_open_callback_.IsOptional())
124 did_open_callback_.RunAndClear(-1);
125 if (!did_read_callback_.IsOptional())
126 did_read_callback_.RunAndClear(-1);
127 }
128
129 int URLLoaderWrapperImpl::GetContentLength() const {
130 return content_length_;
131 }
132
133 bool URLLoaderWrapperImpl::IsAcceptRangesBytes() const {
134 return accept_ranges_bytes_;
135 }
136
137 bool URLLoaderWrapperImpl::IsContentEncoded() const {
138 return content_encoded_;
139 }
140
141 std::string URLLoaderWrapperImpl::GetContentType() const {
142 return content_type_;
143 }
144 std::string URLLoaderWrapperImpl::GetContentDisposition() const {
145 return content_disposition_;
146 }
147
148 int URLLoaderWrapperImpl::GetStatusCode() const {
149 return url_loader_.GetResponseInfo().GetStatusCode();
150 }
151
152 bool URLLoaderWrapperImpl::IsMultipart() const {
153 return is_multipart_;
154 }
155
156 bool URLLoaderWrapperImpl::GetByteRange(int* start, int* end) const {
157 DCHECK(start);
158 DCHECK(end);
159 *start = byte_range_.start();
160 *end = byte_range_.end();
161 return byte_range_.IsValid();
162 }
163
164 bool URLLoaderWrapperImpl::GetDownloadProgress(
165 int64_t* bytes_received,
166 int64_t* total_bytes_to_be_received) const {
167 return url_loader_.GetDownloadProgress(bytes_received,
168 total_bytes_to_be_received);
169 }
170
171 void URLLoaderWrapperImpl::Close() {
172 url_loader_.Close();
173 read_starter_.reset();
174 }
175
176 void URLLoaderWrapperImpl::OpenRange(const std::string& url,
177 const std::string& referrer_url,
178 uint32_t position,
179 uint32_t size,
180 const pp::CompletionCallback& cc) {
181 did_open_callback_ = cc;
182 pp::CompletionCallback callback =
183 callback_factory_.NewCallback(&URLLoaderWrapperImpl::DidOpen);
184 int rv = url_loader_.Open(
185 MakeRangeRequest(plugin_instance_, url, referrer_url, position, size),
186 callback);
187 if (rv != PP_OK_COMPLETIONPENDING)
188 callback.Run(rv);
189 }
190
191 void URLLoaderWrapperImpl::ReadResponseBody(char* buffer,
192 int buffer_size,
193 const pp::CompletionCallback& cc) {
194 did_read_callback_ = cc;
195 buffer_ = buffer;
196 buffer_size_ = buffer_size;
197 read_starter_ = base::MakeUnique<ReadStarter>(this);
198 }
199
200 void URLLoaderWrapperImpl::ReadResponseBodyImpl() {
201 read_starter_.reset();
202 pp::CompletionCallback callback =
203 callback_factory_.NewCallback(&URLLoaderWrapperImpl::DidRead);
204 int rv = url_loader_.ReadResponseBody(buffer_, buffer_size_, callback);
205 if (rv != PP_OK_COMPLETIONPENDING) {
206 callback.Run(rv);
207 }
208 }
209
210 void URLLoaderWrapperImpl::SetResponseHeaders(
211 const std::string& response_headers) {
212 response_headers_ = response_headers;
213 ParseHeaders();
214 }
215
216 void URLLoaderWrapperImpl::ParseHeaders() {
217 content_length_ = -1;
218 accept_ranges_bytes_ = false;
219 content_encoded_ = false;
220 content_type_.clear();
221 content_disposition_.clear();
222 multipart_boundary_.clear();
223 byte_range_ = gfx::Range::InvalidRange();
224 is_multipart_ = false;
225
226 if (response_headers_.empty())
227 return;
228
229 net::HttpUtil::HeadersIterator it(response_headers_.begin(),
230 response_headers_.end(), "\n");
231 while (it.GetNext()) {
232 if (base::LowerCaseEqualsASCII(it.name(), "content-length")) {
233 content_length_ = atoi(it.values().c_str());
234 } else if (base::LowerCaseEqualsASCII(it.name(), "accept-ranges")) {
235 accept_ranges_bytes_ = base::LowerCaseEqualsASCII(it.values(), "bytes");
236 } else if (base::LowerCaseEqualsASCII(it.name(), "content-encoding")) {
237 content_encoded_ = true;
238 } else if (base::LowerCaseEqualsASCII(it.name(), "content-type")) {
239 content_type_ = it.values();
240 size_t semi_colon_pos = content_type_.find(';');
241 if (semi_colon_pos != std::string::npos) {
242 content_type_ = content_type_.substr(0, semi_colon_pos);
243 }
244 base::TrimWhitespaceASCII(content_type_, base::TRIM_ALL, &content_type_);
245 // multipart boundary.
246 std::string type = base::ToLowerASCII(it.values());
247 if (base::StartsWith(type, "multipart/", base::CompareCase::SENSITIVE)) {
248 const char* boundary = strstr(type.c_str(), "boundary=");
249 DCHECK(boundary);
250 if (boundary) {
251 multipart_boundary_ = std::string(boundary + 9);
252 is_multipart_ = !multipart_boundary_.empty();
253 }
254 }
255 } else if (base::LowerCaseEqualsASCII(it.name(), "content-disposition")) {
256 content_disposition_ = it.values();
257 } else if (base::LowerCaseEqualsASCII(it.name(), "content-range")) {
258 int start = 0;
259 int end = 0;
260 if (GetByteRangeFromStr(it.values().c_str(), &start, &end)) {
261 byte_range_ = gfx::Range(start, end);
262 }
263 }
264 }
265 }
266
267 void URLLoaderWrapperImpl::DidOpen(int32_t result) {
268 SetHeadersFromLoader();
269 did_open_callback_.RunAndClear(result);
270 }
271
272 void URLLoaderWrapperImpl::DidRead(int32_t result) {
273 if (multi_part_processed_) {
274 // Reset this flag so we look inside the buffer in calls of DidRead for this
275 // response only once. Note that this code DOES NOT handle multi part
276 // responses with more than one part (we don't issue them at the moment, so
277 // they shouldn't arrive).
278 is_multipart_ = false;
279 }
280 if (result <= 0 || !is_multipart_) {
281 did_read_callback_.RunAndClear(result);
282 return;
283 }
284 if (result <= 2) {
285 // TODO(art-snake): Accumulate data for parse headers.
286 did_read_callback_.RunAndClear(result);
287 return;
288 }
289
290 char* start = buffer_;
291 size_t length = result;
292 multi_part_processed_ = true;
293 for (int i = 2; i < result; ++i) {
294 if (IsDoubleEndLineAtEnd(buffer_, i)) {
295 int start_pos = 0;
296 int end_pos = 0;
297 if (GetByteRangeFromHeaders(std::string(buffer_, i), &start_pos,
298 &end_pos)) {
299 byte_range_ = gfx::Range(start_pos, end_pos);
300 start += i;
301 length -= i;
302 }
303 break;
304 }
305 }
306 result = length;
307 if (result == 0) {
308 // Continue receiving.
309 return ReadResponseBodyImpl();
310 }
311 DCHECK(result > 0);
312 memmove(buffer_, start, result);
313
314 did_read_callback_.RunAndClear(result);
315 }
316
317 void URLLoaderWrapperImpl::SetHeadersFromLoader() {
318 pp::URLResponseInfo response = url_loader_.GetResponseInfo();
319 pp::Var headers_var = response.GetHeaders();
320
321 SetResponseHeaders(headers_var.is_string() ? headers_var.AsString() : "");
322 }
323
324 } // namespace chrome_pdf
OLDNEW
« pdf/document_loader_unittest.cc ('K') | « pdf/url_loader_wrapper_impl.h ('k') | no next file » | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698