File: save_package_file_picker.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (287 lines) | stat: -rw-r--r-- 10,794 bytes parent folder | download | duplicates (6)
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
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

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

#include <stddef.h>

#include <memory>

#include "base/command_line.h"
#include "base/functional/bind.h"
#include "base/i18n/file_util_icu.h"
#include "base/metrics/histogram_macros.h"
#include "base/strings/utf_string_conversions.h"
#include "build/build_config.h"
#include "chrome/browser/download/chrome_download_manager_delegate.h"
#include "chrome/browser/download/download_prefs.h"
#include "chrome/browser/platform_util.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/chrome_select_file_policy.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/grit/generated_resources.h"
#include "components/prefs/pref_member.h"
#include "components/prefs/pref_service.h"
#include "content/public/browser/download_manager.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/save_page_type.h"
#include "content/public/browser/web_contents.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/shell_dialogs/selected_file_info.h"

using content::RenderProcessHost;
using content::SavePageType;
using content::WebContents;

namespace {

// If false, we don't prompt the user as to where to save the file.  This
// exists only for testing.
bool g_should_prompt_for_filename = true;

void OnSavePackageDownloadCreated(download::DownloadItem* download) {
  ChromeDownloadManagerDelegate::DisableSafeBrowsing(download);
}

// Adds "Webpage, HTML Only" type to FileTypeInfo.
void AddHtmlOnlyFileTypeInfo(
    ui::SelectFileDialog::FileTypeInfo* file_type_info,
    const base::FilePath::StringType& extra_extension) {
  file_type_info->extension_description_overrides.push_back(
      l10n_util::GetStringUTF16(IDS_SAVE_PAGE_DESC_HTML_ONLY));

  std::vector<base::FilePath::StringType> extensions;
  extensions.push_back(FILE_PATH_LITERAL("html"));
  extensions.push_back(FILE_PATH_LITERAL("htm"));
  if (!extra_extension.empty())
    extensions.push_back(extra_extension);
  file_type_info->extensions.emplace_back(std::move(extensions));
}

// Adds "Webpage, Single File" type to FileTypeInfo.
void AddSingleFileFileTypeInfo(
    ui::SelectFileDialog::FileTypeInfo* file_type_info) {
  file_type_info->extension_description_overrides.push_back(
      l10n_util::GetStringUTF16(IDS_SAVE_PAGE_DESC_SINGLE_FILE));

  file_type_info->extensions.emplace_back(
      std::initializer_list<base::FilePath::StringType>{
          FILE_PATH_LITERAL("mhtml")});
}

// Chrome OS intentionally does not support "Webpage, Complete" type.
// See https://crbug.com/40951429
#if !BUILDFLAG(IS_CHROMEOS)
// Adds "Webpage, Complete" type to FileTypeInfo.
void AddCompleteFileTypeInfo(
    ui::SelectFileDialog::FileTypeInfo* file_type_info,
    const base::FilePath::StringType& extra_extension) {
  file_type_info->extension_description_overrides.push_back(
      l10n_util::GetStringUTF16(IDS_SAVE_PAGE_DESC_COMPLETE));

  std::vector<base::FilePath::StringType> extensions;
  extensions.push_back(FILE_PATH_LITERAL("htm"));
  extensions.push_back(FILE_PATH_LITERAL("html"));
  if (!extra_extension.empty())
    extensions.push_back(extra_extension);
  file_type_info->extensions.push_back(extensions);
}
#endif  // BUILDFLAG(IS_CHROMEOS)

// Checks whether this is a blocked page (e.g., when a child user is accessing
// a mature site).
// Recall that the blocked page is an interstitial. In the past, old
// (non-committed) interstitials couldn't be easily identified, while the
// committed ones can only be matched by page title. To prevent future bugs due
// to changing the page title, we make a conservative choice here and only
// check for PAGE_TYPE_ERROR. The result is that we may include a few other
// error pages (failed DNS lookups, SSL errors, etc), which shouldn't affect
// functionality.
bool IsErrorPage(content::WebContents* web_contents) {
  if (web_contents->GetController().GetActiveEntry() == nullptr)
    return false;
  return web_contents->GetController().GetLastCommittedEntry()->GetPageType() ==
         content::PAGE_TYPE_ERROR;
}

}  // anonymous namespace

// TODO(crbug.com/41439108): REMOVE DIRTY HACK
// To prevent access to blocked websites, we are temporarily disabling the
// HTML-only download of error pages for child users only.
// Note that MHTML is still available, so the save functionality is preserved.
bool SavePackageFilePicker::ShouldSaveAsOnlyHTML(
    content::WebContents* web_contents) const {
  Profile* profile =
      Profile::FromBrowserContext(web_contents->GetBrowserContext());
  return !profile->IsChild() || !IsErrorPage(web_contents);
}

bool SavePackageFilePicker::ShouldSaveAsMHTMLByDefault() const {
#if !BUILDFLAG(IS_CHROMEOS)
  if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
          switches::kSavePageAsMHTML))
    return false;
#endif
  return can_save_as_complete_;
}

