win: Rewrite ShowSaveDialog with IFileSaveDialog.

This commit is contained in:
Cheng Zhao 2013-09-18 20:28:56 +08:00
parent 9e9579a858
commit 29e071a1ad

View file

@ -4,6 +4,7 @@
#include "browser/ui/file_dialog.h" #include "browser/ui/file_dialog.h"
#include <atlbase.h>
#include <windows.h> #include <windows.h>
#include <commdlg.h> #include <commdlg.h>
#include <shlobj.h> #include <shlobj.h>
@ -15,17 +16,13 @@
#include "base/utf_string_conversions.h" #include "base/utf_string_conversions.h"
#include "base/win/registry.h" #include "base/win/registry.h"
#include "browser/native_window.h" #include "browser/native_window.h"
#include "third_party/wtl/include/atlapp.h"
#include "third_party/wtl/include/atldlgs.h"
namespace file_dialog { namespace file_dialog {
namespace { namespace {
// Given |extension|, if it's not empty, then remove the leading dot.
std::wstring GetExtensionWithoutLeadingDot(const std::wstring& extension) {
DCHECK(extension.empty() || extension[0] == L'.');
return extension.empty() ? extension : extension.substr(1);
}
// Distinguish directories from regular files. // Distinguish directories from regular files.
bool IsDirectory(const base::FilePath& path) { bool IsDirectory(const base::FilePath& path) {
base::PlatformFileInfo file_info; base::PlatformFileInfo file_info;
@ -66,26 +63,21 @@ static bool GetRegistryDescriptionFromExtension(const std::wstring& file_ext,
// If a description is not provided for a file extension, it will be retrieved // If a description is not provided for a file extension, it will be retrieved
// from the registry. If the file extension does not exist in the registry, it // from the registry. If the file extension does not exist in the registry, it
// will be omitted from the filter, as it is likely a bogus extension. // will be omitted from the filter, as it is likely a bogus extension.
std::wstring FormatFilterForExtensions( void FormatFilterForExtensions(
const std::vector<std::wstring>& file_ext, const std::vector<std::wstring>& file_ext,
const std::vector<std::wstring>& ext_desc, bool include_all_files,
bool include_all_files) { std::vector<std::wstring>* ext_desc,
const std::wstring all_ext = L"*.*"; std::vector<COMDLG_FILTERSPEC>* file_types) {
// TODO(zcbenz): Should be localized. DCHECK(file_ext.size() >= ext_desc->size());
const std::wstring all_desc = L"All Files";
DCHECK(file_ext.size() >= ext_desc.size());
if (file_ext.empty()) if (file_ext.empty())
include_all_files = true; include_all_files = true;
std::wstring result;
for (size_t i = 0; i < file_ext.size(); ++i) { for (size_t i = 0; i < file_ext.size(); ++i) {
std::wstring ext = file_ext[i]; std::wstring ext = file_ext[i];
std::wstring desc; std::wstring desc;
if (i < ext_desc.size()) if (i < ext_desc->size())
desc = ext_desc[i]; desc = (*ext_desc)[i];
if (ext.empty()) { if (ext.empty()) {
// Force something reasonable to appear in the dialog box if there is no // Force something reasonable to appear in the dialog box if there is no
@ -113,66 +105,23 @@ std::wstring FormatFilterForExtensions(
// the we create a description "QQQ File (.qqq)"). // the we create a description "QQQ File (.qqq)").
include_all_files = true; include_all_files = true;
// TODO(zcbenz): should be localized. // TODO(zcbenz): should be localized.
desc = base::i18n::ToUpper(WideToUTF16(ext_name)) + L" File (." desc = base::i18n::ToUpper(WideToUTF16(ext_name)) + L" File";
+ ext_name
+ L")";
} }
if (desc.empty()) desc += L" (*." + ext_name + L")";
desc = L"*." + ext_name;
// Store the description.
ext_desc->push_back(desc);
} }
result.append(desc.c_str(), desc.size() + 1); // Append NULL too. COMDLG_FILTERSPEC spec = { (*ext_desc)[i].c_str(), file_ext[i].c_str() };
result.append(ext.c_str(), ext.size() + 1); file_types->push_back(spec);
} }
if (include_all_files) { if (include_all_files) {
result.append(all_desc.c_str(), all_desc.size() + 1); // TODO(zcbenz): Should be localized.
result.append(all_ext.c_str(), all_ext.size() + 1); COMDLG_FILTERSPEC spec = { L"All Files (*.*)", L"*.*" };
file_types->push_back(spec);
} }
result.append(1, '\0'); // Double NULL required.
return result;
}
// This function takes the output of a SaveAs dialog: a filename, a filter and
// the extension originally suggested to the user (shown in the dialog box) and
// returns back the filename with the appropriate extension tacked on. If the
// user requests an unknown extension and is not using the 'All files' filter,
// the suggested extension will be appended, otherwise we will leave the
// filename unmodified. |filename| should contain the filename selected in the
// SaveAs dialog box and may include the path, |filter_selected| should be
// '*.something', for example '*.*' or it can be blank (which is treated as
// *.*). |suggested_ext| should contain the extension without the dot (.) in
// front, for example 'jpg'.
std::wstring AppendExtensionIfNeeded(
const std::wstring& filename,
const std::wstring& filter_selected,
const std::wstring& suggested_ext) {
DCHECK(!filename.empty());
std::wstring return_value = filename;
// If we wanted a specific extension, but the user's filename deleted it or
// changed it to something that the system doesn't understand, re-append.
// Careful: Checking net::GetMimeTypeFromExtension() will only find
// extensions with a known MIME type, which many "known" extensions on Windows
// don't have. So we check directly for the "known extension" registry key.
std::wstring file_extension(
GetExtensionWithoutLeadingDot(base::FilePath(filename).Extension()));
std::wstring key(L"." + file_extension);
if (!(filter_selected.empty() || filter_selected == L"*.*") &&
!base::win::RegKey(HKEY_CLASSES_ROOT, key.c_str(), KEY_READ).Valid() &&
file_extension != suggested_ext) {
if (return_value[return_value.length() - 1] != L'.')
return_value.append(L".");
return_value.append(suggested_ext);
}
// Strip any trailing dots, which Windows doesn't allow.
size_t index = return_value.find_last_not_of(L'.');
if (index < return_value.size() - 1)
return_value.resize(index + 1);
return return_value;
} }
} // namespace } // namespace
@ -188,11 +137,18 @@ bool ShowSaveDialog(atom::NativeWindow* window,
const std::string& title, const std::string& title,
const base::FilePath& default_path, const base::FilePath& default_path,
base::FilePath* path) { base::FilePath* path) {
std::wstring file_ext = default_path.Extension().insert(0, L"*"); HRESULT hr;
std::wstring filter = FormatFilterForExtensions(
std::vector<std::wstring>(1, file_ext), std::vector<std::wstring> file_ext;
std::vector<std::wstring>(), std::vector<std::wstring> desc_ext;
true); std::vector<COMDLG_FILTERSPEC> filters;
// TODO(zcbenz): Accept custom filters from caller.
std::wstring extension = default_path.Extension();
if (!extension.empty())
file_ext.push_back(extension.insert(0, L"*"));
desc_ext.reserve(file_ext.size() + 1);
FormatFilterForExtensions(file_ext, true, &desc_ext, &filters);
std::wstring file_part = default_path.BaseName().value(); std::wstring file_part = default_path.BaseName().value();
// If the default_path is a root directory, file_part will be '\', and the // If the default_path is a root directory, file_part will be '\', and the
@ -210,23 +166,16 @@ bool ShowSaveDialog(atom::NativeWindow* window,
wchar_t file_name[MAX_PATH]; wchar_t file_name[MAX_PATH];
base::wcslcpy(file_name, file_part.c_str(), arraysize(file_name)); base::wcslcpy(file_name, file_part.c_str(), arraysize(file_name));
OPENFILENAME save_as; CShellFileSaveDialog save_dialog(
// We must do this otherwise the ofn's FlagsEx may be initialized to random file_name,
// junk in release builds which can cause the Places Bar not to show up! FOS_FORCEFILESYSTEM | FOS_PATHMUSTEXIST | FOS_OVERWRITEPROMPT,
ZeroMemory(&save_as, sizeof(save_as)); NULL,
save_as.lStructSize = sizeof(OPENFILENAME); filters.data(),
save_as.hwndOwner = window->GetNativeWindow(); filters.size());
save_as.hInstance = NULL;
save_as.lpstrFilter = filter.empty() ? NULL : filter.c_str(); // Set dialog's title if specified.
if (!title.empty())
save_as.lpstrCustomFilter = NULL; save_dialog.GetPtr()->SetTitle(UTF8ToUTF16(title).c_str());
save_as.nMaxCustFilter = 0;
save_as.nFilterIndex = 1;
save_as.lpstrFile = file_name;
save_as.nMaxFile = arraysize(file_name);
save_as.lpstrFileTitle = NULL;
save_as.nMaxFileTitle = 0;
// Set up the initial directory for the dialog. // Set up the initial directory for the dialog.
std::wstring directory; std::wstring directory;
@ -237,49 +186,22 @@ bool ShowSaveDialog(atom::NativeWindow* window,
directory = default_path.DirName().value(); directory = default_path.DirName().value();
} }
save_as.lpstrInitialDir = directory.c_str(); ATL::CComPtr<IShellItem> folder_item;
save_as.lpstrTitle = NULL; hr = SHCreateItemFromParsingName(directory.c_str(),
save_as.Flags = OFN_OVERWRITEPROMPT | OFN_EXPLORER | OFN_ENABLESIZING | NULL,
OFN_NOCHANGEDIR | OFN_PATHMUSTEXIST; IID_PPV_ARGS(&folder_item));
save_as.lpstrDefExt = NULL; // default extension, ignored for now. if (SUCCEEDED(hr))
save_as.lCustData = NULL; save_dialog.GetPtr()->SetDefaultFolder(folder_item);
// Must be NULL or 0. // Show the save as dialog.
save_as.pvReserved = NULL; if (save_dialog.DoModal(window->GetNativeWindow()) == IDCANCEL)
save_as.dwReserved = 0;
if (!GetSaveFileName(&save_as)) {
// Zero means the dialog was closed, otherwise we had an error.
DWORD error_code = CommDlgExtendedError();
if (error_code != 0) {
NOTREACHED() << "GetSaveFileName failed with code: " << error_code;
}
return false; return false;
}
// Return the user's choice. hr = save_dialog.GetFilePath(file_name, MAX_PATH);
*path = base::FilePath(); if (FAILED(hr))
return false;
// Figure out what filter got selected from the vector with embedded nulls. *path = base::FilePath(file_name);
// NOTE: The filter contains a string with embedded nulls, such as:
// JPG Image\0*.jpg\0All files\0*.*\0\0
// The filter index is 1-based index for which pair got selected. So, using
// the example above, if the first index was selected we need to skip 1
// instance of null to get to "*.jpg".
std::vector<std::wstring> filters;
if (!filter.empty() && save_as.nFilterIndex > 0)
base::SplitString(filter, '\0', &filters);
std::wstring filter_selected;
if (!filters.empty())
filter_selected = filters[(2 * (save_as.nFilterIndex - 1)) + 1];
// Get the extension that was suggested to the user (when the Save As dialog
// was opened).
std::wstring suggested_ext =
GetExtensionWithoutLeadingDot(default_path.Extension());
*path = base::FilePath(AppendExtensionIfNeeded(
save_as.lpstrFile, filter_selected, suggested_ext));
return true; return true;
} }