summaryrefslogtreecommitdiffstats
path: root/chrome/browser/download/download_request_manager.cc
blob: 55b48fee37c978d1b48ce4f617662501b376af36 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/download/download_request_manager.h"

#include "base/message_loop.h"
#include "base/thread.h"
#include "chrome/browser/tab_contents/constrained_window.h"
#include "chrome/browser/tab_contents/navigation_controller.h"
#include "chrome/browser/tab_contents/navigation_entry.h"
#include "chrome/browser/tab_contents/tab_contents_delegate.h"
#include "chrome/browser/tab_contents/tab_util.h"
#include "chrome/browser/tab_contents/web_contents.h"
#include "chrome/common/l10n_util.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_service.h"
#include "chrome/views/dialog_delegate.h"
#include "chrome/views/message_box_view.h"
#include "grit/generated_resources.h"

namespace {

// DialogDelegateImpl ----------------------------------------------------------

// DialogDelegateImpl is the DialogDelegate implementation used to prompt the
// the user as to whether they want to allow multiple downloads.
// DialogDelegateImpl delegates the allow/cancel methods to the
// TabDownloadState.
//
// TabDownloadState does not directly implement DialogDelegate, rather it is
// split into DialogDelegateImpl as TabDownloadState may be deleted before
// the dialog.

class DialogDelegateImpl : public views::DialogDelegate {
 public:
  DialogDelegateImpl(TabContents* tab,
                     DownloadRequestManager::TabDownloadState* host);

  void set_host(DownloadRequestManager::TabDownloadState* host) {
    host_ = host;
  }

  // Closes the prompt.
  void CloseWindow();

 private:
  // DialogDelegate methods;
  virtual bool Cancel();
  virtual bool Accept();
  virtual views::View* GetContentsView() { return message_view_; }
  virtual std::wstring GetDialogButtonLabel(DialogButton button) const;
  virtual int GetDefaultDialogButton() const {
    return DIALOGBUTTON_CANCEL;
  }
  virtual void WindowClosing();

  // The TabDownloadState we're displaying the dialog for. May be null.
  DownloadRequestManager::TabDownloadState* host_;

  MessageBoxView* message_view_;

  ConstrainedWindow* window_;

  DISALLOW_COPY_AND_ASSIGN(DialogDelegateImpl);
};

}  // namespace

// TabDownloadState ------------------------------------------------------------

// TabDownloadState maintains the download state for a particular tab.
// TabDownloadState installs observers to update the download status
// appropriately. Additionally TabDownloadState prompts the user as necessary.
// TabDownloadState deletes itself (by invoking DownloadRequestManager::Remove)
// as necessary.

class DownloadRequestManager::TabDownloadState : public NotificationObserver {
 public:
  // Creates a new TabDownloadState. |controller| is the controller the
  // TabDownloadState tracks the state of and is the host for any dialogs that
  // are displayed. |originating_controller| is used to determine the host of
  // the initial download. If |originating_controller| is null, |controller| is
  // used. |originating_controller| is typically null, but differs from
  // |controller| in the case of a constrained popup requesting the download.
  TabDownloadState(DownloadRequestManager* host,
                   NavigationController* controller,
                   NavigationController* originating_controller);
  ~TabDownloadState();

  // Status of the download.
  void set_download_status(DownloadRequestManager::DownloadStatus status) {
    status_ = status;
  }
  DownloadRequestManager::DownloadStatus download_status() const {
    return status_;
  }

  // Invoked when a user gesture occurs (mouse click, enter or space). This
  // may result in invoking Remove on DownloadRequestManager.
  void OnUserGesture();

  // Asks the user if they really want to allow the download.
  // See description above CanDownloadOnIOThread for details on lifetime of
  // callback.
  void PromptUserForDownload(TabContents* tab,
                             DownloadRequestManager::Callback* callback);

  // Are we showing a prompt to the user?
  bool is_showing_prompt() const { return (dialog_delegate_ != NULL); }

  // NavigationController we're tracking.
  NavigationController* controller() const { return controller_; }

  // Invoked from DialogDelegateImpl. Notifies the delegates and changes the
  // status appropriately.
  void Cancel();
  void Accept();

