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"
14 #include "base/bind.h"
15 #include "base/file_util.h"
16 #include "base/files/file_path.h"
17 #include "base/i18n/case_conversion.h"
18 #include "base/message_loop/message_loop.h"
19 #include "base/message_loop/message_loop_proxy.h"
20 #include "base/strings/string_split.h"
21 #include "base/strings/utf_string_conversions.h"
22 #include "base/threading/thread.h"
23 #include "base/win/metro.h"
24 #include "base/win/registry.h"
25 #include "base/win/scoped_comptr.h"
26 #include "base/win/shortcut.h"
27 #include "base/win/windows_version.h"
28 #include "grit/ui_strings.h"
29 #include "ui/base/l10n/l10n_util.h"
30 #include "ui/gfx/native_widget_types.h"
31 #include "ui/shell_dialogs/base_shell_dialog_win.h"
32 #include "ui/shell_dialogs/shell_dialogs_delegate.h"
35 #include "ui/aura/remote_window_tree_host_win.h"
36 #include "ui/aura/root_window.h"
37 #include "ui/aura/window.h"
42 // Given |extension|, if it's not empty, then remove the leading dot.
43 std::wstring GetExtensionWithoutLeadingDot(const std::wstring& extension) {
44 DCHECK(extension.empty() || extension[0] == L'.');
45 return extension.empty() ? extension : extension.substr(1);
48 // Diverts to a metro-specific implementation as appropriate.
49 bool CallGetOpenFileName(OPENFILENAME* ofn) {
50 HMODULE metro_module = base::win::GetMetroModule();
51 if (metro_module != NULL) {
52 typedef BOOL (*MetroGetOpenFileName)(OPENFILENAME*);
53 MetroGetOpenFileName metro_get_open_file_name =
54 reinterpret_cast<MetroGetOpenFileName>(
55 ::GetProcAddress(metro_module, "MetroGetOpenFileName"));
56 if (metro_get_open_file_name == NULL) {
61 return metro_get_open_file_name(ofn) == TRUE;
63 return GetOpenFileName(ofn) == TRUE;
67 // Diverts to a metro-specific implementation as appropriate.
68 bool CallGetSaveFileName(OPENFILENAME* ofn) {
69 HMODULE metro_module = base::win::GetMetroModule();
70 if (metro_module != NULL) {
71 typedef BOOL (*MetroGetSaveFileName)(OPENFILENAME*);
72 MetroGetSaveFileName metro_get_save_file_name =
73 reinterpret_cast<MetroGetSaveFileName>(
74 ::GetProcAddress(metro_module, "MetroGetSaveFileName"));
75 if (metro_get_save_file_name == NULL) {
80 return metro_get_save_file_name(ofn) == TRUE;
82 return GetSaveFileName(ofn) == TRUE;
86 // Distinguish directories from regular files.
87 bool IsDirectory(const base::FilePath& path) {
88 base::File::Info file_info;
89 return base::GetFileInfo(path, &file_info) ?
90 file_info.is_directory : path.EndsWithSeparator();
93 // Get the file type description from the registry. This will be "Text Document"
94 // for .txt files, "JPEG Image" for .jpg files, etc. If the registry doesn't
95 // have an entry for the file type, we return false, true if the description was
96 // found. 'file_ext' must be in form ".txt".
97 static bool GetRegistryDescriptionFromExtension(const std::wstring& file_ext,
98 std::wstring* reg_description) {
99 DCHECK(reg_description);
100 base::win::RegKey reg_ext(HKEY_CLASSES_ROOT, file_ext.c_str(), KEY_READ);
101 std::wstring reg_app;
102 if (reg_ext.ReadValue(NULL, ®_app) == ERROR_SUCCESS && !reg_app.empty()) {
103 base::win::RegKey reg_link(HKEY_CLASSES_ROOT, reg_app.c_str(), KEY_READ);
104 if (reg_link.ReadValue(NULL, reg_description) == ERROR_SUCCESS)
110 // Set up a filter for a Save/Open dialog, which will consist of |file_ext| file
111 // extensions (internally separated by semicolons), |ext_desc| as the text
112 // descriptions of the |file_ext| types (optional), and (optionally) the default
113 // 'All Files' view. The purpose of the filter is to show only files of a
114 // particular type in a Windows Save/Open dialog box. The resulting filter is
115 // returned. The filters created here are:
116 // 1. only files that have 'file_ext' as their extension
117 // 2. all files (only added if 'include_all_files' is true)
119 // file_ext: { "*.txt", "*.htm;*.html" }
120 // ext_desc: { "Text Document" }
121 // returned: "Text Document\0*.txt\0HTML Document\0*.htm;*.html\0"
122 // "All Files\0*.*\0\0" (in one big string)
123 // If a description is not provided for a file extension, it will be retrieved
124 // from the registry. If the file extension does not exist in the registry, it
125 // will be omitted from the filter, as it is likely a bogus extension.
126 std::wstring FormatFilterForExtensions(
127 const std::vector<std::wstring>& file_ext,
128 const std::vector<std::wstring>& ext_desc,
129 bool include_all_files) {
130 const std::wstring all_ext = L"*.*";
131 const std::wstring all_desc =
132 l10n_util::GetStringUTF16(IDS_APP_SAVEAS_ALL_FILES);
134 DCHECK(file_ext.size() >= ext_desc.size());
136 if (file_ext.empty())
137 include_all_files = true;
141 for (size_t i = 0; i < file_ext.size(); ++i) {
142 std::wstring ext = file_ext[i];
144 if (i < ext_desc.size())
148 // Force something reasonable to appear in the dialog box if there is no
149 // extension provided.
150 include_all_files = true;
155 DCHECK(ext.find(L'.') != std::wstring::npos);
156 std::wstring first_extension = ext.substr(ext.find(L'.'));
157 size_t first_separator_index = first_extension.find(L';');
158 if (first_separator_index != std::wstring::npos)
159 first_extension = first_extension.substr(0, first_separator_index);
161 // Find the extension name without the preceeding '.' character.
162 std::wstring ext_name = first_extension;
163 size_t ext_index = ext_name.find_first_not_of(L'.');
164 if (ext_index != std::wstring::npos)
165 ext_name = ext_name.substr(ext_index);
167 if (!GetRegistryDescriptionFromExtension(first_extension, &desc)) {
168 // The extension doesn't exist in the registry. Create a description
169 // based on the unknown extension type (i.e. if the extension is .qqq,
170 // the we create a description "QQQ File (.qqq)").
171 include_all_files = true;
172 desc = l10n_util::GetStringFUTF16(
173 IDS_APP_SAVEAS_EXTENSION_FORMAT,
174 base::i18n::ToUpper(base::WideToUTF16(ext_name)),
178 desc = L"*." + ext_name;
181 result.append(desc.c_str(), desc.size() + 1); // Append NULL too.
182 result.append(ext.c_str(), ext.size() + 1);
185 if (include_all_files) {
186 result.append(all_desc.c_str(), all_desc.size() + 1);
187 result.append(all_ext.c_str(), all_ext.size() + 1);
190 result.append(1, '\0'); // Double NULL required.
194 // Enforce visible dialog box.
195 UINT_PTR CALLBACK SaveAsDialogHook(HWND dialog, UINT message,
196 WPARAM wparam, LPARAM lparam) {
197 static const UINT kPrivateMessage = 0x2F3F;
199 case WM_INITDIALOG: {
200 // Do nothing here. Just post a message to defer actual processing.
201 PostMessage(dialog, kPrivateMessage, 0, 0);
204 case kPrivateMessage: {
205 // The dialog box is the parent of the current handle.
206 HWND real_dialog = GetParent(dialog);
208 // Retrieve the final size.
210 GetWindowRect(real_dialog, &dialog_rect);
212 // Verify that the upper left corner is visible.
213 POINT point = { dialog_rect.left, dialog_rect.top };
214 HMONITOR monitor1 = MonitorFromPoint(point, MONITOR_DEFAULTTONULL);
215 point.x = dialog_rect.right;
216 point.y = dialog_rect.bottom;
218 // Verify that the lower right corner is visible.
219 HMONITOR monitor2 = MonitorFromPoint(point, MONITOR_DEFAULTTONULL);
220 if (monitor1 && monitor2)
223 // Some part of the dialog box is not visible, fix it by moving is to the
224 // client rect position of the browser window.
225 HWND parent_window = GetParent(real_dialog);
228 WINDOWINFO parent_info;
229 parent_info.cbSize = sizeof(WINDOWINFO);
230 GetWindowInfo(parent_window, &parent_info);
231 SetWindowPos(real_dialog, NULL,
232 parent_info.rcClient.left,
233 parent_info.rcClient.top,
235 SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOSIZE |
244 // Prompt the user for location to save a file.
245 // Callers should provide the filter string, and also a filter index.
246 // The parameter |index| indicates the initial index of filter description
247 // and filter pattern for the dialog box. If |index| is zero or greater than
248 // the number of total filter types, the system uses the first filter in the
249 // |filter| buffer. |index| is used to specify the initial selected extension,
250 // and when done contains the extension the user chose. The parameter
251 // |final_name| returns the file name which contains the drive designator,
252 // path, file name, and extension of the user selected file name. |def_ext| is
253 // the default extension to give to the file if the user did not enter an
254 // extension. If |ignore_suggested_ext| is true, any file extension contained in
255 // |suggested_name| will not be used to generate the file name. This is useful
256 // in the case of saving web pages, where we know the extension type already and
257 // where |suggested_name| may contain a '.' character as a valid part of the
258 // name, thus confusing our extension detection code.
259 bool SaveFileAsWithFilter(HWND owner,
260 const std::wstring& suggested_name,
261 const std::wstring& filter,
262 const std::wstring& def_ext,
263 bool ignore_suggested_ext,
265 std::wstring* final_name) {
267 // Having an empty filter makes for a bad user experience. We should always
268 // specify a filter when saving.
269 DCHECK(!filter.empty());
270 const base::FilePath suggested_path(suggested_name);
271 std::wstring file_part = suggested_path.BaseName().value();
272 // If the suggested_name is a root directory, file_part will be '\', and the
273 // call to GetSaveFileName below will fail.
274 if (file_part.size() == 1 && file_part[0] == L'\\')
277 // The size of the in/out buffer in number of characters we pass to win32
278 // GetSaveFileName. From MSDN "The buffer must be large enough to store the
279 // path and file name string or strings, including the terminating NULL
280 // character. ... The buffer should be at least 256 characters long.".
281 // _IsValidPathComDlg does a copy expecting at most MAX_PATH, otherwise will
282 // result in an error of FNERR_INVALIDFILENAME. So we should only pass the
283 // API a buffer of at most MAX_PATH.
284 wchar_t file_name[MAX_PATH];
285 base::wcslcpy(file_name, file_part.c_str(), arraysize(file_name));
287 OPENFILENAME save_as;
288 // We must do this otherwise the ofn's FlagsEx may be initialized to random
289 // junk in release builds which can cause the Places Bar not to show up!
290 ZeroMemory(&save_as, sizeof(save_as));
291 save_as.lStructSize = sizeof(OPENFILENAME);
292 save_as.hwndOwner = owner;
293 save_as.hInstance = NULL;
295 save_as.lpstrFilter = filter.empty() ? NULL : filter.c_str();
297 save_as.lpstrCustomFilter = NULL;
298 save_as.nMaxCustFilter = 0;
299 save_as.nFilterIndex = *index;
300 save_as.lpstrFile = file_name;
301 save_as.nMaxFile = arraysize(file_name);
302 save_as.lpstrFileTitle = NULL;
303 save_as.nMaxFileTitle = 0;
305 // Set up the initial directory for the dialog.
306 std::wstring directory;
307 if (!suggested_name.empty()) {
308 if (IsDirectory(suggested_path)) {
309 directory = suggested_path.value();
312 directory = suggested_path.DirName().value();
316 save_as.lpstrInitialDir = directory.c_str();
317 save_as.lpstrTitle = NULL;
318 save_as.Flags = OFN_OVERWRITEPROMPT | OFN_EXPLORER | OFN_ENABLESIZING |
319 OFN_NOCHANGEDIR | OFN_PATHMUSTEXIST;
320 save_as.lpstrDefExt = &def_ext[0];
321 save_as.lCustData = NULL;
323 if (base::win::GetVersion() < base::win::VERSION_VISTA) {
324 // The save as on Windows XP remembers its last position,
325 // and if the screen resolution changed, it will be off screen.
326 save_as.Flags |= OFN_ENABLEHOOK;
327 save_as.lpfnHook = &SaveAsDialogHook;
330 // Must be NULL or 0.
331 save_as.pvReserved = NULL;
332 save_as.dwReserved = 0;
334 if (!CallGetSaveFileName(&save_as)) {
335 // Zero means the dialog was closed, otherwise we had an error.
336 DWORD error_code = CommDlgExtendedError();
337 if (error_code != 0) {
338 NOTREACHED() << "GetSaveFileName failed with code: " << error_code;
343 // Return the user's choice.
344 final_name->assign(save_as.lpstrFile);
345 *index = save_as.nFilterIndex;
347 // Figure out what filter got selected from the vector with embedded nulls.
348 // NOTE: The filter contains a string with embedded nulls, such as:
349 // JPG Image\0*.jpg\0All files\0*.*\0\0
350 // The filter index is 1-based index for which pair got selected. So, using
351 // the example above, if the first index was selected we need to skip 1
352 // instance of null to get to "*.jpg".
353 std::vector<std::wstring> filters;
354 if (!filter.empty() && save_as.nFilterIndex > 0)
355 base::SplitString(filter, '\0', &filters);
356 std::wstring filter_selected;
357 if (!filters.empty())
358 filter_selected = filters[(2 * (save_as.nFilterIndex - 1)) + 1];
360 // Get the extension that was suggested to the user (when the Save As dialog
361 // was opened). For saving web pages, we skip this step since there may be
362 // 'extension characters' in the title of the web page.
363 std::wstring suggested_ext;
364 if (!ignore_suggested_ext)
365 suggested_ext = GetExtensionWithoutLeadingDot(suggested_path.Extension());
367 // If we can't get the extension from the suggested_name, we use the default
368 // extension passed in. This is to cover cases like when saving a web page,
369 // where we get passed in a name without an extension and a default extension
371 if (suggested_ext.empty())
372 suggested_ext = def_ext;
375 ui::AppendExtensionIfNeeded(*final_name, filter_selected, suggested_ext);
379 // Prompt the user for location to save a file. 'suggested_name' is a full path
380 // that gives the dialog box a hint as to how to initialize itself.
381 // For example, a 'suggested_name' of:
382 // "C:\Documents and Settings\jojo\My Documents\picture.png"
383 // will start the dialog in the "C:\Documents and Settings\jojo\My Documents\"
384 // directory, and filter for .png file types.
385 // 'owner' is the window to which the dialog box is modal, NULL for a modeless
387 // On success, returns true and 'final_name' contains the full path of the file
388 // that the user chose. On error, returns false, and 'final_name' is not
390 bool SaveFileAs(HWND owner,
391 const std::wstring& suggested_name,
392 std::wstring* final_name) {
393 std::wstring file_ext =
394 base::FilePath(suggested_name).Extension().insert(0, L"*");
395 std::wstring filter = FormatFilterForExtensions(
396 std::vector<std::wstring>(1, file_ext),
397 std::vector<std::wstring>(),
400 return SaveFileAsWithFilter(owner,
409 // Implementation of SelectFileDialog that shows a Windows common dialog for
410 // choosing a file or folder.
411 class SelectFileDialogImpl : public ui::SelectFileDialog,
412 public ui::BaseShellDialogImpl {
414 explicit SelectFileDialogImpl(Listener* listener,
415 ui::SelectFilePolicy* policy);
417 // BaseShellDialog implementation:
418 virtual bool IsRunning(gfx::NativeWindow owning_window) const OVERRIDE;
419 virtual void ListenerDestroyed() OVERRIDE;
422 // SelectFileDialog implementation:
423 virtual void SelectFileImpl(
425 const base::string16& title,
426 const base::FilePath& default_path,
427 const FileTypeInfo* file_types,
429 const base::FilePath::StringType& default_extension,
430 gfx::NativeWindow owning_window,
431 void* params) OVERRIDE;
434 virtual ~SelectFileDialogImpl();
436 // A struct for holding all the state necessary for displaying a Save dialog.
437 struct ExecuteSelectParams {
438 ExecuteSelectParams(Type type,
439 const std::wstring& title,
440 const base::FilePath& default_path,
441 const FileTypeInfo* file_types,
443 const std::wstring& default_extension,
449 default_path(default_path),
450 file_type_index(file_type_index),
451 default_extension(default_extension),
452 run_state(run_state),
453 ui_proxy(base::MessageLoopForUI::current()->message_loop_proxy()),
457 this->file_types = *file_types;
459 SelectFileDialog::Type type;
461 base::FilePath default_path;
462 FileTypeInfo file_types;
464 std::wstring default_extension;
466 scoped_refptr<base::MessageLoopProxy> ui_proxy;
471 // Shows the file selection dialog modal to |owner| and calls the result
472 // back on the ui thread. Run on the dialog thread.
473 void ExecuteSelectFile(const ExecuteSelectParams& params);
475 // Notifies the listener that a folder was chosen. Run on the ui thread.
476 void FileSelected(const base::FilePath& path, int index,
477 void* params, RunState run_state);
479 // Notifies listener that multiple files were chosen. Run on the ui thread.
480 void MultiFilesSelected(const std::vector<base::FilePath>& paths,
484 // Notifies the listener that no file was chosen (the action was canceled).
485 // Run on the ui thread.
486 void FileNotSelected(void* params, RunState run_state);
488 // Runs a Folder selection dialog box, passes back the selected folder in
489 // |path| and returns true if the user clicks OK. If the user cancels the
490 // dialog box the value in |path| is not modified and returns false. |title|
491 // is the user-supplied title text to show for the dialog box. Run on the
493 bool RunSelectFolderDialog(const std::wstring& title,
495 base::FilePath* path);
497 // Runs an Open file dialog box, with similar semantics for input paramaters
498 // as RunSelectFolderDialog.
499 bool RunOpenFileDialog(const std::wstring& title,
500 const std::wstring& filters,
502 base::FilePath* path);
504 // Runs an Open file dialog box that supports multi-select, with similar
505 // semantics for input paramaters as RunOpenFileDialog.
506 bool RunOpenMultiFileDialog(const std::wstring& title,
507 const std::wstring& filter,
509 std::vector<base::FilePath>* paths);
511 // The callback function for when the select folder dialog is opened.
512 static int CALLBACK BrowseCallbackProc(HWND window, UINT message,
516 virtual bool HasMultipleFileTypeChoicesImpl() OVERRIDE;
518 // Returns the filter to be used while displaying the open/save file dialog.
519 // This is computed from the extensions for the file types being opened.
520 // |file_types| can be NULL in which case the returned filter will be empty.
521 base::string16 GetFilterForFileTypes(const FileTypeInfo* file_types);
523 bool has_multiple_file_type_choices_;
525 DISALLOW_COPY_AND_ASSIGN(SelectFileDialogImpl);
528 SelectFileDialogImpl::SelectFileDialogImpl(Listener* listener,
529 ui::SelectFilePolicy* policy)
530 : SelectFileDialog(listener, policy),
531 BaseShellDialogImpl(),
532 has_multiple_file_type_choices_(false) {
535 SelectFileDialogImpl::~SelectFileDialogImpl() {
538 void SelectFileDialogImpl::SelectFileImpl(
540 const base::string16& title,
541 const base::FilePath& default_path,
542 const FileTypeInfo* file_types,
544 const base::FilePath::StringType& default_extension,
545 gfx::NativeWindow owning_window,
547 has_multiple_file_type_choices_ =
548 file_types ? file_types->extensions.size() > 1 : true;
549 #if defined(USE_AURA)
550 // If the owning_window passed in is in metro then we need to forward the
551 // file open/save operations to metro.
552 if (GetShellDialogsDelegate() &&
553 GetShellDialogsDelegate()->IsWindowInMetro(owning_window)) {
554 if (type == SELECT_SAVEAS_FILE) {
555 aura::HandleSaveFile(
556 base::UTF16ToWide(title),
558 GetFilterForFileTypes(file_types),
561 base::Bind(&ui::SelectFileDialog::Listener::FileSelected,
562 base::Unretained(listener_)),
563 base::Bind(&ui::SelectFileDialog::Listener::FileSelectionCanceled,
564 base::Unretained(listener_)));
566 } else if (type == SELECT_OPEN_FILE) {
567 aura::HandleOpenFile(
568 base::UTF16ToWide(title),
570 GetFilterForFileTypes(file_types),
571 base::Bind(&ui::SelectFileDialog::Listener::FileSelected,
572 base::Unretained(listener_)),
573 base::Bind(&ui::SelectFileDialog::Listener::FileSelectionCanceled,
574 base::Unretained(listener_)));
576 } else if (type == SELECT_OPEN_MULTI_FILE) {
577 aura::HandleOpenMultipleFiles(
578 base::UTF16ToWide(title),
580 GetFilterForFileTypes(file_types),
581 base::Bind(&ui::SelectFileDialog::Listener::MultiFilesSelected,
582 base::Unretained(listener_)),
583 base::Bind(&ui::SelectFileDialog::Listener::FileSelectionCanceled,
584 base::Unretained(listener_)));
586 } else if (type == SELECT_FOLDER || type == SELECT_UPLOAD_FOLDER) {
587 base::string16 title_string = title;
588 if (type == SELECT_UPLOAD_FOLDER && title_string.empty()) {
589 // If it's for uploading don't use default dialog title to
590 // make sure we clearly tell it's for uploading.
591 title_string = l10n_util::GetStringUTF16(
592 IDS_SELECT_UPLOAD_FOLDER_DIALOG_TITLE);
594 aura::HandleSelectFolder(
595 base::UTF16ToWide(title_string),
596 base::Bind(&ui::SelectFileDialog::Listener::FileSelected,
597 base::Unretained(listener_)),
598 base::Bind(&ui::SelectFileDialog::Listener::FileSelectionCanceled,
599 base::Unretained(listener_)));
603 HWND owner = owning_window && owning_window->GetRootWindow()
604 ? owning_window->GetDispatcher()->host()->GetAcceleratedWidget() : NULL;
606 HWND owner = owning_window;
608 ExecuteSelectParams execute_params(type, base::UTF16ToWide(title),
609 default_path, file_types, file_type_index,
610 default_extension, BeginRun(owner),
612 execute_params.run_state.dialog_thread->message_loop()->PostTask(
614 base::Bind(&SelectFileDialogImpl::ExecuteSelectFile, this,
618 bool SelectFileDialogImpl::HasMultipleFileTypeChoicesImpl() {
619 return has_multiple_file_type_choices_;
622 bool SelectFileDialogImpl::IsRunning(gfx::NativeWindow owning_window) const {
623 #if defined(USE_AURA)
624 if (!owning_window->GetRootWindow())
626 HWND owner = owning_window->GetDispatcher()->host()->GetAcceleratedWidget();
628 HWND owner = owning_window;
630 return listener_ && IsRunningDialogForOwner(owner);
633 void SelectFileDialogImpl::ListenerDestroyed() {
634 // Our associated listener has gone away, so we shouldn't call back to it if
635 // our worker thread returns after the listener is dead.
639 void SelectFileDialogImpl::ExecuteSelectFile(
640 const ExecuteSelectParams& params) {
641 base::string16 filter = GetFilterForFileTypes(¶ms.file_types);
643 base::FilePath path = params.default_path;
644 bool success = false;
645 unsigned filter_index = params.file_type_index;
646 if (params.type == SELECT_FOLDER || params.type == SELECT_UPLOAD_FOLDER) {
647 std::wstring title = params.title;
648 if (title.empty() && params.type == SELECT_UPLOAD_FOLDER) {
649 // If it's for uploading don't use default dialog title to
650 // make sure we clearly tell it's for uploading.
651 title = base::UTF16ToWide(
652 l10n_util::GetStringUTF16(IDS_SELECT_UPLOAD_FOLDER_DIALOG_TITLE));
654 success = RunSelectFolderDialog(title,
655 params.run_state.owner,
657 } else if (params.type == SELECT_SAVEAS_FILE) {
658 std::wstring path_as_wstring = path.value();
659 success = SaveFileAsWithFilter(params.run_state.owner,
660 params.default_path.value(), filter,
661 params.default_extension, false, &filter_index, &path_as_wstring);
663 path = base::FilePath(path_as_wstring);
664 DisableOwner(params.run_state.owner);
665 } else if (params.type == SELECT_OPEN_FILE) {
666 success = RunOpenFileDialog(params.title, filter,
667 params.run_state.owner, &path);
668 } else if (params.type == SELECT_OPEN_MULTI_FILE) {
669 std::vector<base::FilePath> paths;
670 if (RunOpenMultiFileDialog(params.title, filter,
671 params.run_state.owner, &paths)) {
672 params.ui_proxy->PostTask(
674 base::Bind(&SelectFileDialogImpl::MultiFilesSelected, this, paths,
675 params.params, params.run_state));
681 params.ui_proxy->PostTask(
683 base::Bind(&SelectFileDialogImpl::FileSelected, this, path,
684 filter_index, params.params, params.run_state));
686 params.ui_proxy->PostTask(
688 base::Bind(&SelectFileDialogImpl::FileNotSelected, this, params.params,
693 void SelectFileDialogImpl::FileSelected(const base::FilePath& selected_folder,
696 RunState run_state) {
698 listener_->FileSelected(selected_folder, index, params);
702 void SelectFileDialogImpl::MultiFilesSelected(
703 const std::vector<base::FilePath>& selected_files,
705 RunState run_state) {
707 listener_->MultiFilesSelected(selected_files, params);
711 void SelectFileDialogImpl::FileNotSelected(void* params, RunState run_state) {
713 listener_->FileSelectionCanceled(params);
717 int CALLBACK SelectFileDialogImpl::BrowseCallbackProc(HWND window,
721 if (message == BFFM_INITIALIZED) {
722 // WParam is TRUE since passing a path.
723 // data lParam member of the BROWSEINFO structure.
724 SendMessage(window, BFFM_SETSELECTION, TRUE, (LPARAM)data);
729 bool SelectFileDialogImpl::RunSelectFolderDialog(const std::wstring& title,
731 base::FilePath* path) {
734 wchar_t dir_buffer[MAX_PATH + 1];
737 BROWSEINFO browse_info = {0};
738 browse_info.hwndOwner = owner;
739 browse_info.lpszTitle = title.c_str();
740 browse_info.pszDisplayName = dir_buffer;
741 browse_info.ulFlags = BIF_USENEWUI | BIF_RETURNONLYFSDIRS;
743 if (path->value().length()) {
744 // Highlight the current value.
745 browse_info.lParam = (LPARAM)path->value().c_str();
746 browse_info.lpfn = &BrowseCallbackProc;
749 LPITEMIDLIST list = SHBrowseForFolder(&browse_info);
752 STRRET out_dir_buffer;
753 ZeroMemory(&out_dir_buffer, sizeof(out_dir_buffer));
754 out_dir_buffer.uType = STRRET_WSTR;
755 base::win::ScopedComPtr<IShellFolder> shell_folder;
756 if (SHGetDesktopFolder(shell_folder.Receive()) == NOERROR) {
757 HRESULT hr = shell_folder->GetDisplayNameOf(list, SHGDN_FORPARSING,
759 if (SUCCEEDED(hr) && out_dir_buffer.uType == STRRET_WSTR) {
760 *path = base::FilePath(out_dir_buffer.pOleStr);
761 CoTaskMemFree(out_dir_buffer.pOleStr);
764 // Use old way if we don't get what we want.
765 wchar_t old_out_dir_buffer[MAX_PATH + 1];
766 if (SHGetPathFromIDList(list, old_out_dir_buffer)) {
767 *path = base::FilePath(old_out_dir_buffer);
772 // According to MSDN, win2000 will not resolve shortcuts, so we do it
774 base::win::ResolveShortcut(*path, path, NULL);
781 bool SelectFileDialogImpl::RunOpenFileDialog(
782 const std::wstring& title,
783 const std::wstring& filter,
785 base::FilePath* path) {
787 // We must do this otherwise the ofn's FlagsEx may be initialized to random
788 // junk in release builds which can cause the Places Bar not to show up!
789 ZeroMemory(&ofn, sizeof(ofn));
790 ofn.lStructSize = sizeof(ofn);
791 ofn.hwndOwner = owner;
793 wchar_t filename[MAX_PATH];
794 // According to http://support.microsoft.com/?scid=kb;en-us;222003&x=8&y=12,
795 // The lpstrFile Buffer MUST be NULL Terminated.
797 // Define the dir in here to keep the string buffer pointer pointed to
798 // ofn.lpstrInitialDir available during the period of running the
801 // Use lpstrInitialDir to specify the initial directory
802 if (!path->empty()) {
803 if (IsDirectory(*path)) {
804 ofn.lpstrInitialDir = path->value().c_str();
806 dir = path->DirName();
807 ofn.lpstrInitialDir = dir.value().c_str();
808 // Only pure filename can be put in lpstrFile field.
809 base::wcslcpy(filename, path->BaseName().value().c_str(),
810 arraysize(filename));
814 ofn.lpstrFile = filename;
815 ofn.nMaxFile = MAX_PATH;
817 // We use OFN_NOCHANGEDIR so that the user can rename or delete the directory
818 // without having to close Chrome first.
819 ofn.Flags = OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR;
822 ofn.lpstrFilter = filter.c_str();
823 bool success = CallGetOpenFileName(&ofn);
826 *path = base::FilePath(filename);
830 bool SelectFileDialogImpl::RunOpenMultiFileDialog(
831 const std::wstring& title,
832 const std::wstring& filter,
834 std::vector<base::FilePath>* paths) {
836 // We must do this otherwise the ofn's FlagsEx may be initialized to random
837 // junk in release builds which can cause the Places Bar not to show up!
838 ZeroMemory(&ofn, sizeof(ofn));
839 ofn.lStructSize = sizeof(ofn);
840 ofn.hwndOwner = owner;
842 scoped_ptr<wchar_t[]> filename(new wchar_t[UNICODE_STRING_MAX_CHARS]);
845 ofn.lpstrFile = filename.get();
846 ofn.nMaxFile = UNICODE_STRING_MAX_CHARS;
847 // We use OFN_NOCHANGEDIR so that the user can rename or delete the directory
848 // without having to close Chrome first.
849 ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_EXPLORER
850 | OFN_HIDEREADONLY | OFN_ALLOWMULTISELECT | OFN_NOCHANGEDIR;
852 if (!filter.empty()) {
853 ofn.lpstrFilter = filter.c_str();
856 bool success = CallGetOpenFileName(&ofn);
859 std::vector<base::FilePath> files;
860 const wchar_t* selection = ofn.lpstrFile;
861 while (*selection) { // Empty string indicates end of list.
862 files.push_back(base::FilePath(selection));
863 // Skip over filename and null-terminator.
864 selection += files.back().value().length() + 1;
868 } else if (files.size() == 1) {
869 // When there is one file, it contains the path and filename.
872 // Otherwise, the first string is the path, and the remainder are
874 std::vector<base::FilePath>::iterator path = files.begin();
875 for (std::vector<base::FilePath>::iterator file = path + 1;
876 file != files.end(); ++file) {
877 paths->push_back(path->Append(*file));
884 base::string16 SelectFileDialogImpl::GetFilterForFileTypes(
885 const FileTypeInfo* file_types) {
887 return base::string16();
889 std::vector<base::string16> exts;
890 for (size_t i = 0; i < file_types->extensions.size(); ++i) {
891 const std::vector<base::string16>& inner_exts = file_types->extensions[i];
892 base::string16 ext_string;
893 for (size_t j = 0; j < inner_exts.size(); ++j) {
894 if (!ext_string.empty())
895 ext_string.push_back(L';');
896 ext_string.append(L"*.");
897 ext_string.append(inner_exts[j]);
899 exts.push_back(ext_string);
901 return FormatFilterForExtensions(
903 file_types->extension_description_overrides,
904 file_types->include_all_files);
911 // This function takes the output of a SaveAs dialog: a filename, a filter and
912 // the extension originally suggested to the user (shown in the dialog box) and
913 // returns back the filename with the appropriate extension tacked on. If the
914 // user requests an unknown extension and is not using the 'All files' filter,
915 // the suggested extension will be appended, otherwise we will leave the
916 // filename unmodified. |filename| should contain the filename selected in the
917 // SaveAs dialog box and may include the path, |filter_selected| should be
918 // '*.something', for example '*.*' or it can be blank (which is treated as
919 // *.*). |suggested_ext| should contain the extension without the dot (.) in
920 // front, for example 'jpg'.
921 std::wstring AppendExtensionIfNeeded(
922 const std::wstring& filename,
923 const std::wstring& filter_selected,
924 const std::wstring& suggested_ext) {
925 DCHECK(!filename.empty());
926 std::wstring return_value = filename;
928 // If we wanted a specific extension, but the user's filename deleted it or
929 // changed it to something that the system doesn't understand, re-append.
930 // Careful: Checking net::GetMimeTypeFromExtension() will only find
931 // extensions with a known MIME type, which many "known" extensions on Windows
932 // don't have. So we check directly for the "known extension" registry key.
933 std::wstring file_extension(
934 GetExtensionWithoutLeadingDot(base::FilePath(filename).Extension()));
935 std::wstring key(L"." + file_extension);
936 if (!(filter_selected.empty() || filter_selected == L"*.*") &&
937 !base::win::RegKey(HKEY_CLASSES_ROOT, key.c_str(), KEY_READ).Valid() &&
938 file_extension != suggested_ext) {
939 if (return_value[return_value.length() - 1] != L'.')
940 return_value.append(L".");
941 return_value.append(suggested_ext);
944 // Strip any trailing dots, which Windows doesn't allow.
945 size_t index = return_value.find_last_not_of(L'.');
946 if (index < return_value.size() - 1)
947 return_value.resize(index + 1);
952 SelectFileDialog* CreateWinSelectFileDialog(
953 SelectFileDialog::Listener* listener,
954 SelectFilePolicy* policy) {
955 return new SelectFileDialogImpl(listener, policy);