1// Copyright (c) 2011 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "chrome/browser/ui/download/download_tab_helper.h"
6
7#include "chrome/browser/download/download_manager.h"
8#include "chrome/browser/download/download_util.h"
9#include "chrome/browser/profiles/profile.h"
10#include "chrome/common/render_messages.h"
11#include "content/browser/tab_contents/tab_contents.h"
12#include "content/common/view_messages.h"
13
14DownloadTabHelper::DownloadTabHelper(TabContents* tab_contents)
15    : TabContentsObserver(tab_contents) {
16  DCHECK(tab_contents);
17}
18
19DownloadTabHelper::~DownloadTabHelper() {
20}
21
22void DownloadTabHelper::OnSavePage() {
23  // If we can not save the page, try to download it.
24  if (!SavePackage::IsSavableContents(tab_contents()->contents_mime_type())) {
25    DownloadManager* dlm = tab_contents()->profile()->GetDownloadManager();
26    const GURL& current_page_url = tab_contents()->GetURL();
27    if (dlm && current_page_url.is_valid()) {
28      dlm->DownloadUrl(current_page_url, GURL(), "", tab_contents());
29      download_util::RecordDownloadCount(
30          download_util::INITIATED_BY_SAVE_PACKAGE_FAILURE_COUNT);
31    }
32    return;
33  }
34
35  tab_contents()->Stop();
36
37  // Create the save package and possibly prompt the user for the name to save
38  // the page as. The user prompt is an asynchronous operation that runs on
39  // another thread.
40  save_package_ = new SavePackage(tab_contents());
41  save_package_->GetSaveInfo();
42}
43
44void DownloadTabHelper::OnSaveURL(const GURL& url) {
45  DownloadManager* dlm = tab_contents()->profile()->GetDownloadManager();
46  dlm->DownloadUrl(url, tab_contents()->GetURL(), "", tab_contents());
47}
48
49// Used in automated testing to bypass prompting the user for file names.
50// Instead, the names and paths are hard coded rather than running them through
51// file name sanitation and extension / mime checking.
52bool DownloadTabHelper::SavePage(const FilePath& main_file,
53                                 const FilePath& dir_path,
54                                 SavePackage::SavePackageType save_type) {
55  // Stop the page from navigating.
56  tab_contents()->Stop();
57
58  save_package_ =
59      new SavePackage(tab_contents(), save_type, main_file, dir_path);
60  return save_package_->Init();
61}
62
63bool DownloadTabHelper::OnMessageReceived(const IPC::Message& message) {
64  bool handled = true;
65  IPC_BEGIN_MESSAGE_MAP(DownloadTabHelper, message)
66    IPC_MESSAGE_HANDLER(ViewHostMsg_SaveURLAs, OnSaveURL)
67    IPC_MESSAGE_UNHANDLED(handled = false)
68  IPC_END_MESSAGE_MAP()
69
70  return handled;
71}
72
73