1 // Copyright (c) 2012 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.
5 #include "ui/shell_dialogs/select_file_dialog_win.h"
12 #include "base/bind.h"
13 #include "base/files/file_path.h"
14 #include "base/files/file_util.h"
15 #include "base/i18n/case_conversion.h"
16 #include "base/message_loop/message_loop.h"
17 #include "base/message_loop/message_loop_proxy.h"
18 #include "base/threading/thread.h"
19 #include "base/tuple.h"
20 #include "base/win/registry.h"
21 #include "base/win/scoped_comptr.h"
22 #include "base/win/shortcut.h"
23 #include "ui/aura/window.h"
24 #include "ui/aura/window_event_dispatcher.h"
25 #include "ui/aura/window_tree_host.h"
26 #include "ui/base/l10n/l10n_util.h"
27 #include "ui/base/win/open_file_name_win.h"
28 #include "ui/gfx/native_widget_types.h"
29 #include "ui/shell_dialogs/base_shell_dialog_win.h"
30 #include "ui/shell_dialogs/shell_dialogs_delegate.h"
31 #include "ui/strings/grit/ui_strings.h"
32 #include "win8/viewer/metro_viewer_process_host.h"
36 bool CallBuiltinGetOpenFileName(OPENFILENAME
* ofn
) {
37 return ::GetOpenFileName(ofn
) == TRUE
;
40 bool CallBuiltinGetSaveFileName(OPENFILENAME
* ofn
) {
41 return ::GetSaveFileName(ofn
) == TRUE
;
44 // Given |extension|, if it's not empty, then remove the leading dot.
45 std::wstring
GetExtensionWithoutLeadingDot(const std::wstring
& extension
) {
46 DCHECK(extension
.empty() || extension
[0] == L
'.');
47 return extension
.empty() ? extension
: extension
.substr(1);
50 // Distinguish directories from regular files.
51 bool IsDirectory(const base::FilePath
& path
) {
52 base::File::Info file_info
;
53 return base::GetFileInfo(path
, &file_info
) ?
54 file_info
.is_directory
: path
.EndsWithSeparator();
57 // Get the file type description from the registry. This will be "Text Document"
58 // for .txt files, "JPEG Image" for .jpg files, etc. If the registry doesn't
59 // have an entry for the file type, we return false, true if the description was
60 // found. 'file_ext' must be in form ".txt".
61 static bool GetRegistryDescriptionFromExtension(const std::wstring
& file_ext
,
62 std::wstring
* reg_description
) {
63 DCHECK(reg_description
);
64 base::win::RegKey
reg_ext(HKEY_CLASSES_ROOT
, file_ext
.c_str(), KEY_READ
);
66 if (reg_ext
.ReadValue(NULL
, ®_app
) == ERROR_SUCCESS
&& !reg_app
.empty()) {
67 base::win::RegKey
reg_link(HKEY_CLASSES_ROOT
, reg_app
.c_str(), KEY_READ
);
68 if (reg_link
.ReadValue(NULL
, reg_description
) == ERROR_SUCCESS
)
74 // Set up a filter for a Save/Open dialog, which will consist of |file_ext| file
75 // extensions (internally separated by semicolons), |ext_desc| as the text
76 // descriptions of the |file_ext| types (optional), and (optionally) the default
77 // 'All Files' view. The purpose of the filter is to show only files of a
78 // particular type in a Windows Save/Open dialog box. The resulting filter is
79 // returned. The filters created here are:
80 // 1. only files that have 'file_ext' as their extension
81 // 2. all files (only added if 'include_all_files' is true)
83 // file_ext: { "*.txt", "*.htm;*.html" }
84 // ext_desc: { "Text Document" }
85 // returned: "Text Document\0*.txt\0HTML Document\0*.htm;*.html\0"
86 // "All Files\0*.*\0\0" (in one big string)
87 // If a description is not provided for a file extension, it will be retrieved
88 // from the registry. If the file extension does not exist in the registry, it
89 // will be omitted from the filter, as it is likely a bogus extension.
90 std::wstring
FormatFilterForExtensions(
91 const std::vector
<std::wstring
>& file_ext
,
92 const std::vector
<std::wstring
>& ext_desc
,
93 bool include_all_files
) {
94 const std::wstring all_ext
= L
"*.*";
95 const std::wstring all_desc
=
96 l10n_util::GetStringUTF16(IDS_APP_SAVEAS_ALL_FILES
);
98 DCHECK(file_ext
.size() >= ext_desc
.size());
100 if (file_ext
.empty())
101 include_all_files
= true;
105 for (size_t i
= 0; i
< file_ext
.size(); ++i
) {
106 std::wstring ext
= file_ext
[i
];
108 if (i
< ext_desc
.size())
112 // Force something reasonable to appear in the dialog box if there is no
113 // extension provided.
114 include_all_files
= true;
119 DCHECK(ext
.find(L
'.') != std::wstring::npos
);
120 std::wstring first_extension
= ext
.substr(ext
.find(L
'.'));
121 size_t first_separator_index
= first_extension
.find(L
';');
122 if (first_separator_index
!= std::wstring::npos
)
123 first_extension
= first_extension
.substr(0, first_separator_index
);
125 // Find the extension name without the preceeding '.' character.
126 std::wstring ext_name
= first_extension
;
127 size_t ext_index
= ext_name
.find_first_not_of(L
'.');
128 if (ext_index
!= std::wstring::npos
)
129 ext_name
= ext_name
.substr(ext_index
);
131 if (!GetRegistryDescriptionFromExtension(first_extension
, &desc
)) {
132 // The extension doesn't exist in the registry. Create a description
133 // based on the unknown extension type (i.e. if the extension is .qqq,
134 // the we create a description "QQQ File (.qqq)").
135 include_all_files
= true;
136 desc
= l10n_util::GetStringFUTF16(IDS_APP_SAVEAS_EXTENSION_FORMAT
,
137 base::i18n::ToUpper(ext_name
),
141 desc
= L
"*." + ext_name
;
144 result
.append(desc
.c_str(), desc
.size() + 1); // Append NULL too.
145 result
.append(ext
.c_str(), ext
.size() + 1);
148 if (include_all_files
) {
149 result
.append(all_desc
.c_str(), all_desc
.size() + 1);
150 result
.append(all_ext
.c_str(), all_ext
.size() + 1);
153 result
.append(1, '\0'); // Double NULL required.
157 // Implementation of SelectFileDialog that shows a Windows common dialog for
158 // choosing a file or folder.
159 class SelectFileDialogImpl
: public ui::SelectFileDialog
,
160 public ui::BaseShellDialogImpl
{
162 SelectFileDialogImpl(
164 ui::SelectFilePolicy
* policy
,
165 const base::Callback
<bool(OPENFILENAME
*)>& get_open_file_name_impl
,
166 const base::Callback
<bool(OPENFILENAME
*)>& get_save_file_name_impl
);
168 // BaseShellDialog implementation:
169 bool IsRunning(gfx::NativeWindow owning_window
) const override
;
170 void ListenerDestroyed() override
;
173 // SelectFileDialog implementation:
176 const base::string16
& title
,
177 const base::FilePath
& default_path
,
178 const FileTypeInfo
* file_types
,
180 const base::FilePath::StringType
& default_extension
,
181 gfx::NativeWindow owning_window
,
182 void* params
) override
;
185 ~SelectFileDialogImpl() override
;
187 // A struct for holding all the state necessary for displaying a Save dialog.
188 struct ExecuteSelectParams
{
189 ExecuteSelectParams(Type type
,
190 const std::wstring
& title
,
191 const base::FilePath
& default_path
,
192 const FileTypeInfo
* file_types
,
194 const std::wstring
& default_extension
,
200 default_path(default_path
),
201 file_type_index(file_type_index
),
202 default_extension(default_extension
),
203 run_state(run_state
),
204 ui_proxy(base::MessageLoopForUI::current()->message_loop_proxy()),
208 this->file_types
= *file_types
;
210 SelectFileDialog::Type type
;
212 base::FilePath default_path
;
213 FileTypeInfo file_types
;
215 std::wstring default_extension
;
217 scoped_refptr
<base::MessageLoopProxy
> ui_proxy
;
222 // Shows the file selection dialog modal to |owner| and calls the result
223 // back on the ui thread. Run on the dialog thread.
224 void ExecuteSelectFile(const ExecuteSelectParams
& params
);
226 // Prompt the user for location to save a file.
227 // Callers should provide the filter string, and also a filter index.
228 // The parameter |index| indicates the initial index of filter description
229 // and filter pattern for the dialog box. If |index| is zero or greater than
230 // the number of total filter types, the system uses the first filter in the
231 // |filter| buffer. |index| is used to specify the initial selected extension,
232 // and when done contains the extension the user chose. The parameter
233 // |final_name| returns the file name which contains the drive designator,
234 // path, file name, and extension of the user selected file name. |def_ext| is
235 // the default extension to give to the file if the user did not enter an
236 // extension. If |ignore_suggested_ext| is true, any file extension contained
237 // in |suggested_name| will not be used to generate the file name. This is
238 // useful in the case of saving web pages, where we know the extension type
239 // already and where |suggested_name| may contain a '.' character as a valid
240 // part of the name, thus confusing our extension detection code.
241 bool SaveFileAsWithFilter(HWND owner
,
242 const std::wstring
& suggested_name
,
243 const std::wstring
& filter
,
244 const std::wstring
& def_ext
,
245 bool ignore_suggested_ext
,
247 std::wstring
* final_name
);
249 // Notifies the listener that a folder was chosen. Run on the ui thread.
250 void FileSelected(const base::FilePath
& path
, int index
,
251 void* params
, RunState run_state
);
253 // Notifies listener that multiple files were chosen. Run on the ui thread.
254 void MultiFilesSelected(const std::vector
<base::FilePath
>& paths
,
258 // Notifies the listener that no file was chosen (the action was canceled).
259 // Run on the ui thread.
260 void FileNotSelected(void* params
, RunState run_state
);
262 // Runs a Folder selection dialog box, passes back the selected folder in
263 // |path| and returns true if the user clicks OK. If the user cancels the
264 // dialog box the value in |path| is not modified and returns false. |title|
265 // is the user-supplied title text to show for the dialog box. Run on the
267 bool RunSelectFolderDialog(const std::wstring
& title
,
269 base::FilePath
* path
);
271 // Runs an Open file dialog box, with similar semantics for input paramaters
272 // as RunSelectFolderDialog.
273 bool RunOpenFileDialog(const std::wstring
& title
,
274 const std::wstring
& filters
,
276 base::FilePath
* path
);
278 // Runs an Open file dialog box that supports multi-select, with similar
279 // semantics for input paramaters as RunOpenFileDialog.
280 bool RunOpenMultiFileDialog(const std::wstring
& title
,
281 const std::wstring
& filter
,
283 std::vector
<base::FilePath
>* paths
);
285 // The callback function for when the select folder dialog is opened.
286 static int CALLBACK
BrowseCallbackProc(HWND window
, UINT message
,
290 bool HasMultipleFileTypeChoicesImpl() override
;
292 // Returns the filter to be used while displaying the open/save file dialog.
293 // This is computed from the extensions for the file types being opened.
294 // |file_types| can be NULL in which case the returned filter will be empty.
295 base::string16
GetFilterForFileTypes(const FileTypeInfo
* file_types
);
297 bool has_multiple_file_type_choices_
;
298 base::Callback
<bool(OPENFILENAME
*)> get_open_file_name_impl_
;
299 base::Callback
<bool(OPENFILENAME
*)> get_save_file_name_impl_
;
301 DISALLOW_COPY_AND_ASSIGN(SelectFileDialogImpl
);
304 SelectFileDialogImpl::SelectFileDialogImpl(
306 ui::SelectFilePolicy
* policy
,
307 const base::Callback
<bool(OPENFILENAME
*)>& get_open_file_name_impl
,
308 const base::Callback
<bool(OPENFILENAME
*)>& get_save_file_name_impl
)
309 : SelectFileDialog(listener
, policy
),
310 BaseShellDialogImpl(),
311 has_multiple_file_type_choices_(false),
312 get_open_file_name_impl_(get_open_file_name_impl
),
313 get_save_file_name_impl_(get_save_file_name_impl
) {
316 SelectFileDialogImpl::~SelectFileDialogImpl() {
319 void SelectFileDialogImpl::SelectFileImpl(
321 const base::string16
& title
,
322 const base::FilePath
& default_path
,
323 const FileTypeInfo
* file_types
,
325 const base::FilePath::StringType
& default_extension
,
326 gfx::NativeWindow owning_window
,
328 has_multiple_file_type_choices_
=
329 file_types
? file_types
->extensions
.size() > 1 : true;
330 // If the owning_window passed in is in metro then we need to forward the
331 // file open/save operations to metro.
332 if (GetShellDialogsDelegate() &&
333 GetShellDialogsDelegate()->IsWindowInMetro(owning_window
)) {
334 if (type
== SELECT_SAVEAS_FILE
) {
335 win8::MetroViewerProcessHost::HandleSaveFile(
338 GetFilterForFileTypes(file_types
),
341 base::Bind(&ui::SelectFileDialog::Listener::FileSelected
,
342 base::Unretained(listener_
)),
343 base::Bind(&ui::SelectFileDialog::Listener::FileSelectionCanceled
,
344 base::Unretained(listener_
)));
346 } else if (type
== SELECT_OPEN_FILE
) {
347 win8::MetroViewerProcessHost::HandleOpenFile(
350 GetFilterForFileTypes(file_types
),
351 base::Bind(&ui::SelectFileDialog::Listener::FileSelected
,
352 base::Unretained(listener_
)),
353 base::Bind(&ui::SelectFileDialog::Listener::FileSelectionCanceled
,
354 base::Unretained(listener_
)));
356 } else if (type
== SELECT_OPEN_MULTI_FILE
) {
357 win8::MetroViewerProcessHost::HandleOpenMultipleFiles(
360 GetFilterForFileTypes(file_types
),
361 base::Bind(&ui::SelectFileDialog::Listener::MultiFilesSelected
,
362 base::Unretained(listener_
)),
363 base::Bind(&ui::SelectFileDialog::Listener::FileSelectionCanceled
,
364 base::Unretained(listener_
)));
366 } else if (type
== SELECT_FOLDER
|| type
== SELECT_UPLOAD_FOLDER
) {
367 base::string16 title_string
= title
;
368 if (type
== SELECT_UPLOAD_FOLDER
&& title_string
.empty()) {
369 // If it's for uploading don't use default dialog title to
370 // make sure we clearly tell it's for uploading.
371 title_string
= l10n_util::GetStringUTF16(
372 IDS_SELECT_UPLOAD_FOLDER_DIALOG_TITLE
);
374 win8::MetroViewerProcessHost::HandleSelectFolder(
376 base::Bind(&ui::SelectFileDialog::Listener::FileSelected
,
377 base::Unretained(listener_
)),
378 base::Bind(&ui::SelectFileDialog::Listener::FileSelectionCanceled
,
379 base::Unretained(listener_
)));
383 HWND owner
= owning_window
&& owning_window
->GetRootWindow()
384 ? owning_window
->GetHost()->GetAcceleratedWidget() : NULL
;
386 ExecuteSelectParams
execute_params(type
, title
,
387 default_path
, file_types
, file_type_index
,
388 default_extension
, BeginRun(owner
),
390 execute_params
.run_state
.dialog_thread
->message_loop()->PostTask(
392 base::Bind(&SelectFileDialogImpl::ExecuteSelectFile
, this,
396 bool SelectFileDialogImpl::HasMultipleFileTypeChoicesImpl() {
397 return has_multiple_file_type_choices_
;
400 bool SelectFileDialogImpl::IsRunning(gfx::NativeWindow owning_window
) const {
401 if (!owning_window
->GetRootWindow())
403 HWND owner
= owning_window
->GetHost()->GetAcceleratedWidget();
404 return listener_
&& IsRunningDialogForOwner(owner
);
407 void SelectFileDialogImpl::ListenerDestroyed() {
408 // Our associated listener has gone away, so we shouldn't call back to it if
409 // our worker thread returns after the listener is dead.
413 void SelectFileDialogImpl::ExecuteSelectFile(
414 const ExecuteSelectParams
& params
) {
415 base::string16 filter
= GetFilterForFileTypes(¶ms
.file_types
);
417 base::FilePath path
= params
.default_path
;
418 bool success
= false;
419 unsigned filter_index
= params
.file_type_index
;
420 if (params
.type
== SELECT_FOLDER
|| params
.type
== SELECT_UPLOAD_FOLDER
) {
421 std::wstring title
= params
.title
;
422 if (title
.empty() && params
.type
== SELECT_UPLOAD_FOLDER
) {
423 // If it's for uploading don't use default dialog title to
424 // make sure we clearly tell it's for uploading.
425 title
= l10n_util::GetStringUTF16(IDS_SELECT_UPLOAD_FOLDER_DIALOG_TITLE
);
427 success
= RunSelectFolderDialog(title
,
428 params
.run_state
.owner
,
430 } else if (params
.type
== SELECT_SAVEAS_FILE
) {
431 std::wstring path_as_wstring
= path
.value();
432 success
= SaveFileAsWithFilter(params
.run_state
.owner
,
433 params
.default_path
.value(), filter
,
434 params
.default_extension
, false, &filter_index
, &path_as_wstring
);
436 path
= base::FilePath(path_as_wstring
);
437 DisableOwner(params
.run_state
.owner
);
438 } else if (params
.type
== SELECT_OPEN_FILE
) {
439 success
= RunOpenFileDialog(params
.title
, filter
,
440 params
.run_state
.owner
, &path
);
441 } else if (params
.type
== SELECT_OPEN_MULTI_FILE
) {
442 std::vector
<base::FilePath
> paths
;
443 if (RunOpenMultiFileDialog(params
.title
, filter
,
444 params
.run_state
.owner
, &paths
)) {
445 params
.ui_proxy
->PostTask(
447 base::Bind(&SelectFileDialogImpl::MultiFilesSelected
, this, paths
,
448 params
.params
, params
.run_state
));
454 params
.ui_proxy
->PostTask(
456 base::Bind(&SelectFileDialogImpl::FileSelected
, this, path
,
457 filter_index
, params
.params
, params
.run_state
));
459 params
.ui_proxy
->PostTask(
461 base::Bind(&SelectFileDialogImpl::FileNotSelected
, this, params
.params
,
466 bool SelectFileDialogImpl::SaveFileAsWithFilter(
468 const std::wstring
& suggested_name
,
469 const std::wstring
& filter
,
470 const std::wstring
& def_ext
,
471 bool ignore_suggested_ext
,
473 std::wstring
* final_name
) {
475 // Having an empty filter makes for a bad user experience. We should always
476 // specify a filter when saving.
477 DCHECK(!filter
.empty());
479 ui::win::OpenFileName
save_as(owner
,
480 OFN_OVERWRITEPROMPT
| OFN_EXPLORER
|
481 OFN_ENABLESIZING
| OFN_NOCHANGEDIR
|
484 const base::FilePath suggested_path
= base::FilePath(suggested_name
);
485 if (!suggested_name
.empty()) {
486 base::FilePath suggested_file_name
;
487 base::FilePath suggested_directory
;
488 if (IsDirectory(suggested_path
)) {
489 suggested_directory
= suggested_path
;
491 suggested_directory
= suggested_path
.DirName();
492 suggested_file_name
= suggested_path
.BaseName();
493 // If the suggested_name is a root directory, file_part will be '\', and
494 // the call to GetSaveFileName below will fail.
495 if (suggested_file_name
.value() == L
"\\")
496 suggested_file_name
.clear();
498 save_as
.SetInitialSelection(suggested_directory
, suggested_file_name
);
501 save_as
.GetOPENFILENAME()->lpstrFilter
=
502 filter
.empty() ? NULL
: filter
.c_str();
503 save_as
.GetOPENFILENAME()->nFilterIndex
= *index
;
504 save_as
.GetOPENFILENAME()->lpstrDefExt
= &def_ext
[0];
505 save_as
.MaybeInstallWindowPositionHookForSaveAsOnXP();
507 if (!get_save_file_name_impl_
.Run(save_as
.GetOPENFILENAME()))
510 // Return the user's choice.
511 final_name
->assign(save_as
.GetOPENFILENAME()->lpstrFile
);
512 *index
= save_as
.GetOPENFILENAME()->nFilterIndex
;
514 // Figure out what filter got selected. The filter index is 1-based.
515 std::wstring filter_selected
;
517 std::vector
<base::Tuple
<base::string16
, base::string16
>> filters
=
518 ui::win::OpenFileName::GetFilters(save_as
.GetOPENFILENAME());
519 if (*index
> filters
.size())
520 NOTREACHED() << "Invalid filter index.";
522 filter_selected
= base::get
<1>(filters
[*index
- 1]);
525 // Get the extension that was suggested to the user (when the Save As dialog
526 // was opened). For saving web pages, we skip this step since there may be
527 // 'extension characters' in the title of the web page.
528 std::wstring suggested_ext
;
529 if (!ignore_suggested_ext
)
530 suggested_ext
= GetExtensionWithoutLeadingDot(suggested_path
.Extension());
532 // If we can't get the extension from the suggested_name, we use the default
533 // extension passed in. This is to cover cases like when saving a web page,
534 // where we get passed in a name without an extension and a default extension
536 if (suggested_ext
.empty())
537 suggested_ext
= def_ext
;
540 ui::AppendExtensionIfNeeded(*final_name
, filter_selected
, suggested_ext
);
544 void SelectFileDialogImpl::FileSelected(const base::FilePath
& selected_folder
,
547 RunState run_state
) {
549 listener_
->FileSelected(selected_folder
, index
, params
);
553 void SelectFileDialogImpl::MultiFilesSelected(
554 const std::vector
<base::FilePath
>& selected_files
,
556 RunState run_state
) {
558 listener_
->MultiFilesSelected(selected_files
, params
);
562 void SelectFileDialogImpl::FileNotSelected(void* params
, RunState run_state
) {
564 listener_
->FileSelectionCanceled(params
);
568 int CALLBACK
SelectFileDialogImpl::BrowseCallbackProc(HWND window
,
572 if (message
== BFFM_INITIALIZED
) {
573 // WParam is TRUE since passing a path.
574 // data lParam member of the BROWSEINFO structure.
575 SendMessage(window
, BFFM_SETSELECTION
, TRUE
, (LPARAM
)data
);
580 bool SelectFileDialogImpl::RunSelectFolderDialog(const std::wstring
& title
,
582 base::FilePath
* path
) {
585 wchar_t dir_buffer
[MAX_PATH
+ 1];
588 BROWSEINFO browse_info
= {0};
589 browse_info
.hwndOwner
= owner
;
590 browse_info
.lpszTitle
= title
.c_str();
591 browse_info
.pszDisplayName
= dir_buffer
;
592 browse_info
.ulFlags
= BIF_USENEWUI
| BIF_RETURNONLYFSDIRS
;
594 if (path
->value().length()) {
595 // Highlight the current value.
596 browse_info
.lParam
= (LPARAM
)path
->value().c_str();
597 browse_info
.lpfn
= &BrowseCallbackProc
;
600 LPITEMIDLIST list
= SHBrowseForFolder(&browse_info
);
603 STRRET out_dir_buffer
;
604 ZeroMemory(&out_dir_buffer
, sizeof(out_dir_buffer
));
605 out_dir_buffer
.uType
= STRRET_WSTR
;
606 base::win::ScopedComPtr
<IShellFolder
> shell_folder
;
607 if (SHGetDesktopFolder(shell_folder
.Receive()) == NOERROR
) {
608 HRESULT hr
= shell_folder
->GetDisplayNameOf(list
, SHGDN_FORPARSING
,
610 if (SUCCEEDED(hr
) && out_dir_buffer
.uType
== STRRET_WSTR
) {
611 *path
= base::FilePath(out_dir_buffer
.pOleStr
);
612 CoTaskMemFree(out_dir_buffer
.pOleStr
);
615 // Use old way if we don't get what we want.
616 wchar_t old_out_dir_buffer
[MAX_PATH
+ 1];
617 if (SHGetPathFromIDList(list
, old_out_dir_buffer
)) {
618 *path
= base::FilePath(old_out_dir_buffer
);
623 // According to MSDN, win2000 will not resolve shortcuts, so we do it
625 base::win::ResolveShortcut(*path
, path
, NULL
);
632 bool SelectFileDialogImpl::RunOpenFileDialog(
633 const std::wstring
& title
,
634 const std::wstring
& filter
,
636 base::FilePath
* path
) {
637 // We use OFN_NOCHANGEDIR so that the user can rename or delete the directory
638 // without having to close Chrome first.
639 ui::win::OpenFileName
ofn(owner
, OFN_FILEMUSTEXIST
| OFN_NOCHANGEDIR
);
640 if (!path
->empty()) {
641 if (IsDirectory(*path
))
642 ofn
.SetInitialSelection(*path
, base::FilePath());
644 ofn
.SetInitialSelection(path
->DirName(), path
->BaseName());
648 ofn
.GetOPENFILENAME()->lpstrFilter
= filter
.c_str();
650 bool success
= get_open_file_name_impl_
.Run(ofn
.GetOPENFILENAME());
653 *path
= ofn
.GetSingleResult();
657 bool SelectFileDialogImpl::RunOpenMultiFileDialog(
658 const std::wstring
& title
,
659 const std::wstring
& filter
,
661 std::vector
<base::FilePath
>* paths
) {
662 // We use OFN_NOCHANGEDIR so that the user can rename or delete the directory
663 // without having to close Chrome first.
664 ui::win::OpenFileName
ofn(owner
,
665 OFN_PATHMUSTEXIST
| OFN_FILEMUSTEXIST
|
666 OFN_EXPLORER
| OFN_HIDEREADONLY
|
667 OFN_ALLOWMULTISELECT
| OFN_NOCHANGEDIR
);
670 ofn
.GetOPENFILENAME()->lpstrFilter
= filter
.c_str();
672 base::FilePath directory
;
673 std::vector
<base::FilePath
> filenames
;
675 if (get_open_file_name_impl_
.Run(ofn
.GetOPENFILENAME()))
676 ofn
.GetResult(&directory
, &filenames
);
680 for (std::vector
<base::FilePath
>::iterator it
= filenames
.begin();
681 it
!= filenames
.end();
683 paths
->push_back(directory
.Append(*it
));
686 return !paths
->empty();
689 base::string16
SelectFileDialogImpl::GetFilterForFileTypes(
690 const FileTypeInfo
* file_types
) {
692 return base::string16();
694 std::vector
<base::string16
> exts
;
695 for (size_t i
= 0; i
< file_types
->extensions
.size(); ++i
) {
696 const std::vector
<base::string16
>& inner_exts
= file_types
->extensions
[i
];
697 base::string16 ext_string
;
698 for (size_t j
= 0; j
< inner_exts
.size(); ++j
) {
699 if (!ext_string
.empty())
700 ext_string
.push_back(L
';');
701 ext_string
.append(L
"*.");
702 ext_string
.append(inner_exts
[j
]);
704 exts
.push_back(ext_string
);
706 return FormatFilterForExtensions(
708 file_types
->extension_description_overrides
,
709 file_types
->include_all_files
);
716 // This function takes the output of a SaveAs dialog: a filename, a filter and
717 // the extension originally suggested to the user (shown in the dialog box) and
718 // returns back the filename with the appropriate extension tacked on. If the
719 // user requests an unknown extension and is not using the 'All files' filter,
720 // the suggested extension will be appended, otherwise we will leave the
721 // filename unmodified. |filename| should contain the filename selected in the
722 // SaveAs dialog box and may include the path, |filter_selected| should be
723 // '*.something', for example '*.*' or it can be blank (which is treated as
724 // *.*). |suggested_ext| should contain the extension without the dot (.) in
725 // front, for example 'jpg'.
726 std::wstring
AppendExtensionIfNeeded(
727 const std::wstring
& filename
,
728 const std::wstring
& filter_selected
,
729 const std::wstring
& suggested_ext
) {
730 DCHECK(!filename
.empty());
731 std::wstring return_value
= filename
;
733 // If we wanted a specific extension, but the user's filename deleted it or
734 // changed it to something that the system doesn't understand, re-append.
735 // Careful: Checking net::GetMimeTypeFromExtension() will only find
736 // extensions with a known MIME type, which many "known" extensions on Windows
737 // don't have. So we check directly for the "known extension" registry key.
738 std::wstring
file_extension(
739 GetExtensionWithoutLeadingDot(base::FilePath(filename
).Extension()));
740 std::wstring
key(L
"." + file_extension
);
741 if (!(filter_selected
.empty() || filter_selected
== L
"*.*") &&
742 !base::win::RegKey(HKEY_CLASSES_ROOT
, key
.c_str(), KEY_READ
).Valid() &&
743 file_extension
!= suggested_ext
) {
744 if (return_value
[return_value
.length() - 1] != L
'.')
745 return_value
.append(L
".");
746 return_value
.append(suggested_ext
);
749 // Strip any trailing dots, which Windows doesn't allow.
750 size_t index
= return_value
.find_last_not_of(L
'.');
751 if (index
< return_value
.size() - 1)
752 return_value
.resize(index
+ 1);
757 SelectFileDialog
* CreateWinSelectFileDialog(
758 SelectFileDialog::Listener
* listener
,
759 SelectFilePolicy
* policy
,
760 const base::Callback
<bool(OPENFILENAME
* ofn
)>& get_open_file_name_impl
,
761 const base::Callback
<bool(OPENFILENAME
* ofn
)>& get_save_file_name_impl
) {
762 return new SelectFileDialogImpl(
763 listener
, policy
, get_open_file_name_impl
, get_save_file_name_impl
);
766 SelectFileDialog
* CreateDefaultWinSelectFileDialog(
767 SelectFileDialog::Listener
* listener
,
768 SelectFilePolicy
* policy
) {
769 return CreateWinSelectFileDialog(listener
,
771 base::Bind(&CallBuiltinGetOpenFileName
),
772 base::Bind(&CallBuiltinGetSaveFileName
));