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/aura/window.h"
30 #include "ui/aura/window_event_dispatcher.h"
31 #include "ui/aura/window_tree_host.h"
32 #include "ui/base/l10n/l10n_util.h"
33 #include "ui/gfx/native_widget_types.h"
34 #include "ui/shell_dialogs/base_shell_dialog_win.h"
35 #include "ui/shell_dialogs/shell_dialogs_delegate.h"
36 #include "win8/viewer/metro_viewer_process_host.h"
40 // Given |extension|, if it's not empty, then remove the leading dot.
41 std::wstring GetExtensionWithoutLeadingDot(const std::wstring& extension) {
42 DCHECK(extension.empty() || extension[0] == L'.');
43 return extension.empty() ? extension : extension.substr(1);
46 // Diverts to a metro-specific implementation as appropriate.
47 bool CallGetOpenFileName(OPENFILENAME* ofn) {
48 HMODULE metro_module = base::win::GetMetroModule();
49 if (metro_module != NULL) {
50 typedef BOOL (*MetroGetOpenFileName)(OPENFILENAME*);
51 MetroGetOpenFileName metro_get_open_file_name =
52 reinterpret_cast<MetroGetOpenFileName>(
53 ::GetProcAddress(metro_module, "MetroGetOpenFileName"));
54 if (metro_get_open_file_name == NULL) {
59 return metro_get_open_file_name(ofn) == TRUE;
61 return GetOpenFileName(ofn) == TRUE;
65 // Diverts to a metro-specific implementation as appropriate.
66 bool CallGetSaveFileName(OPENFILENAME* ofn) {
67 HMODULE metro_module = base::win::GetMetroModule();
68 if (metro_module != NULL) {
69 typedef BOOL (*MetroGetSaveFileName)(OPENFILENAME*);
70 MetroGetSaveFileName metro_get_save_file_name =
71 reinterpret_cast<MetroGetSaveFileName>(
72 ::GetProcAddress(metro_module, "MetroGetSaveFileName"));
73 if (metro_get_save_file_name == NULL) {
78 return metro_get_save_file_name(ofn) == TRUE;
80 return GetSaveFileName(ofn) == TRUE;
84 // Distinguish directories from regular files.
85 bool IsDirectory(const base::FilePath& path) {
86 base::File::Info file_info;
87 return base::GetFileInfo(path, &file_info) ?
88 file_info.is_directory : path.EndsWithSeparator();
91 // Get the file type description from the registry. This will be "Text Document"
92 // for .txt files, "JPEG Image" for .jpg files, etc. If the registry doesn't
93 // have an entry for the file type, we return false, true if the description was
94 // found. 'file_ext' must be in form ".txt".
95 static bool GetRegistryDescriptionFromExtension(const std::wstring& file_ext,
96 std::wstring* reg_description) {
97 DCHECK(reg_description);
98 base::win::RegKey reg_ext(HKEY_CLASSES_ROOT, file_ext.c_str(), KEY_READ);
100 if (reg_ext.ReadValue(NULL, ®_app) == ERROR_SUCCESS && !reg_app.empty()) {
101 base::win::RegKey reg_link(HKEY_CLASSES_ROOT, reg_app.c_str(), KEY_READ);
102 if (reg_link.ReadValue(NULL, reg_description) == ERROR_SUCCESS)
108 // Set up a filter for a Save/Open dialog, which will consist of |file_ext| file
109 // extensions (internally separated by semicolons), |ext_desc| as the text
110 // descriptions of the |file_ext| types (optional), and (optionally) the default
111 // 'All Files' view. The purpose of the filter is to show only files of a
112 // particular type in a Windows Save/Open dialog box. The resulting filter is
113 // returned. The filters created here are:
114 // 1. only files that have 'file_ext' as their extension
115 // 2. all files (only added if 'include_all_files' is true)
117 // file_ext: { "*.txt", "*.htm;*.html" }
118 // ext_desc: { "Text Document" }
119 // returned: "Text Document\0*.txt\0HTML Document\0*.htm;*.html\0"
120 // "All Files\0*.*\0\0" (in one big string)
121 // If a description is not provided for a file extension, it will be retrieved
122 // from the registry. If the file extension does not exist in the registry, it
123 // will be omitted from the filter, as it is likely a bogus extension.
124 std::wstring FormatFilterForExtensions(
125 const std::vector<std::wstring>& file_ext,
126 const std::vector<std::wstring>& ext_desc,
127 bool include_all_files) {
128 const std::wstring all_ext = L"*.*";
129 const std::wstring all_desc =
130 l10n_util::GetStringUTF16(IDS_APP_SAVEAS_ALL_FILES);
132 DCHECK(file_ext.size() >= ext_desc.size());
134 if (file_ext.empty())
135 include_all_files = true;
139 for (size_t i = 0; i < file_ext.size(); ++i) {
140 std::wstring ext = file_ext[i];
142 if (i < ext_desc.size())
146 // Force something reasonable to appear in the dialog box if there is no
147 // extension provided.
148 include_all_files = true;
153 DCHECK(ext.find(L'.') != std::wstring::npos);
154 std::wstring first_extension = ext.substr(ext.find(L'.'));
155 size_t first_separator_index = first_extension.find(L';');
156 if (first_separator_index != std::wstring::npos)
157 first_extension = first_extension.substr(0, first_separator_index);
159 // Find the extension name without the preceeding '.' character.
160 std::wstring ext_name = first_extension;
161 size_t ext_index = ext_name.find_first_not_of(L'.');
162 if (ext_index != std::wstring::npos)
163 ext_name = ext_name.substr(ext_index);
165 if (!GetRegistryDescriptionFromExtension(first_extension, &desc)) {
166 // The extension doesn't exist in the registry. Create a description
167 // based on the unknown extension type (i.e. if the extension is .qqq,
168 // the we create a description "QQQ File (.qqq)").
169 include_all_files = true;
170 desc = l10n_util::GetStringFUTF16(
171 IDS_APP_SAVEAS_EXTENSION_FORMAT,
172 base::i18n::ToUpper(base::WideToUTF16(ext_name)),
176 desc = L"*." + ext_name;
179 result.append(desc.c_str(), desc.size() + 1); // Append NULL too.
180 result.append(ext.c_str(), ext.size() + 1);
183 if (include_all_files) {
184 result.append(all_desc.c_str(), all_desc.size() + 1);
185 result.append(all_ext.c_str(), all_ext.size() + 1);
188 result.append(1, '\0'); // Double NULL required.
192 // Enforce visible dialog box.
193 UINT_PTR CALLBACK SaveAsDialogHook(HWND dialog, UINT message,
194 WPARAM wparam, LPARAM lparam) {
195 static const UINT kPrivateMessage = 0x2F3F;
197 case WM_INITDIALOG: {
198 // Do nothing here. Just post a message to defer actual processing.
199 PostMessage(dialog, kPrivateMessage, 0, 0);
202 case kPrivateMessage: {
203 // The dialog box is the parent of the current handle.
204 HWND real_dialog = GetParent(dialog);
206 // Retrieve the final size.
208 GetWindowRect(real_dialog, &dialog_rect);
210 // Verify that the upper left corner is visible.
211 POINT point = { dialog_rect.left, dialog_rect.top };
212 HMONITOR monitor1 = MonitorFromPoint(point, MONITOR_DEFAULTTONULL);
213 point.x = dialog_rect.right;
214 point.y = dialog_rect.bottom;
216 // Verify that the lower right corner is visible.
217 HMONITOR monitor2 = MonitorFromPoint(point, MONITOR_DEFAULTTONULL);
218 if (monitor1 && monitor2)
221 // Some part of the dialog box is not visible, fix it by moving is to the
222 // client rect position of the browser window.
223 HWND parent_window = GetParent(real_dialog);
226 WINDOWINFO parent_info;
227 parent_info.cbSize = sizeof(WINDOWINFO);
228 GetWindowInfo(parent_window, &parent_info);
229 SetWindowPos(real_dialog, NULL,
230 parent_info.rcClient.left,
231 parent_info.rcClient.top,
233 SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOSIZE |
242 // Prompt the user for location to save a file.
243 // Callers should provide the filter string, and also a filter index.
244 // The parameter |index| indicates the initial index of filter description
245 // and filter pattern for the dialog box. If |index| is zero or greater than
246 // the number of total filter types, the system uses the first filter in the
247 // |filter| buffer. |index| is used to specify the initial selected extension,
248 // and when done contains the extension the user chose. The parameter
249 // |final_name| returns the file name which contains the drive designator,
250 // path, file name, and extension of the user selected file name. |def_ext| is
251 // the default extension to give to the file if the user did not enter an
252 // extension. If |ignore_suggested_ext| is true, any file extension contained in
253 // |suggested_name| will not be used to generate the file name. This is useful
254 // in the case of saving web pages, where we know the extension type already and
255 // where |suggested_name| may contain a '.' character as a valid part of the
256 // name, thus confusing our extension detection code.
257 bool SaveFileAsWithFilter(HWND owner,
258 const std::wstring& suggested_name,
259 const std::wstring& filter,
260 const std::wstring& def_ext,
261 bool ignore_suggested_ext,
263 std::wstring* final_name) {
265 // Having an empty filter makes for a bad user experience. We should always
266 // specify a filter when saving.
267 DCHECK(!filter.empty());
268 const base::FilePath suggested_path(suggested_name);
269 std::wstring file_part = suggested_path.BaseName().value();
270 // If the suggested_name is a root directory, file_part will be '\', and the
271 // call to GetSaveFileName below will fail.
272 if (file_part.size() == 1 && file_part[0] == L'\\')
275 // The size of the in/out buffer in number of characters we pass to win32
276 // GetSaveFileName. From MSDN "The buffer must be large enough to store the
277 // path and file name string or strings, including the terminating NULL
278 // character. ... The buffer should be at least 256 characters long.".
279 // _IsValidPathComDlg does a copy expecting at most MAX_PATH, otherwise will
280 // result in an error of FNERR_INVALIDFILENAME. So we should only pass the
281 // API a buffer of at most MAX_PATH.
282 wchar_t file_name[MAX_PATH];
283 base::wcslcpy(file_name, file_part.c_str(), arraysize(file_name));
285 OPENFILENAME save_as;
286 // We must do this otherwise the ofn's FlagsEx may be initialized to random
287 // junk in release builds which can cause the Places Bar not to show up!
288 ZeroMemory(&save_as, sizeof(save_as));
289 save_as.lStructSize = sizeof(OPENFILENAME);
290 save_as.hwndOwner = owner;
291 save_as.hInstance = NULL;
293 save_as.lpstrFilter = filter.empty() ? NULL : filter.c_str();
295 save_as.lpstrCustomFilter = NULL;
296 save_as.nMaxCustFilter = 0;
297 save_as.nFilterIndex = *index;
298 save_as.lpstrFile = file_name;
299 save_as.nMaxFile = arraysize(file_name);
300 save_as.lpstrFileTitle = NULL;
301 save_as.nMaxFileTitle = 0;
303 // Set up the initial directory for the dialog.
304 std::wstring directory;
305 if (!suggested_name.empty()) {
306 if (IsDirectory(suggested_path)) {
307 directory = suggested_path.value();
310 directory = suggested_path.DirName().value();
314 save_as.lpstrInitialDir = directory.c_str();
315 save_as.lpstrTitle = NULL;
316 save_as.Flags = OFN_OVERWRITEPROMPT | OFN_EXPLORER | OFN_ENABLESIZING |
317 OFN_NOCHANGEDIR | OFN_PATHMUSTEXIST;
318 save_as.lpstrDefExt = &def_ext[0];
319 save_as.lCustData = NULL;
321 if (base::win::GetVersion() < base::win::VERSION_VISTA) {
322 // The save as on Windows XP remembers its last position,
323 // and if the screen resolution changed, it will be off screen.
324 save_as.Flags |= OFN_ENABLEHOOK;
325 save_as.lpfnHook = &SaveAsDialogHook;
328 // Must be NULL or 0.
329 save_as.pvReserved = NULL;
330 save_as.dwReserved = 0;
332 if (!CallGetSaveFileName(&save_as)) {
333 // Zero means the dialog was closed, otherwise we had an error.
334 DWORD error_code = CommDlgExtendedError();
335 if (error_code != 0) {
336 NOTREACHED() << "GetSaveFileName failed with code: " << error_code;
341 // Return the user's choice.
342 final_name->assign(save_as.lpstrFile);
343 *index = save_as.nFilterIndex;
345 // Figure out what filter got selected from the vector with embedded nulls.
346 // NOTE: The filter contains a string with embedded nulls, such as:
347 // JPG Image\0*.jpg\0All files\0*.*\0\0
348 // The filter index is 1-based index for which pair got selected. So, using
349 // the example above, if the first index was selected we need to skip 1
350 // instance of null to get to "*.jpg".
351 std::vector<std::wstring> filters;
352 if (!filter.empty() && save_as.nFilterIndex > 0)
353 base::SplitString(filter, '\0', &filters);
354 std::wstring filter_selected;
355 if (!filters.empty())
356 filter_selected = filters[(2 * (save_as.nFilterIndex - 1)) + 1];
358 // Get the extension that was suggested to the user (when the Save As dialog
359 // was opened). For saving web pages, we skip this step since there may be
360 // 'extension characters' in the title of the web page.
361 std::wstring suggested_ext;
362 if (!ignore_suggested_ext)
363 suggested_ext = GetExtensionWithoutLeadingDot(suggested_path.Extension());
365 // If we can't get the extension from the suggested_name, we use the default
366 // extension passed in. This is to cover cases like when saving a web page,
367 // where we get passed in a name without an extension and a default extension
369 if (suggested_ext.empty())
370 suggested_ext = def_ext;
373 ui::AppendExtensionIfNeeded(*final_name, filter_selected, suggested_ext);
377 // Prompt the user for location to save a file. 'suggested_name' is a full path
378 // that gives the dialog box a hint as to how to initialize itself.
379 // For example, a 'suggested_name' of:
380 // "C:\Documents and Settings\jojo\My Documents\picture.png"
381 // will start the dialog in the "C:\Documents and Settings\jojo\My Documents\"
382 // directory, and filter for .png file types.
383 // 'owner' is the window to which the dialog box is modal, NULL for a modeless
385 // On success, returns true and 'final_name' contains the full path of the file
386 // that the user chose. On error, returns false, and 'final_name' is not
388 bool SaveFileAs(HWND owner,
389 const std::wstring& suggested_name,
390 std::wstring* final_name) {
391 std::wstring file_ext =
392 base::FilePath(suggested_name).Extension().insert(0, L"*");
393 std::wstring filter = FormatFilterForExtensions(
394 std::vector<std::wstring>(1, file_ext),
395 std::vector<std::wstring>(),
398 return SaveFileAsWithFilter(owner,
407 // Implementation of SelectFileDialog that shows a Windows common dialog for
408 // choosing a file or folder.
409 class SelectFileDialogImpl : public ui::SelectFileDialog,
410 public ui::BaseShellDialogImpl {
412 explicit SelectFileDialogImpl(Listener* listener,
413 ui::SelectFilePolicy* policy);
415 // BaseShellDialog implementation:
416 virtual bool IsRunning(gfx::NativeWindow owning_window) const OVERRIDE;
417 virtual void ListenerDestroyed() OVERRIDE;
420 // SelectFileDialog implementation:
421 virtual void SelectFileImpl(
423 const base::string16& title,
424 const base::FilePath& default_path,
425 const FileTypeInfo* file_types,
427 const base::FilePath::StringType& default_extension,
428 gfx::NativeWindow owning_window,
429 void* params) OVERRIDE;
432 virtual ~SelectFileDialogImpl();
434 // A struct for holding all the state necessary for displaying a Save dialog.
435 struct ExecuteSelectParams {
436 ExecuteSelectParams(Type type,
437 const std::wstring& title,
438 const base::FilePath& default_path,
439 const FileTypeInfo* file_types,
441 const std::wstring& default_extension,
447 default_path(default_path),
448 file_type_index(file_type_index),
449 default_extension(default_extension),
450 run_state(run_state),
451 ui_proxy(base::MessageLoopForUI::current()->message_loop_proxy()),
455 this->file_types = *file_types;
457 SelectFileDialog::Type type;
459 base::FilePath default_path;
460 FileTypeInfo file_types;
462 std::wstring default_extension;
464 scoped_refptr<base::MessageLoopProxy> ui_proxy;
469 // Shows the file selection dialog modal to |owner| and calls the result
470 // back on the ui thread. Run on the dialog thread.
471 void ExecuteSelectFile(const ExecuteSelectParams& params);
473 // Notifies the listener that a folder was chosen. Run on the ui thread.
474 void FileSelected(const base::FilePath& path, int index,
475 void* params, RunState run_state);
477 // Notifies listener that multiple files were chosen. Run on the ui thread.
478 void MultiFilesSelected(const std::vector<base::FilePath>& paths,
482 // Notifies the listener that no file was chosen (the action was canceled).
483 // Run on the ui thread.
484 void FileNotSelected(void* params, RunState run_state);
486 // Runs a Folder selection dialog box, passes back the selected folder in
487 // |path| and returns true if the user clicks OK. If the user cancels the
488 // dialog box the value in |path| is not modified and returns false. |title|
489 // is the user-supplied title text to show for the dialog box. Run on the
491 bool RunSelectFolderDialog(const std::wstring& title,
493 base::FilePath* path);
495 // Runs an Open file dialog box, with similar semantics for input paramaters
496 // as RunSelectFolderDialog.
497 bool RunOpenFileDialog(const std::wstring& title,
498 const std::wstring& filters,
500 base::FilePath* path);
502 // Runs an Open file dialog box that supports multi-select, with similar
503 // semantics for input paramaters as RunOpenFileDialog.
504 bool RunOpenMultiFileDialog(const std::wstring& title,
505 const std::wstring& filter,
507 std::vector<base::FilePath>* paths);
509 // The callback function for when the select folder dialog is opened.
510 static int CALLBACK BrowseCallbackProc(HWND window, UINT message,
514 virtual bool HasMultipleFileTypeChoicesImpl() OVERRIDE;
516 // Returns the filter to be used while displaying the open/save file dialog.
517 // This is computed from the extensions for the file types being opened.
518 // |file_types| can be NULL in which case the returned filter will be empty.
519 base::string16 GetFilterForFileTypes(const FileTypeInfo* file_types);
521 bool has_multiple_file_type_choices_;
523 DISALLOW_COPY_AND_ASSIGN(SelectFileDialogImpl);
526 SelectFileDialogImpl::SelectFileDialogImpl(Listener* listener,
527 ui::SelectFilePolicy* policy)
528 : SelectFileDialog(listener, policy),
529 BaseShellDialogImpl(),
530 has_multiple_file_type_choices_(false) {
533 SelectFileDialogImpl::~SelectFileDialogImpl() {
536 void SelectFileDialogImpl::SelectFileImpl(
538 const base::string16& title,
539 const base::FilePath& default_path,
540 const FileTypeInfo* file_types,
542 const base::FilePath::StringType& default_extension,
543 gfx::NativeWindow owning_window,
545 has_multiple_file_type_choices_ =
546 file_types ? file_types->extensions.size() > 1 : true;
547 // If the owning_window passed in is in metro then we need to forward the
548 // file open/save operations to metro.
549 if (GetShellDialogsDelegate() &&
550 GetShellDialogsDelegate()->IsWindowInMetro(owning_window)) {
551 if (type == SELECT_SAVEAS_FILE) {
552 win8::MetroViewerProcessHost::HandleSaveFile(
555 GetFilterForFileTypes(file_types),
558 base::Bind(&ui::SelectFileDialog::Listener::FileSelected,
559 base::Unretained(listener_)),
560 base::Bind(&ui::SelectFileDialog::Listener::FileSelectionCanceled,
561 base::Unretained(listener_)));
563 } else if (type == SELECT_OPEN_FILE) {
564 win8::MetroViewerProcessHost::HandleOpenFile(
567 GetFilterForFileTypes(file_types),
568 base::Bind(&ui::SelectFileDialog::Listener::FileSelected,
569 base::Unretained(listener_)),
570 base::Bind(&ui::SelectFileDialog::Listener::FileSelectionCanceled,
571 base::Unretained(listener_)));
573 } else if (type == SELECT_OPEN_MULTI_FILE) {
574 win8::MetroViewerProcessHost::HandleOpenMultipleFiles(
577 GetFilterForFileTypes(file_types),
578 base::Bind(&ui::SelectFileDialog::Listener::MultiFilesSelected,
579 base::Unretained(listener_)),
580 base::Bind(&ui::SelectFileDialog::Listener::FileSelectionCanceled,
581 base::Unretained(listener_)));
583 } else if (type == SELECT_FOLDER || type == SELECT_UPLOAD_FOLDER) {
584 base::string16 title_string = title;
585 if (type == SELECT_UPLOAD_FOLDER && title_string.empty()) {
586 // If it's for uploading don't use default dialog title to
587 // make sure we clearly tell it's for uploading.
588 title_string = l10n_util::GetStringUTF16(
589 IDS_SELECT_UPLOAD_FOLDER_DIALOG_TITLE);
591 win8::MetroViewerProcessHost::HandleSelectFolder(
593 base::Bind(&ui::SelectFileDialog::Listener::FileSelected,
594 base::Unretained(listener_)),
595 base::Bind(&ui::SelectFileDialog::Listener::FileSelectionCanceled,
596 base::Unretained(listener_)));
600 HWND owner = owning_window && owning_window->GetRootWindow()
601 ? owning_window->GetHost()->GetAcceleratedWidget() : NULL;
603 ExecuteSelectParams execute_params(type, title,
604 default_path, file_types, file_type_index,
605 default_extension, BeginRun(owner),
607 execute_params.run_state.dialog_thread->message_loop()->PostTask(
609 base::Bind(&SelectFileDialogImpl::ExecuteSelectFile, this,
613 bool SelectFileDialogImpl::HasMultipleFileTypeChoicesImpl() {
614 return has_multiple_file_type_choices_;
617 bool SelectFileDialogImpl::IsRunning(gfx::NativeWindow owning_window) const {
618 if (!owning_window->GetRootWindow())
620 HWND owner = owning_window->GetHost()->GetAcceleratedWidget();
621 return listener_ && IsRunningDialogForOwner(owner);
624 void SelectFileDialogImpl::ListenerDestroyed() {
625 // Our associated listener has gone away, so we shouldn't call back to it if
626 // our worker thread returns after the listener is dead.
630 void SelectFileDialogImpl::ExecuteSelectFile(
631 const ExecuteSelectParams& params) {
632 base::string16 filter = GetFilterForFileTypes(¶ms.file_types);
634 base::FilePath path = params.default_path;
635 bool success = false;
636 unsigned filter_index = params.file_type_index;
637 if (params.type == SELECT_FOLDER || params.type == SELECT_UPLOAD_FOLDER) {
638 std::wstring title = params.title;
639 if (title.empty() && params.type == SELECT_UPLOAD_FOLDER) {
640 // If it's for uploading don't use default dialog title to
641 // make sure we clearly tell it's for uploading.
642 title = l10n_util::GetStringUTF16(IDS_SELECT_UPLOAD_FOLDER_DIALOG_TITLE);
644 success = RunSelectFolderDialog(title,
645 params.run_state.owner,
647 } else if (params.type == SELECT_SAVEAS_FILE) {
648 std::wstring path_as_wstring = path.value();
649 success = SaveFileAsWithFilter(params.run_state.owner,
650 params.default_path.value(), filter,
651 params.default_extension, false, &filter_index, &path_as_wstring);
653 path = base::FilePath(path_as_wstring);
654 DisableOwner(params.run_state.owner);
655 } else if (params.type == SELECT_OPEN_FILE) {
656 success = RunOpenFileDialog(params.title, filter,
657 params.run_state.owner, &path);
658 } else if (params.type == SELECT_OPEN_MULTI_FILE) {
659 std::vector<base::FilePath> paths;
660 if (RunOpenMultiFileDialog(params.title, filter,
661 params.run_state.owner, &paths)) {
662 params.ui_proxy->PostTask(
664 base::Bind(&SelectFileDialogImpl::MultiFilesSelected, this, paths,
665 params.params, params.run_state));
671 params.ui_proxy->PostTask(
673 base::Bind(&SelectFileDialogImpl::FileSelected, this, path,
674 filter_index, params.params, params.run_state));
676 params.ui_proxy->PostTask(
678 base::Bind(&SelectFileDialogImpl::FileNotSelected, this, params.params,
683 void SelectFileDialogImpl::FileSelected(const base::FilePath& selected_folder,
686 RunState run_state) {
688 listener_->FileSelected(selected_folder, index, params);
692 void SelectFileDialogImpl::MultiFilesSelected(
693 const std::vector<base::FilePath>& selected_files,
695 RunState run_state) {
697 listener_->MultiFilesSelected(selected_files, params);
701 void SelectFileDialogImpl::FileNotSelected(void* params, RunState run_state) {
703 listener_->FileSelectionCanceled(params);
707 int CALLBACK SelectFileDialogImpl::BrowseCallbackProc(HWND window,
711 if (message == BFFM_INITIALIZED) {
712 // WParam is TRUE since passing a path.
713 // data lParam member of the BROWSEINFO structure.
714 SendMessage(window, BFFM_SETSELECTION, TRUE, (LPARAM)data);
719 bool SelectFileDialogImpl::RunSelectFolderDialog(const std::wstring& title,
721 base::FilePath* path) {
724 wchar_t dir_buffer[MAX_PATH + 1];
727 BROWSEINFO browse_info = {0};
728 browse_info.hwndOwner = owner;
729 browse_info.lpszTitle = title.c_str();
730 browse_info.pszDisplayName = dir_buffer;
731 browse_info.ulFlags = BIF_USENEWUI | BIF_RETURNONLYFSDIRS;
733 if (path->value().length()) {
734 // Highlight the current value.
735 browse_info.lParam = (LPARAM)path->value().c_str();
736 browse_info.lpfn = &BrowseCallbackProc;
739 LPITEMIDLIST list = SHBrowseForFolder(&browse_info);
742 STRRET out_dir_buffer;
743 ZeroMemory(&out_dir_buffer, sizeof(out_dir_buffer));
744 out_dir_buffer.uType = STRRET_WSTR;
745 base::win::ScopedComPtr<IShellFolder> shell_folder;
746 if (SHGetDesktopFolder(shell_folder.Receive()) == NOERROR) {
747 HRESULT hr = shell_folder->GetDisplayNameOf(list, SHGDN_FORPARSING,
749 if (SUCCEEDED(hr) && out_dir_buffer.uType == STRRET_WSTR) {
750 *path = base::FilePath(out_dir_buffer.pOleStr);
751 CoTaskMemFree(out_dir_buffer.pOleStr);
754 // Use old way if we don't get what we want.
755 wchar_t old_out_dir_buffer[MAX_PATH + 1];
756 if (SHGetPathFromIDList(list, old_out_dir_buffer)) {
757 *path = base::FilePath(old_out_dir_buffer);
762 // According to MSDN, win2000 will not resolve shortcuts, so we do it
764 base::win::ResolveShortcut(*path, path, NULL);
771 bool SelectFileDialogImpl::RunOpenFileDialog(
772 const std::wstring& title,
773 const std::wstring& filter,
775 base::FilePath* path) {
777 // We must do this otherwise the ofn's FlagsEx may be initialized to random
778 // junk in release builds which can cause the Places Bar not to show up!
779 ZeroMemory(&ofn, sizeof(ofn));
780 ofn.lStructSize = sizeof(ofn);
781 ofn.hwndOwner = owner;
783 wchar_t filename[MAX_PATH];
784 // According to http://support.microsoft.com/?scid=kb;en-us;222003&x=8&y=12,
785 // The lpstrFile Buffer MUST be NULL Terminated.
787 // Define the dir in here to keep the string buffer pointer pointed to
788 // ofn.lpstrInitialDir available during the period of running the
791 // Use lpstrInitialDir to specify the initial directory
792 if (!path->empty()) {
793 if (IsDirectory(*path)) {
794 ofn.lpstrInitialDir = path->value().c_str();
796 dir = path->DirName();
797 ofn.lpstrInitialDir = dir.value().c_str();
798 // Only pure filename can be put in lpstrFile field.
799 base::wcslcpy(filename, path->BaseName().value().c_str(),
800 arraysize(filename));
804 ofn.lpstrFile = filename;
805 ofn.nMaxFile = MAX_PATH;
807 // We use OFN_NOCHANGEDIR so that the user can rename or delete the directory
808 // without having to close Chrome first.
809 ofn.Flags = OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR;
812 ofn.lpstrFilter = filter.c_str();
813 bool success = CallGetOpenFileName(&ofn);
816 *path = base::FilePath(filename);
820 bool SelectFileDialogImpl::RunOpenMultiFileDialog(
821 const std::wstring& title,
822 const std::wstring& filter,
824 std::vector<base::FilePath>* paths) {
826 // We must do this otherwise the ofn's FlagsEx may be initialized to random
827 // junk in release builds which can cause the Places Bar not to show up!
828 ZeroMemory(&ofn, sizeof(ofn));
829 ofn.lStructSize = sizeof(ofn);
830 ofn.hwndOwner = owner;
832 scoped_ptr<wchar_t[]> filename(new wchar_t[UNICODE_STRING_MAX_CHARS]);
835 ofn.lpstrFile = filename.get();
836 ofn.nMaxFile = UNICODE_STRING_MAX_CHARS;
837 // We use OFN_NOCHANGEDIR so that the user can rename or delete the directory
838 // without having to close Chrome first.
839 ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_EXPLORER
840 | OFN_HIDEREADONLY | OFN_ALLOWMULTISELECT | OFN_NOCHANGEDIR;
842 if (!filter.empty()) {
843 ofn.lpstrFilter = filter.c_str();
846 bool success = CallGetOpenFileName(&ofn);
849 std::vector<base::FilePath> files;
850 const wchar_t* selection = ofn.lpstrFile;
851 while (*selection) { // Empty string indicates end of list.
852 files.push_back(base::FilePath(selection));
853 // Skip over filename and null-terminator.
854 selection += files.back().value().length() + 1;
858 } else if (files.size() == 1) {
859 // When there is one file, it contains the path and filename.
862 // Otherwise, the first string is the path, and the remainder are
864 std::vector<base::FilePath>::iterator path = files.begin();
865 for (std::vector<base::FilePath>::iterator file = path + 1;
866 file != files.end(); ++file) {
867 paths->push_back(path->Append(*file));
874 base::string16 SelectFileDialogImpl::GetFilterForFileTypes(
875 const FileTypeInfo* file_types) {
877 return base::string16();
879 std::vector<base::string16> exts;
880 for (size_t i = 0; i < file_types->extensions.size(); ++i) {
881 const std::vector<base::string16>& inner_exts = file_types->extensions[i];
882 base::string16 ext_string;
883 for (size_t j = 0; j < inner_exts.size(); ++j) {
884 if (!ext_string.empty())
885 ext_string.push_back(L';');
886 ext_string.append(L"*.");
887 ext_string.append(inner_exts[j]);
889 exts.push_back(ext_string);
891 return FormatFilterForExtensions(
893 file_types->extension_description_overrides,
894 file_types->include_all_files);
901 // This function takes the output of a SaveAs dialog: a filename, a filter and
902 // the extension originally suggested to the user (shown in the dialog box) and
903 // returns back the filename with the appropriate extension tacked on. If the
904 // user requests an unknown extension and is not using the 'All files' filter,
905 // the suggested extension will be appended, otherwise we will leave the
906 // filename unmodified. |filename| should contain the filename selected in the
907 // SaveAs dialog box and may include the path, |filter_selected| should be
908 // '*.something', for example '*.*' or it can be blank (which is treated as
909 // *.*). |suggested_ext| should contain the extension without the dot (.) in
910 // front, for example 'jpg'.
911 std::wstring AppendExtensionIfNeeded(
912 const std::wstring& filename,
913 const std::wstring& filter_selected,
914 const std::wstring& suggested_ext) {
915 DCHECK(!filename.empty());
916 std::wstring return_value = filename;
918 // If we wanted a specific extension, but the user's filename deleted it or
919 // changed it to something that the system doesn't understand, re-append.
920 // Careful: Checking net::GetMimeTypeFromExtension() will only find
921 // extensions with a known MIME type, which many "known" extensions on Windows
922 // don't have. So we check directly for the "known extension" registry key.
923 std::wstring file_extension(
924 GetExtensionWithoutLeadingDot(base::FilePath(filename).Extension()));
925 std::wstring key(L"." + file_extension);
926 if (!(filter_selected.empty() || filter_selected == L"*.*") &&
927 !base::win::RegKey(HKEY_CLASSES_ROOT, key.c_str(), KEY_READ).Valid() &&
928 file_extension != suggested_ext) {
929 if (return_value[return_value.length() - 1] != L'.')
930 return_value.append(L".");
931 return_value.append(suggested_ext);
934 // Strip any trailing dots, which Windows doesn't allow.
935 size_t index = return_value.find_last_not_of(L'.');
936 if (index < return_value.size() - 1)
937 return_value.resize(index + 1);
942 SelectFileDialog* CreateWinSelectFileDialog(
943 SelectFileDialog::Listener* listener,
944 SelectFilePolicy* policy) {
945 return new SelectFileDialogImpl(listener, policy);