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

Side by Side Diff: content/browser/download/download_item_impl.cc

Issue 10912173: Replace the DownloadFileManager with direct ownership of DownloadFileImpl (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: Merged to LKGR (r159273) Created 8 years, 2 months 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 | Annotate | Revision Log
OLDNEW
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 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 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 // File method ordering: Methods in this file are in the same order 5 // File method ordering: Methods in this file are in the same order as
6 // as in download_item_impl.h, with the following exception: The public 6 // in download_item_impl.h, with the following exception: The public
7 // interfaces DelayedDownloadOpened, OnDownloadTargetDetermined, and 7 // interfaces Start, DelayedDownloadOpened, and OnDownloadCompleting
8 // OnDownloadCompleting are placed in chronological order with the other 8 // are placed in chronological order with the other (private) routines
9 // (private) routines that together define a DownloadItem's state transitions 9 // that together define a DownloadItem's state transitions as the
10 // as the download progresses. See "Download progression cascade" later in 10 // download progresses. See "Download progression cascade" later in
11 // this file. 11 // this file.
12 12
13 // A regular DownloadItem (created for a download in this session of the 13 // A regular DownloadItem (created for a download in this session of the
14 // browser) normally goes through the following states: 14 // browser) normally goes through the following states:
15 // * Created (when download starts) 15 // * Created (when download starts)
16 // * Destination filename determined 16 // * Destination filename determined
17 // * Entered into the history database. 17 // * Entered into the history database.
18 // * Made visible in the download shelf. 18 // * Made visible in the download shelf.
19 // * All the data is saved. Note that the actual data download occurs 19 // * All the data is saved. Note that the actual data download occurs
20 // in parallel with the above steps, but until those steps are 20 // in parallel with the above steps, but until those steps are
21 // complete, the state of the data save will be ignored. 21 // complete, the state of the data save will be ignored.
22 // * Download file is renamed to its final name, and possibly 22 // * Download file is renamed to its final name, and possibly
23 // auto-opened. 23 // auto-opened.
24 24
25 #include "content/browser/download/download_item_impl.h" 25 #include "content/browser/download/download_item_impl.h"
26 26
27 #include <vector> 27 #include <vector>
28 28
29 #include "base/basictypes.h" 29 #include "base/basictypes.h"
30 #include "base/bind.h" 30 #include "base/bind.h"
31 #include "base/file_util.h" 31 #include "base/file_util.h"
32 #include "base/format_macros.h" 32 #include "base/format_macros.h"
33 #include "base/logging.h" 33 #include "base/logging.h"
34 #include "base/metrics/histogram.h" 34 #include "base/metrics/histogram.h"
35 #include "base/stl_util.h" 35 #include "base/stl_util.h"
36 #include "base/stringprintf.h" 36 #include "base/stringprintf.h"
37 #include "base/utf_string_conversions.h" 37 #include "base/utf_string_conversions.h"
38 #include "content/browser/download/download_create_info.h" 38 #include "content/browser/download/download_create_info.h"
39 #include "content/browser/download/download_file.h" 39 #include "content/browser/download/download_file.h"
40 #include "content/browser/download/download_file_manager.h"
41 #include "content/browser/download/download_interrupt_reasons_impl.h" 40 #include "content/browser/download/download_interrupt_reasons_impl.h"
42 #include "content/browser/download/download_item_impl_delegate.h" 41 #include "content/browser/download/download_item_impl_delegate.h"
43 #include "content/browser/download/download_request_handle.h" 42 #include "content/browser/download/download_request_handle.h"
44 #include "content/browser/download/download_stats.h" 43 #include "content/browser/download/download_stats.h"
45 #include "content/browser/web_contents/web_contents_impl.h" 44 #include "content/browser/web_contents/web_contents_impl.h"
46 #include "content/public/browser/browser_thread.h" 45 #include "content/public/browser/browser_thread.h"
47 #include "content/public/browser/content_browser_client.h" 46 #include "content/public/browser/content_browser_client.h"
48 #include "content/public/browser/download_persistent_store_info.h" 47 #include "content/public/browser/download_persistent_store_info.h"
49 #include "net/base/net_util.h" 48 #include "net/base/net_util.h"
50 49
(...skipping 46 matching lines...) Expand 10 before | Expand all | Expand 10 after
97 return NULL; 96 return NULL;
98 } 97 }
99 virtual void PauseRequest() const OVERRIDE {} 98 virtual void PauseRequest() const OVERRIDE {}
100 virtual void ResumeRequest() const OVERRIDE {} 99 virtual void ResumeRequest() const OVERRIDE {}
101 virtual void CancelRequest() const OVERRIDE {} 100 virtual void CancelRequest() const OVERRIDE {}
102 virtual std::string DebugString() const OVERRIDE { 101 virtual std::string DebugString() const OVERRIDE {
103 return "Null DownloadRequestHandle"; 102 return "Null DownloadRequestHandle";
104 } 103 }
105 }; 104 };
106 105
106 // Wrapper around DownloadFile::Detach and DownloadFile::Cancel that
107 // takes ownership of the DownloadFile and hence implicitly destroys it
108 // at the end of the function.
109 static void DownloadFileDetach(
110 scoped_ptr<DownloadFile> download_file, base::Closure callback) {
111 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
112 download_file->Detach(callback);
113 }
114
115 static void DownloadFileCancel(scoped_ptr<DownloadFile> download_file) {
116 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
117 download_file->Cancel();
118 }
119
107 } // namespace 120 } // namespace
108 121
109 namespace content { 122 namespace content {
110 123
111 // Our download table ID starts at 1, so we use 0 to represent a download that 124 // Our download table ID starts at 1, so we use 0 to represent a download that
112 // has started, but has not yet had its data persisted in the table. We use fake 125 // has started, but has not yet had its data persisted in the table. We use fake
113 // database handles in incognito mode starting at -1 and progressively getting 126 // database handles in incognito mode starting at -1 and progressively getting
114 // more negative. 127 // more negative.
115 // static 128 // static
116 const int DownloadItem::kUninitializedHandle = 0; 129 const int DownloadItem::kUninitializedHandle = 0;
117 130
118 const char DownloadItem::kEmptyFileHash[] = ""; 131 const char DownloadItem::kEmptyFileHash[] = "";
119 132
120 } 133 }
121 134
122 // Our download table ID starts at 1, so we use 0 to represent a download that 135 // Our download table ID starts at 1, so we use 0 to represent a download that
123 // has started, but has not yet had its data persisted in the table. We use fake 136 // has started, but has not yet had its data persisted in the table. We use fake
124 // database handles in incognito mode starting at -1 and progressively getting 137 // database handles in incognito mode starting at -1 and progressively getting
125 // more negative. 138 // more negative.
126 139
127 // Constructor for reading from the history service. 140 // Constructor for reading from the history service.
128 DownloadItemImpl::DownloadItemImpl(DownloadItemImplDelegate* delegate, 141 DownloadItemImpl::DownloadItemImpl(DownloadItemImplDelegate* delegate,
129 DownloadId download_id, 142 DownloadId download_id,
130 const DownloadPersistentStoreInfo& info, 143 const DownloadPersistentStoreInfo& info,
131 const net::BoundNetLog& bound_net_log) 144 const net::BoundNetLog& bound_net_log)
132 : download_id_(download_id), 145 : is_save_package_download_(false),
146 download_id_(download_id),
133 current_path_(info.path), 147 current_path_(info.path),
134 target_path_(info.path), 148 target_path_(info.path),
135 target_disposition_(TARGET_DISPOSITION_OVERWRITE), 149 target_disposition_(TARGET_DISPOSITION_OVERWRITE),
136 url_chain_(1, info.url), 150 url_chain_(1, info.url),
137 referrer_url_(info.referrer_url), 151 referrer_url_(info.referrer_url),
138 transition_type_(content::PAGE_TRANSITION_LINK), 152 transition_type_(content::PAGE_TRANSITION_LINK),
139 has_user_gesture_(false), 153 has_user_gesture_(false),
140 total_bytes_(info.total_bytes), 154 total_bytes_(info.total_bytes),
141 received_bytes_(info.received_bytes), 155 received_bytes_(info.received_bytes),
142 bytes_per_sec_(0), 156 bytes_per_sec_(0),
(...skipping 26 matching lines...) Expand all
169 Init(false /* not actively downloading */, 183 Init(false /* not actively downloading */,
170 download_net_logs::SRC_HISTORY_IMPORT); 184 download_net_logs::SRC_HISTORY_IMPORT);
171 } 185 }
172 186
173 // Constructing for a regular download: 187 // Constructing for a regular download:
174 DownloadItemImpl::DownloadItemImpl( 188 DownloadItemImpl::DownloadItemImpl(
175 DownloadItemImplDelegate* delegate, 189 DownloadItemImplDelegate* delegate,
176 const DownloadCreateInfo& info, 190 const DownloadCreateInfo& info,
177 scoped_ptr<DownloadRequestHandleInterface> request_handle, 191 scoped_ptr<DownloadRequestHandleInterface> request_handle,
178 const net::BoundNetLog& bound_net_log) 192 const net::BoundNetLog& bound_net_log)
179 : request_handle_(request_handle.Pass()), 193 : is_save_package_download_(false),
194 request_handle_(request_handle.Pass()),
180 download_id_(info.download_id), 195 download_id_(info.download_id),
181 target_disposition_( 196 target_disposition_(
182 (info.prompt_user_for_save_location) ? 197 (info.prompt_user_for_save_location) ?
183 TARGET_DISPOSITION_PROMPT : TARGET_DISPOSITION_OVERWRITE), 198 TARGET_DISPOSITION_PROMPT : TARGET_DISPOSITION_OVERWRITE),
184 url_chain_(info.url_chain), 199 url_chain_(info.url_chain),
185 referrer_url_(info.referrer_url), 200 referrer_url_(info.referrer_url),
186 suggested_filename_(UTF16ToUTF8(info.save_info.suggested_name)), 201 suggested_filename_(UTF16ToUTF8(info.save_info.suggested_name)),
187 forced_file_path_(info.save_info.file_path), 202 forced_file_path_(info.save_info.file_path),
188 transition_type_(info.transition_type), 203 transition_type_(info.transition_type),
189 has_user_gesture_(info.has_user_gesture), 204 has_user_gesture_(info.has_user_gesture),
(...skipping 39 matching lines...) Expand 10 before | Expand all | Expand 10 after
229 bound_net_log_.source().ToEventParametersCallback()); 244 bound_net_log_.source().ToEventParametersCallback());
230 } 245 }
231 246
232 // Constructing for the "Save Page As..." feature: 247 // Constructing for the "Save Page As..." feature:
233 DownloadItemImpl::DownloadItemImpl(DownloadItemImplDelegate* delegate, 248 DownloadItemImpl::DownloadItemImpl(DownloadItemImplDelegate* delegate,
234 const FilePath& path, 249 const FilePath& path,
235 const GURL& url, 250 const GURL& url,
236 DownloadId download_id, 251 DownloadId download_id,
237 const std::string& mime_type, 252 const std::string& mime_type,
238 const net::BoundNetLog& bound_net_log) 253 const net::BoundNetLog& bound_net_log)
239 : request_handle_(new NullDownloadRequestHandle()), 254 : is_save_package_download_(true),
255 request_handle_(new NullDownloadRequestHandle()),
240 download_id_(download_id), 256 download_id_(download_id),
241 current_path_(path), 257 current_path_(path),
242 target_path_(path), 258 target_path_(path),
243 target_disposition_(TARGET_DISPOSITION_OVERWRITE), 259 target_disposition_(TARGET_DISPOSITION_OVERWRITE),
244 url_chain_(1, url), 260 url_chain_(1, url),
245 referrer_url_(GURL()), 261 referrer_url_(GURL()),
246 transition_type_(content::PAGE_TRANSITION_LINK), 262 transition_type_(content::PAGE_TRANSITION_LINK),
247 has_user_gesture_(false), 263 has_user_gesture_(false),
248 mime_type_(mime_type), 264 mime_type_(mime_type),
249 original_mime_type_(mime_type), 265 original_mime_type_(mime_type),
(...skipping 20 matching lines...) Expand all
270 delegate_delayed_complete_(false), 286 delegate_delayed_complete_(false),
271 bound_net_log_(bound_net_log), 287 bound_net_log_(bound_net_log),
272 ALLOW_THIS_IN_INITIALIZER_LIST(weak_ptr_factory_(this)) { 288 ALLOW_THIS_IN_INITIALIZER_LIST(weak_ptr_factory_(this)) {
273 delegate_->Attach(); 289 delegate_->Attach();
274 Init(true /* actively downloading */, 290 Init(true /* actively downloading */,
275 download_net_logs::SRC_SAVE_PAGE_AS); 291 download_net_logs::SRC_SAVE_PAGE_AS);
276 } 292 }
277 293
278 DownloadItemImpl::~DownloadItemImpl() { 294 DownloadItemImpl::~DownloadItemImpl() {
279 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); 295 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
296
297 // Should always have been nuked before now, at worst in
298 // DownloadManager shutdown.
299 DCHECK(!download_file_.get());
300
280 FOR_EACH_OBSERVER(Observer, observers_, OnDownloadDestroyed(this)); 301 FOR_EACH_OBSERVER(Observer, observers_, OnDownloadDestroyed(this));
281 delegate_->AssertStateConsistent(this); 302 delegate_->AssertStateConsistent(this);
282 delegate_->Detach(); 303 delegate_->Detach();
283 } 304 }
284 305
285 void DownloadItemImpl::AddObserver(Observer* observer) { 306 void DownloadItemImpl::AddObserver(Observer* observer) {
286 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); 307 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
287 308
288 observers_.AddObserver(observer); 309 observers_.AddObserver(observer);
289 } 310 }
(...skipping 56 matching lines...) Expand 10 before | Expand all | Expand 10 after
346 VLOG(20) << __FUNCTION__ << "() download = " << DebugString(true); 367 VLOG(20) << __FUNCTION__ << "() download = " << DebugString(true);
347 if (state_ != IN_PROGRESS_INTERNAL) { 368 if (state_ != IN_PROGRESS_INTERNAL) {
348 // Small downloads might be complete before this method has 369 // Small downloads might be complete before this method has
349 // a chance to run. 370 // a chance to run.
350 return; 371 return;
351 } 372 }
352 373
353 download_stats::RecordDownloadCount(download_stats::CANCELLED_COUNT); 374 download_stats::RecordDownloadCount(download_stats::CANCELLED_COUNT);
354 375
355 TransitionTo(CANCELLED_INTERNAL); 376 TransitionTo(CANCELLED_INTERNAL);
377
378 // Cancel and remove the download file.
379 // TODO(rdsmith/benjhayden): Remove condition as part of
380 // SavePackage integration.
381 if (!is_save_package_download_) {
382 CHECK(download_file_.get());
383 BrowserThread::PostTask(
384 BrowserThread::FILE, FROM_HERE,
385 // Will be deleted at end of task execution.
386 base::Bind(&DownloadFileCancel, base::Passed(download_file_.Pass())));
387 }
388
389 // Cancel the originating URL request.
390 request_handle_->CancelRequest();
391
356 if (user_cancel) 392 if (user_cancel)
357 delegate_->DownloadStopped(this); 393 delegate_->DownloadStopped(this);
358 } 394 }
359 395
360 void DownloadItemImpl::Delete(DeleteReason reason) { 396 void DownloadItemImpl::Delete(DeleteReason reason) {
361 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); 397 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
362 398
363 switch (reason) { 399 switch (reason) {
364 case DELETE_DUE_TO_USER_DISCARD: 400 case DELETE_DUE_TO_USER_DISCARD:
365 UMA_HISTOGRAM_ENUMERATION( 401 UMA_HISTOGRAM_ENUMERATION(
(...skipping 393 matching lines...) Expand 10 before | Expand all | Expand 10 after
759 " db_handle = %" PRId64 795 " db_handle = %" PRId64
760 " total = %" PRId64 796 " total = %" PRId64
761 " received = %" PRId64 797 " received = %" PRId64
762 " reason = %s" 798 " reason = %s"
763 " paused = %c" 799 " paused = %c"
764 " safety = %s" 800 " safety = %s"
765 " last_modified = '%s'" 801 " last_modified = '%s'"
766 " etag = '%s'" 802 " etag = '%s'"
767 " url_chain = \n\t\"%s\"\n\t" 803 " url_chain = \n\t\"%s\"\n\t"
768 " full_path = \"%" PRFilePath "\"" 804 " full_path = \"%" PRFilePath "\""
769 " target_path = \"%" PRFilePath "\"", 805 " target_path = \"%" PRFilePath "\""
806 " has download file = %s",
770 GetDbHandle(), 807 GetDbHandle(),
771 GetTotalBytes(), 808 GetTotalBytes(),
772 GetReceivedBytes(), 809 GetReceivedBytes(),
773 InterruptReasonDebugString(last_reason_).c_str(), 810 InterruptReasonDebugString(last_reason_).c_str(),
774 IsPaused() ? 'T' : 'F', 811 IsPaused() ? 'T' : 'F',
775 DebugSafetyStateString(GetSafetyState()), 812 DebugSafetyStateString(GetSafetyState()),
776 GetLastModifiedTime().c_str(), 813 GetLastModifiedTime().c_str(),
777 GetETag().c_str(), 814 GetETag().c_str(),
778 url_list.c_str(), 815 url_list.c_str(),
779 GetFullPath().value().c_str(), 816 GetFullPath().value().c_str(),
780 GetTargetFilePath().value().c_str()); 817 GetTargetFilePath().value().c_str(),
818 download_file_.get() ? "true" : "false");
781 } else { 819 } else {
782 description += base::StringPrintf(" url = \"%s\"", url_list.c_str()); 820 description += base::StringPrintf(" url = \"%s\"", url_list.c_str());
783 } 821 }
784 822
785 description += " }"; 823 description += " }";
786 824
787 return description; 825 return description;
788 } 826 }
789 827
790 void DownloadItemImpl::MockDownloadOpenForTesting() { 828 void DownloadItemImpl::MockDownloadOpenForTesting() {
791 open_enabled_ = false; 829 open_enabled_ = false;
792 } 830 }
793 831
794 void DownloadItemImpl::NotifyRemoved() { 832 void DownloadItemImpl::NotifyRemoved() {
795 FOR_EACH_OBSERVER(Observer, observers_, OnDownloadRemoved(this)); 833 FOR_EACH_OBSERVER(Observer, observers_, OnDownloadRemoved(this));
796 } 834 }
797 835
798 void DownloadItemImpl::OnDownloadedFileRemoved() { 836 void DownloadItemImpl::OnDownloadedFileRemoved() {
799 file_externally_removed_ = true; 837 file_externally_removed_ = true;
800 UpdateObservers(); 838 UpdateObservers();
801 } 839 }
802 840
803 void DownloadItemImpl::OffThreadCancel() {
804 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
805 request_handle_->CancelRequest();
806
807 BrowserThread::PostTask(
808 BrowserThread::FILE, FROM_HERE,
809 base::Bind(&DownloadFileManager::CancelDownload,
810 delegate_->GetDownloadFileManager(), download_id_));
811 }
812
813 // An error occurred somewhere. 841 // An error occurred somewhere.
814 void DownloadItemImpl::Interrupt(content::DownloadInterruptReason reason) { 842 void DownloadItemImpl::Interrupt(content::DownloadInterruptReason reason) {
815 // Somewhat counter-intuitively, it is possible for us to receive an 843 // Somewhat counter-intuitively, it is possible for us to receive an
816 // interrupt after we've already been interrupted. The generation of 844 // interrupt after we've already been interrupted. The generation of
817 // interrupts from the file thread Renames and the generation of 845 // interrupts from the file thread Renames and the generation of
818 // interrupts from disk writes go through two different mechanisms (driven 846 // interrupts from disk writes go through two different mechanisms (driven
819 // by rename requests from UI thread and by write requests from IO thread, 847 // by rename requests from UI thread and by write requests from IO thread,
820 // respectively), and since we choose not to keep state on the File thread, 848 // respectively), and since we choose not to keep state on the File thread,
821 // this is the place where the races collide. It's also possible for 849 // this is the place where the races collide. It's also possible for
822 // interrupts to race with cancels. 850 // interrupts to race with cancels.
823 851
824 // Whatever happens, the first one to hit the UI thread wins. 852 // Whatever happens, the first one to hit the UI thread wins.
825 if (state_ != IN_PROGRESS_INTERNAL) 853 if (state_ != IN_PROGRESS_INTERNAL)
826 return; 854 return;
827 855
828 last_reason_ = reason; 856 last_reason_ = reason;
829 TransitionTo(INTERRUPTED_INTERNAL); 857 TransitionTo(INTERRUPTED_INTERNAL);
858
859 // Cancel and remove the download file.
860 // TODO(rdsmith/benjhayden): Remove condition as part of
861 // SavePackage integration.
862 if (!is_save_package_download_) {
863 CHECK(download_file_.get());
864 BrowserThread::PostTask(
865 BrowserThread::FILE, FROM_HERE,
866 // Will be deleted at end of task execution.
867 base::Bind(&DownloadFileCancel, base::Passed(download_file_.Pass())));
868 }
869
870 // Cancel the originating URL request.
871 request_handle_->CancelRequest();
872
830 download_stats::RecordDownloadInterrupted( 873 download_stats::RecordDownloadInterrupted(
831 reason, received_bytes_, total_bytes_); 874 reason, received_bytes_, total_bytes_);
832 delegate_->DownloadStopped(this); 875 delegate_->DownloadStopped(this);
833 } 876 }
834 877
878 base::WeakPtr<content::DownloadDestinationObserver>
879 DownloadItemImpl::DestinationObserverAsWeakPtr() {
880 return weak_ptr_factory_.GetWeakPtr();
881 }
882
883 bool DownloadItemImpl::IsSavePackageDownload() const {
884 return is_save_package_download_;
885 }
886
835 void DownloadItemImpl::SetTotalBytes(int64 total_bytes) { 887 void DownloadItemImpl::SetTotalBytes(int64 total_bytes) {
836 total_bytes_ = total_bytes; 888 total_bytes_ = total_bytes;
837 } 889 }
838 890
839 // Updates from the download thread may have been posted while this download 891 // Updates from the download thread may have been posted while this download
840 // was being cancelled in the UI thread, so we'll accept them unless we're 892 // was being cancelled in the UI thread, so we'll accept them unless we're
841 // complete. 893 // complete.
842 void DownloadItemImpl::UpdateProgress(int64 bytes_so_far, 894 void DownloadItemImpl::UpdateProgress(int64 bytes_so_far,
843 int64 bytes_per_sec, 895 int64 bytes_per_sec,
844 const std::string& hash_state) { 896 const std::string& hash_state) {
(...skipping 22 matching lines...) Expand all
867 919
868 if (bound_net_log_.IsLoggingAllEvents()) { 920 if (bound_net_log_.IsLoggingAllEvents()) {
869 bound_net_log_.AddEvent( 921 bound_net_log_.AddEvent(
870 net::NetLog::TYPE_DOWNLOAD_ITEM_UPDATED, 922 net::NetLog::TYPE_DOWNLOAD_ITEM_UPDATED,
871 net::NetLog::Int64Callback("bytes_so_far", received_bytes_)); 923 net::NetLog::Int64Callback("bytes_so_far", received_bytes_));
872 } 924 }
873 925
874 UpdateObservers(); 926 UpdateObservers();
875 } 927 }
876 928
877 void DownloadItemImpl::OnAllDataSaved( 929 void DownloadItemImpl::OnAllDataSaved(const std::string& final_hash) {
878 int64 size, const std::string& final_hash) {
879 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); 930 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
880 931
932 DCHECK_EQ(IN_PROGRESS_INTERNAL, state_);
881 DCHECK(!all_data_saved_); 933 DCHECK(!all_data_saved_);
882 all_data_saved_ = true; 934 all_data_saved_ = true;
883 ProgressComplete(size, final_hash); 935
936 // Store final hash and null out intermediate serialized hash state.
937 hash_ = final_hash;
938 hash_state_ = "";
939
884 UpdateObservers(); 940 UpdateObservers();
885 } 941 }
886 942
887 void DownloadItemImpl::MarkAsComplete() { 943 void DownloadItemImpl::MarkAsComplete() {
888 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); 944 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
889 945
890 DCHECK(all_data_saved_); 946 DCHECK(all_data_saved_);
891 end_time_ = base::Time::Now(); 947 end_time_ = base::Time::Now();
892 TransitionTo(COMPLETE_INTERNAL); 948 TransitionTo(COMPLETE_INTERNAL);
893 } 949 }
894 950
895 void DownloadItemImpl::SetIsPersisted() { 951 void DownloadItemImpl::SetIsPersisted() {
896 is_persisted_ = true; 952 is_persisted_ = true;
897 UpdateObservers(); 953 UpdateObservers();
898 } 954 }
899 955
900 void DownloadItemImpl::SetDbHandle(int64 handle) { 956 void DownloadItemImpl::SetDbHandle(int64 handle) {
901 db_handle_ = handle; 957 db_handle_ = handle;
902 958
903 bound_net_log_.AddEvent( 959 bound_net_log_.AddEvent(
904 net::NetLog::TYPE_DOWNLOAD_ITEM_IN_HISTORY, 960 net::NetLog::TYPE_DOWNLOAD_ITEM_IN_HISTORY,
905 net::NetLog::Int64Callback("db_handle", db_handle_)); 961 net::NetLog::Int64Callback("db_handle", db_handle_));
906 } 962 }
907 963
964 void DownloadItemImpl::DestinationUpdate(int64 bytes_so_far,
965 int64 bytes_per_sec,
966 const std::string& hash_state) {
967 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
968
969 if (!IsInProgress()) {
970 // Ignore if we're no longer in-progress. This can happen if we race a
971 // Cancel on the UI thread with an update on the FILE thread.
972 //
973 // TODO(rdsmith): Arguably we should let this go through, as this means
974 // the download really did get further than we know before it was
975 // cancelled. But the gain isn't very large, and the code is more
976 // fragile if it has to support in progress updates in a non-in-progress
977 // state. This issue should be readdressed when we revamp performance
978 // reporting.
979 return;
980 }
981 bytes_per_sec_ = bytes_per_sec;
982 hash_state_ = hash_state;
983 received_bytes_ = bytes_so_far;
984
985 // If we've received more data than we were expecting (bad server info?),
986 // revert to 'unknown size mode'.
987 if (received_bytes_ > total_bytes_)
988 total_bytes_ = 0;
989
990 if (bound_net_log_.IsLoggingAllEvents()) {
991 bound_net_log_.AddEvent(
992 net::NetLog::TYPE_DOWNLOAD_ITEM_UPDATED,
993 net::NetLog::Int64Callback("bytes_so_far", received_bytes_));
994 }
995
996 UpdateObservers();
997 }
998
999 void DownloadItemImpl::DestinationError(
1000 content::DownloadInterruptReason reason) {
1001 // The DestinationError and Interrupt routines are being kept separate
1002 // to allow for a future merging of the Cancel and Interrupt routines..
1003 Interrupt(reason);
1004 }
1005
1006 void DownloadItemImpl::DestinationCompleted(const std::string& final_hash) {
1007 if (!IsInProgress())
1008 return;
1009 OnAllDataSaved(final_hash);
1010 delegate_->MaybeCompleteDownload(this);
1011 }
1012
908 // **** Download progression cascade 1013 // **** Download progression cascade
909 1014
910 void DownloadItemImpl::Init(bool active, 1015 void DownloadItemImpl::Init(bool active,
911 download_net_logs::DownloadType download_type) { 1016 download_net_logs::DownloadType download_type) {
912 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); 1017 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
913 1018
914 if (active) 1019 if (active)
915 download_stats::RecordDownloadCount(download_stats::START_COUNT); 1020 download_stats::RecordDownloadCount(download_stats::START_COUNT);
916 1021
917 if (target_path_.empty()) 1022 if (target_path_.empty())
(...skipping 23 matching lines...) Expand all
941 bound_net_log_.AddEvent( 1046 bound_net_log_.AddEvent(
942 net::NetLog::TYPE_DOWNLOAD_ITEM_IN_HISTORY, 1047 net::NetLog::TYPE_DOWNLOAD_ITEM_IN_HISTORY,
943 net::NetLog::Int64Callback("db_handle", db_handle_)); 1048 net::NetLog::Int64Callback("db_handle", db_handle_));
944 1049
945 bound_net_log_.EndEvent(net::NetLog::TYPE_DOWNLOAD_ITEM_ACTIVE); 1050 bound_net_log_.EndEvent(net::NetLog::TYPE_DOWNLOAD_ITEM_ACTIVE);
946 } 1051 }
947 1052
948 VLOG(20) << __FUNCTION__ << "() " << DebugString(true); 1053 VLOG(20) << __FUNCTION__ << "() " << DebugString(true);
949 } 1054 }
950 1055
951 // Called by DownloadManagerImpl when the download target path has been 1056 // We're starting the download.
1057 void DownloadItemImpl::Start(scoped_ptr<content::DownloadFile> file) {
1058 DCHECK(!download_file_.get());
1059 DCHECK(file.get());
1060 download_file_ = file.Pass();
1061
1062 BrowserThread::PostTask(
1063 BrowserThread::FILE, FROM_HERE,
1064 base::Bind(&DownloadFile::Initialize,
1065 // Safe because we control download file lifetime.
1066 base::Unretained(download_file_.get()),
1067 base::Bind(&DownloadItemImpl::OnDownloadFileInitialized,
1068 weak_ptr_factory_.GetWeakPtr())));
1069 }
1070
1071 void DownloadItemImpl::OnDownloadFileInitialized(
1072 content::DownloadInterruptReason result) {
1073 if (result != content::DOWNLOAD_INTERRUPT_REASON_NONE) {
1074 Interrupt(result);
1075 // TODO(rdsmith): It makes no sense to continue along the
1076 // regular download path after we've gotten an error. But it's
1077 // the way the code has historically worked, and this allows us
1078 // to get the download persisted and observers of the download manager
1079 // notified, so tests work. When we execute all side effects of cancel
1080 // (including queue removal) immedately rather than waiting for
1081 // persistence we should replace this comment with a "return;".
1082 }
1083
1084 delegate_->DetermineDownloadTarget(
1085 this, base::Bind(&DownloadItemImpl::OnDownloadTargetDetermined,
1086 weak_ptr_factory_.GetWeakPtr()));
1087 }
1088
1089 // Called by delegate_ when the download target path has been
952 // determined. 1090 // determined.
953 void DownloadItemImpl::OnDownloadTargetDetermined( 1091 void DownloadItemImpl::OnDownloadTargetDetermined(
954 const FilePath& target_path, 1092 const FilePath& target_path,
955 TargetDisposition disposition, 1093 TargetDisposition disposition,
956 content::DownloadDangerType danger_type, 1094 content::DownloadDangerType danger_type,
957 const FilePath& intermediate_path) { 1095 const FilePath& intermediate_path) {
958 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); 1096 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
959 1097
960 // If the |target_path| is empty, then we consider this download to be 1098 // If the |target_path| is empty, then we consider this download to be
961 // canceled. 1099 // canceled.
(...skipping 20 matching lines...) Expand all
982 // whatever was recorded for consistency. 1120 // whatever was recorded for consistency.
983 OnDownloadRenamedToIntermediateName(last_reason_, FilePath()); 1121 OnDownloadRenamedToIntermediateName(last_reason_, FilePath());
984 return; 1122 return;
985 } 1123 }
986 1124
987 // Rename to intermediate name. 1125 // Rename to intermediate name.
988 // TODO(asanka): Skip this rename if AllDataSaved() is true. This avoids a 1126 // TODO(asanka): Skip this rename if AllDataSaved() is true. This avoids a
989 // spurious rename when we can just rename to the final 1127 // spurious rename when we can just rename to the final
990 // filename. Unnecessary renames may cause bugs like 1128 // filename. Unnecessary renames may cause bugs like
991 // http://crbug.com/74187. 1129 // http://crbug.com/74187.
992 DownloadFileManager::RenameCompletionCallback callback = 1130 DCHECK(!is_save_package_download_);
1131 CHECK(download_file_.get());
1132 DownloadFile::RenameCompletionCallback callback =
993 base::Bind(&DownloadItemImpl::OnDownloadRenamedToIntermediateName, 1133 base::Bind(&DownloadItemImpl::OnDownloadRenamedToIntermediateName,
994 weak_ptr_factory_.GetWeakPtr()); 1134 weak_ptr_factory_.GetWeakPtr());
995 BrowserThread::PostTask( 1135 BrowserThread::PostTask(
996 BrowserThread::FILE, FROM_HERE, 1136 BrowserThread::FILE, FROM_HERE,
997 base::Bind(&DownloadFileManager::RenameDownloadFile, 1137 base::Bind(&DownloadFile::Rename,
998 delegate_->GetDownloadFileManager(), GetGlobalId(), 1138 // Safe because we control download file lifetime.
1139 base::Unretained(download_file_.get()),
999 intermediate_path, false, callback)); 1140 intermediate_path, false, callback));
1000 } 1141 }
1001 1142
1002 void DownloadItemImpl::OnDownloadRenamedToIntermediateName( 1143 void DownloadItemImpl::OnDownloadRenamedToIntermediateName(
1003 content::DownloadInterruptReason reason, 1144 content::DownloadInterruptReason reason,
1004 const FilePath& full_path) { 1145 const FilePath& full_path) {
1005 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); 1146 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1006 if (content::DOWNLOAD_INTERRUPT_REASON_NONE != reason) { 1147 if (content::DOWNLOAD_INTERRUPT_REASON_NONE != reason) {
1007 Interrupt(reason); 1148 Interrupt(reason);
1008 } else { 1149 } else {
(...skipping 16 matching lines...) Expand all
1025 1166
1026 if (state_ != IN_PROGRESS_INTERNAL) 1167 if (state_ != IN_PROGRESS_INTERNAL)
1027 return; 1168 return;
1028 1169
1029 VLOG(20) << __FUNCTION__ << "()" 1170 VLOG(20) << __FUNCTION__ << "()"
1030 << " needs rename = " << NeedsRename() 1171 << " needs rename = " << NeedsRename()
1031 << " " << DebugString(true); 1172 << " " << DebugString(true);
1032 DCHECK(!GetTargetFilePath().empty()); 1173 DCHECK(!GetTargetFilePath().empty());
1033 DCHECK_NE(DANGEROUS, GetSafetyState()); 1174 DCHECK_NE(DANGEROUS, GetSafetyState());
1034 1175
1176 // TODO(rdsmith/benjhayden): Remove as part of SavePackage integration.
1177 if (is_save_package_download_) {
1178 // Avoid doing anything on the file thread; there's nothing we control
1179 // there.
1180 OnDownloadFileReleased();
1181 return;
1182 }
1183
1184 CHECK(download_file_.get());
1035 if (NeedsRename()) { 1185 if (NeedsRename()) {
1036 DownloadFileManager::RenameCompletionCallback callback = 1186 content::DownloadFile::RenameCompletionCallback callback =
1037 base::Bind(&DownloadItemImpl::OnDownloadRenamedToFinalName, 1187 base::Bind(&DownloadItemImpl::OnDownloadRenamedToFinalName,
1038 weak_ptr_factory_.GetWeakPtr()); 1188 weak_ptr_factory_.GetWeakPtr());
1039 BrowserThread::PostTask( 1189 BrowserThread::PostTask(
1040 BrowserThread::FILE, FROM_HERE, 1190 BrowserThread::FILE, FROM_HERE,
1041 base::Bind(&DownloadFileManager::RenameDownloadFile, 1191 base::Bind(&DownloadFile::Rename,
1042 delegate_->GetDownloadFileManager(), GetGlobalId(), 1192 base::Unretained(download_file_.get()),
1043 GetTargetFilePath(), true, callback)); 1193 GetTargetFilePath(), true, callback));
1044 } else { 1194 } else {
1045 // Complete the download and release the DownloadFile. 1195 ReleaseDownloadFile();
1046 BrowserThread::PostTask(
1047 BrowserThread::FILE, FROM_HERE,
1048 base::Bind(&DownloadFileManager::CompleteDownload,
1049 delegate_->GetDownloadFileManager(), GetGlobalId(),
1050 base::Bind(&DownloadItemImpl::OnDownloadFileReleased,
1051 weak_ptr_factory_.GetWeakPtr())));
1052 TransitionTo(COMPLETING_INTERNAL);
1053 } 1196 }
1054 } 1197 }
1055 1198
1056 void DownloadItemImpl::OnDownloadRenamedToFinalName( 1199 void DownloadItemImpl::OnDownloadRenamedToFinalName(
1057 content::DownloadInterruptReason reason, 1200 content::DownloadInterruptReason reason,
1058 const FilePath& full_path) { 1201 const FilePath& full_path) {
1059 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); 1202 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1060 1203
1061 // If a cancel or interrupt hit, we'll cancel the DownloadFile, which 1204 // If a cancel or interrupt hit, we'll cancel the DownloadFile, which
1062 // will result in deleting the file on the file thread. So we don't 1205 // will result in deleting the file on the file thread. So we don't
(...skipping 11 matching lines...) Expand all
1074 Interrupt(reason); 1217 Interrupt(reason);
1075 return; 1218 return;
1076 } 1219 }
1077 1220
1078 // full_path is now the current and target file path. 1221 // full_path is now the current and target file path.
1079 DCHECK(!full_path.empty()); 1222 DCHECK(!full_path.empty());
1080 target_path_ = full_path; 1223 target_path_ = full_path;
1081 SetFullPath(full_path); 1224 SetFullPath(full_path);
1082 delegate_->DownloadRenamedToFinalName(this); 1225 delegate_->DownloadRenamedToFinalName(this);
1083 1226
1227 ReleaseDownloadFile();
1228 }
1229
1230 void DownloadItemImpl::ReleaseDownloadFile() {
1084 // Complete the download and release the DownloadFile. 1231 // Complete the download and release the DownloadFile.
1232 DCHECK(!is_save_package_download_);
1233 CHECK(download_file_.get());
1085 BrowserThread::PostTask( 1234 BrowserThread::PostTask(
1086 BrowserThread::FILE, FROM_HERE, 1235 BrowserThread::FILE, FROM_HERE,
1087 base::Bind(&DownloadFileManager::CompleteDownload, 1236 base::Bind(&DownloadFileDetach, base::Passed(download_file_.Pass()),
1088 delegate_->GetDownloadFileManager(), GetGlobalId(),
1089 base::Bind(&DownloadItemImpl::OnDownloadFileReleased, 1237 base::Bind(&DownloadItemImpl::OnDownloadFileReleased,
1090 weak_ptr_factory_.GetWeakPtr()))); 1238 weak_ptr_factory_.GetWeakPtr())));
1239
1240 // We're not completely done with the download item yet, but at this
1241 // point we're committed to complete the download. Cancels (or Interrupts,
1242 // though it's not clear how they could happen) after this point will be
1243 // ignored.
1091 TransitionTo(COMPLETING_INTERNAL); 1244 TransitionTo(COMPLETING_INTERNAL);
1092 } 1245 }
1093 1246
1094 void DownloadItemImpl::OnDownloadFileReleased() { 1247 void DownloadItemImpl::OnDownloadFileReleased() {
1095 if (delegate_->ShouldOpenDownload(this)) 1248 if (delegate_->ShouldOpenDownload(this))
1096 Completed(); 1249 Completed();
1097 else 1250 else
1098 delegate_delayed_complete_ = true; 1251 delegate_delayed_complete_ = true;
1099 } 1252 }
1100 1253
1101 void DownloadItemImpl::DelayedDownloadOpened(bool auto_opened) { 1254 void DownloadItemImpl::DelayedDownloadOpened(bool auto_opened) {
1102 auto_opened_ = auto_opened; 1255 auto_opened_ = auto_opened;
1103 Completed(); 1256 Completed();
1257 UpdateObservers();
1104 } 1258 }
1105 1259
1106 void DownloadItemImpl::Completed() { 1260 void DownloadItemImpl::Completed() {
1107 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); 1261 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1108 1262
1109 VLOG(20) << __FUNCTION__ << "() " << DebugString(false); 1263 VLOG(20) << __FUNCTION__ << "() " << DebugString(false);
1110 1264
1111 DCHECK(all_data_saved_); 1265 DCHECK(all_data_saved_);
1112 end_time_ = base::Time::Now(); 1266 end_time_ = base::Time::Now();
1113 TransitionTo(COMPLETE_INTERNAL); 1267 TransitionTo(COMPLETE_INTERNAL);
(...skipping 16 matching lines...) Expand all
1130 } 1284 }
1131 } 1285 }
1132 1286
1133 // **** End of Download progression cascade 1287 // **** End of Download progression cascade
1134 1288
1135 bool DownloadItemImpl::NeedsRename() const { 1289 bool DownloadItemImpl::NeedsRename() const {
1136 DCHECK(target_path_.DirName() == current_path_.DirName()); 1290 DCHECK(target_path_.DirName() == current_path_.DirName());
1137 return target_path_ != current_path_; 1291 return target_path_ != current_path_;
1138 } 1292 }
1139 1293
1140 void DownloadItemImpl::ProgressComplete(int64 bytes_so_far,
1141 const std::string& final_hash) {
1142 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1143
1144 hash_ = final_hash;
1145 hash_state_ = "";
1146
1147 received_bytes_ = bytes_so_far;
1148
1149 // If we've received more data than we were expecting (bad server info?),
1150 // revert to 'unknown size mode'.
1151 if (received_bytes_ > total_bytes_)
1152 total_bytes_ = 0;
1153 }
1154
1155 void DownloadItemImpl::TransitionTo(DownloadInternalState new_state) { 1294 void DownloadItemImpl::TransitionTo(DownloadInternalState new_state) {
1156 if (state_ == new_state) 1295 if (state_ == new_state)
1157 return; 1296 return;
1158 1297
1159 DownloadInternalState old_state = state_; 1298 DownloadInternalState old_state = state_;
1160 state_ = new_state; 1299 state_ = new_state;
1161 1300
1162 switch (state_) { 1301 switch (state_) {
1163 case COMPLETING_INTERNAL: 1302 case COMPLETING_INTERNAL:
1164 bound_net_log_.AddEvent( 1303 bound_net_log_.AddEvent(
(...skipping 116 matching lines...) Expand 10 before | Expand all | Expand 10 after
1281 return "COMPLETE"; 1420 return "COMPLETE";
1282 case CANCELLED_INTERNAL: 1421 case CANCELLED_INTERNAL:
1283 return "CANCELLED"; 1422 return "CANCELLED";
1284 case INTERRUPTED_INTERNAL: 1423 case INTERRUPTED_INTERNAL:
1285 return "INTERRUPTED"; 1424 return "INTERRUPTED";
1286 default: 1425 default:
1287 NOTREACHED() << "Unknown download state " << state; 1426 NOTREACHED() << "Unknown download state " << state;
1288 return "unknown"; 1427 return "unknown";
1289 }; 1428 };
1290 } 1429 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698