 private:
  // NotificationObserver method.
  void Observe(NotificationType type,
               const NotificationSource& source,
               const NotificationDetails& details);

  // Notifies the callbacks as to whether the download is allowed or not.
  // Updates status_ appropriately.
  void NotifyCallbacks(bool allow);

  DownloadRequestManager* host_;

  NavigationController* controller_;

  // Host of the first page the download started on. This may be empty.
  std::string initial_page_host_;

  DownloadRequestManager::DownloadStatus status_;

  // Callbacks we need to notify. This is only non-empty if we're showing a
  // dialog.
  // See description above CanDownloadOnIOThread for details on lifetime of
  // callbacks.
  std::vector<DownloadRequestManager::Callback*> callbacks_;

  // Used to remove observers installed on NavigationController.
  NotificationRegistrar registrar_;

  // Handles showing the dialog to the user, may be null.
  DialogDelegateImpl* dialog_delegate_;

  DISALLOW_COPY_AND_ASSIGN(TabDownloadState);
};

DownloadRequestManager::TabDownloadState::TabDownloadState(
    DownloadRequestManager* host,
    NavigationController* controller,
    NavigationController* originating_controller)
    : host_(host),
      controller_(controller),
      status_(DownloadRequestManager::ALLOW_ONE_DOWNLOAD),
      dialog_delegate_(NULL) {
  Source<NavigationController> notification_source(controller);
  registrar_.Add(this, NotificationType::NAV_ENTRY_PENDING,
                 notification_source);
  registrar_.Add(this, NotificationType::TAB_CLOSED, notification_source);

  NavigationEntry* active_entry = originating_controller ?
      originating_controller->GetActiveEntry() : controller->GetActiveEntry();
  if (active_entry)
    initial_page_host_ = active_entry->url().host();
}

DownloadRequestManager::TabDownloadState::~TabDownloadState() {
  // We should only be destroyed after the callbacks have been notified.
  DCHECK(callbacks_.empty());

  // And we should have closed the message box.
  DCHECK(!dialog_delegate_);
}

void DownloadRequestManager::TabDownloadState::OnUserGesture() {
  if (is_showing_prompt()) {
    // Don't change the state if the user clicks on the page some where.
    return;
  }

  if (status_ != DownloadRequestManager::ALLOW_ALL_DOWNLOADS &&
      status_ != DownloadRequestManager::DOWNLOADS_NOT_ALLOWED) {
    // Revert to default status.
    host_->Remove(this);
    // WARNING: We've been deleted.
    return;
  }
}

void DownloadRequestManager::TabDownloadState::PromptUserForDownload(
    TabContents* tab,
    DownloadRequestManager::Callback* callback) {
  callbacks_.push_back(callback);

  if (is_showing_prompt())
    return;  // Already showing prompt.

  if (DownloadRequestManager::delegate_)
    NotifyCallbacks(DownloadRequestManager::delegate_->ShouldAllowDownload());
  else
    dialog_delegate_ = new DialogDelegateImpl(tab, this);
}

void DownloadRequestManager::TabDownloadState::Cancel() {
  NotifyCallbacks(false);
}

void DownloadRequestManager::TabDownloadState::Accept() {
  NotifyCallbacks(true);
}

