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/threading/thread.h"
18 #include "base/tuple.h"
19 #include "base/win/registry.h"
20 #include "base/win/scoped_comptr.h"
21 #include "base/win/shortcut.h"
22 #include "ui/aura/window.h"
23 #include "ui/aura/window_event_dispatcher.h"
24 #include "ui/aura/window_tree_host.h"
25 #include "ui/base/l10n/l10n_util.h"
26 #include "ui/base/win/open_file_name_win.h"
27 #include "ui/gfx/native_widget_types.h"
28 #include "ui/shell_dialogs/base_shell_dialog_win.h"
29 #include "ui/shell_dialogs/shell_dialogs_delegate.h"
30 #include "ui/strings/grit/ui_strings.h"
31 #include "win8/viewer/metro_viewer_process_host.h"
35 bool CallBuiltinGetOpenFileName(OPENFILENAME
* ofn
) {
36 return ::GetOpenFileName(ofn
) == TRUE
;
39 bool CallBuiltinGetSaveFileName(OPENFILENAME
* ofn
) {
40 return ::GetSaveFileName(ofn
) == TRUE
;
43 // Given |extension|, if it's not empty, then remove the leading dot.
44 std::wstring
GetExtensionWithoutLeadingDot(const std::wstring
& extension
) {
45 DCHECK(extension
.empty() || extension
[0] == L
'.');
46 return extension
.empty() ? extension
: extension
.substr(1);
49 // Distinguish directories from regular files.
50 bool IsDirectory(const base::FilePath
& path
) {
51 base::File::Info file_info
;
52 return base::GetFileInfo(path
, &file_info
) ?
53 file_info
.is_directory
: path
.EndsWithSeparator();
56 // Get the file type description from the registry. This will be "Text Document"
57 // for .txt files, "JPEG Image" for .jpg files, etc. If the registry doesn't
58 // have an entry for the file type, we return false, true if the description was
59 // found. 'file_ext' must be in form ".txt".
60 static bool GetRegistryDescriptionFromExtension(const std::wstring
& file_ext
,
61 std::wstring
* reg_description
) {
62 DCHECK(reg_description
);
63 base::win::RegKey
reg_ext(HKEY_CLASSES_ROOT
, file_ext
.c_str(), KEY_READ
);
65 if (reg_ext
.ReadValue(NULL
, ®_app
) == ERROR_SUCCESS
&& !reg_app
.empty()) {
66 base::win::RegKey
reg_link(HKEY_CLASSES_ROOT
, reg_app
.c_str(), KEY_READ
);
67 if (reg_link
.ReadValue(NULL
, reg_description
) == ERROR_SUCCESS
)
73 // Set up a filter for a Save/Open dialog, which will consist of |file_ext| file
74 // extensions (internally separated by semicolons), |ext_desc| as the text
75 // descriptions of the |file_ext| types (optional), and (optionally) the default
76 // 'All Files' view. The purpose of the filter is to show only files of a
77 // particular type in a Windows Save/Open dialog box. The resulting filter is
78 // returned. The filters created here are:
79 // 1. only files that have 'file_ext' as their extension
80 // 2. all files (only added if 'include_all_files' is true)
82 // file_ext: { "*.txt", "*.htm;*.html" }
83 // ext_desc: { "Text Document" }
84 // returned: "Text Document\0*.txt\0HTML Document\0*.htm;*.html\0"
85 // "All Files\0*.*\0\0" (in one big string)
86 // If a description is not provided for a file extension, it will be retrieved
87 // from the registry. If the file extension does not exist in the registry, it
88 // will be omitted from the filter, as it is likely a bogus extension.
89 std::wstring
FormatFilterForExtensions(
90 const std::vector
<std::wstring
>& file_ext
,
91 const std::vector
<std::wstring
>& ext_desc
,
92 bool include_all_files
) {
93 const std::wstring all_ext
= L
"*.*";
94 const std::wstring all_desc
=
95 l10n_util::GetStringUTF16(IDS_APP_SAVEAS_ALL_FILES
);
97 DCHECK(file_ext
.size() >= ext_desc
.size());
100 include_all_files
= true;
104 for (size_t i
= 0; i
< file_ext
.size(); ++i
) {
105 std::wstring ext
= file_ext
[i
];
107 if (i
< ext_desc
.size())
111 // Force something reasonable to appear in the dialog box if there is no
112 // extension provided.
113 include_all_files
= true;
118 DCHECK(ext
.find(L
'.') != std::wstring::npos
);
119 std::wstring first_extension
= ext
.substr(ext
.find(L
'.'));
120 size_t first_separator_index
= first_extension
.find(L
';');
121 if (first_separator_index
!= std::wstring::npos
)
122 first_extension
= first_extension
.substr(0, first_separator_index
);
124 // Find the extension name without the preceeding '.' character.
125 std::wstring ext_name
= first_extension
;
126 size_t ext_index
= ext_name
.find_first_not_of(L
'.');
127 if (ext_index
!= std::wstring::npos
)
128 ext_name
= ext_name
.substr(ext_index
);
130 if (!GetRegistryDescriptionFromExtension(first_extension
, &desc
)) {
131 // The extension doesn't exist in the registry. Create a description
132 // based on the unknown extension type (i.e. if the extension is .qqq,
133 // the we create a description "QQQ File (.qqq)").
134 include_all_files
= true;
135 desc
= l10n_util::GetStringFUTF16(IDS_APP_SAVEAS_EXTENSION_FORMAT
,
136 base::i18n::ToUpper(ext_name
),
140 desc
= L
"*." + ext_name
;
143 result
.append(desc
.c_str(), desc
.size() + 1); // Append NULL too.
144 result
.append(ext
.c_str(), ext
.size() + 1);
147 if (include_all_files
) {
148 result
.append(all_desc
.c_str(), all_desc
.size() + 1);
149 result
.append(all_ext
.c_str(), all_ext
.size() + 1);
152 result
.append(1, '\0'); // Double NULL required.
156 // Implementation of SelectFileDialog that shows a Windows common dialog for
157 // choosing a file or folder.
158 class SelectFileDialogImpl
: public ui::SelectFileDialog
,
159 public ui::BaseShellDialogImpl
{
161 SelectFileDialogImpl(
163 ui::SelectFilePolicy
* policy
,
164 const base::Callback
<bool(OPENFILENAME
*)>& get_open_file_name_impl
,
165 const base::Callback
<bool(OPENFILENAME
*)>& get_save_file_name_impl
);
167 // BaseShellDialog implementation:
168 bool IsRunning(gfx::NativeWindow owning_window
) const override
;
169 void ListenerDestroyed() override
;
172 // SelectFileDialog implementation:
175 const base::string16
& title
,
176 const base::FilePath
& default_path
,
177 const FileTypeInfo
* file_types
,
179 const base::FilePath::StringType
& default_extension
,
180 gfx::NativeWindow owning_window
,
181 void* params
) override
;
184 ~SelectFileDialogImpl() override
;
186 // A struct for holding all the state necessary for displaying a Save dialog.
187 struct ExecuteSelectParams
{
188 ExecuteSelectParams(Type type
,
189 const std::wstring
& title
,
190 const base::FilePath
& default_path
,
191 const FileTypeInfo
* file_types
,
193 const std::wstring
& default_extension
,
199 default_path(default_path
),
200 file_type_index(file_type_index
),
201 default_extension(default_extension
),
202 run_state(run_state
),
203 ui_task_runner(base::MessageLoopForUI::current()->task_runner()),
207 this->file_types
= *file_types
;
209 SelectFileDialog::Type type
;
211 base::FilePath default_path
;
212 FileTypeInfo file_types
;
214 std::wstring default_extension
;
216 scoped_refptr
<base::SingleThreadTaskRunner
> ui_task_runner
;
221 // Shows the file selection dialog modal to |owner| and calls the result
222 // back on the ui thread. Run on the dialog thread.
223 void ExecuteSelectFile(const ExecuteSelectParams
& params
);
225 // Prompt the user for location to save a file.
226 // Callers should provide the filter string, and also a filter index.
227 // The parameter |index| indicates the initial index of filter description
228 // and filter pattern for the dialog box. If |index| is zero or greater than
229 // the number of total filter types, the system uses the first filter in the
230 // |filter| buffer. |index| is used to specify the initial selected extension,
231 // and when done contains the extension the user chose. The parameter
232 // |final_name| returns the file name which contains the drive designator,
233 // path, file name, and extension of the user selected file name. |def_ext| is
234 // the default extension to give to the file if the user did not enter an
235 // extension. If |ignore_suggested_ext| is true, any file extension contained
236 // in |suggested_name| will not be used to generate the file name. This is
237 // useful in the case of saving web pages, where we know the extension type
238 // already and where |suggested_name| may contain a '.' character as a valid
239 // part of the name, thus confusing our extension detection code.
240 bool SaveFileAsWithFilter(HWND owner
,
241 const std::wstring
& suggested_name
,
242 const std::wstring
& filter
,
243 const std::wstring
& def_ext
,
244 bool ignore_suggested_ext
,
246 std::wstring
* final_name
);
248 // Notifies the listener that a folder was chosen. Run on the ui thread.
249 void FileSelected(const base::FilePath
& path
, int index
,
250 void* params
, RunState run_state
);
252 // Notifies listener that multiple files were chosen. Run on the ui thread.
253 void MultiFilesSelected(const std::vector
<base::FilePath
>& paths
,
257 // Notifies the listener that no file was chosen (the action was canceled).
258 // Run on the ui thread.
259 void FileNotSelected(void* params
, RunState run_state
);
261 // Runs a Folder selection dialog box, passes back the selected folder in
262 // |path| and returns true if the user clicks OK. If the user cancels the
263 // dialog box the value in |path| is not modified and returns false. |title|
264 // is the user-supplied title text to show for the dialog box. Run on the
266 bool RunSelectFolderDialog(const std::wstring
& title
,
268 base::FilePath
* path
);
270 // Runs an Open file dialog box, with similar semantics for input paramaters
271 // as RunSelectFolderDialog.
272 bool RunOpenFileDialog(const std::wstring
& title
,
273 const std::wstring
& filters
,
275 base::FilePath
* path
);
277 // Runs an Open file dialog box that supports multi-select, with similar
278 // semantics for input paramaters as RunOpenFileDialog.
279 bool RunOpenMultiFileDialog(const std::wstring
& title
,
280 const std::wstring
& filter
,
282 std::vector
<base::FilePath
>* paths
);
284 // The callback function for when the select folder dialog is opened.
285 static int CALLBACK
BrowseCallbackProc(HWND window
, UINT message
,
289 bool HasMultipleFileTypeChoicesImpl() override
;
291 // Returns the filter to be used while displaying the open/save file dialog.
292 // This is computed from the extensions for the file types being opened.
293 // |file_types| can be NULL in which case the returned filter will be empty.
294 base::string16
GetFilterForFileTypes(const FileTypeInfo
* file_types
);
296 bool has_multiple_file_type_choices_
;
297 base::Callback
<bool(OPENFILENAME
*)> get_open_file_name_impl_
;
298 base::Callback
<bool(OPENFILENAME
*)> get_save_file_name_impl_
;
300 DISALLOW_COPY_AND_ASSIGN(SelectFileDialogImpl
);
303 SelectFileDialogImpl::SelectFileDialogImpl(
305 ui::SelectFilePolicy
* policy
,
306 const base::Callback
<bool(OPENFILENAME
*)>& get_open_file_name_impl
,
307 const base::Callback
<bool(OPENFILENAME
*)>& get_save_file_name_impl
)
308 : SelectFileDialog(listener
, policy
),
309 BaseShellDialogImpl(),
310 has_multiple_file_type_choices_(false),
311 get_open_file_name_impl_(get_open_file_name_impl
),
312 get_save_file_name_impl_(get_save_file_name_impl
) {
315 SelectFileDialogImpl::~SelectFileDialogImpl() {
318 void SelectFileDialogImpl::SelectFileImpl(
320 const base::string16
& title
,
321 const base::FilePath
& default_path
,
322 const FileTypeInfo
* file_types
,
324 const base::FilePath::StringType
& default_extension
,
325 gfx::NativeWindow owning_window
,
327 has_multiple_file_type_choices_
=
328 file_types
? file_types
->extensions
.size() > 1 : true;
329 // If the owning_window passed in is in metro then we need to forward the
330 // file open/save operations to metro.
331 if (GetShellDialogsDelegate() &&
332 GetShellDialogsDelegate()->IsWindowInMetro(owning_window
)) {
333 if (type
== SELECT_SAVEAS_FILE
) {
334 win8::MetroViewerProcessHost::HandleSaveFile(
337 GetFilterForFileTypes(file_types
),
340 base::Bind(&ui::SelectFileDialog::Listener::FileSelected
,
341 base::Unretained(listener_
)),
342 base::Bind(&ui::SelectFileDialog::Listener::FileSelectionCanceled
,
343 base::Unretained(listener_
)));
345 } else if (type
== SELECT_OPEN_FILE
) {
346 win8::MetroViewerProcessHost::HandleOpenFile(
349 GetFilterForFileTypes(file_types
),
350 base::Bind(&ui::SelectFileDialog::Listener::FileSelected
,
351 base::Unretained(listener_
)),
352 base::Bind(&ui::SelectFileDialog::Listener::FileSelectionCanceled
,
353 base::Unretained(listener_
)));
355 } else if (type
== SELECT_OPEN_MULTI_FILE
) {
356 win8::MetroViewerProcessHost::HandleOpenMultipleFiles(
359 GetFilterForFileTypes(file_types
),
360 base::Bind(&ui::SelectFileDialog::Listener::MultiFilesSelected
,
361 base::Unretained(listener_
)),
362 base::Bind(&ui::SelectFileDialog::Listener::FileSelectionCanceled
,
363 base::Unretained(listener_
)));
365 } else if (type
== SELECT_FOLDER
|| type
== SELECT_UPLOAD_FOLDER
) {
366 base::string16 title_string
= title
;
367 if (type
== SELECT_UPLOAD_FOLDER
&& title_string
.empty()) {
368 // If it's for uploading don't use default dialog title to
369 // make sure we clearly tell it's for uploading.
370 title_string
= l10n_util::GetStringUTF16(
371 IDS_SELECT_UPLOAD_FOLDER_DIALOG_TITLE
);
373 win8::MetroViewerProcessHost::HandleSelectFolder(
375 base::Bind(&ui::SelectFileDialog::Listener::FileSelected
,
376 base::Unretained(listener_
)),
377 base::Bind(&ui::SelectFileDialog::Listener::FileSelectionCanceled
,
378 base::Unretained(listener_
)));
382 HWND owner
= owning_window
&& owning_window
->GetRootWindow()
383 ? owning_window
->GetHost()->GetAcceleratedWidget() : NULL
;
385 ExecuteSelectParams
execute_params(type
, title
,
386 default_path
, file_types
, file_type_index
,
387 default_extension
, BeginRun(owner
),
389 execute_params
.run_state
.dialog_thread
->message_loop()->PostTask(
391 base::Bind(&SelectFileDialogImpl::ExecuteSelectFile
, this,
395 bool SelectFileDialogImpl::HasMultipleFileTypeChoicesImpl() {
396 return has_multiple_file_type_choices_
;
399 bool SelectFileDialogImpl::IsRunning(gfx::NativeWindow owning_window
) const {
400 if (!owning_window
->GetRootWindow())
402 HWND owner
= owning_window
->GetHost()->GetAcceleratedWidget();
403 return listener_
&& IsRunningDialogForOwner(owner
);
406 void SelectFileDialogImpl::ListenerDestroyed() {
407 // Our associated listener has gone away, so we shouldn't call back to it if
408 // our worker thread returns after the listener is dead.
412 void SelectFileDialogImpl::ExecuteSelectFile(
413 const ExecuteSelectParams
& params
) {
414 base::string16 filter
= GetFilterForFileTypes(¶ms
.file_types
);
416 base::FilePath path
= params
.default_path
;
417 bool success
= false;
418 unsigned filter_index
= params
.file_type_index
;
419 if (params
.type
== SELECT_FOLDER
|| params
.type
== SELECT_UPLOAD_FOLDER
) {
420 std::wstring title
= params
.title
;
421 if (title
.empty() && params
.type
== SELECT_UPLOAD_FOLDER
) {
422 // If it's for uploading don't use default dialog title to
423 // make sure we clearly tell it's for uploading.
424 title
= l10n_util::GetStringUTF16(IDS_SELECT_UPLOAD_FOLDER_DIALOG_TITLE
);
426 success
= RunSelectFolderDialog(title
,
427 params
.run_state
.owner
,
429 } else if (params
.type
== SELECT_SAVEAS_FILE
) {
430 std::wstring path_as_wstring
= path
.value();
431 success
= SaveFileAsWithFilter(params
.run_state
.owner
,
432 params
.default_path
.value(), filter
,
433 params
.default_extension
, false, &filter_index
, &path_as_wstring
);
435 path
= base::FilePath(path_as_wstring
);
436 DisableOwner(params
.run_state
.owner
);
437 } else if (params
.type
== SELECT_OPEN_FILE
) {
438 success
= RunOpenFileDialog(params
.title
, filter
,
439 params
.run_state
.owner
, &path
);
440 } else if (params
.type
== SELECT_OPEN_MULTI_FILE
) {
441 std::vector
<base::FilePath
> paths
;
442 if (RunOpenMultiFileDialog(params
.title
, filter
,
443 params
.run_state
.owner
, &paths
)) {
444 params
.ui_task_runner
->PostTask(
445 FROM_HERE
, base::Bind(&SelectFileDialogImpl::MultiFilesSelected
, this,
446 paths
, params
.params
, params
.run_state
));
452 params
.ui_task_runner
->PostTask(
453 FROM_HERE
, base::Bind(&SelectFileDialogImpl::FileSelected
, this, path
,
454 filter_index
, params
.params
, params
.run_state
));
456 params
.ui_task_runner
->PostTask(
457 FROM_HERE
, base::Bind(&SelectFileDialogImpl::FileNotSelected
, this,
458 params
.params
, params
.run_state
));
462 bool SelectFileDialogImpl::SaveFileAsWithFilter(
464 const std::wstring
& suggested_name
,
465 const std::wstring
& filter
,
466 const std::wstring
& def_ext
,
467 bool ignore_suggested_ext
,
469 std::wstring
* final_name
) {
471 // Having an empty filter makes for a bad user experience. We should always
472 // specify a filter when saving.
473 DCHECK(!filter
.empty());
475 ui::win::OpenFileName
save_as(owner
,
476 OFN_OVERWRITEPROMPT
| OFN_EXPLORER
|
477 OFN_ENABLESIZING
| OFN_NOCHANGEDIR
|
480 const base::FilePath suggested_path
= base::FilePath(suggested_name
);
481 if (!suggested_name
.empty()) {
482 base::FilePath suggested_file_name
;
483 base::FilePath suggested_directory
;
484 if (IsDirectory(suggested_path
)) {
485 suggested_directory
= suggested_path
;
487 suggested_directory
= suggested_path
.DirName();
488 suggested_file_name
= suggested_path
.BaseName();
489 // If the suggested_name is a root directory, file_part will be '\', and
490 // the call to GetSaveFileName below will fail.
491 if (suggested_file_name
.value() == L
"\\")
492 suggested_file_name
.clear();
494 save_as
.SetInitialSelection(suggested_directory
, suggested_file_name
);
497 save_as
.GetOPENFILENAME()->lpstrFilter
=
498 filter
.empty() ? NULL
: filter
.c_str();
499 save_as
.GetOPENFILENAME()->nFilterIndex
= *index
;
500 save_as
.GetOPENFILENAME()->lpstrDefExt
= &def_ext
[0];
501 save_as
.MaybeInstallWindowPositionHookForSaveAsOnXP();
503 if (!get_save_file_name_impl_
.Run(save_as
.GetOPENFILENAME()))
506 // Return the user's choice.
507 final_name
->assign(save_as
.GetOPENFILENAME()->lpstrFile
);
508 *index
= save_as
.GetOPENFILENAME()->nFilterIndex
;
510 // Figure out what filter got selected. The filter index is 1-based.
511 std::wstring filter_selected
;
513 std::vector
<base::Tuple
<base::string16
, base::string16
>> filters
=
514 ui::win::OpenFileName::GetFilters(save_as
.GetOPENFILENAME());
515 if (*index
> filters
.size())
516 NOTREACHED() << "Invalid filter index.";
518 filter_selected
= base::get
<1>(filters
[*index
- 1]);
521 // Get the extension that was suggested to the user (when the Save As dialog
522 // was opened). For saving web pages, we skip this step since there may be
523 // 'extension characters' in the title of the web page.
524 std::wstring suggested_ext
;
525 if (!ignore_suggested_ext
)
526 suggested_ext
= GetExtensionWithoutLeadingDot(suggested_path
.Extension());
528 // If we can't get the extension from the suggested_name, we use the default
529 // extension passed in. This is to cover cases like when saving a web page,
530 // where we get passed in a name without an extension and a default extension
532 if (suggested_ext
.empty())
533 suggested_ext
= def_ext
;
536 ui::AppendExtensionIfNeeded(*final_name
, filter_selected
, suggested_ext
);
540 void SelectFileDialogImpl::FileSelected(const base::FilePath
& selected_folder
,
543 RunState run_state
) {
545 listener_
->FileSelected(selected_folder
, index
, params
);
549 void SelectFileDialogImpl::MultiFilesSelected(
550 const std::vector
<base::FilePath
>& selected_files
,
552 RunState run_state
) {
554 listener_
->MultiFilesSelected(selected_files
, params
);
558 void SelectFileDialogImpl::FileNotSelected(void* params
, RunState run_state
) {
560 listener_
->FileSelectionCanceled(params
);
564 int CALLBACK
SelectFileDialogImpl::BrowseCallbackProc(HWND window
,
568 if (message
== BFFM_INITIALIZED
) {
569 // WParam is TRUE since passing a path.
570 // data lParam member of the BROWSEINFO structure.
571 SendMessage(window
, BFFM_SETSELECTION
, TRUE
, (LPARAM
)data
);
576 bool SelectFileDialogImpl::RunSelectFolderDialog(const std::wstring
& title
,
578 base::FilePath
* path
) {
581 wchar_t dir_buffer
[MAX_PATH
+ 1];
584 BROWSEINFO browse_info
= {0};
585 browse_info
.hwndOwner
= owner
;
586 browse_info
.lpszTitle
= title
.c_str();
587 browse_info
.pszDisplayName
= dir_buffer
;
588 browse_info
.ulFlags
= BIF_USENEWUI
| BIF_RETURNONLYFSDIRS
;
590 if (path
->value().length()) {
591 // Highlight the current value.
592 browse_info
.lParam
= (LPARAM
)path
->value().c_str();
593 browse_info
.lpfn
= &BrowseCallbackProc
;
596 LPITEMIDLIST list
= SHBrowseForFolder(&browse_info
);
599 STRRET out_dir_buffer
;
600 ZeroMemory(&out_dir_buffer
, sizeof(out_dir_buffer
));
601 out_dir_buffer
.uType
= STRRET_WSTR
;
602 base::win::ScopedComPtr
<IShellFolder
> shell_folder
;
603 if (SHGetDesktopFolder(shell_folder
.Receive()) == NOERROR
) {
604 HRESULT hr
= shell_folder
->GetDisplayNameOf(list
, SHGDN_FORPARSING
,
606 if (SUCCEEDED(hr
) && out_dir_buffer
.uType
== STRRET_WSTR
) {
607 *path
= base::FilePath(out_dir_buffer
.pOleStr
);
608 CoTaskMemFree(out_dir_buffer
.pOleStr
);
611 // Use old way if we don't get what we want.
612 wchar_t old_out_dir_buffer
[MAX_PATH
+ 1];
613 if (SHGetPathFromIDList(list
, old_out_dir_buffer
)) {
614 *path
= base::FilePath(old_out_dir_buffer
);
619 // According to MSDN, win2000 will not resolve shortcuts, so we do it
621 base::win::ResolveShortcut(*path
, path
, NULL
);
628 bool SelectFileDialogImpl::RunOpenFileDialog(
629 const std::wstring
& title
,
630 const std::wstring
& filter
,
632 base::FilePath
* path
) {
633 // We use OFN_NOCHANGEDIR so that the user can rename or delete the directory
634 // without having to close Chrome first.
635 ui::win::OpenFileName
ofn(owner
, OFN_FILEMUSTEXIST
| OFN_NOCHANGEDIR
);
636 if (!path
->empty()) {
637 if (IsDirectory(*path
))
638 ofn
.SetInitialSelection(*path
, base::FilePath());
640 ofn
.SetInitialSelection(path
->DirName(), path
->BaseName());
644 ofn
.GetOPENFILENAME()->lpstrFilter
= filter
.c_str();
646 bool success
= get_open_file_name_impl_
.Run(ofn
.GetOPENFILENAME());
649 *path
= ofn
.GetSingleResult();
653 bool SelectFileDialogImpl::RunOpenMultiFileDialog(
654 const std::wstring
& title
,
655 const std::wstring
& filter
,
657 std::vector
<base::FilePath
>* paths
) {
658 // We use OFN_NOCHANGEDIR so that the user can rename or delete the directory
659 // without having to close Chrome first.
660 ui::win::OpenFileName
ofn(owner
,
661 OFN_PATHMUSTEXIST
| OFN_FILEMUSTEXIST
|
662 OFN_EXPLORER
| OFN_HIDEREADONLY
|
663 OFN_ALLOWMULTISELECT
| OFN_NOCHANGEDIR
);
666 ofn
.GetOPENFILENAME()->lpstrFilter
= filter
.c_str();
668 base::FilePath directory
;
669 std::vector
<base::FilePath
> filenames
;
671 if (get_open_file_name_impl_
.Run(ofn
.GetOPENFILENAME()))
672 ofn
.GetResult(&directory
, &filenames
);
676 for (std::vector
<base::FilePath
>::iterator it
= filenames
.begin();
677 it
!= filenames
.end();
679 paths
->push_back(directory
.Append(*it
));
682 return !paths
->empty();
685 base::string16
SelectFileDialogImpl::GetFilterForFileTypes(
686 const FileTypeInfo
* file_types
) {
688 return base::string16();
690 std::vector
<base::string16
> exts
;
691 for (size_t i
= 0; i
< file_types
->extensions
.size(); ++i
) {
692 const std::vector
<base::string16
>& inner_exts
= file_types
->extensions
[i
];
693 base::string16 ext_string
;
694 for (size_t j
= 0; j
< inner_exts
.size(); ++j
) {
695 if (!ext_string
.empty())
696 ext_string
.push_back(L
';');
697 ext_string
.append(L
"*.");
698 ext_string
.append(inner_exts
[j
]);
700 exts
.push_back(ext_string
);
702 return FormatFilterForExtensions(
704 file_types
->extension_description_overrides
,
705 file_types
->include_all_files
);
712 // This function takes the output of a SaveAs dialog: a filename, a filter and
713 // the extension originally suggested to the user (shown in the dialog box) and
714 // returns back the filename with the appropriate extension tacked on. If the
715 // user requests an unknown extension and is not using the 'All files' filter,
716 // the suggested extension will be appended, otherwise we will leave the
717 // filename unmodified. |filename| should contain the filename selected in the
718 // SaveAs dialog box and may include the path, |filter_selected| should be
719 // '*.something', for example '*.*' or it can be blank (which is treated as
720 // *.*). |suggested_ext| should contain the extension without the dot (.) in
721 // front, for example 'jpg'.
722 std::wstring
AppendExtensionIfNeeded(
723 const std::wstring
& filename
,
724 const std::wstring
& filter_selected
,
725 const std::wstring
& suggested_ext
) {
726 DCHECK(!filename
.empty());
727 std::wstring return_value
= filename
;
729 // If we wanted a specific extension, but the user's filename deleted it or
730 // changed it to something that the system doesn't understand, re-append.
731 // Careful: Checking net::GetMimeTypeFromExtension() will only find
732 // extensions with a known MIME type, which many "known" extensions on Windows
733 // don't have. So we check directly for the "known extension" registry key.
734 std::wstring
file_extension(
735 GetExtensionWithoutLeadingDot(base::FilePath(filename
).Extension()));
736 std::wstring
key(L
"." + file_extension
);
737 if (!(filter_selected
.empty() || filter_selected
== L
"*.*") &&
738 !base::win::RegKey(HKEY_CLASSES_ROOT
, key
.c_str(), KEY_READ
).Valid() &&
739 file_extension
!= suggested_ext
) {
740 if (return_value
[return_value
.length() - 1] != L
'.')
741 return_value
.append(L
".");
742 return_value
.append(suggested_ext
);
745 // Strip any trailing dots, which Windows doesn't allow.
746 size_t index
= return_value
.find_last_not_of(L
'.');
747 if (index
< return_value
.size() - 1)
748 return_value
.resize(index
+ 1);
753 SelectFileDialog
* CreateWinSelectFileDialog(
754 SelectFileDialog::Listener
* listener
,
755 SelectFilePolicy
* policy
,
756 const base::Callback
<bool(OPENFILENAME
* ofn
)>& get_open_file_name_impl
,
757 const base::Callback
<bool(OPENFILENAME
* ofn
)>& get_save_file_name_impl
) {
758 return new SelectFileDialogImpl(
759 listener
, policy
, get_open_file_name_impl
, get_save_file_name_impl
);
762 SelectFileDialog
* CreateDefaultWinSelectFileDialog(
763 SelectFileDialog::Listener
* listener
,
764 SelectFilePolicy
* policy
) {
765 return CreateWinSelectFileDialog(listener
,
767 base::Bind(&CallBuiltinGetOpenFileName
),
768 base::Bind(&CallBuiltinGetSaveFileName
));