SavePackageFilePicker::SavePackageFilePicker(
    content::WebContents* web_contents,
    const base::FilePath& suggested_path,
    const base::FilePath::StringType& default_extension,
    bool can_save_as_complete,
    DownloadPrefs* download_prefs,
    content::SavePackagePathPickedCallback callback)
    : render_process_id_(
          web_contents->GetPrimaryMainFrame()->GetProcess()->GetDeprecatedID()),
      can_save_as_complete_(can_save_as_complete),
      download_prefs_(download_prefs),
      callback_(std::move(callback)) {
  base::FilePath suggested_path_copy = suggested_path;
  base::FilePath::StringType default_extension_copy = default_extension;
  size_t file_type_index = 0;
  ui::SelectFileDialog::FileTypeInfo file_type_info;

  file_type_info.allowed_paths =
      ui::SelectFileDialog::FileTypeInfo::NATIVE_PATH;

  if (can_save_as_complete_) {
    // The option index is not zero-based. Put a dummy entry.
    save_types_.push_back(content::SAVE_PAGE_TYPE_UNKNOWN);

    base::FilePath::StringType extra_extension;
    if (!ShouldSaveAsMHTMLByDefault() &&
        !suggested_path_copy.FinalExtension().empty() &&
        !suggested_path_copy.MatchesExtension(FILE_PATH_LITERAL(".htm")) &&
        !suggested_path_copy.MatchesExtension(FILE_PATH_LITERAL(".html"))) {
      extra_extension = suggested_path_copy.FinalExtension().substr(1);
    }

    if (ShouldSaveAsOnlyHTML(web_contents)) {
      AddHtmlOnlyFileTypeInfo(&file_type_info, extra_extension);
      save_types_.push_back(content::SAVE_PAGE_TYPE_AS_ONLY_HTML);
    }

    AddSingleFileFileTypeInfo(&file_type_info);
    save_types_.push_back(content::SAVE_PAGE_TYPE_AS_MHTML);

#if !BUILDFLAG(IS_CHROMEOS)
    AddCompleteFileTypeInfo(&file_type_info, extra_extension);
    save_types_.push_back(content::SAVE_PAGE_TYPE_AS_COMPLETE_HTML);
#endif  // BUILDFLAG(IS_CHROMEOS)

    file_type_info.include_all_files = false;

    const content::SavePageType preferred_save_type =
        ShouldSaveAsMHTMLByDefault() ? content::SAVE_PAGE_TYPE_AS_MHTML
                                     : static_cast<content::SavePageType>(
                                           download_prefs_->save_file_type());

    // Select the item saved in the pref.
    for (size_t i = 0; i < save_types_.size(); ++i) {
      if (save_types_[i] == preferred_save_type) {
        file_type_index = i;
        break;
      }
    }

    // If the item saved in the pref was not found, use the last item.
    if (!file_type_index) {
      file_type_index = save_types_.size() - 1;
    }
  } else {
    // The contents can not be saved as complete-HTML, so do not show the file
    // filters.
    file_type_info.extensions.resize(1);
    file_type_info.extensions[0].push_back(
        suggested_path_copy.FinalExtension());

    if (!file_type_info.extensions[0][0].empty()) {
      // Drop the .
      file_type_info.extensions[0][0].erase(0, 1);
    }

    file_type_info.include_all_files = true;
    file_type_index = 1;
  }

  if (file_type_index < save_types_.size() &&
      save_types_[file_type_index] == content::SAVE_PAGE_TYPE_AS_MHTML) {
    default_extension_copy = FILE_PATH_LITERAL("mhtml");
    suggested_path_copy =
        suggested_path_copy.ReplaceExtension(default_extension_copy);
  }

  if (g_should_prompt_for_filename) {
    select_file_dialog_ = ui::SelectFileDialog::Create(
        this, std::make_unique<ChromeSelectFilePolicy>(web_contents));
    select_file_dialog_->SelectFile(
        ui::SelectFileDialog::SELECT_SAVEAS_FILE, std::u16string(),
        suggested_path_copy, &file_type_info, file_type_index,
        default_extension_copy,
        platform_util::GetTopLevel(web_contents->GetNativeView()),
        /*caller=*/
        web_contents
            ? &web_contents->GetPrimaryMainFrame()->GetLastCommittedURL()
            : nullptr);
    return;
  }

  // If |g_should_prompt_for_filename| is unset or |select_file_dialog_| could
  // not be instantiated for some reason, just use 'suggested_path_copy' instead
  // of opening the dialog prompt. Go through FileSelected() for consistency.
  FileSelected(ui::SelectedFileInfo(suggested_path_copy), file_type_index);
}

SavePackageFilePicker::~SavePackageFilePicker() {
  if (select_file_dialog_) {
    select_file_dialog_->ListenerDestroyed();
  }
}

void SavePackageFilePicker::SetShouldPromptUser(bool should_prompt) {
  g_should_prompt_for_filename = should_prompt;
}

void SavePackageFilePicker::FileSelected(const ui::SelectedFileInfo& file,
                                         int index) {
  std::unique_ptr<SavePackageFilePicker> delete_this(this);
  RenderProcessHost* process = RenderProcessHost::FromID(render_process_id_);
  if (!process)
    return;
  SavePageType save_type = content::SAVE_PAGE_TYPE_UNKNOWN;

  if (can_save_as_complete_) {
    DCHECK_LT(index, static_cast<int>(save_types_.size()));
    save_type = save_types_[index];
    if (select_file_dialog_ &&
        select_file_dialog_->HasMultipleFileTypeChoices()) {
      download_prefs_->SetSaveFileType(save_type);
    }
  } else {
    // Use "HTML Only" type as a dummy.
    save_type = content::SAVE_PAGE_TYPE_AS_ONLY_HTML;
  }

  base::FilePath path = file.path();
  base::i18n::NormalizeFileNameEncoding(&path);

  download_prefs_->SetSaveFilePath(path.DirName());

  content::SavePackagePathPickedParams params;
  params.file_path = path;
  params.save_type = save_type;
#if BUILDFLAG(IS_MAC)
  params.file_tags = file.file_tags;
#endif
  std::move(callback_).Run(std::move(params),
                           base::BindOnce(&OnSavePackageDownloadCreated));
}

void SavePackageFilePicker::FileSelectionCanceled() {
  delete this;
}