void DownloadRequestManager::TabDownloadState::Observe(
    NotificationType type,
    const NotificationSource& source,
    const NotificationDetails& details) {
  if ((type != NotificationType::NAV_ENTRY_PENDING &&
       type != NotificationType::TAB_CLOSED) ||
      Source<NavigationController>(source).ptr() != controller_) {
    NOTREACHED();
    return;
  }

  switch(type.value) {
    case NotificationType::NAV_ENTRY_PENDING: {
      // NOTE: resetting state on a pending navigate isn't ideal. In particular
      // it is possible that queued up downloads for the page before the
      // pending navigate will be delivered to us after we process this
      // request. If this happens we may let a download through that we
      // shouldn't have. But this is rather rare, and it is difficult to get
      // 100% right, so we don't deal with it.
      NavigationEntry* entry = controller_->GetPendingEntry();
      if (!entry)
        return;

      if (PageTransition::IsRedirect(entry->transition_type())) {
        // Redirects don't count.
        return;
      }

      if (is_showing_prompt()) {
        // We're prompting the user and they navigated away. Close the popup and
        // cancel the downloads.
        dialog_delegate_->CloseWindow();
        // After switch we'll notify callbacks and get deleted.
      } else if (status_ == DownloadRequestManager::ALLOW_ALL_DOWNLOADS ||
                 status_ == DownloadRequestManager::DOWNLOADS_NOT_ALLOWED) {
        // User has either allowed all downloads or canceled all downloads. Only
        // reset the download state if the user is navigating to a different
        // host (or host is empty).
        if (!initial_page_host_.empty() && !entry->url().host().empty() &&
            entry->url().host() == initial_page_host_) {
          return;
        }
      }  // else case: we're not prompting user and user hasn't allowed or
         // disallowed downloads, break so that we get deleted after switch.
      break;
    }

    case NotificationType::TAB_CLOSED:
      // Tab closed, no need to handle closing the dialog as it's owned by the
      // TabContents, break so that we get deleted after switch.
      break;

    default:
      NOTREACHED();
  }

  NotifyCallbacks(false);
  host_->Remove(this);
}

void DownloadRequestManager::TabDownloadState::NotifyCallbacks(bool allow) {
  if (dialog_delegate_) {
    // Reset the delegate so we don't get notified again.
    dialog_delegate_->set_host(NULL);
    dialog_delegate_ = NULL;
  }
  status_ = allow ?
      DownloadRequestManager::ALLOW_ALL_DOWNLOADS :
      DownloadRequestManager::DOWNLOADS_NOT_ALLOWED;
  std::vector<DownloadRequestManager::Callback*> callbacks;
  callbacks.swap(callbacks_);
  for (size_t i = 0; i < callbacks.size(); ++i)
    host_->ScheduleNotification(callbacks[i], allow);
}

namespace {

// DialogDelegateImpl ----------------------------------------------------------

DialogDelegateImpl::DialogDelegateImpl(
    TabContents* tab,
    DownloadRequestManager::TabDownloadState* host)
    : host_(host) {
  message_view_ = new MessageBoxView(
      MessageBoxView::kIsConfirmMessageBox,
      l10n_util::GetString(IDS_MULTI_DOWNLOAD_WARNING),
      std::wstring());
  window_ = tab->CreateConstrainedDialog(this, message_view_);
}

void DialogDelegateImpl::CloseWindow() {
  window_->CloseConstrainedWindow();
}

bool DialogDelegateImpl::Cancel() {
  if (host_)
    host_->Cancel();
  return true;
}

bool DialogDelegateImpl::Accept() {
  if (host_)
    host_->Accept();
  return true;
}

std::wstring DialogDelegateImpl::GetDialogButtonLabel(
    DialogButton button) const {
  if (button == DIALOGBUTTON_OK)
    return l10n_util::GetString(IDS_MULTI_DOWNLOAD_WARNING_ALLOW);
  if (button == DIALOGBUTTON_CANCEL)
    return l10n_util::GetString(IDS_MULTI_DOWNLOAD_WARNING_DENY);
  return std::wstring();
}

void DialogDelegateImpl::WindowClosing() {
  DCHECK(!host_);
  delete this;
}

}  // namespace

// DownloadRequestManager ------------------------------------------------------

DownloadRequestManager::DownloadRequestManager(MessageLoop* io_loop,
                                               MessageLoop* ui_loop)
    : io_loop_(io_loop),
      ui_loop_(ui_loop) {
}

DownloadRequestManager::~DownloadRequestManager() {
  // All the tabs should have closed before us, which sends notification and
  // removes from state_map_. As such, there should be no pending callbacks.
  DCHECK(state_map_.empty());
}

DownloadRequestManager::DownloadStatus
    DownloadRequestManager::GetDownloadStatus(TabContents* tab) {
  TabDownloadState* state = GetDownloadState(tab->controller(), NULL, false);
  return state ? state->download_status() : ALLOW_ONE_DOWNLOAD;
}

