electron/shell/browser/ui/file_dialog_win.cc
electron-roller[bot] dd03cceda0
chore: bump chromium to 137.0.7128.1 (main) (#46482)
* chore: bump chromium in DEPS to 137.0.7107.0

* chore: bump chromium in DEPS to 137.0.7109.0

* chore: bump chromium in DEPS to 137.0.7111.0

* chore: bump chromium in DEPS to 137.0.7113.0

* 6384240: Remove double-declaration for accessibility on macOS | 6384240

* 6422872: Remove unused includes in isolation_info_mojom_traits.h | 6422872

* chore: update patches

* 6400733: Avoid ipc_message_macros.h usage in some foo_param_traits_macros.h files | 6400733

* chore: update patches

* 6423410: Enable unsafe buffer warnings for chromium, try #3. | 6423410

* chore: iwyu

* refactor: prefer value initialization over memset()

From the looks up upstream commits in base/, it looks like memset()
could trigger `-Wunsafe-buffer-usage` warnings soon?

Value initialization is more C++ish and less error-prone anyway,
due to memset()'s easily swappable parameters.

* refactor: NotifyIcon::InitIconData() returns a NOTIFYICONDATA

This follows F.20 in the C++ Core Guidelines and also removes the need
for memset()

* 6423410: Enable unsafe buffer warnings for chromium, try #3. | 6423410

remove all uses of:

- strcmp()

* fixup!  6423410: Enable unsafe buffer warnings for chromium, try #3. | 6423410

* 6433203: Add a PassKey to RegisterDeleteDelegateCallback(). | 6433203

* chore: bump chromium in DEPS to 137.0.7115.0

* 6387077: [PermissionOptions] Generalize PermissionRequestDescription | 6387077

* chore: update patches

* 6387077: [PermissionOptions] Generalize PermissionRequestDescription | 6387077

* fix: add pragma for MacSDK unsafe buffers | 6423410: Enable unsafe buffer warnings for chromium, try #3. | 6423410

* chore: bump chromium in DEPS to 137.0.7117.0

* chore: update patches

* chore: update filesnames.libcxx.gni

* 6431756: Replace SetOwnedByWidget() bool arg with a PassKey. | 6431756

* 6387077: [PermissionOptions] Generalize PermissionRequestDescription | 6387077

* 6428345: Remove ExtensionService usage from ChromeExtensionRegistrarDelegate | 6428345

* 6384315: Migrate extensions_enabled from ExtensionService to Registrar | 6384315

* 6428749: [extensions] Refactor ExtensionService for AddNewAndUpdateExtension. | 6428749

* chore: bump chromium in DEPS to 137.0.7119.0

* 6440290: corner-shape: support inset shadow | 6440290

* 6429230: FSA: Move blocked paths to the PermissionContext class | 6429230

* chore: update patches

* chore: bump chromium in DEPS to 137.0.7121.0

* chore: update patches

* fix: partially revert 6443473: Remove ItemDelete from the Mac version of AppleKeychain | 6443473

* fix: update filenames.libcxx.gni

* chore: bump chromium in DEPS to 137.0.7123.0

* chore: update patches

* chore: "grandfather in" electron views too

Lock further access to View::set_owned_by_client() | 6448510

* chore: update feat_corner_smoothing_css_rule_and_blink_painting.patch

corner-shape: support inset shadow | 6440290

* refactor: grandfather in AutofillPopupView as a subclass of WidgetDelegateView

Add a PassKey for std::make_unique<WidgetDelegateView>() | 6442265

* Provide dbus appmenu information on Wayland | 6405535

* [extensions] Move OnExtensionInstalled out of ExtensionService. | 6443325

* refactor: grandfather in NativeWindowViews for delete callbacks

6433203: Add a PassKey to RegisterDeleteDelegateCallback(). | 6433203

* chore: merge the four "grandfather" patches into one

* [A11yPerformance] Remove IsAccessibilityAllowed() | 6404386: [A11yPerformance] Remove IsAccessibilityAllowed() | 6404386

NB: the changes here are copied from the upstream changes in
chrome/browser/ui/webui/accessibility/accessibility_ui.cc

* 6420753: [PermissionOptions] Use PermissionDescriptorPtr in PermissionController | 6420753

* 6429573: [accessibility] Move mode change out of AccessibilityNotificationWaiter | 6429573

* chore: e patches all

* 6419936: [win] Change ScreenWin public static methods to virtual | 6419936

* 6423410: Enable unsafe buffer warnings for chromium, try #3. | 6423410

remove all uses of:

- fprintf()
- fputs()
- snprintf()
- vsnprintf()

* fix: size conversion FTBFS on Win

* 6423410: Enable unsafe buffer warnings for chromium, try #3. | 6423410

remove all uses of:

- wcscpy_s()

* 6423410: Enable unsafe buffer warnings for chromium, try #3. | 6423410

remove all uses of:

- wcsncpy_s()

* chore: update mas_avoid_private_macos_api_usage.patch.patch

6394283: Remove double-declaration for accessibility on iOS | 6394283

Lots of context shear in this commit but the only interesting part is:

-+  return nullptr;
++  return {};

Which is needed because the return type is sometimes not a pointer.

* chore: e patches all

* chore: disable -Wmacro-redefined warning in electron_main_win.cc

* chore: bump chromium in DEPS to 137.0.7123.5

* refactor: patch electron PermissionTypes into blink

6387077: [PermissionOptions] Generalize PermissionRequestDescription | 6387077

* chore: e patches all

* chore: remove the box_painter_base.cc part of feat_corner_smoothing_css_rule_and_blink_painting.patch

as per code review @ https://github.com/electron/electron/pull/46482#pullrequestreview-2777338370

* test: enable window-smaller-than-64x64 test on Linux

* chore: bump chromium in DEPS to 137.0.7124.1

* chore: bump chromium in DEPS to 137.0.7125.1

* chore: bump chromium in DEPS to 137.0.7127.3

* 6459201: [Extensions] Remove ExtensionSystem::FinishDelayedInstallationIfReady() | 6459201

* 6454796: [Extensions] Move (most) registrar delayed install logic to //extensions | 6454796

* chore: bump chromium in DEPS to 137.0.7128.1

* chore: e patches all

* chore: node ./script/gen-libc++-filenames.js

* [views] Gate DesktopWindowTreeHostWin::window_enlargement_ behind flag

Refs 6428649

* feat: allow opt-out animated_content_sampler.

Refs 6438681

* Trigger CI

---------

Co-authored-by: electron-roller[bot] <84116207+electron-roller[bot]@users.noreply.github.com>
Co-authored-by: Keeley Hammond <khammond@slack-corp.com>
Co-authored-by: Charles Kerr <charles@charleskerr.com>
Co-authored-by: Keeley Hammond <vertedinde@electronjs.org>
Co-authored-by: deepak1556 <hop2deep@gmail.com>
Co-authored-by: John Kleinschmidt <jkleinsc@electronjs.org>
2025-04-22 15:53:29 -04:00

271 lines
8.7 KiB
C++

// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/ui/file_dialog.h"
#include <windows.h> // windows.h must be included first
#include "base/win/shlwapi.h" // NOLINT(build/include_order)
// atlbase.h for CComPtr
#include <atlbase.h> // NOLINT(build/include_order)
#include <shlobj.h> // NOLINT(build/include_order)
#include <shobjidl.h> // NOLINT(build/include_order)
#include "base/files/file_util.h"
#include "base/i18n/case_conversion.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/win/registry.h"
#include "shell/browser/native_window_views.h"
#include "shell/browser/ui/win/dialog_thread.h"
#include "shell/common/gin_converters/file_path_converter.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/promise.h"
namespace file_dialog {
DialogSettings::DialogSettings() = default;
DialogSettings::DialogSettings(const DialogSettings&) = default;
DialogSettings::~DialogSettings() = default;
namespace {
// Distinguish directories from regular files.
bool IsDirectory(const base::FilePath& path) {
base::File::Info file_info;
return base::GetFileInfo(path, &file_info) ? file_info.is_directory
: path.EndsWithSeparator();
}
void ConvertFilters(const Filters& filters,
std::vector<std::wstring>* buffer,
std::vector<COMDLG_FILTERSPEC>* filterspec) {
if (filters.empty()) {
COMDLG_FILTERSPEC spec = {L"All Files (*.*)", L"*.*"};
filterspec->push_back(spec);
return;
}
buffer->reserve(filters.size() * 2);
for (const Filter& filter : filters) {
COMDLG_FILTERSPEC spec;
buffer->push_back(base::UTF8ToWide(filter.first));
spec.pszName = buffer->back().c_str();
std::vector<std::string> extensions(filter.second);
for (std::string& extension : extensions)
extension.insert(0, "*.");
buffer->push_back(base::UTF8ToWide(base::JoinString(extensions, ";")));
spec.pszSpec = buffer->back().c_str();
filterspec->push_back(spec);
}
}
auto GetFileNameFromShellItem(IShellItem* pShellItem, SIGDN type) {
std::optional<base::FilePath> path;
if (wchar_t* name = {}; SUCCEEDED(pShellItem->GetDisplayName(type, &name))) {
path.emplace(name);
::CoTaskMemFree(name);
}
return path;
}
static void SetDefaultFolder(IFileDialog* dialog,
const base::FilePath file_path) {
std::wstring directory =
IsDirectory(file_path) ? file_path.value() : file_path.DirName().value();
ATL::CComPtr<IShellItem> folder_item;
HRESULT hr = SHCreateItemFromParsingName(directory.c_str(), nullptr,
IID_PPV_ARGS(&folder_item));
if (SUCCEEDED(hr))
dialog->SetFolder(folder_item);
}
static HRESULT ShowFileDialog(IFileDialog* dialog,
const DialogSettings& settings) {
HWND parent_window =
settings.parent_window
? static_cast<electron::NativeWindowViews*>(settings.parent_window)
->GetAcceleratedWidget()
: nullptr;
return dialog->Show(parent_window);
}
static void ApplySettings(IFileDialog* dialog, const DialogSettings& settings) {
std::wstring file_part;
if (!IsDirectory(settings.default_path))
file_part = settings.default_path.BaseName().value();
dialog->SetFileName(file_part.c_str());
if (!settings.title.empty())
dialog->SetTitle(base::UTF8ToWide(settings.title).c_str());
if (!settings.button_label.empty())
dialog->SetOkButtonLabel(base::UTF8ToWide(settings.button_label).c_str());
std::vector<std::wstring> buffer;
std::vector<COMDLG_FILTERSPEC> filterspec;
ConvertFilters(settings.filters, &buffer, &filterspec);
if (!filterspec.empty()) {
dialog->SetFileTypes(filterspec.size(), filterspec.data());
}
// By default, *.* will be added to the file name if file type is "*.*". In
// Electron, we disable it to make a better experience.
//
// From MSDN: https://msdn.microsoft.com/en-us/library/windows/desktop/
// bb775970(v=vs.85).aspx
//
// If SetDefaultExtension is not called, the dialog will not update
// automatically when user choose a new file type in the file dialog.
//
// We set file extension to the first none-wildcard extension to make
// sure the dialog will update file extension automatically.
for (size_t i = 0; i < filterspec.size(); ++i) {
std::wstring spec(filterspec[i].pszSpec);
if (spec != L"*.*") {
// SetFileTypeIndex is regarded as one-based index.
dialog->SetFileTypeIndex(i + 1);
// "*.jpg;*.png" => "*.jpg"
std::wstring first_spec = spec.substr(0, spec.find(L';'));
// "*.jpg" => "jpg"
dialog->SetDefaultExtension(first_spec.substr(2).c_str());
break;
}
}
if (settings.default_path.IsAbsolute()) {
SetDefaultFolder(dialog, settings.default_path);
}
}
} // namespace
bool ShowOpenDialogSync(const DialogSettings& settings,
std::vector<base::FilePath>* paths) {
ATL::CComPtr<IFileOpenDialog> file_open_dialog;
HRESULT hr = file_open_dialog.CoCreateInstance(CLSID_FileOpenDialog);
if (FAILED(hr))
return false;
DWORD options = FOS_FORCEFILESYSTEM | FOS_FILEMUSTEXIST;
if (settings.properties & OPEN_DIALOG_OPEN_DIRECTORY)
options |= FOS_PICKFOLDERS;
if (settings.properties & OPEN_DIALOG_MULTI_SELECTIONS)
options |= FOS_ALLOWMULTISELECT;
if (settings.properties & OPEN_DIALOG_SHOW_HIDDEN_FILES)
options |= FOS_FORCESHOWHIDDEN;
if (settings.properties & OPEN_DIALOG_PROMPT_TO_CREATE)
options |= FOS_CREATEPROMPT;
if (settings.properties & FILE_DIALOG_DONT_ADD_TO_RECENT)
options |= FOS_DONTADDTORECENT;
file_open_dialog->SetOptions(options);
ApplySettings(file_open_dialog, settings);
hr = ShowFileDialog(file_open_dialog, settings);
if (FAILED(hr))
return false;
ATL::CComPtr<IShellItemArray> items;
hr = file_open_dialog->GetResults(&items);
if (FAILED(hr))
return false;
ATL::CComPtr<IShellItem> item;
DWORD count = 0;
hr = items->GetCount(&count);
if (FAILED(hr))
return false;
paths->reserve(count);
for (DWORD i = 0; i < count; ++i) {
hr = items->GetItemAt(i, &item);
if (FAILED(hr))
return false;
auto path = GetFileNameFromShellItem(item, SIGDN_FILESYSPATH);
if (!path)
return false;
paths->emplace_back(std::move(*path));
}
return true;
}
void ShowOpenDialog(const DialogSettings& settings,
gin_helper::Promise<gin_helper::Dictionary> promise) {
auto done = [](gin_helper::Promise<gin_helper::Dictionary> promise,
bool success, std::vector<base::FilePath> result) {
v8::HandleScope handle_scope(promise.isolate());
auto dict = gin::Dictionary::CreateEmpty(promise.isolate());
dict.Set("canceled", !success);
dict.Set("filePaths", result);
promise.Resolve(dict);
};
dialog_thread::Run(base::BindOnce(ShowOpenDialogSync, settings),
base::BindOnce(done, std::move(promise)));
}
bool ShowSaveDialogSync(const DialogSettings& settings, base::FilePath* path) {
ATL::CComPtr<IFileSaveDialog> file_save_dialog;
HRESULT hr = file_save_dialog.CoCreateInstance(CLSID_FileSaveDialog);
if (FAILED(hr))
return false;
DWORD options = FOS_FORCEFILESYSTEM | FOS_PATHMUSTEXIST | FOS_OVERWRITEPROMPT;
if (settings.properties & SAVE_DIALOG_SHOW_HIDDEN_FILES)
options |= FOS_FORCESHOWHIDDEN;
if (settings.properties & SAVE_DIALOG_DONT_ADD_TO_RECENT)
options |= FOS_DONTADDTORECENT;
file_save_dialog->SetOptions(options);
ApplySettings(file_save_dialog, settings);
hr = ShowFileDialog(file_save_dialog, settings);
if (FAILED(hr))
return false;
CComPtr<IShellItem> pItem;
hr = file_save_dialog->GetResult(&pItem);
if (FAILED(hr))
return false;
PWSTR result_path = nullptr;
hr = pItem->GetDisplayName(SIGDN_FILESYSPATH, &result_path);
if (!SUCCEEDED(hr))
return false;
*path = base::FilePath(result_path);
CoTaskMemFree(result_path);
return true;
}
void ShowSaveDialog(const DialogSettings& settings,
gin_helper::Promise<gin_helper::Dictionary> promise) {
auto done = [](gin_helper::Promise<gin_helper::Dictionary> promise,
bool success, base::FilePath result) {
v8::HandleScope handle_scope(promise.isolate());
auto dict = gin::Dictionary::CreateEmpty(promise.isolate());
dict.Set("canceled", !success);
dict.Set("filePath", result);
promise.Resolve(dict);
};
dialog_thread::Run(base::BindOnce(ShowSaveDialogSync, settings),
base::BindOnce(done, std::move(promise)));
}
} // namespace file_dialog