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

Side by Side Diff: chrome/browser/ui/webui/downloads_dom_handler.cc

Issue 10854127: Rewrite DownloadsDOMHandler (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: . Created 8 years, 4 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 #include "chrome/browser/ui/webui/downloads_dom_handler.h" 5 #include "chrome/browser/ui/webui/downloads_dom_handler.h"
6 6
7 #include <algorithm> 7 #include <algorithm>
8 #include <functional> 8 #include <functional>
9 9
10 #include "base/basictypes.h" 10 #include "base/basictypes.h"
(...skipping 41 matching lines...) Expand 10 before | Expand all | Expand 10 after
52 #endif 52 #endif
53 53
54 using content::BrowserContext; 54 using content::BrowserContext;
55 using content::BrowserThread; 55 using content::BrowserThread;
56 using content::UserMetricsAction; 56 using content::UserMetricsAction;
57 57
58 namespace { 58 namespace {
59 59
60 // Maximum number of downloads to show. TODO(glen): Remove this and instead 60 // Maximum number of downloads to show. TODO(glen): Remove this and instead
61 // stuff the downloads down the pipe slowly. 61 // stuff the downloads down the pipe slowly.
62 static const int kMaxDownloads = 150; 62 static const size_t kMaxDownloads = 150;
63 63
64 // Sort DownloadItems into descending order by their start time. 64 // Sort DownloadItems into descending order by their start time.
65 class DownloadItemSorter : public std::binary_function<content::DownloadItem*, 65 class DownloadItemSorter : public std::binary_function<content::DownloadItem*,
66 content::DownloadItem*, 66 content::DownloadItem*,
67 bool> { 67 bool> {
68 public: 68 public:
69 bool operator()(const content::DownloadItem* lhs, 69 bool operator()(const content::DownloadItem* lhs,
70 const content::DownloadItem* rhs) { 70 const content::DownloadItem* rhs) {
71 return lhs->GetStartTime() > rhs->GetStartTime(); 71 return lhs->GetStartTime() > rhs->GetStartTime();
72 } 72 }
(...skipping 39 matching lines...) Expand 10 before | Expand all | Expand 10 after
112 // NOT_DANGEROUS or MAYBE_DANGEROUS_CONTENT. 112 // NOT_DANGEROUS or MAYBE_DANGEROUS_CONTENT.
113 NOTREACHED(); 113 NOTREACHED();
114 return ""; 114 return "";
115 } 115 }
116 } 116 }
117 117
118 // Return a JSON dictionary containing some of the attributes of |download|. 118 // Return a JSON dictionary containing some of the attributes of |download|.
119 // The JSON dictionary will also have a field "id" set to |id|, and a field 119 // The JSON dictionary will also have a field "id" set to |id|, and a field
120 // "otr" set to |incognito|. 120 // "otr" set to |incognito|.
121 DictionaryValue* CreateDownloadItemValue( 121 DictionaryValue* CreateDownloadItemValue(
122 content::DownloadItem* download, 122 content::DownloadItem* download_item,
123 int id,
124 bool incognito) { 123 bool incognito) {
125 DictionaryValue* file_value = new DictionaryValue(); 124 DictionaryValue* file_value = new DictionaryValue();
126 125
127 file_value->SetInteger( 126 file_value->SetInteger(
128 "started", static_cast<int>(download->GetStartTime().ToTimeT())); 127 "started", static_cast<int>(download_item->GetStartTime().ToTimeT()));
129 file_value->SetString( 128 file_value->SetString(
130 "since_string", TimeFormat::RelativeDate(download->GetStartTime(), NULL)); 129 "since_string", TimeFormat::RelativeDate(
130 download_item->GetStartTime(), NULL));
131 file_value->SetString( 131 file_value->SetString(
132 "date_string", base::TimeFormatShortDate(download->GetStartTime())); 132 "date_string", base::TimeFormatShortDate(download_item->GetStartTime()));
133 file_value->SetInteger("id", id); 133 file_value->SetInteger("id", download_item->GetId());
134 134
135 FilePath download_path(download->GetTargetFilePath()); 135 FilePath download_path(download_item->GetTargetFilePath());
136 file_value->Set("file_path", base::CreateFilePathValue(download_path)); 136 file_value->Set("file_path", base::CreateFilePathValue(download_path));
137 file_value->SetString("file_url", 137 file_value->SetString("file_url",
138 net::FilePathToFileURL(download_path).spec()); 138 net::FilePathToFileURL(download_path).spec());
139 139
140 // Keep file names as LTR. 140 // Keep file names as LTR.
141 string16 file_name = download->GetFileNameToReportUser().LossyDisplayName(); 141 string16 file_name =
142 download_item->GetFileNameToReportUser().LossyDisplayName();
142 file_name = base::i18n::GetDisplayStringInLTRDirectionality(file_name); 143 file_name = base::i18n::GetDisplayStringInLTRDirectionality(file_name);
143 file_value->SetString("file_name", file_name); 144 file_value->SetString("file_name", file_name);
144 file_value->SetString("url", download->GetURL().spec()); 145 file_value->SetString("url", download_item->GetURL().spec());
145 file_value->SetBoolean("otr", incognito); 146 file_value->SetBoolean("otr", incognito);
146 file_value->SetInteger("total", static_cast<int>(download->GetTotalBytes())); 147 file_value->SetInteger("total", static_cast<int>(
148 download_item->GetTotalBytes()));
147 file_value->SetBoolean("file_externally_removed", 149 file_value->SetBoolean("file_externally_removed",
148 download->GetFileExternallyRemoved()); 150 download_item->GetFileExternallyRemoved());
149 151
150 if (download->IsInProgress()) { 152 if (download_item->IsInProgress()) {
151 if (download->GetSafetyState() == content::DownloadItem::DANGEROUS) { 153 if (download_item->GetSafetyState() == content::DownloadItem::DANGEROUS) {
152 file_value->SetString("state", "DANGEROUS"); 154 file_value->SetString("state", "DANGEROUS");
153 // These are the only danger states we expect to see (and the UI is 155 // These are the only danger states we expect to see (and the UI is
154 // equipped to handle): 156 // equipped to handle):
155 DCHECK(download->GetDangerType() == 157 DCHECK(download_item->GetDangerType() ==
156 content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE || 158 content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE ||
157 download->GetDangerType() == 159 download_item->GetDangerType() ==
158 content::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL || 160 content::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL ||
159 download->GetDangerType() == 161 download_item->GetDangerType() ==
160 content::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT || 162 content::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT ||
161 download->GetDangerType() == 163 download_item->GetDangerType() ==
162 content::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT); 164 content::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT);
163 const char* danger_type_value = 165 const char* danger_type_value =
164 GetDangerTypeString(download->GetDangerType()); 166 GetDangerTypeString(download_item->GetDangerType());
165 file_value->SetString("danger_type", danger_type_value); 167 file_value->SetString("danger_type", danger_type_value);
166 } else if (download->IsPaused()) { 168 } else if (download_item->IsPaused()) {
167 file_value->SetString("state", "PAUSED"); 169 file_value->SetString("state", "PAUSED");
168 } else { 170 } else {
169 file_value->SetString("state", "IN_PROGRESS"); 171 file_value->SetString("state", "IN_PROGRESS");
170 } 172 }
171 173
172 file_value->SetString("progress_status_text", 174 file_value->SetString("progress_status_text",
173 download_util::GetProgressStatusText(download)); 175 download_util::GetProgressStatusText(download_item));
174 176
175 file_value->SetInteger("percent", 177 file_value->SetInteger("percent",
176 static_cast<int>(download->PercentComplete())); 178 static_cast<int>(download_item->PercentComplete()));
177 file_value->SetInteger("received", 179 file_value->SetInteger("received",
178 static_cast<int>(download->GetReceivedBytes())); 180 static_cast<int>(download_item->GetReceivedBytes()));
179 } else if (download->IsInterrupted()) { 181 } else if (download_item->IsInterrupted()) {
180 file_value->SetString("state", "INTERRUPTED"); 182 file_value->SetString("state", "INTERRUPTED");
181 183
182 file_value->SetString("progress_status_text", 184 file_value->SetString("progress_status_text",
183 download_util::GetProgressStatusText(download)); 185 download_util::GetProgressStatusText(download_item));
184 186
185 file_value->SetInteger("percent", 187 file_value->SetInteger("percent",
186 static_cast<int>(download->PercentComplete())); 188 static_cast<int>(download_item->PercentComplete()));
187 file_value->SetInteger("received", 189 file_value->SetInteger("received",
188 static_cast<int>(download->GetReceivedBytes())); 190 static_cast<int>(download_item->GetReceivedBytes()));
189 file_value->SetString("last_reason_text", 191 file_value->SetString("last_reason_text",
190 BaseDownloadItemModel::InterruptReasonMessage( 192 BaseDownloadItemModel::InterruptReasonMessage(
191 download->GetLastReason())); 193 download_item->GetLastReason()));
192 } else if (download->IsCancelled()) { 194 } else if (download_item->IsCancelled()) {
193 file_value->SetString("state", "CANCELLED"); 195 file_value->SetString("state", "CANCELLED");
194 } else if (download->IsComplete()) { 196 } else if (download_item->IsComplete()) {
195 if (download->GetSafetyState() == content::DownloadItem::DANGEROUS) 197 if (download_item->GetSafetyState() == content::DownloadItem::DANGEROUS)
196 file_value->SetString("state", "DANGEROUS"); 198 file_value->SetString("state", "DANGEROUS");
197 else 199 else
198 file_value->SetString("state", "COMPLETE"); 200 file_value->SetString("state", "COMPLETE");
199 } else { 201 } else {
200 NOTREACHED() << "state undefined"; 202 NOTREACHED() << "state undefined";
201 } 203 }
202 204
203 return file_value; 205 return file_value;
204 } 206 }
205 207
206 // Return true if |download_id| refers to a download that belongs to the 208 // Return true if |download_id| refers to a download that belongs to the
207 // incognito download manager, if one exists. 209 // incognito download manager, if one exists.
208 bool IsItemIncognito( 210 bool IsItemIncognito(
209 int32 download_id, 211 int32 download_id,
210 content::DownloadManager* manager, 212 content::DownloadManager* manager,
211 content::DownloadManager* original_manager) { 213 content::DownloadManager* original_manager) {
212 // |original_manager| is only non-NULL if |manager| is incognito. 214 // |original_manager| is only non-NULL if |manager| is incognito.
213 return (original_manager && 215 return (original_manager &&
214 (manager->GetDownload(download_id) != NULL)); 216 (manager->GetDownload(download_id) != NULL));
215 } 217 }
216 218
219 // Filter out extension downloads and downloads that don't have a filename yet.
220 bool IsDownloadDisplayable(const content::DownloadItem& item) {
221 return (!download_crx_util::IsExtensionDownload(item) &&
222 !item.IsTemporary() &&
223 !item.GetFileNameToReportUser().empty() &&
224 !item.GetTargetFilePath().empty());
225 }
226
217 } // namespace 227 } // namespace
218 228
219 DownloadsDOMHandler::DownloadsDOMHandler(content::DownloadManager* dlm) 229 DownloadsDOMHandler::DownloadsDOMHandler(content::DownloadManager* dlm)
220 : search_text_(), 230 : search_text_(),
221 download_manager_(dlm), 231 download_manager_(dlm),
222 original_profile_download_manager_(NULL), 232 original_profile_download_manager_(NULL),
223 initialized_(false), 233 update_scheduled_(false),
224 ALLOW_THIS_IN_INITIALIZER_LIST(weak_ptr_factory_(this)) { 234 ALLOW_THIS_IN_INITIALIZER_LIST(weak_ptr_factory_(this)) {
225 // Create our fileicon data source. 235 // Create our fileicon data source.
226 Profile* profile = Profile::FromBrowserContext(dlm->GetBrowserContext()); 236 Profile* profile = Profile::FromBrowserContext(dlm->GetBrowserContext());
227 ChromeURLDataManager::AddDataSource(profile, new FileIconSource()); 237 ChromeURLDataManager::AddDataSource(profile, new FileIconSource());
228 238
229 // Figure out our parent DownloadManager, if any. 239 // Observe the DownloadManagers.
230 Profile* original_profile = profile->GetOriginalProfile(); 240 download_manager_->AddObserver(this);
231 if (original_profile != profile) { 241 if (profile->IsOffTheRecord()) {
232 original_profile_download_manager_ = 242 original_profile_download_manager_ =
233 BrowserContext::GetDownloadManager(original_profile); 243 BrowserContext::GetDownloadManager(profile->GetOriginalProfile());
244 original_profile_download_manager_->AddObserver(this);
245 }
246
247 // Observe all the DownloadItems.
248 content::DownloadManager::DownloadVector downloads;
249 SearchDownloads(&downloads);
250 for (content::DownloadManager::DownloadVector::const_iterator
251 iter = downloads.begin();
252 iter != downloads.end(); ++iter) {
253 (*iter)->AddObserver(this);
254 observing_items_.insert(*iter);
234 } 255 }
235 } 256 }
236 257
237 DownloadsDOMHandler::~DownloadsDOMHandler() { 258 DownloadsDOMHandler::~DownloadsDOMHandler() {
238 ClearDownloadItems(); 259 for (DownloadSet::const_iterator it = observing_items_.begin();
260 it != observing_items_.end(); ++it) {
261 (*it)->RemoveObserver(this);
262 }
263 observing_items_.clear();
239 download_manager_->RemoveObserver(this); 264 download_manager_->RemoveObserver(this);
240 if (original_profile_download_manager_) 265 if (original_profile_download_manager_) {
James Hawkins 2012/08/19 06:17:29 Remove added braces; the precedence in this code i
benjhayden 2012/08/19 22:20:27 Done.
241 original_profile_download_manager_->RemoveObserver(this); 266 original_profile_download_manager_->RemoveObserver(this);
267 }
242 } 268 }
243 269
244 // DownloadsDOMHandler, public: ----------------------------------------------- 270 // DownloadsDOMHandler, public: -----------------------------------------------
245 271
246 void DownloadsDOMHandler::OnPageLoaded(const base::ListValue* args) { 272 void DownloadsDOMHandler::OnPageLoaded(const base::ListValue* args) {
247 if (initialized_) 273 SendCurrentDownloads();
248 return;
249 initialized_ = true;
250
251 download_manager_->AddObserver(this);
252 if (original_profile_download_manager_)
253 original_profile_download_manager_->AddObserver(this);
254 } 274 }
255 275
256 void DownloadsDOMHandler::RegisterMessages() { 276 void DownloadsDOMHandler::RegisterMessages() {
257 web_ui()->RegisterMessageCallback("onPageLoaded", 277 web_ui()->RegisterMessageCallback("onPageLoaded",
258 base::Bind(&DownloadsDOMHandler::OnPageLoaded, 278 base::Bind(&DownloadsDOMHandler::OnPageLoaded,
259 base::Unretained(this))); 279 weak_ptr_factory_.GetWeakPtr()));
260 web_ui()->RegisterMessageCallback("getDownloads", 280 web_ui()->RegisterMessageCallback("getDownloads",
261 base::Bind(&DownloadsDOMHandler::HandleGetDownloads, 281 base::Bind(&DownloadsDOMHandler::HandleGetDownloads,
262 base::Unretained(this))); 282 weak_ptr_factory_.GetWeakPtr()));
263 web_ui()->RegisterMessageCallback("openFile", 283 web_ui()->RegisterMessageCallback("openFile",
264 base::Bind(&DownloadsDOMHandler::HandleOpenFile, 284 base::Bind(&DownloadsDOMHandler::HandleOpenFile,
265 base::Unretained(this))); 285 weak_ptr_factory_.GetWeakPtr()));
266 web_ui()->RegisterMessageCallback("drag", 286 web_ui()->RegisterMessageCallback("drag",
267 base::Bind(&DownloadsDOMHandler::HandleDrag, 287 base::Bind(&DownloadsDOMHandler::HandleDrag,
268 base::Unretained(this))); 288 weak_ptr_factory_.GetWeakPtr()));
269 web_ui()->RegisterMessageCallback("saveDangerous", 289 web_ui()->RegisterMessageCallback("saveDangerous",
270 base::Bind(&DownloadsDOMHandler::HandleSaveDangerous, 290 base::Bind(&DownloadsDOMHandler::HandleSaveDangerous,
271 base::Unretained(this))); 291 weak_ptr_factory_.GetWeakPtr()));
272 web_ui()->RegisterMessageCallback("discardDangerous", 292 web_ui()->RegisterMessageCallback("discardDangerous",
273 base::Bind(&DownloadsDOMHandler::HandleDiscardDangerous, 293 base::Bind(&DownloadsDOMHandler::HandleDiscardDangerous,
274 base::Unretained(this))); 294 weak_ptr_factory_.GetWeakPtr()));
275 web_ui()->RegisterMessageCallback("show", 295 web_ui()->RegisterMessageCallback("show",
276 base::Bind(&DownloadsDOMHandler::HandleShow, 296 base::Bind(&DownloadsDOMHandler::HandleShow,
277 base::Unretained(this))); 297 weak_ptr_factory_.GetWeakPtr()));
278 web_ui()->RegisterMessageCallback("togglepause", 298 web_ui()->RegisterMessageCallback("togglepause",
279 base::Bind(&DownloadsDOMHandler::HandlePause, 299 base::Bind(&DownloadsDOMHandler::HandlePause,
280 base::Unretained(this))); 300 weak_ptr_factory_.GetWeakPtr()));
281 web_ui()->RegisterMessageCallback("resume", 301 web_ui()->RegisterMessageCallback("resume",
282 base::Bind(&DownloadsDOMHandler::HandlePause, 302 base::Bind(&DownloadsDOMHandler::HandlePause,
283 base::Unretained(this))); 303 weak_ptr_factory_.GetWeakPtr()));
284 web_ui()->RegisterMessageCallback("remove", 304 web_ui()->RegisterMessageCallback("remove",
285 base::Bind(&DownloadsDOMHandler::HandleRemove, 305 base::Bind(&DownloadsDOMHandler::HandleRemove,
286 base::Unretained(this))); 306 weak_ptr_factory_.GetWeakPtr()));
287 web_ui()->RegisterMessageCallback("cancel", 307 web_ui()->RegisterMessageCallback("cancel",
288 base::Bind(&DownloadsDOMHandler::HandleCancel, 308 base::Bind(&DownloadsDOMHandler::HandleCancel,
289 base::Unretained(this))); 309 weak_ptr_factory_.GetWeakPtr()));
290 web_ui()->RegisterMessageCallback("clearAll", 310 web_ui()->RegisterMessageCallback("clearAll",
291 base::Bind(&DownloadsDOMHandler::HandleClearAll, 311 base::Bind(&DownloadsDOMHandler::HandleClearAll,
292 base::Unretained(this))); 312 weak_ptr_factory_.GetWeakPtr()));
293 web_ui()->RegisterMessageCallback("openDownloadsFolder", 313 web_ui()->RegisterMessageCallback("openDownloadsFolder",
294 base::Bind(&DownloadsDOMHandler::HandleOpenDownloadsFolder, 314 base::Bind(&DownloadsDOMHandler::HandleOpenDownloadsFolder,
295 base::Unretained(this))); 315 weak_ptr_factory_.GetWeakPtr()));
296 } 316 }
297 317
298 void DownloadsDOMHandler::OnDownloadUpdated(content::DownloadItem* download) { 318 void DownloadsDOMHandler::OnDownloadCreated(
299 // Get the id for the download. Our downloads are sorted latest to first, 319 content::DownloadManager* manager, content::DownloadItem* download_item) {
300 // and the id is the index into that list. We should be careful of sync 320 // DownloadsDOMHandler observes all items, and only chooses which downloads to
James Hawkins 2012/08/19 06:17:29 nit: Remove comma.
benjhayden 2012/08/19 22:20:27 Done.
301 // errors between the UI and the download_items_ list (we may wish to use 321 // display in SendCurrentDownloads() and OnDownloadUpdated() using
302 // something other than 'id'). 322 // IsDownloadDisplayable().
303 OrderedDownloads::iterator it = std::find(download_items_.begin(), 323 download_item->AddObserver(this);
304 download_items_.end(), 324 observing_items_.insert(download_item);
305 download); 325 if (IsDownloadDisplayable(*download_item) &&
306 if (it == download_items_.end()) 326 !update_scheduled_) {
307 return; 327 // Don't call SendCurrentDownloads() every time anything changes. Batch them
328 // together instead. We may handle hundreds of OnDownloadCreated() calls in
James Hawkins 2012/08/19 06:17:29 nit: Remove 'we'.
benjhayden 2012/08/19 22:20:27 Done.
329 // a single UI message loop iteration when the history is loaded.
330 update_scheduled_ = true;
331 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
332 base::Bind(&DownloadsDOMHandler::SendCurrentDownloads,
James Hawkins 2012/08/19 06:17:29 nit: Start of parameter rows must align on the sam
benjhayden 2012/08/19 22:20:27 Done.
333 weak_ptr_factory_.GetWeakPtr()));
334 }
335 }
308 336
309 const int id = static_cast<int>(it - download_items_.begin()); 337 void DownloadsDOMHandler::OnDownloadUpdated(
310 338 content::DownloadItem* download_item) {
311 ListValue results_value; 339 if (IsDownloadDisplayable(*download_item)) {
312 results_value.Append(CreateDownloadItemValue(download, id, IsItemIncognito( 340 base::ListValue results_value;
313 download->GetId(), 341 results_value.Append(CreateDownloadItemValue(download_item, IsItemIncognito(
314 download_manager_, 342 download_item->GetId(),
315 original_profile_download_manager_))); 343 download_manager_,
316 web_ui()->CallJavascriptFunction("downloadUpdated", results_value); 344 original_profile_download_manager_)));
345 CallDownloadUpdated(results_value);
346 }
317 } 347 }
318 348
319 void DownloadsDOMHandler::OnDownloadDestroyed( 349 void DownloadsDOMHandler::OnDownloadDestroyed(
320 content::DownloadItem* download) { 350 content::DownloadItem* download_item) {
321 download->RemoveObserver(this); 351 download_item->RemoveObserver(this);
322 OrderedDownloads::iterator it = std::find(download_items_.begin(), 352 observing_items_.erase(download_item);
323 download_items_.end(), 353 // Don't call SendCurrentDownloads() every time anything changes. Batch them
324 download); 354 // together instead. We may handle hundreds of OnDownloadDestroyed() calls in
James Hawkins 2012/08/19 06:17:29 nit: Remove 'we'.
benjhayden 2012/08/19 22:20:27 Done.
325 if (it != download_items_.end()) 355 // a single UI message loop iteration when the user Clears All downloads.
326 *it = NULL; 356 if (!update_scheduled_) {
James Hawkins 2012/08/19 06:17:29 It appears some of this code can be shared with On
benjhayden 2012/08/19 22:20:27 Done.
327 // A later ModelChanged() notification will change the WebUI's 357 update_scheduled_ = true;
328 // view of the downloads list. 358 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
329 } 359 base::Bind(&DownloadsDOMHandler::SendCurrentDownloads,
James Hawkins 2012/08/19 06:17:29 nit: Start of parameter rows must align on the sam
benjhayden 2012/08/19 22:20:27 Done.
330 360 weak_ptr_factory_.GetWeakPtr()));
331 // A download has started or been deleted. Query our DownloadManager for the
332 // current set of downloads.
333 void DownloadsDOMHandler::ModelChanged(content::DownloadManager* manager) {
334 DCHECK(manager == download_manager_ ||
335 manager == original_profile_download_manager_);
336
337 ClearDownloadItems();
338 download_manager_->SearchDownloads(WideToUTF16(search_text_),
339 &download_items_);
340 // If we have a parent DownloadManager, let it add its downloads to the
341 // results.
342 if (original_profile_download_manager_) {
343 original_profile_download_manager_->SearchDownloads(
344 WideToUTF16(search_text_), &download_items_);
345 } 361 }
346
347 sort(download_items_.begin(), download_items_.end(), DownloadItemSorter());
348
349 // Remove any extension downloads.
350 for (size_t i = 0; i < download_items_.size();) {
351 if (download_crx_util::IsExtensionDownload(*download_items_[i]))
352 download_items_.erase(download_items_.begin() + i);
353 else
354 i++;
355 }
356
357 // Add ourself to all download items as an observer.
358 for (OrderedDownloads::iterator it = download_items_.begin();
359 it != download_items_.end(); ++it) {
360 if (static_cast<int>(it - download_items_.begin()) > kMaxDownloads)
361 break;
362
363 // We should never see anything that isn't already in the history.
364 DCHECK(*it);
365 DCHECK((*it)->IsPersisted());
366
367 (*it)->AddObserver(this);
368 }
369
370 SendCurrentDownloads();
371 } 362 }
372 363
373 void DownloadsDOMHandler::ManagerGoingDown(content::DownloadManager* manager) { 364 void DownloadsDOMHandler::ManagerGoingDown(content::DownloadManager* manager) {
374 // This should never happen. The lifetime of the DownloadsDOMHandler 365 // This should never happen. The lifetime of the DownloadsDOMHandler
375 // is tied to the tab in which downloads.html is displayed, which cannot 366 // is tied to the tab in which downloads.html is displayed, which cannot
376 // outlive the Browser that contains it, which cannot outlive the Profile 367 // outlive the Browser that contains it, which cannot outlive the Profile
377 // it is associated with. If that profile is an incognito profile, 368 // it is associated with. If that profile is an incognito profile,
378 // it cannot outlive its original profile. Thus this class should be 369 // it cannot outlive its original profile. Thus this class should be
379 // destroyed before a ManagerGoingDown() notification occurs. 370 // destroyed before a ManagerGoingDown() notification occurs.
380 NOTREACHED(); 371 NOTREACHED();
381 } 372 }
382 373
383 void DownloadsDOMHandler::HandleGetDownloads(const ListValue* args) { 374 void DownloadsDOMHandler::HandleGetDownloads(const base::ListValue* args) {
384 CountDownloadsDOMEvents(DOWNLOADS_DOM_EVENT_GET_DOWNLOADS); 375 CountDownloadsDOMEvents(DOWNLOADS_DOM_EVENT_GET_DOWNLOADS);
385 std::wstring new_search = UTF16ToWideHack(ExtractStringValue(args)); 376 search_text_ = ExtractStringValue(args);
386 if (search_text_.compare(new_search) != 0) { 377 SendCurrentDownloads();
387 search_text_ = new_search;
388 ModelChanged(download_manager_);
389 } else {
390 SendCurrentDownloads();
391 }
392
393 download_manager_->CheckForHistoryFilesRemoval(); 378 download_manager_->CheckForHistoryFilesRemoval();
394 } 379 }
395 380
396 void DownloadsDOMHandler::HandleOpenFile(const ListValue* args) { 381 void DownloadsDOMHandler::HandleOpenFile(const base::ListValue* args) {
397 CountDownloadsDOMEvents(DOWNLOADS_DOM_EVENT_OPEN_FILE); 382 CountDownloadsDOMEvents(DOWNLOADS_DOM_EVENT_OPEN_FILE);
398 content::DownloadItem* file = GetDownloadByValue(args); 383 content::DownloadItem* file = GetDownloadByValue(args);
399 if (file) 384 if (file)
400 file->OpenDownload(); 385 file->OpenDownload();
401 } 386 }
402 387
403 void DownloadsDOMHandler::HandleDrag(const ListValue* args) { 388 void DownloadsDOMHandler::HandleDrag(const base::ListValue* args) {
404 CountDownloadsDOMEvents(DOWNLOADS_DOM_EVENT_DRAG); 389 CountDownloadsDOMEvents(DOWNLOADS_DOM_EVENT_DRAG);
405 content::DownloadItem* file = GetDownloadByValue(args); 390 content::DownloadItem* file = GetDownloadByValue(args);
406 if (file) { 391 content::WebContents* web_contents = GetWebUIWebContents();
407 IconManager* im = g_browser_process->icon_manager(); 392 if (!file || !web_contents)
408 gfx::Image* icon = im->LookupIcon(file->GetUserVerifiedFilePath(), 393 return;
409 IconLoader::NORMAL); 394 gfx::Image* icon = g_browser_process->icon_manager()->LookupIcon(
410 gfx::NativeView view = web_ui()->GetWebContents()->GetNativeView(); 395 file->GetUserVerifiedFilePath(), IconLoader::NORMAL);
411 { 396 gfx::NativeView view = web_contents->GetNativeView();
412 // Enable nested tasks during DnD, while |DragDownload()| blocks. 397 {
413 MessageLoop::ScopedNestableTaskAllower allow(MessageLoop::current()); 398 // Enable nested tasks during DnD, while |DragDownload()| blocks.
414 download_util::DragDownload(file, icon, view); 399 MessageLoop::ScopedNestableTaskAllower allow(MessageLoop::current());
415 } 400 download_util::DragDownload(file, icon, view);
416 } 401 }
417 } 402 }
418 403
419 void DownloadsDOMHandler::HandleSaveDangerous(const ListValue* args) { 404 void DownloadsDOMHandler::HandleSaveDangerous(const base::ListValue* args) {
420 CountDownloadsDOMEvents(DOWNLOADS_DOM_EVENT_SAVE_DANGEROUS); 405 CountDownloadsDOMEvents(DOWNLOADS_DOM_EVENT_SAVE_DANGEROUS);
421 content::DownloadItem* file = GetDownloadByValue(args); 406 content::DownloadItem* file = GetDownloadByValue(args);
422 if (file) 407 if (file)
423 ShowDangerPrompt(file); 408 ShowDangerPrompt(file);
424 // TODO(benjhayden): else ModelChanged()? Downloads might be able to disappear
425 // out from under us, so update our idea of the downloads as soon as possible.
426 } 409 }
427 410
428 void DownloadsDOMHandler::HandleDiscardDangerous(const ListValue* args) { 411 void DownloadsDOMHandler::HandleDiscardDangerous(const base::ListValue* args) {
429 CountDownloadsDOMEvents(DOWNLOADS_DOM_EVENT_DISCARD_DANGEROUS); 412 CountDownloadsDOMEvents(DOWNLOADS_DOM_EVENT_DISCARD_DANGEROUS);
430 content::DownloadItem* file = GetDownloadByValue(args); 413 content::DownloadItem* file = GetDownloadByValue(args);
431 if (file) 414 if (file)
432 file->Delete(content::DownloadItem::DELETE_DUE_TO_USER_DISCARD); 415 file->Delete(content::DownloadItem::DELETE_DUE_TO_USER_DISCARD);
433 } 416 }
434 417
435 void DownloadsDOMHandler::HandleShow(const ListValue* args) { 418 void DownloadsDOMHandler::HandleShow(const base::ListValue* args) {
436 CountDownloadsDOMEvents(DOWNLOADS_DOM_EVENT_SHOW); 419 CountDownloadsDOMEvents(DOWNLOADS_DOM_EVENT_SHOW);
437 content::DownloadItem* file = GetDownloadByValue(args); 420 content::DownloadItem* file = GetDownloadByValue(args);
438 if (file) 421 if (file)
439 file->ShowDownloadInShell(); 422 file->ShowDownloadInShell();
440 } 423 }
441 424
442 void DownloadsDOMHandler::HandlePause(const ListValue* args) { 425 void DownloadsDOMHandler::HandlePause(const base::ListValue* args) {
443 CountDownloadsDOMEvents(DOWNLOADS_DOM_EVENT_PAUSE); 426 CountDownloadsDOMEvents(DOWNLOADS_DOM_EVENT_PAUSE);
444 content::DownloadItem* file = GetDownloadByValue(args); 427 content::DownloadItem* file = GetDownloadByValue(args);
445 if (file) 428 if (file)
446 file->TogglePause(); 429 file->TogglePause();
447 } 430 }
448 431
449 void DownloadsDOMHandler::HandleRemove(const ListValue* args) { 432 void DownloadsDOMHandler::HandleRemove(const base::ListValue* args) {
450 CountDownloadsDOMEvents(DOWNLOADS_DOM_EVENT_REMOVE); 433 CountDownloadsDOMEvents(DOWNLOADS_DOM_EVENT_REMOVE);
451 content::DownloadItem* file = GetDownloadByValue(args); 434 content::DownloadItem* file = GetDownloadByValue(args);
452 if (file) { 435 if (file) {
453 DCHECK(file->IsPersisted()); 436 DCHECK(file->IsPersisted());
454 file->Remove(); 437 file->Remove();
455 } 438 }
456 } 439 }
457 440
458 void DownloadsDOMHandler::HandleCancel(const ListValue* args) { 441 void DownloadsDOMHandler::HandleCancel(const base::ListValue* args) {
459 CountDownloadsDOMEvents(DOWNLOADS_DOM_EVENT_CANCEL); 442 CountDownloadsDOMEvents(DOWNLOADS_DOM_EVENT_CANCEL);
460 content::DownloadItem* file = GetDownloadByValue(args); 443 content::DownloadItem* file = GetDownloadByValue(args);
461 if (file) 444 if (file)
462 file->Cancel(true); 445 file->Cancel(true);
463 } 446 }
464 447
465 void DownloadsDOMHandler::HandleClearAll(const ListValue* args) { 448 void DownloadsDOMHandler::HandleClearAll(const base::ListValue* args) {
466 CountDownloadsDOMEvents(DOWNLOADS_DOM_EVENT_CLEAR_ALL); 449 CountDownloadsDOMEvents(DOWNLOADS_DOM_EVENT_CLEAR_ALL);
467 download_manager_->RemoveAllDownloads(); 450 download_manager_->RemoveAllDownloads();
468 451
469 // If this is an incognito downloader, clear All should clear main download 452 // If this is an incognito downloader, clear All should clear main download
470 // manager as well. 453 // manager as well.
471 if (original_profile_download_manager_) 454 if (original_profile_download_manager_)
472 original_profile_download_manager_->RemoveAllDownloads(); 455 original_profile_download_manager_->RemoveAllDownloads();
473 } 456 }
474 457
475 void DownloadsDOMHandler::HandleOpenDownloadsFolder(const ListValue* args) { 458 void DownloadsDOMHandler::HandleOpenDownloadsFolder(
459 const base::ListValue* args) {
476 CountDownloadsDOMEvents(DOWNLOADS_DOM_EVENT_OPEN_FOLDER); 460 CountDownloadsDOMEvents(DOWNLOADS_DOM_EVENT_OPEN_FOLDER);
477 platform_util::OpenItem( 461 platform_util::OpenItem(
478 DownloadPrefs::FromDownloadManager(download_manager_)->DownloadPath()); 462 DownloadPrefs::FromDownloadManager(download_manager_)->DownloadPath());
479 } 463 }
480 464
481 // DownloadsDOMHandler, private: ---------------------------------------------- 465 // DownloadsDOMHandler, private: ----------------------------------------------
482 466
483 void DownloadsDOMHandler::SendCurrentDownloads() { 467 void DownloadsDOMHandler::SendCurrentDownloads() {
484 ListValue results_value; 468 update_scheduled_ = false;
485 for (OrderedDownloads::iterator it = download_items_.begin(); 469 content::DownloadManager::DownloadVector downloads;
486 it != download_items_.end(); ++it) { 470 SearchDownloads(&downloads);
487 if (!*it) 471 sort(downloads.begin(), downloads.end(), DownloadItemSorter());
488 continue; 472 base::ListValue results_value;
489 int index = static_cast<int>(it - download_items_.begin()); 473 for (content::DownloadManager::DownloadVector::const_iterator
490 if (index <= kMaxDownloads) 474 iter = downloads.begin();
491 results_value.Append(CreateDownloadItemValue(*it, index, IsItemIncognito( 475 iter != downloads.end(); ++iter) {
492 (*it)->GetId(), 476 if (IsDownloadDisplayable(**iter)) {
477 results_value.Append(CreateDownloadItemValue(*iter, IsItemIncognito(
478 (*iter)->GetId(),
493 download_manager_, 479 download_manager_,
James Hawkins 2012/08/19 06:17:29 Optional nit: Consolidate parameters to save a row
benjhayden 2012/08/19 22:20:27 Done.
494 original_profile_download_manager_))); 480 original_profile_download_manager_)));
481 }
482 if (results_value.GetSize() == kMaxDownloads)
483 break;
495 } 484 }
485 CallDownloadsList(results_value);
486 }
496 487
497 web_ui()->CallJavascriptFunction("downloadsList", results_value); 488 void DownloadsDOMHandler::SearchDownloads(
489 content::DownloadManager::DownloadVector* downloads) {
490 download_manager_->SearchDownloads(search_text_, downloads);
491 if (original_profile_download_manager_) {
492 original_profile_download_manager_->SearchDownloads(
493 search_text_, downloads);
494 }
498 } 495 }
499 496
500 void DownloadsDOMHandler::ShowDangerPrompt( 497 void DownloadsDOMHandler::ShowDangerPrompt(
501 content::DownloadItem* dangerous_item) { 498 content::DownloadItem* dangerous_item) {
502 DownloadDangerPrompt* danger_prompt = DownloadDangerPrompt::Create( 499 DownloadDangerPrompt* danger_prompt = DownloadDangerPrompt::Create(
503 dangerous_item, 500 dangerous_item,
504 TabContents::FromWebContents(web_ui()->GetWebContents()), 501 TabContents::FromWebContents(GetWebUIWebContents()),
505 base::Bind(&DownloadsDOMHandler::DangerPromptAccepted, 502 base::Bind(&DownloadsDOMHandler::DangerPromptAccepted,
506 weak_ptr_factory_.GetWeakPtr(), dangerous_item->GetId()), 503 weak_ptr_factory_.GetWeakPtr(), dangerous_item->GetId()),
507 base::Closure()); 504 base::Closure());
508 // danger_prompt will delete itself. 505 // danger_prompt will delete itself.
509 DCHECK(danger_prompt); 506 DCHECK(danger_prompt);
510 } 507 }
511 508
512 void DownloadsDOMHandler::DangerPromptAccepted(int download_id) { 509 void DownloadsDOMHandler::DangerPromptAccepted(int download_id) {
513 content::DownloadItem* item = download_manager_->GetActiveDownloadItem( 510 content::DownloadItem* item = download_manager_->GetActiveDownloadItem(
514 download_id); 511 download_id);
515 if (!item) 512 if (!item)
516 return; 513 return;
517 CountDownloadsDOMEvents(DOWNLOADS_DOM_EVENT_SAVE_DANGEROUS); 514 CountDownloadsDOMEvents(DOWNLOADS_DOM_EVENT_SAVE_DANGEROUS);
518 item->DangerousDownloadValidated(); 515 item->DangerousDownloadValidated();
519 } 516 }
520 517
521 void DownloadsDOMHandler::ClearDownloadItems() { 518 content::DownloadItem* DownloadsDOMHandler::GetDownloadByValue(
522 // Clear out old state and remove self as observer for each download. 519 const base::ListValue* args) {
523 for (OrderedDownloads::iterator it = download_items_.begin(); 520 int id = -1;
524 it != download_items_.end(); ++it) { 521 if (!ExtractIntegerValue(args, &id))
525 if (!*it) 522 return NULL;
526 continue; 523 content::DownloadItem* download_item = download_manager_->GetDownload(id);
527 (*it)->RemoveObserver(this); 524 if (download_item == NULL) {
525 download_item = original_profile_download_manager_->GetDownload(id);
528 } 526 }
529 download_items_.clear(); 527 return download_item;
530 } 528 }
531 529
532 content::DownloadItem* DownloadsDOMHandler::GetDownloadById(int id) { 530 content::WebContents* DownloadsDOMHandler::GetWebUIWebContents() {
533 for (OrderedDownloads::iterator it = download_items_.begin(); 531 return web_ui()->GetWebContents();
534 it != download_items_.end(); ++it) {
535 if (static_cast<int>(it - download_items_.begin() == id)) {
536 return (*it);
537 }
538 }
539
540 return NULL;
541 } 532 }
542 533
543 content::DownloadItem* DownloadsDOMHandler::GetDownloadByValue( 534 void DownloadsDOMHandler::CallDownloadsList(const base::ListValue& downloads) {
544 const ListValue* args) { 535 web_ui()->CallJavascriptFunction("downloadsList", downloads);
545 int id;
546 if (ExtractIntegerValue(args, &id)) {
547 return GetDownloadById(id);
548 }
549 return NULL;
550 } 536 }
537
538 void DownloadsDOMHandler::CallDownloadUpdated(
539 const base::ListValue& download_item) {
540 web_ui()->CallJavascriptFunction("downloadUpdated", download_item);
541 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698