void DownloadRequestManager::CanDownloadOnIOThread(int render_process_host_id,
                                                   int render_view_id,
                                                   Callback* callback) {
  // This is invoked on the IO thread. Schedule the task to run on the UI
  // thread so that we can query UI state.
  DCHECK(!io_loop_ || io_loop_ == MessageLoop::current());
  ui_loop_->PostTask(FROM_HERE,
      NewRunnableMethod(this, &DownloadRequestManager::CanDownload,
                        render_process_host_id, render_view_id, callback));
}

void DownloadRequestManager::OnUserGesture(TabContents* tab) {
  NavigationController* controller = tab->controller();
  if (!controller) {
    NOTREACHED();
    return;
  }

  TabDownloadState* state = GetDownloadState(controller, NULL, false);
  if (!state)
    return;

  state->OnUserGesture();
}

// static
void DownloadRequestManager::SetTestingDelegate(TestingDelegate* delegate) {
  delegate_ = delegate;
}

DownloadRequestManager::TabDownloadState* DownloadRequestManager::
    GetDownloadState(NavigationController* controller,
                     NavigationController* originating_controller,
                     bool create) {
  DCHECK(controller);
  StateMap::iterator i = state_map_.find(controller);
  if (i != state_map_.end())
    return i->second;

  if (!create)
    return NULL;

  TabDownloadState* state =
      new TabDownloadState(this, controller, originating_controller);
  state_map_[controller] = state;
  return state;
}

void DownloadRequestManager::CanDownload(int render_process_host_id,
                                         int render_view_id,
                                         Callback* callback) {
  DCHECK(!ui_loop_ || MessageLoop::current() == ui_loop_);

  WebContents* originating_tab =
      tab_util::GetWebContentsByID(render_process_host_id, render_view_id);
  if (!originating_tab) {
    // The tab was closed, don't allow the download.
    ScheduleNotification(callback, false);
    return;
  }
  CanDownloadImpl(originating_tab, callback);
}

void DownloadRequestManager::CanDownloadImpl(
    TabContents* originating_tab,
    Callback* callback) {
  TabContents* effective_tab = originating_tab;
  if (effective_tab->delegate() &&
      effective_tab->delegate()->GetConstrainingContents(effective_tab)) {
    // The tab requesting the download is a constrained popup that is not
    // shown, treat the request as if it came from the parent.
    effective_tab =
        effective_tab->delegate()->GetConstrainingContents(effective_tab);
  }

  NavigationController* controller = effective_tab->controller();
  DCHECK(controller);
  TabDownloadState* state = GetDownloadState(
      controller, originating_tab->controller(), true);
  switch (state->download_status()) {
    case ALLOW_ALL_DOWNLOADS:
      ScheduleNotification(callback, true);
      break;

    case ALLOW_ONE_DOWNLOAD:
      state->set_download_status(PROMPT_BEFORE_DOWNLOAD);
      ScheduleNotification(callback, true);
      break;

    case DOWNLOADS_NOT_ALLOWED:
      ScheduleNotification(callback, false);
      break;

    case PROMPT_BEFORE_DOWNLOAD:
      state->PromptUserForDownload(effective_tab, callback);
      break;

    default:
      NOTREACHED();
  }
}

void DownloadRequestManager::ScheduleNotification(Callback* callback,
                                                  bool allow) {
  if (io_loop_) {
    io_loop_->PostTask(FROM_HERE,
        NewRunnableMethod(this, &DownloadRequestManager::NotifyCallback,
                          callback, allow));
  } else {
    NotifyCallback(callback, allow);
  }
}

void DownloadRequestManager::NotifyCallback(Callback* callback, bool allow) {
  // We better be on the IO thread now.
  DCHECK(!io_loop_ || MessageLoop::current() == io_loop_);
  if (allow)
    callback->ContinueDownload();
  else
    callback->CancelDownload();
}

void DownloadRequestManager::Remove(TabDownloadState* state) {
  DCHECK(state_map_.find(state->controller()) != state_map_.end());
  state_map_.erase(state->controller());
  delete state;
}

// static
DownloadRequestManager::TestingDelegate* DownloadRequestManager::delegate_ =
    NULL;