blob: 2283b3263fe8c6890cc63cd027dc6e63a8cf8968 [file] [log] [blame]
[email protected]21ca982c2010-01-26 22:49:551// Copyright (c) 2010 The Chromium Authors. All rights reserved.
license.botbf09a502008-08-24 00:55:552// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commit09911bf2008-07-26 23:55:294
[email protected]cdaa8652008-09-13 02:48:595#include "chrome/browser/download/download_manager.h"
initial.commit09911bf2008-07-26 23:55:296
[email protected]a92b8642009-05-05 23:38:567#include "app/l10n_util.h"
[email protected]21ca982c2010-01-26 22:49:558#include "app/resource_bundle.h"
[email protected]2041cf342010-02-19 03:15:599#include "base/callback.h"
initial.commit09911bf2008-07-26 23:55:2910#include "base/file_util.h"
11#include "base/logging.h"
initial.commit09911bf2008-07-26 23:55:2912#include "base/path_service.h"
[email protected]1b5044d2009-02-24 00:04:1413#include "base/rand_util.h"
[email protected]92926d92010-09-02 18:35:0614#include "base/stl_util-inl.h"
[email protected]1b5044d2009-02-24 00:04:1415#include "base/sys_string_conversions.h"
initial.commit09911bf2008-07-26 23:55:2916#include "base/task.h"
[email protected]ce7f62e32010-08-10 23:43:5917#include "base/utf_string_conversions.h"
[email protected]d2a8fb72010-01-21 05:31:4218#include "build/build_config.h"
[email protected]6c69796d2010-07-16 21:41:1619#include "chrome/browser/browser.h"
initial.commit09911bf2008-07-26 23:55:2920#include "chrome/browser/browser_list.h"
21#include "chrome/browser/browser_process.h"
[email protected]d83d03aa2009-11-02 21:44:3722#include "chrome/browser/chrome_thread.h"
[email protected]6c69796d2010-07-16 21:41:1623#include "chrome/browser/download/download_file_manager.h"
[email protected]82f37b02010-07-29 22:04:5724#include "chrome/browser/download/download_history.h"
[email protected]6c69796d2010-07-16 21:41:1625#include "chrome/browser/download/download_item.h"
[email protected]e5dc4222010-08-30 22:16:3226#include "chrome/browser/download/download_prefs.h"
[email protected]e9ef0a62009-08-11 22:50:1327#include "chrome/browser/download/download_util.h"
[email protected]8f783752009-04-01 23:33:4528#include "chrome/browser/extensions/extensions_service.h"
[email protected]6c69796d2010-07-16 21:41:1629#include "chrome/browser/history/download_types.h"
[email protected]be180c802009-10-23 06:33:3130#include "chrome/browser/net/chrome_url_request_context.h"
[email protected]14a000d2010-04-29 21:44:2431#include "chrome/browser/platform_util.h"
initial.commit09911bf2008-07-26 23:55:2932#include "chrome/browser/profile.h"
[email protected]8c8657d62009-01-16 18:31:2633#include "chrome/browser/renderer_host/render_process_host.h"
[email protected]6524b5f92009-01-22 17:48:2534#include "chrome/browser/renderer_host/render_view_host.h"
[email protected]21ca982c2010-01-26 22:49:5535#include "chrome/browser/tab_contents/infobar_delegate.h"
[email protected]57c6a652009-05-04 07:58:3436#include "chrome/browser/tab_contents/tab_contents.h"
[email protected]d2a8fb72010-01-21 05:31:4237#include "chrome/browser/tab_contents/tab_util.h"
initial.commit09911bf2008-07-26 23:55:2938#include "chrome/common/chrome_paths.h"
[email protected]91e1bd82009-09-03 22:04:4039#include "chrome/common/notification_service.h"
40#include "chrome/common/notification_type.h"
initial.commit09911bf2008-07-26 23:55:2941#include "chrome/common/pref_names.h"
[email protected]46072d42008-07-28 14:49:3542#include "googleurl/src/gurl.h"
[email protected]34ac8f32009-02-22 23:03:2743#include "grit/generated_resources.h"
[email protected]21ca982c2010-01-26 22:49:5544#include "grit/theme_resources.h"
initial.commit09911bf2008-07-26 23:55:2945#include "net/base/mime_util.h"
46#include "net/base/net_util.h"
initial.commit09911bf2008-07-26 23:55:2947
[email protected]b7f05882009-02-22 01:21:5648#if defined(OS_WIN)
[email protected]4a0765a2009-05-08 23:12:2549#include "app/win_util.h"
[email protected]a0a9577b2009-05-27 23:52:3250#endif
51
[email protected]21ca982c2010-01-26 22:49:5552namespace {
53
[email protected]b0ab1d42010-02-24 19:29:2854// Used to sort download items based on descending start time.
55bool CompareStartTime(DownloadItem* first, DownloadItem* second) {
56 return first->start_time() > second->start_time();
57}
58
[email protected]21ca982c2010-01-26 22:49:5559} // namespace
60
initial.commit09911bf2008-07-26 23:55:2961DownloadManager::DownloadManager()
62 : shutdown_needed_(false),
63 profile_(NULL),
[email protected]82f37b02010-07-29 22:04:5764 file_manager_(NULL) {
initial.commit09911bf2008-07-26 23:55:2965}
66
67DownloadManager::~DownloadManager() {
[email protected]b0ab1d42010-02-24 19:29:2868 FOR_EACH_OBSERVER(Observer, observers_, ManagerGoingDown());
69
initial.commit09911bf2008-07-26 23:55:2970 if (shutdown_needed_)
71 Shutdown();
72}
73
74void DownloadManager::Shutdown() {
75 DCHECK(shutdown_needed_) << "Shutdown called when not needed.";
76
[email protected]47dbcd42010-09-01 17:30:1877 if (file_manager_) {
78 ChromeThread::PostTask(ChromeThread::FILE, FROM_HERE,
79 NewRunnableMethod(file_manager_,
80 &DownloadFileManager::OnDownloadManagerShutdown,
81 this));
82 }
initial.commit09911bf2008-07-26 23:55:2983
initial.commit09911bf2008-07-26 23:55:2984 // 'in_progress_' may contain DownloadItems that have not finished the start
85 // complete (from the history service) and thus aren't in downloads_.
86 DownloadMap::iterator it = in_progress_.begin();
[email protected]9ccbb372008-10-10 18:50:3287 std::set<DownloadItem*> to_remove;
initial.commit09911bf2008-07-26 23:55:2988 for (; it != in_progress_.end(); ++it) {
89 DownloadItem* download = it->second;
[email protected]9ccbb372008-10-10 18:50:3290 if (download->safety_state() == DownloadItem::DANGEROUS) {
91 // Forget about any download that the user did not approve.
92 // Note that we cannot call download->Remove() this would invalidate our
93 // iterator.
94 to_remove.insert(download);
95 continue;
initial.commit09911bf2008-07-26 23:55:2996 }
[email protected]9ccbb372008-10-10 18:50:3297 DCHECK_EQ(DownloadItem::IN_PROGRESS, download->state());
98 download->Cancel(false);
[email protected]82f37b02010-07-29 22:04:5799 download_history_->UpdateEntry(download);
100 if (download->db_handle() == DownloadHistory::kUninitializedHandle) {
initial.commit09911bf2008-07-26 23:55:29101 // An invalid handle means that 'download' does not yet exist in
102 // 'downloads_', so we have to delete it here.
103 delete download;
104 }
105 }
106
[email protected]9ccbb372008-10-10 18:50:32107 // 'dangerous_finished_' contains all complete downloads that have not been
108 // approved. They should be removed.
109 it = dangerous_finished_.begin();
110 for (; it != dangerous_finished_.end(); ++it)
111 to_remove.insert(it->second);
112
113 // Remove the dangerous download that are not approved.
114 for (std::set<DownloadItem*>::const_iterator rm_it = to_remove.begin();
115 rm_it != to_remove.end(); ++rm_it) {
116 DownloadItem* download = *rm_it;
[email protected]e10e17c72008-10-15 17:48:32117 int64 handle = download->db_handle();
[email protected]9ccbb372008-10-10 18:50:32118 download->Remove(true);
[email protected]e10e17c72008-10-15 17:48:32119 // Same as above, delete the download if it is not in 'downloads_' (as the
120 // Remove() call above won't have deleted it).
[email protected]82f37b02010-07-29 22:04:57121 if (handle == DownloadHistory::kUninitializedHandle)
[email protected]9ccbb372008-10-10 18:50:32122 delete download;
123 }
124 to_remove.clear();
125
initial.commit09911bf2008-07-26 23:55:29126 in_progress_.clear();
[email protected]9ccbb372008-10-10 18:50:32127 dangerous_finished_.clear();
initial.commit09911bf2008-07-26 23:55:29128 STLDeleteValues(&downloads_);
129
130 file_manager_ = NULL;
131
initial.commit09911bf2008-07-26 23:55:29132 // Make sure the save as dialog doesn't notify us back if we're gone before
133 // it returns.
134 if (select_file_dialog_.get())
135 select_file_dialog_->ListenerDestroyed();
136
[email protected]82f37b02010-07-29 22:04:57137 download_history_.reset();
138
initial.commit09911bf2008-07-26 23:55:29139 shutdown_needed_ = false;
140}
141
[email protected]82f37b02010-07-29 22:04:57142void DownloadManager::GetTemporaryDownloads(
143 const FilePath& dir_path, std::vector<DownloadItem*>* result) {
144 DCHECK(result);
[email protected]6aa4a1c02010-01-15 18:49:58145
146 for (DownloadMap::iterator it = downloads_.begin();
147 it != downloads_.end(); ++it) {
148 if (it->second->is_temporary() &&
149 it->second->full_path().DirName() == dir_path)
[email protected]82f37b02010-07-29 22:04:57150 result->push_back(it->second);
[email protected]6aa4a1c02010-01-15 18:49:58151 }
[email protected]6aa4a1c02010-01-15 18:49:58152}
153
[email protected]82f37b02010-07-29 22:04:57154void DownloadManager::GetAllDownloads(
155 const FilePath& dir_path, std::vector<DownloadItem*>* result) {
156 DCHECK(result);
[email protected]8ddbd66a2010-05-21 16:38:34157
158 for (DownloadMap::iterator it = downloads_.begin();
159 it != downloads_.end(); ++it) {
160 if (!it->second->is_temporary() &&
161 (dir_path.empty() || it->second->full_path().DirName() == dir_path))
[email protected]82f37b02010-07-29 22:04:57162 result->push_back(it->second);
[email protected]8ddbd66a2010-05-21 16:38:34163 }
[email protected]8ddbd66a2010-05-21 16:38:34164}
165
[email protected]82f37b02010-07-29 22:04:57166void DownloadManager::GetCurrentDownloads(
167 const FilePath& dir_path, std::vector<DownloadItem*>* result) {
168 DCHECK(result);
[email protected]c4a530b2010-03-08 17:33:03169
170 for (DownloadMap::iterator it = downloads_.begin();
171 it != downloads_.end(); ++it) {
172 if (!it->second->is_temporary() &&
173 (it->second->state() == DownloadItem::IN_PROGRESS ||
174 it->second->safety_state() == DownloadItem::DANGEROUS) &&
175 (dir_path.empty() || it->second->full_path().DirName() == dir_path))
[email protected]82f37b02010-07-29 22:04:57176 result->push_back(it->second);
[email protected]c4a530b2010-03-08 17:33:03177 }
[email protected]c4a530b2010-03-08 17:33:03178}
179
[email protected]d3b12902010-08-16 23:39:42180void DownloadManager::SearchDownloads(const string16& query,
181 std::vector<DownloadItem*>* result) {
182 DCHECK(result);
183
184 string16 query_lower(l10n_util::ToLower(query));
185
186 for (DownloadMap::iterator it = downloads_.begin();
187 it != downloads_.end(); ++it) {
188 DownloadItem* download_item = it->second;
189
190 if (download_item->is_temporary() || download_item->is_extension_install())
191 continue;
192
193 // Display Incognito downloads only in Incognito window, and vice versa.
194 // The Incognito Downloads page will get the list of non-Incognito downloads
195 // from its parent profile.
196 if (profile_->IsOffTheRecord() != download_item->is_otr())
197 continue;
198
199 if (download_item->MatchesQuery(query_lower))
200 result->push_back(download_item);
201 }
202
203 // If we have a parent profile, let it add its downloads to the results.
204 Profile* original_profile = profile_->GetOriginalProfile();
205 if (original_profile != profile_)
206 original_profile->GetDownloadManager()->SearchDownloads(query, result);
207}
208
initial.commit09911bf2008-07-26 23:55:29209// Query the history service for information about all persisted downloads.
210bool DownloadManager::Init(Profile* profile) {
211 DCHECK(profile);
212 DCHECK(!shutdown_needed_) << "DownloadManager already initialized.";
213 shutdown_needed_ = true;
214
215 profile_ = profile;
[email protected]be180c802009-10-23 06:33:31216 request_context_getter_ = profile_->GetRequestContext();
[email protected]d3b12902010-08-16 23:39:42217 download_history_.reset(new DownloadHistory(profile));
[email protected]82f37b02010-07-29 22:04:57218 download_history_->Load(
219 NewCallback(this, &DownloadManager::OnQueryDownloadEntriesComplete));
[email protected]024f2f02010-04-30 22:51:46220
[email protected]e5dc4222010-08-30 22:16:32221 download_prefs_.reset(new DownloadPrefs(profile_->GetPrefs()));
222
[email protected]2941c2392010-07-15 22:54:30223 // In test mode, there may be no ResourceDispatcherHost. In this case it's
224 // safe to avoid setting |file_manager_| because we only call a small set of
225 // functions, none of which need it.
initial.commit09911bf2008-07-26 23:55:29226 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
[email protected]2941c2392010-07-15 22:54:30227 if (rdh) {
228 file_manager_ = rdh->download_file_manager();
229 DCHECK(file_manager_);
initial.commit09911bf2008-07-26 23:55:29230 }
231
[email protected]b0ab1d42010-02-24 19:29:28232 other_download_manager_observer_.reset(
233 new OtherDownloadManagerObserver(this));
234
initial.commit09911bf2008-07-26 23:55:29235 return true;
236}
237
initial.commit09911bf2008-07-26 23:55:29238// We have received a message from DownloadFileManager about a new download. We
239// create a download item and store it in our download map, and inform the
240// history system of a new download. Since this method can be called while the
241// history service thread is still reading the persistent state, we do not
242// insert the new DownloadItem into 'downloads_' or inform our observers at this
243// point. OnCreateDatabaseEntryComplete() handles that finalization of the the
244// download creation as a callback from the history thread.
245void DownloadManager::StartDownload(DownloadCreateInfo* info) {
[email protected]d83d03aa2009-11-02 21:44:37246 DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
initial.commit09911bf2008-07-26 23:55:29247 DCHECK(info);
248
[email protected]a60c8ae2009-12-25 06:50:57249 // Check whether this download is for an extension install or not.
[email protected]e6875c12010-07-18 11:14:13250 // Allow extensions to be explicitly saved.
251 if (!info->prompt_user_for_save_location) {
[email protected]a60c8ae2009-12-25 06:50:57252 if (UserScript::HasUserScriptFileExtension(info->url) ||
253 info->mime_type == Extension::kMimeType)
254 info->is_extension_install = true;
255 }
256
[email protected]8af9d032010-02-10 00:00:32257 if (info->save_info.file_path.empty()) {
[email protected]2941c2392010-07-15 22:54:30258 FilePath generated_name;
[email protected]7ba53e12010-08-05 17:14:00259 download_util::GenerateFileNameFromInfo(info, &generated_name);
[email protected]2941c2392010-07-15 22:54:30260
261 // Freeze the user's preference for showing a Save As dialog. We're going
262 // to bounce around a bunch of threads and we don't want to worry about race
263 // conditions where the user changes this pref out from under us.
[email protected]e5dc4222010-08-30 22:16:32264 if (download_prefs_->prompt_for_download()) {
[email protected]2941c2392010-07-15 22:54:30265 // But ignore the user's preference for the following scenarios:
266 // 1) Extension installation. Note that we only care here about the case
267 // where an extension is installed, not when one is downloaded with
268 // "save as...".
269 // 2) Filetypes marked "always open." If the user just wants this file
270 // opened, don't bother asking where to keep it.
271 if (!info->is_extension_install &&
272 !ShouldOpenFileBasedOnExtension(generated_name))
[email protected]e6875c12010-07-18 11:14:13273 info->prompt_user_for_save_location = true;
[email protected]2941c2392010-07-15 22:54:30274 }
275
[email protected]8af9d032010-02-10 00:00:32276 // Determine the proper path for a download, by either one of the following:
277 // 1) using the default download directory.
278 // 2) prompting the user.
[email protected]80dc3612010-07-27 19:35:08279 if (info->prompt_user_for_save_location && !last_download_path_.empty()){
[email protected]8af9d032010-02-10 00:00:32280 info->suggested_path = last_download_path_;
[email protected]80dc3612010-07-27 19:35:08281 } else {
[email protected]e5dc4222010-08-30 22:16:32282 info->suggested_path = download_prefs_->download_path();
[email protected]80dc3612010-07-27 19:35:08283 }
[email protected]8af9d032010-02-10 00:00:32284 info->suggested_path = info->suggested_path.Append(generated_name);
285 } else {
286 info->suggested_path = info->save_info.file_path;
287 }
initial.commit09911bf2008-07-26 23:55:29288
[email protected]e6875c12010-07-18 11:14:13289 if (!info->prompt_user_for_save_location &&
290 info->save_info.file_path.empty()) {
[email protected]4289d9b2009-07-25 21:17:34291 // Downloads can be marked as dangerous for two reasons:
292 // a) They have a dangerous-looking filename
293 // b) They are an extension that is not from the gallery
[email protected]e5dc4222010-08-30 22:16:32294 if (download_util::IsExecutableFile(info->suggested_path.BaseName()))
[email protected]4289d9b2009-07-25 21:17:34295 info->is_dangerous = true;
[email protected]a60c8ae2009-12-25 06:50:57296 else if (info->is_extension_install &&
[email protected]b7c2f252009-12-08 00:47:23297 !ExtensionsService::IsDownloadFromGallery(info->url,
298 info->referrer_url)) {
[email protected]4289d9b2009-07-25 21:17:34299 info->is_dangerous = true;
300 }
[email protected]e9ebf3fc2008-10-17 22:06:58301 }
302
initial.commit09911bf2008-07-26 23:55:29303 // We need to move over to the download thread because we don't want to stat
304 // the suggested path on the UI thread.
[email protected]d83d03aa2009-11-02 21:44:37305 ChromeThread::PostTask(
306 ChromeThread::FILE, FROM_HERE,
307 NewRunnableMethod(
308 this, &DownloadManager::CheckIfSuggestedPathExists, info));
initial.commit09911bf2008-07-26 23:55:29309}
310
311void DownloadManager::CheckIfSuggestedPathExists(DownloadCreateInfo* info) {
[email protected]aa033af2010-07-27 18:16:39312 DCHECK(ChromeThread::CurrentlyOn(ChromeThread::FILE));
initial.commit09911bf2008-07-26 23:55:29313 DCHECK(info);
314
315 // Check writability of the suggested path. If we can't write to it, default
316 // to the user's "My Documents" directory. We'll prompt them in this case.
[email protected]7ae7c2cb2009-01-06 23:31:41317 FilePath dir = info->suggested_path.DirName();
318 FilePath filename = info->suggested_path.BaseName();
[email protected]9ccbb372008-10-10 18:50:32319 if (!file_util::PathIsWritable(dir)) {
[email protected]e6875c12010-07-18 11:14:13320 info->prompt_user_for_save_location = true;
initial.commit09911bf2008-07-26 23:55:29321 PathService::Get(chrome::DIR_USER_DOCUMENTS, &info->suggested_path);
[email protected]7ae7c2cb2009-01-06 23:31:41322 info->suggested_path = info->suggested_path.Append(filename);
initial.commit09911bf2008-07-26 23:55:29323 }
324
[email protected]6cade212008-12-03 00:32:22325 // If the download is deemed dangerous, we'll use a temporary name for it.
[email protected]e9ebf3fc2008-10-17 22:06:58326 if (info->is_dangerous) {
[email protected]7ae7c2cb2009-01-06 23:31:41327 info->original_name = FilePath(info->suggested_path).BaseName();
[email protected]9ccbb372008-10-10 18:50:32328 // Create a temporary file to hold the file until the user approves its
329 // download.
[email protected]7ae7c2cb2009-01-06 23:31:41330 FilePath::StringType file_name;
331 FilePath path;
[email protected]9ccbb372008-10-10 18:50:32332 while (path.empty()) {
[email protected]594cd7d2010-07-21 03:23:56333 SStringPrintf(&file_name, FILE_PATH_LITERAL("unconfirmed %d.crdownload"),
[email protected]9ccbb372008-10-10 18:50:32334 base::RandInt(0, 100000));
[email protected]7ae7c2cb2009-01-06 23:31:41335 path = dir.Append(file_name);
[email protected]7d3851d82008-12-12 03:26:07336 if (file_util::PathExists(path))
[email protected]7ae7c2cb2009-01-06 23:31:41337 path = FilePath();
[email protected]9ccbb372008-10-10 18:50:32338 }
339 info->suggested_path = path;
[email protected]7a256ea2008-10-17 17:34:16340 } else {
[email protected]594cd7d2010-07-21 03:23:56341 // Do not add the path uniquifier if we are saving to a specific path as in
342 // the drag-out case.
343 if (info->save_info.file_path.empty()) {
344 info->path_uniquifier = download_util::GetUniquePathNumberWithCrDownload(
345 info->suggested_path);
346 }
[email protected]7a256ea2008-10-17 17:34:16347 // We know the final path, build it if necessary.
348 if (info->path_uniquifier > 0) {
[email protected]5a2388a2010-03-26 16:13:39349 download_util::AppendNumberToPath(&(info->suggested_path),
350 info->path_uniquifier);
[email protected]7a256ea2008-10-17 17:34:16351 // Setting path_uniquifier to 0 to make sure we don't try to unique it
352 // later on.
353 info->path_uniquifier = 0;
[email protected]7d3851d82008-12-12 03:26:07354 } else if (info->path_uniquifier == -1) {
355 // We failed to find a unique path. We have to prompt the user.
[email protected]e6875c12010-07-18 11:14:13356 info->prompt_user_for_save_location = true;
[email protected]7a256ea2008-10-17 17:34:16357 }
[email protected]9ccbb372008-10-10 18:50:32358 }
359
[email protected]594cd7d2010-07-21 03:23:56360 // Create an empty file at the suggested path so that we don't allocate the
361 // same "non-existant" path to multiple downloads.
362 // See: http://code.google.com/p/chromium/issues/detail?id=3662
[email protected]e6875c12010-07-18 11:14:13363 if (!info->prompt_user_for_save_location &&
364 info->save_info.file_path.empty()) {
[email protected]594cd7d2010-07-21 03:23:56365 if (info->is_dangerous)
366 file_util::WriteFile(info->suggested_path, "", 0);
367 else
368 file_util::WriteFile(download_util::GetCrDownloadPath(
369 info->suggested_path), "", 0);
[email protected]7d3851d82008-12-12 03:26:07370 }
371
[email protected]d83d03aa2009-11-02 21:44:37372 ChromeThread::PostTask(
373 ChromeThread::UI, FROM_HERE,
initial.commit09911bf2008-07-26 23:55:29374 NewRunnableMethod(this,
375 &DownloadManager::OnPathExistenceAvailable,
376 info));
377}
378
379void DownloadManager::OnPathExistenceAvailable(DownloadCreateInfo* info) {
[email protected]d83d03aa2009-11-02 21:44:37380 DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
initial.commit09911bf2008-07-26 23:55:29381 DCHECK(info);
382
[email protected]e6875c12010-07-18 11:14:13383 if (info->prompt_user_for_save_location) {
initial.commit09911bf2008-07-26 23:55:29384 // We must ask the user for the place to put the download.
385 if (!select_file_dialog_.get())
386 select_file_dialog_ = SelectFileDialog::Create(this);
387
[email protected]76543b92009-08-31 17:27:45388 TabContents* contents = tab_util::GetTabContentsByID(info->child_id,
389 info->render_view_id);
[email protected]b949f1112009-04-12 20:03:08390 SelectFileDialog::FileTypeInfo file_type_info;
391 file_type_info.extensions.resize(1);
392 file_type_info.extensions[0].push_back(info->suggested_path.Extension());
[email protected]15bc8052009-04-17 19:57:24393 if (!file_type_info.extensions[0][0].empty())
394 file_type_info.extensions[0][0].erase(0, 1); // drop the .
[email protected]b949f1112009-04-12 20:03:08395 file_type_info.include_all_files = true;
[email protected]076700e62009-04-01 18:41:23396 gfx::NativeWindow owning_window =
397 contents ? platform_util::GetTopLevel(contents->GetNativeView()) : NULL;
initial.commit09911bf2008-07-26 23:55:29398 select_file_dialog_->SelectFile(SelectFileDialog::SELECT_SAVEAS_FILE,
[email protected]561abe62009-04-06 18:08:34399 string16(),
400 info->suggested_path,
[email protected]b949f1112009-04-12 20:03:08401 &file_type_info, 0, FILE_PATH_LITERAL(""),
[email protected]0f44d3e2009-03-12 23:36:30402 owning_window, info);
initial.commit09911bf2008-07-26 23:55:29403 } else {
404 // No prompting for download, just continue with the suggested name.
405 ContinueStartDownload(info, info->suggested_path);
406 }
407}
408
409void DownloadManager::ContinueStartDownload(DownloadCreateInfo* info,
[email protected]7ae7c2cb2009-01-06 23:31:41410 const FilePath& target_path) {
[email protected]aa033af2010-07-27 18:16:39411 DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
412
initial.commit09911bf2008-07-26 23:55:29413 scoped_ptr<DownloadCreateInfo> infop(info);
414 info->path = target_path;
415
[email protected]aa033af2010-07-27 18:16:39416 DownloadItem* download = new DownloadItem(this, *info,
417 profile_->IsOffTheRecord());
418 DCHECK(!ContainsKey(in_progress_, info->download_id));
419 in_progress_[info->download_id] = download;
initial.commit09911bf2008-07-26 23:55:29420
[email protected]aa033af2010-07-27 18:16:39421 bool download_finished = ContainsKey(pending_finished_downloads_,
422 info->download_id);
[email protected]594cd7d2010-07-21 03:23:56423
424 if (download_finished || info->is_dangerous) {
425 // The download has already finished or the download is not safe.
426 // We can now rename the file to its final name (or its tentative name
427 // in dangerous download cases).
428 ChromeThread::PostTask(
429 ChromeThread::FILE, FROM_HERE,
430 NewRunnableMethod(
431 file_manager_, &DownloadFileManager::OnFinalDownloadName,
432 download->id(), target_path, !info->is_dangerous, this));
433 } else {
434 // The download hasn't finished and it is a safe download. We need to
435 // rename it to its intermediate '.crdownload' path.
436 FilePath download_path = download_util::GetCrDownloadPath(target_path);
437 ChromeThread::PostTask(
438 ChromeThread::FILE, FROM_HERE,
439 NewRunnableMethod(
440 file_manager_, &DownloadFileManager::OnIntermediateDownloadName,
441 download->id(), download_path, this));
442 download->set_need_final_rename(true);
443 }
444
445 if (download_finished) {
446 // If the download already completed by the time we reached this point, then
447 // notify observers that it did.
[email protected]aa033af2010-07-27 18:16:39448 DownloadFinished(info->download_id,
449 pending_finished_downloads_[info->download_id]);
[email protected]594cd7d2010-07-21 03:23:56450 }
initial.commit09911bf2008-07-26 23:55:29451
452 download->Rename(target_path);
453
[email protected]82f37b02010-07-29 22:04:57454 download_history_->AddEntry(*info, download,
455 NewCallback(this, &DownloadManager::OnCreateDownloadEntryComplete));
[email protected]6a7fb042010-02-01 16:30:47456
457 UpdateAppIcon();
initial.commit09911bf2008-07-26 23:55:29458}
459
initial.commit09911bf2008-07-26 23:55:29460void DownloadManager::UpdateDownload(int32 download_id, int64 size) {
461 DownloadMap::iterator it = in_progress_.find(download_id);
462 if (it != in_progress_.end()) {
463 DownloadItem* download = it->second;
464 download->Update(size);
[email protected]82f37b02010-07-29 22:04:57465 download_history_->UpdateEntry(download);
initial.commit09911bf2008-07-26 23:55:29466 }
[email protected]6a7fb042010-02-01 16:30:47467 UpdateAppIcon();
initial.commit09911bf2008-07-26 23:55:29468}
469
470void DownloadManager::DownloadFinished(int32 download_id, int64 size) {
471 DownloadMap::iterator it = in_progress_.find(download_id);
[email protected]9ccbb372008-10-10 18:50:32472 if (it == in_progress_.end()) {
initial.commit09911bf2008-07-26 23:55:29473 // The download is done, but the user hasn't selected a final location for
474 // it yet (the Save As dialog box is probably still showing), so just keep
475 // track of the fact that this download id is complete, when the
476 // DownloadItem is constructed later we'll notify its completion then.
477 PendingFinishedMap::iterator erase_it =
478 pending_finished_downloads_.find(download_id);
479 DCHECK(erase_it == pending_finished_downloads_.end());
480 pending_finished_downloads_[download_id] = size;
[email protected]9ccbb372008-10-10 18:50:32481 return;
initial.commit09911bf2008-07-26 23:55:29482 }
[email protected]9ccbb372008-10-10 18:50:32483
484 // Remove the id from the list of pending ids.
485 PendingFinishedMap::iterator erase_it =
486 pending_finished_downloads_.find(download_id);
487 if (erase_it != pending_finished_downloads_.end())
488 pending_finished_downloads_.erase(erase_it);
489
490 DownloadItem* download = it->second;
491 download->Finished(size);
492
493 // Clean up will happen when the history system create callback runs if we
494 // don't have a valid db_handle yet.
[email protected]82f37b02010-07-29 22:04:57495 if (download->db_handle() != DownloadHistory::kUninitializedHandle) {
[email protected]9ccbb372008-10-10 18:50:32496 in_progress_.erase(it);
[email protected]82f37b02010-07-29 22:04:57497 download_history_->UpdateEntry(download);
[email protected]9ccbb372008-10-10 18:50:32498 }
499
[email protected]6a7fb042010-02-01 16:30:47500 UpdateAppIcon();
501
[email protected]9ccbb372008-10-10 18:50:32502 // If this a dangerous download not yet validated by the user, don't do
503 // anything. When the user notifies us, it will trigger a call to
504 // ProceedWithFinishedDangerousDownload.
505 if (download->safety_state() == DownloadItem::DANGEROUS) {
506 dangerous_finished_[download_id] = download;
507 return;
508 }
509
510 if (download->safety_state() == DownloadItem::DANGEROUS_BUT_VALIDATED) {
[email protected]6cade212008-12-03 00:32:22511 // We first need to rename the downloaded file from its temporary name to
[email protected]9ccbb372008-10-10 18:50:32512 // its final name before we can continue.
[email protected]d83d03aa2009-11-02 21:44:37513 ChromeThread::PostTask(
514 ChromeThread::FILE, FROM_HERE,
[email protected]9ccbb372008-10-10 18:50:32515 NewRunnableMethod(
516 this, &DownloadManager::ProceedWithFinishedDangerousDownload,
517 download->db_handle(),
518 download->full_path(), download->original_name()));
519 return;
520 }
[email protected]594cd7d2010-07-21 03:23:56521
522 if (download->need_final_rename()) {
523 ChromeThread::PostTask(
524 ChromeThread::FILE, FROM_HERE,
525 NewRunnableMethod(
526 file_manager_, &DownloadFileManager::OnFinalDownloadName,
527 download->id(), download->full_path(), false, this));
528 return;
529 }
530
[email protected]9ccbb372008-10-10 18:50:32531 ContinueDownloadFinished(download);
532}
533
[email protected]8f783752009-04-01 23:33:45534void DownloadManager::DownloadRenamedToFinalName(int download_id,
535 const FilePath& full_path) {
[email protected]aa033af2010-07-27 18:16:39536 DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
537
[email protected]2e030682010-07-23 19:45:36538 DownloadItem* item = GetDownloadItem(download_id);
539 if (!item)
540 return;
541 item->OnNameFinalized();
[email protected]594cd7d2010-07-21 03:23:56542
[email protected]2e030682010-07-23 19:45:36543 // This was called from DownloadFinished; continue to call
544 // ContinueDownloadFinished.
545 if (item->need_final_rename()) {
546 item->set_need_final_rename(false);
547 ContinueDownloadFinished(item);
[email protected]6aa4a1c02010-01-15 18:49:58548 }
[email protected]8f783752009-04-01 23:33:45549}
550
[email protected]9ccbb372008-10-10 18:50:32551void DownloadManager::ContinueDownloadFinished(DownloadItem* download) {
[email protected]aa033af2010-07-27 18:16:39552 DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
553
[email protected]9ccbb372008-10-10 18:50:32554 // If this was a dangerous download, it has now been approved and must be
555 // removed from dangerous_finished_ so it does not get deleted on shutdown.
[email protected]aa033af2010-07-27 18:16:39556 dangerous_finished_.erase(download->id());
[email protected]9ccbb372008-10-10 18:50:32557
[email protected]0aad67b2009-07-15 20:34:28558 // Handle chrome extensions explicitly and skip the shell execute.
[email protected]a60c8ae2009-12-25 06:50:57559 if (download->is_extension_install()) {
[email protected]7ba53e12010-08-05 17:14:00560 download_util::OpenChromeExtension(profile_, this, *download);
[email protected]0aad67b2009-07-15 20:34:28561 download->set_auto_opened(true);
562 } else if (download->open_when_complete() ||
[email protected]6aa4a1c02010-01-15 18:49:58563 ShouldOpenFileBasedOnExtension(download->full_path()) ||
564 download->is_temporary()) {
565 // If the download is temporary, like in drag-and-drop, do not open it but
566 // we still need to set it auto-opened so that it can be removed from the
567 // download shelf.
568 if (!download->is_temporary())
569 OpenDownloadInShell(download, NULL);
[email protected]0aad67b2009-07-15 20:34:28570 download->set_auto_opened(true);
571 }
[email protected]9ccbb372008-10-10 18:50:32572
[email protected]0aad67b2009-07-15 20:34:28573 // Notify our observers that we are complete (the call to Finished() set the
574 // state to complete but did not notify).
575 download->UpdateObservers();
[email protected]6aa4a1c02010-01-15 18:49:58576
577 // The download file is meant to be completed if both the filename is
578 // finalized and the file data is downloaded. The ordering of these two
579 // actions is indeterministic. Thus, if the filename is not finalized yet,
580 // delay the notification.
581 if (download->name_finalized())
582 download->NotifyObserversDownloadFileCompleted();
[email protected]0aad67b2009-07-15 20:34:28583}
[email protected]eccb9d12009-10-28 05:40:09584
[email protected]9ccbb372008-10-10 18:50:32585// Called on the file thread. Renames the downloaded file to its original name.
586void DownloadManager::ProceedWithFinishedDangerousDownload(
587 int64 download_handle,
[email protected]7ae7c2cb2009-01-06 23:31:41588 const FilePath& path,
589 const FilePath& original_name) {
[email protected]9ccbb372008-10-10 18:50:32590 bool success = false;
[email protected]7ae7c2cb2009-01-06 23:31:41591 FilePath new_path;
[email protected]7a256ea2008-10-17 17:34:16592 int uniquifier = 0;
[email protected]9ccbb372008-10-10 18:50:32593 if (file_util::PathExists(path)) {
[email protected]889ed35c2009-01-21 00:07:24594 new_path = path.DirName().Append(original_name);
[email protected]7a256ea2008-10-17 17:34:16595 // Make our name unique at this point, as if a dangerous file is downloading
596 // and a 2nd download is started for a file with the same name, they would
597 // have the same path. This is because we uniquify the name on download
598 // start, and at that time the first file does not exists yet, so the second
599 // file gets the same name.
[email protected]5a2388a2010-03-26 16:13:39600 uniquifier = download_util::GetUniquePathNumber(new_path);
[email protected]7a256ea2008-10-17 17:34:16601 if (uniquifier > 0)
[email protected]5a2388a2010-03-26 16:13:39602 download_util::AppendNumberToPath(&new_path, uniquifier);
[email protected]9ccbb372008-10-10 18:50:32603 success = file_util::Move(path, new_path);
604 } else {
605 NOTREACHED();
606 }
[email protected]6cade212008-12-03 00:32:22607
[email protected]d83d03aa2009-11-02 21:44:37608 ChromeThread::PostTask(
609 ChromeThread::UI, FROM_HERE,
[email protected]9ccbb372008-10-10 18:50:32610 NewRunnableMethod(this, &DownloadManager::DangerousDownloadRenamed,
[email protected]7a256ea2008-10-17 17:34:16611 download_handle, success, new_path, uniquifier));
[email protected]9ccbb372008-10-10 18:50:32612}
613
614// Call from the file thread when the finished dangerous download was renamed.
615void DownloadManager::DangerousDownloadRenamed(int64 download_handle,
616 bool success,
[email protected]7ae7c2cb2009-01-06 23:31:41617 const FilePath& new_path,
[email protected]7a256ea2008-10-17 17:34:16618 int new_path_uniquifier) {
[email protected]9ccbb372008-10-10 18:50:32619 DownloadMap::iterator it = downloads_.find(download_handle);
620 if (it == downloads_.end()) {
621 NOTREACHED();
622 return;
623 }
624
625 DownloadItem* download = it->second;
626 // If we failed to rename the file, we'll just keep the name as is.
[email protected]7a256ea2008-10-17 17:34:16627 if (success) {
628 // We need to update the path uniquifier so that the UI shows the right
629 // name when calling GetFileName().
630 download->set_path_uniquifier(new_path_uniquifier);
[email protected]9ccbb372008-10-10 18:50:32631 RenameDownload(download, new_path);
[email protected]7a256ea2008-10-17 17:34:16632 }
[email protected]9ccbb372008-10-10 18:50:32633
634 // Continue the download finished sequence.
635 ContinueDownloadFinished(download);
initial.commit09911bf2008-07-26 23:55:29636}
637
initial.commit09911bf2008-07-26 23:55:29638void DownloadManager::DownloadCancelled(int32 download_id) {
639 DownloadMap::iterator it = in_progress_.find(download_id);
640 if (it == in_progress_.end())
641 return;
642 DownloadItem* download = it->second;
643
initial.commit09911bf2008-07-26 23:55:29644 // Clean up will happen when the history system create callback runs if we
645 // don't have a valid db_handle yet.
[email protected]82f37b02010-07-29 22:04:57646 if (download->db_handle() != DownloadHistory::kUninitializedHandle) {
initial.commit09911bf2008-07-26 23:55:29647 in_progress_.erase(it);
[email protected]82f37b02010-07-29 22:04:57648 download_history_->UpdateEntry(download);
initial.commit09911bf2008-07-26 23:55:29649 }
650
[email protected]d7d1c5c2009-08-05 23:52:50651 DownloadCancelledInternal(download_id,
652 download->render_process_id(),
653 download->request_id());
[email protected]6a7fb042010-02-01 16:30:47654 UpdateAppIcon();
[email protected]d7d1c5c2009-08-05 23:52:50655}
656
657void DownloadManager::DownloadCancelledInternal(int download_id,
658 int render_process_id,
659 int request_id) {
[email protected]d85cf072009-10-27 03:59:31660 // Cancel the network request. RDH is guaranteed to outlive the IO thread.
661 ChromeThread::PostTask(
662 ChromeThread::IO, FROM_HERE,
[email protected]ae8945192010-07-20 16:56:26663 NewRunnableFunction(&download_util::CancelDownloadRequest,
[email protected]d85cf072009-10-27 03:59:31664 g_browser_process->resource_dispatcher_host(),
665 render_process_id,
666 request_id));
[email protected]d7d1c5c2009-08-05 23:52:50667
[email protected]d83d03aa2009-11-02 21:44:37668 ChromeThread::PostTask(
669 ChromeThread::FILE, FROM_HERE,
670 NewRunnableMethod(
671 file_manager_, &DownloadFileManager::CancelDownload, download_id));
initial.commit09911bf2008-07-26 23:55:29672}
673
[email protected]7ba53e12010-08-05 17:14:00674// DownloadManager is owned by RDH, no need for reference counting.
675DISABLE_RUNNABLE_METHOD_REFCOUNT(ResourceDispatcherHost);
676
initial.commit09911bf2008-07-26 23:55:29677void DownloadManager::PauseDownload(int32 download_id, bool pause) {
678 DownloadMap::iterator it = in_progress_.find(download_id);
[email protected]d85cf072009-10-27 03:59:31679 if (it == in_progress_.end())
680 return;
initial.commit09911bf2008-07-26 23:55:29681
[email protected]d85cf072009-10-27 03:59:31682 DownloadItem* download = it->second;
683 if (pause == download->is_paused())
684 return;
initial.commit09911bf2008-07-26 23:55:29685
[email protected]d85cf072009-10-27 03:59:31686 // Inform the ResourceDispatcherHost of the new pause state.
687 ChromeThread::PostTask(
688 ChromeThread::IO, FROM_HERE,
[email protected]7ba53e12010-08-05 17:14:00689 NewRunnableMethod(g_browser_process->resource_dispatcher_host(),
690 &ResourceDispatcherHost::PauseRequest,
691 download->render_process_id(),
692 download->request_id(),
693 pause));
[email protected]9ccbb372008-10-10 18:50:32694}
695
[email protected]6a7fb042010-02-01 16:30:47696void DownloadManager::UpdateAppIcon() {
697 int64 total_bytes = 0;
698 int64 received_bytes = 0;
699 int download_count = 0;
700 bool progress_known = true;
701
702 for (DownloadMap::iterator i = in_progress_.begin();
703 i != in_progress_.end();
704 ++i) {
705 ++download_count;
706 const DownloadItem* item = i->second;
707 if (item->total_bytes() > 0) {
708 total_bytes += item->total_bytes();
709 received_bytes += item->received_bytes();
710 } else {
711 // This download didn't specify a Content-Length, so the combined progress
712 // bar neeeds to be indeterminate.
713 progress_known = false;
714 }
715 }
716
717 float progress = 0;
718 if (progress_known && download_count)
[email protected]7ba53e12010-08-05 17:14:00719 progress = static_cast<float>(received_bytes) / total_bytes;
[email protected]6a7fb042010-02-01 16:30:47720
721 download_util::UpdateAppIconDownloadProgress(download_count,
722 progress_known,
723 progress);
724}
725
[email protected]9ccbb372008-10-10 18:50:32726void DownloadManager::RenameDownload(DownloadItem* download,
[email protected]7ae7c2cb2009-01-06 23:31:41727 const FilePath& new_path) {
[email protected]9ccbb372008-10-10 18:50:32728 download->Rename(new_path);
[email protected]82f37b02010-07-29 22:04:57729 download_history_->UpdateDownloadPath(download, new_path);
[email protected]9ccbb372008-10-10 18:50:32730}
731
initial.commit09911bf2008-07-26 23:55:29732void DownloadManager::RemoveDownload(int64 download_handle) {
733 DownloadMap::iterator it = downloads_.find(download_handle);
734 if (it == downloads_.end())
735 return;
736
737 // Make history update.
738 DownloadItem* download = it->second;
[email protected]82f37b02010-07-29 22:04:57739 download_history_->RemoveEntry(download);
initial.commit09911bf2008-07-26 23:55:29740
741 // Remove from our tables and delete.
742 downloads_.erase(it);
[email protected]9ccbb372008-10-10 18:50:32743 it = dangerous_finished_.find(download->id());
744 if (it != dangerous_finished_.end())
745 dangerous_finished_.erase(it);
initial.commit09911bf2008-07-26 23:55:29746
747 // Tell observers to refresh their views.
[email protected]b0ab1d42010-02-24 19:29:28748 NotifyModelChanged();
[email protected]6f712872008-11-07 00:35:36749
750 delete download;
initial.commit09911bf2008-07-26 23:55:29751}
752
[email protected]e93d2822009-01-30 05:59:59753int DownloadManager::RemoveDownloadsBetween(const base::Time remove_begin,
754 const base::Time remove_end) {
[email protected]82f37b02010-07-29 22:04:57755 download_history_->RemoveEntriesBetween(remove_begin, remove_end);
initial.commit09911bf2008-07-26 23:55:29756
initial.commit09911bf2008-07-26 23:55:29757 DownloadMap::iterator it = downloads_.begin();
[email protected]78b8fcc92009-03-31 17:36:28758 std::vector<DownloadItem*> pending_deletes;
initial.commit09911bf2008-07-26 23:55:29759 while (it != downloads_.end()) {
760 DownloadItem* download = it->second;
761 DownloadItem::DownloadState state = download->state();
762 if (download->start_time() >= remove_begin &&
763 (remove_end.is_null() || download->start_time() < remove_end) &&
764 (state == DownloadItem::COMPLETE ||
765 state == DownloadItem::CANCELLED)) {
766 // Remove from the map and move to the next in the list.
[email protected]b7f05882009-02-22 01:21:56767 downloads_.erase(it++);
[email protected]a6604d92008-10-30 00:58:58768
769 // Also remove it from any completed dangerous downloads.
770 DownloadMap::iterator dit = dangerous_finished_.find(download->id());
771 if (dit != dangerous_finished_.end())
772 dangerous_finished_.erase(dit);
773
[email protected]78b8fcc92009-03-31 17:36:28774 pending_deletes.push_back(download);
[email protected]b0ab1d42010-02-24 19:29:28775 // Observer interface.
initial.commit09911bf2008-07-26 23:55:29776
initial.commit09911bf2008-07-26 23:55:29777 continue;
778 }
779
780 ++it;
781 }
782
783 // Tell observers to refresh their views.
[email protected]78b8fcc92009-03-31 17:36:28784 int num_deleted = static_cast<int>(pending_deletes.size());
initial.commit09911bf2008-07-26 23:55:29785 if (num_deleted > 0)
[email protected]b0ab1d42010-02-24 19:29:28786 NotifyModelChanged();
initial.commit09911bf2008-07-26 23:55:29787
[email protected]78b8fcc92009-03-31 17:36:28788 // Delete the download items after updating the observers.
789 STLDeleteContainerPointers(pending_deletes.begin(), pending_deletes.end());
790 pending_deletes.clear();
791
initial.commit09911bf2008-07-26 23:55:29792 return num_deleted;
793}
794
[email protected]e93d2822009-01-30 05:59:59795int DownloadManager::RemoveDownloads(const base::Time remove_begin) {
796 return RemoveDownloadsBetween(remove_begin, base::Time());
initial.commit09911bf2008-07-26 23:55:29797}
798
[email protected]d41355e6f2009-04-07 21:21:12799int DownloadManager::RemoveAllDownloads() {
[email protected]024f2f02010-04-30 22:51:46800 if (this != profile_->GetOriginalProfile()->GetDownloadManager()) {
801 // This is an incognito downloader. Clear All should clear main download
802 // manager as well.
803 profile_->GetOriginalProfile()->GetDownloadManager()->RemoveAllDownloads();
804 }
[email protected]d41355e6f2009-04-07 21:21:12805 // The null times make the date range unbounded.
806 return RemoveDownloadsBetween(base::Time(), base::Time());
807}
808
initial.commit09911bf2008-07-26 23:55:29809// Initiate a download of a specific URL. We send the request to the
810// ResourceDispatcherHost, and let it send us responses like a regular
811// download.
812void DownloadManager::DownloadUrl(const GURL& url,
813 const GURL& referrer,
[email protected]c9825a42009-05-01 22:51:50814 const std::string& referrer_charset,
[email protected]57c6a652009-05-04 07:58:34815 TabContents* tab_contents) {
[email protected]ae8945192010-07-20 16:56:26816 DownloadUrlToFile(url, referrer, referrer_charset, DownloadSaveInfo(),
817 tab_contents);
[email protected]6aa4a1c02010-01-15 18:49:58818}
819
820void DownloadManager::DownloadUrlToFile(const GURL& url,
821 const GURL& referrer,
822 const std::string& referrer_charset,
[email protected]8af9d032010-02-10 00:00:32823 const DownloadSaveInfo& save_info,
[email protected]6aa4a1c02010-01-15 18:49:58824 TabContents* tab_contents) {
[email protected]57c6a652009-05-04 07:58:34825 DCHECK(tab_contents);
[email protected]ae8945192010-07-20 16:56:26826 ChromeThread::PostTask(ChromeThread::IO, FROM_HERE,
827 NewRunnableFunction(&download_util::DownloadUrl,
828 url,
829 referrer,
830 referrer_charset,
831 save_info,
832 g_browser_process->resource_dispatcher_host(),
833 tab_contents->GetRenderProcessHost()->id(),
834 tab_contents->render_view_host()->routing_id(),
835 request_context_getter_));
initial.commit09911bf2008-07-26 23:55:29836}
837
initial.commit09911bf2008-07-26 23:55:29838void DownloadManager::AddObserver(Observer* observer) {
839 observers_.AddObserver(observer);
840 observer->ModelChanged();
841}
842
843void DownloadManager::RemoveObserver(Observer* observer) {
844 observers_.RemoveObserver(observer);
845}
846
847// Post Windows Shell operations to the Download thread, to avoid blocking the
848// user interface.
849void DownloadManager::ShowDownloadInShell(const DownloadItem* download) {
850 DCHECK(file_manager_);
[email protected]d83d03aa2009-11-02 21:44:37851 DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
[email protected]8b6ff012009-08-18 22:29:58852#if defined(OS_MACOSX)
853 // Mac needs to run this operation on the UI thread.
854 platform_util::ShowItemInFolder(download->full_path());
855#else
[email protected]d83d03aa2009-11-02 21:44:37856 ChromeThread::PostTask(
857 ChromeThread::FILE, FROM_HERE,
858 NewRunnableMethod(
859 file_manager_, &DownloadFileManager::OnShowDownloadInShell,
860 FilePath(download->full_path())));
[email protected]8b6ff012009-08-18 22:29:58861#endif
initial.commit09911bf2008-07-26 23:55:29862}
863
[email protected]ee8f30e62010-08-26 17:17:51864void DownloadManager::OpenDownload(DownloadItem* download,
[email protected]8f783752009-04-01 23:33:45865 gfx::NativeView parent_window) {
[email protected]0e34d7892009-06-05 19:17:40866 // Open Chrome extensions with ExtensionsService. For everything else do shell
[email protected]8f783752009-04-01 23:33:45867 // execute.
[email protected]a60c8ae2009-12-25 06:50:57868 if (download->is_extension_install()) {
[email protected]ee8f30e62010-08-26 17:17:51869 download->Opened();
[email protected]7ba53e12010-08-05 17:14:00870 download_util::OpenChromeExtension(profile_, this, *download);
[email protected]8f783752009-04-01 23:33:45871 } else {
872 OpenDownloadInShell(download, parent_window);
873 }
874}
875
[email protected]ee8f30e62010-08-26 17:17:51876void DownloadManager::OpenDownloadInShell(DownloadItem* download,
[email protected]e93d2822009-01-30 05:59:59877 gfx::NativeView parent_window) {
initial.commit09911bf2008-07-26 23:55:29878 DCHECK(file_manager_);
[email protected]d83d03aa2009-11-02 21:44:37879 DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
[email protected]ee8f30e62010-08-26 17:17:51880 download->Opened();
[email protected]8b6ff012009-08-18 22:29:58881#if defined(OS_MACOSX)
882 // Mac OS X requires opening downloads on the UI thread.
883 platform_util::OpenItem(download->full_path());
884#else
[email protected]d83d03aa2009-11-02 21:44:37885 ChromeThread::PostTask(
886 ChromeThread::FILE, FROM_HERE,
887 NewRunnableMethod(
888 file_manager_, &DownloadFileManager::OnOpenDownloadInShell,
889 download->full_path(), download->url(), parent_window));
[email protected]8b6ff012009-08-18 22:29:58890#endif
initial.commit09911bf2008-07-26 23:55:29891}
892
[email protected]eccb9d12009-10-28 05:40:09893bool DownloadManager::ShouldOpenFileBasedOnExtension(
894 const FilePath& path) const {
[email protected]eccb9d12009-10-28 05:40:09895 FilePath::StringType extension = path.Extension();
896 if (extension.empty())
897 return false;
[email protected]7ba53e12010-08-05 17:14:00898 if (download_util::IsExecutableExtension(extension))
[email protected]eccb9d12009-10-28 05:40:09899 return false;
[email protected]92e11c82010-01-13 06:39:56900 if (Extension::IsExtension(path))
901 return false;
[email protected]eccb9d12009-10-28 05:40:09902 DCHECK(extension[0] == FilePath::kExtensionSeparator);
903 extension.erase(0, 1);
[email protected]e5dc4222010-08-30 22:16:32904 return download_prefs_->IsAutoOpenEnabledForExtension(extension);
initial.commit09911bf2008-07-26 23:55:29905}
906
[email protected]561abe62009-04-06 18:08:34907void DownloadManager::FileSelected(const FilePath& path,
[email protected]23b357b2009-03-30 20:02:36908 int index, void* params) {
initial.commit09911bf2008-07-26 23:55:29909 DownloadCreateInfo* info = reinterpret_cast<DownloadCreateInfo*>(params);
[email protected]e6875c12010-07-18 11:14:13910 if (info->prompt_user_for_save_location)
[email protected]7ae7c2cb2009-01-06 23:31:41911 last_download_path_ = path.DirName();
initial.commit09911bf2008-07-26 23:55:29912 ContinueStartDownload(info, path);
913}
914
915void DownloadManager::FileSelectionCanceled(void* params) {
916 // The user didn't pick a place to save the file, so need to cancel the
917 // download that's already in progress to the temporary location.
918 DownloadCreateInfo* info = reinterpret_cast<DownloadCreateInfo*>(params);
[email protected]d7d1c5c2009-08-05 23:52:50919 DownloadCancelledInternal(info->download_id,
[email protected]76543b92009-08-31 17:27:45920 info->child_id,
[email protected]d7d1c5c2009-08-05 23:52:50921 info->request_id);
initial.commit09911bf2008-07-26 23:55:29922}
923
[email protected]9ccbb372008-10-10 18:50:32924void DownloadManager::DangerousDownloadValidated(DownloadItem* download) {
925 DCHECK_EQ(DownloadItem::DANGEROUS, download->safety_state());
926 download->set_safety_state(DownloadItem::DANGEROUS_BUT_VALIDATED);
927 download->UpdateObservers();
928
929 // If the download is not complete, nothing to do. The required
930 // post-processing will be performed when it does complete.
931 if (download->state() != DownloadItem::COMPLETE)
932 return;
933
[email protected]d83d03aa2009-11-02 21:44:37934 ChromeThread::PostTask(
935 ChromeThread::FILE, FROM_HERE,
936 NewRunnableMethod(
937 this, &DownloadManager::ProceedWithFinishedDangerousDownload,
938 download->db_handle(), download->full_path(),
939 download->original_name()));
[email protected]9ccbb372008-10-10 18:50:32940}
941
initial.commit09911bf2008-07-26 23:55:29942// Operations posted to us from the history service ----------------------------
943
944// The history service has retrieved all download entries. 'entries' contains
945// 'DownloadCreateInfo's in sorted order (by ascending start_time).
946void DownloadManager::OnQueryDownloadEntriesComplete(
947 std::vector<DownloadCreateInfo>* entries) {
948 for (size_t i = 0; i < entries->size(); ++i) {
[email protected]aa033af2010-07-27 18:16:39949 DownloadItem* download = new DownloadItem(this, entries->at(i));
950 DCHECK(!ContainsKey(downloads_, download->db_handle()));
initial.commit09911bf2008-07-26 23:55:29951 downloads_[download->db_handle()] = download;
initial.commit09911bf2008-07-26 23:55:29952 }
[email protected]b0ab1d42010-02-24 19:29:28953 NotifyModelChanged();
initial.commit09911bf2008-07-26 23:55:29954}
955
initial.commit09911bf2008-07-26 23:55:29956// Once the new DownloadItem's creation info has been committed to the history
957// service, we associate the DownloadItem with the db handle, update our
958// 'downloads_' map and inform observers.
959void DownloadManager::OnCreateDownloadEntryComplete(DownloadCreateInfo info,
960 int64 db_handle) {
961 DownloadMap::iterator it = in_progress_.find(info.download_id);
962 DCHECK(it != in_progress_.end());
963
964 DownloadItem* download = it->second;
[email protected]d2a8fb72010-01-21 05:31:42965
966 // It's not immediately obvious, but HistoryBackend::CreateDownload() can
967 // call this function with an invalid |db_handle|. For instance, this can
968 // happen when the history database is offline. We cannot have multiple
969 // DownloadItems with the same invalid db_handle, so we need to assign a
970 // unique |db_handle| here.
[email protected]82f37b02010-07-29 22:04:57971 if (db_handle == DownloadHistory::kUninitializedHandle)
972 db_handle = download_history_->GetNextFakeDbHandle();
[email protected]d2a8fb72010-01-21 05:31:42973
[email protected]82f37b02010-07-29 22:04:57974 DCHECK(download->db_handle() == DownloadHistory::kUninitializedHandle);
initial.commit09911bf2008-07-26 23:55:29975 download->set_db_handle(db_handle);
976
977 // Insert into our full map.
978 DCHECK(downloads_.find(download->db_handle()) == downloads_.end());
979 downloads_[download->db_handle()] = download;
980
[email protected]5e595482009-05-06 20:16:53981 // Show in the appropropriate browser UI.
982 ShowDownloadInBrowser(info, download);
initial.commit09911bf2008-07-26 23:55:29983
984 // Inform interested objects about the new download.
[email protected]b0ab1d42010-02-24 19:29:28985 NotifyModelChanged();
initial.commit09911bf2008-07-26 23:55:29986
987 // If this download has been completed before we've received the db handle,
988 // post one final message to the history service so that it can be properly
989 // in sync with the DownloadItem's completion status, and also inform any
990 // observers so that they get more than just the start notification.
991 if (download->state() != DownloadItem::IN_PROGRESS) {
992 in_progress_.erase(it);
[email protected]82f37b02010-07-29 22:04:57993 download_history_->UpdateEntry(download);
initial.commit09911bf2008-07-26 23:55:29994 download->UpdateObservers();
995 }
[email protected]6a7fb042010-02-01 16:30:47996
997 UpdateAppIcon();
initial.commit09911bf2008-07-26 23:55:29998}
999
[email protected]5e595482009-05-06 20:16:531000void DownloadManager::ShowDownloadInBrowser(const DownloadCreateInfo& info,
1001 DownloadItem* download) {
[email protected]8ddbd66a2010-05-21 16:38:341002 // The 'contents' may no longer exist if the user closed the tab before we
1003 // get this start completion event. If it does, tell the origin TabContents
1004 // to display its download shelf.
[email protected]76543b92009-08-31 17:27:451005 TabContents* contents = tab_util::GetTabContentsByID(info.child_id,
1006 info.render_view_id);
[email protected]5e595482009-05-06 20:16:531007
1008 // If the contents no longer exists, we start the download in the last active
1009 // browser. This is not ideal but better than fully hiding the download from
1010 // the user.
1011 if (!contents) {
1012 Browser* last_active = BrowserList::GetLastActive();
1013 if (last_active)
1014 contents = last_active->GetSelectedTabContents();
1015 }
1016
1017 if (contents)
1018 contents->OnStartDownload(download);
1019}
1020
[email protected]6cade212008-12-03 00:32:221021// Clears the last download path, used to initialize "save as" dialogs.
[email protected]905a08d2008-11-19 07:24:121022void DownloadManager::ClearLastDownloadPath() {
[email protected]7ae7c2cb2009-01-06 23:31:411023 last_download_path_ = FilePath();
[email protected]eea46622009-07-15 20:49:381024}
[email protected]b0ab1d42010-02-24 19:29:281025
1026void DownloadManager::NotifyModelChanged() {
1027 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1028}
1029
[email protected]2e030682010-07-23 19:45:361030DownloadItem* DownloadManager::GetDownloadItem(int id) {
1031 for (DownloadMap::iterator it = downloads_.begin();
1032 it != downloads_.end(); ++it) {
1033 DownloadItem* item = it->second;
1034 if (item->id() == id)
1035 return item;
1036 }
1037 return NULL;
1038}
1039
[email protected]b0ab1d42010-02-24 19:29:281040// DownloadManager::OtherDownloadManagerObserver implementation ----------------
1041
1042DownloadManager::OtherDownloadManagerObserver::OtherDownloadManagerObserver(
1043 DownloadManager* observing_download_manager)
1044 : observing_download_manager_(observing_download_manager),
1045 observed_download_manager_(NULL) {
1046 if (observing_download_manager->profile_->GetOriginalProfile() ==
1047 observing_download_manager->profile_) {
1048 return;
1049 }
1050
1051 observed_download_manager_ = observing_download_manager_->
1052 profile_->GetOriginalProfile()->GetDownloadManager();
1053 observed_download_manager_->AddObserver(this);
1054}
1055
1056DownloadManager::OtherDownloadManagerObserver::~OtherDownloadManagerObserver() {
1057 if (observed_download_manager_)
1058 observed_download_manager_->RemoveObserver(this);
1059}
1060
1061void DownloadManager::OtherDownloadManagerObserver::ModelChanged() {
1062 observing_download_manager_->NotifyModelChanged();
1063}
1064
[email protected]b0ab1d42010-02-24 19:29:281065void DownloadManager::OtherDownloadManagerObserver::ManagerGoingDown() {
1066 observed_download_manager_ = NULL;
1067}