Fix build break
[chromium-blink-merge.git] / ui / shell_dialogs / select_file_dialog_win.cc
blobb3f31ed839d0bdb5f47514b3c8ef7147bce9da05
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"
7 #include <windows.h>
8 #include <commdlg.h>
9 #include <shlobj.h>
11 #include <algorithm>
12 #include <set>
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.h"
19 #include "base/message_loop/message_loop_proxy.h"
20 #include "base/strings/string_split.h"
21 #include "base/threading/thread.h"
22 #include "base/utf_string_conversions.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"
34 #if defined(USE_AURA)
35 #include "ui/aura/remote_root_window_host_win.h"
36 #include "ui/aura/root_window.h"
37 #endif
39 namespace {
41 // Given |extension|, if it's not empty, then remove the leading dot.
42 std::wstring GetExtensionWithoutLeadingDot(const std::wstring& extension) {
43 DCHECK(extension.empty() || extension[0] == L'.');
44 return extension.empty() ? extension : extension.substr(1);
47 // Diverts to a metro-specific implementation as appropriate.
48 bool CallGetOpenFileName(OPENFILENAME* ofn) {
49 HMODULE metro_module = base::win::GetMetroModule();
50 if (metro_module != NULL) {
51 typedef BOOL (*MetroGetOpenFileName)(OPENFILENAME*);
52 MetroGetOpenFileName metro_get_open_file_name =
53 reinterpret_cast<MetroGetOpenFileName>(
54 ::GetProcAddress(metro_module, "MetroGetOpenFileName"));
55 if (metro_get_open_file_name == NULL) {
56 NOTREACHED();
57 return false;
60 return metro_get_open_file_name(ofn) == TRUE;
61 } else {
62 return GetOpenFileName(ofn) == TRUE;
66 // Diverts to a metro-specific implementation as appropriate.
67 bool CallGetSaveFileName(OPENFILENAME* ofn) {
68 HMODULE metro_module = base::win::GetMetroModule();
69 if (metro_module != NULL) {
70 typedef BOOL (*MetroGetSaveFileName)(OPENFILENAME*);
71 MetroGetSaveFileName metro_get_save_file_name =
72 reinterpret_cast<MetroGetSaveFileName>(
73 ::GetProcAddress(metro_module, "MetroGetSaveFileName"));
74 if (metro_get_save_file_name == NULL) {
75 NOTREACHED();
76 return false;
79 return metro_get_save_file_name(ofn) == TRUE;
80 } else {
81 return GetSaveFileName(ofn) == TRUE;
85 // Distinguish directories from regular files.
86 bool IsDirectory(const base::FilePath& path) {
87 base::PlatformFileInfo file_info;
88 return file_util::GetFileInfo(path, &file_info) ?
89 file_info.is_directory : path.EndsWithSeparator();
92 // Get the file type description from the registry. This will be "Text Document"
93 // for .txt files, "JPEG Image" for .jpg files, etc. If the registry doesn't
94 // have an entry for the file type, we return false, true if the description was
95 // found. 'file_ext' must be in form ".txt".
96 static bool GetRegistryDescriptionFromExtension(const std::wstring& file_ext,
97 std::wstring* reg_description) {
98 DCHECK(reg_description);
99 base::win::RegKey reg_ext(HKEY_CLASSES_ROOT, file_ext.c_str(), KEY_READ);
100 std::wstring reg_app;
101 if (reg_ext.ReadValue(NULL, &reg_app) == ERROR_SUCCESS && !reg_app.empty()) {
102 base::win::RegKey reg_link(HKEY_CLASSES_ROOT, reg_app.c_str(), KEY_READ);
103 if (reg_link.ReadValue(NULL, reg_description) == ERROR_SUCCESS)
104 return true;
106 return false;
109 // Set up a filter for a Save/Open dialog, which will consist of |file_ext| file
110 // extensions (internally separated by semicolons), |ext_desc| as the text
111 // descriptions of the |file_ext| types (optional), and (optionally) the default
112 // 'All Files' view. The purpose of the filter is to show only files of a
113 // particular type in a Windows Save/Open dialog box. The resulting filter is
114 // returned. The filters created here are:
115 // 1. only files that have 'file_ext' as their extension
116 // 2. all files (only added if 'include_all_files' is true)
117 // Example:
118 // file_ext: { "*.txt", "*.htm;*.html" }
119 // ext_desc: { "Text Document" }
120 // returned: "Text Document\0*.txt\0HTML Document\0*.htm;*.html\0"
121 // "All Files\0*.*\0\0" (in one big string)
122 // If a description is not provided for a file extension, it will be retrieved
123 // from the registry. If the file extension does not exist in the registry, it
124 // will be omitted from the filter, as it is likely a bogus extension.
125 std::wstring FormatFilterForExtensions(
126 const std::vector<std::wstring>& file_ext,
127 const std::vector<std::wstring>& ext_desc,
128 bool include_all_files) {
129 const std::wstring all_ext = L"*.*";
130 const std::wstring all_desc =
131 l10n_util::GetStringUTF16(IDS_APP_SAVEAS_ALL_FILES);
133 DCHECK(file_ext.size() >= ext_desc.size());
135 if (file_ext.empty())
136 include_all_files = true;
138 std::wstring result;
140 for (size_t i = 0; i < file_ext.size(); ++i) {
141 std::wstring ext = file_ext[i];
142 std::wstring desc;
143 if (i < ext_desc.size())
144 desc = ext_desc[i];
146 if (ext.empty()) {
147 // Force something reasonable to appear in the dialog box if there is no
148 // extension provided.
149 include_all_files = true;
150 continue;
153 if (desc.empty()) {
154 DCHECK(ext.find(L'.') != std::wstring::npos);
155 std::wstring first_extension = ext.substr(ext.find(L'.'));
156 size_t first_separator_index = first_extension.find(L';');
157 if (first_separator_index != std::wstring::npos)
158 first_extension = first_extension.substr(0, first_separator_index);
160 // Find the extension name without the preceeding '.' character.
161 std::wstring ext_name = first_extension;
162 size_t ext_index = ext_name.find_first_not_of(L'.');
163 if (ext_index != std::wstring::npos)
164 ext_name = ext_name.substr(ext_index);
166 if (!GetRegistryDescriptionFromExtension(first_extension, &desc)) {
167 // The extension doesn't exist in the registry. Create a description
168 // based on the unknown extension type (i.e. if the extension is .qqq,
169 // the we create a description "QQQ File (.qqq)").
170 include_all_files = true;
171 desc = l10n_util::GetStringFUTF16(
172 IDS_APP_SAVEAS_EXTENSION_FORMAT,
173 base::i18n::ToUpper(WideToUTF16(ext_name)),
174 ext_name);
176 if (desc.empty())
177 desc = L"*." + ext_name;
180 result.append(desc.c_str(), desc.size() + 1); // Append NULL too.
181 result.append(ext.c_str(), ext.size() + 1);
184 if (include_all_files) {
185 result.append(all_desc.c_str(), all_desc.size() + 1);
186 result.append(all_ext.c_str(), all_ext.size() + 1);
189 result.append(1, '\0'); // Double NULL required.
190 return result;
193 // Enforce visible dialog box.
194 UINT_PTR CALLBACK SaveAsDialogHook(HWND dialog, UINT message,
195 WPARAM wparam, LPARAM lparam) {
196 static const UINT kPrivateMessage = 0x2F3F;
197 switch (message) {
198 case WM_INITDIALOG: {
199 // Do nothing here. Just post a message to defer actual processing.
200 PostMessage(dialog, kPrivateMessage, 0, 0);
201 return TRUE;
203 case kPrivateMessage: {
204 // The dialog box is the parent of the current handle.
205 HWND real_dialog = GetParent(dialog);
207 // Retrieve the final size.
208 RECT dialog_rect;
209 GetWindowRect(real_dialog, &dialog_rect);
211 // Verify that the upper left corner is visible.
212 POINT point = { dialog_rect.left, dialog_rect.top };
213 HMONITOR monitor1 = MonitorFromPoint(point, MONITOR_DEFAULTTONULL);
214 point.x = dialog_rect.right;
215 point.y = dialog_rect.bottom;
217 // Verify that the lower right corner is visible.
218 HMONITOR monitor2 = MonitorFromPoint(point, MONITOR_DEFAULTTONULL);
219 if (monitor1 && monitor2)
220 return 0;
222 // Some part of the dialog box is not visible, fix it by moving is to the
223 // client rect position of the browser window.
224 HWND parent_window = GetParent(real_dialog);
225 if (!parent_window)
226 return 0;
227 WINDOWINFO parent_info;
228 parent_info.cbSize = sizeof(WINDOWINFO);
229 GetWindowInfo(parent_window, &parent_info);
230 SetWindowPos(real_dialog, NULL,
231 parent_info.rcClient.left,
232 parent_info.rcClient.top,
233 0, 0, // Size.
234 SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOSIZE |
235 SWP_NOZORDER);
237 return 0;
240 return 0;
243 // Prompt the user for location to save a file.
244 // Callers should provide the filter string, and also a filter index.
245 // The parameter |index| indicates the initial index of filter description
246 // and filter pattern for the dialog box. If |index| is zero or greater than
247 // the number of total filter types, the system uses the first filter in the
248 // |filter| buffer. |index| is used to specify the initial selected extension,
249 // and when done contains the extension the user chose. The parameter
250 // |final_name| returns the file name which contains the drive designator,
251 // path, file name, and extension of the user selected file name. |def_ext| is
252 // the default extension to give to the file if the user did not enter an
253 // extension. If |ignore_suggested_ext| is true, any file extension contained in
254 // |suggested_name| will not be used to generate the file name. This is useful
255 // in the case of saving web pages, where we know the extension type already and
256 // where |suggested_name| may contain a '.' character as a valid part of the
257 // name, thus confusing our extension detection code.
258 bool SaveFileAsWithFilter(HWND owner,
259 const std::wstring& suggested_name,
260 const std::wstring& filter,
261 const std::wstring& def_ext,
262 bool ignore_suggested_ext,
263 unsigned* index,
264 std::wstring* final_name) {
265 DCHECK(final_name);
266 // Having an empty filter makes for a bad user experience. We should always
267 // specify a filter when saving.
268 DCHECK(!filter.empty());
269 const base::FilePath suggested_path(suggested_name);
270 std::wstring file_part = suggested_path.BaseName().value();
271 // If the suggested_name is a root directory, file_part will be '\', and the
272 // call to GetSaveFileName below will fail.
273 if (file_part.size() == 1 && file_part[0] == L'\\')
274 file_part.clear();
276 // The size of the in/out buffer in number of characters we pass to win32
277 // GetSaveFileName. From MSDN "The buffer must be large enough to store the
278 // path and file name string or strings, including the terminating NULL
279 // character. ... The buffer should be at least 256 characters long.".
280 // _IsValidPathComDlg does a copy expecting at most MAX_PATH, otherwise will
281 // result in an error of FNERR_INVALIDFILENAME. So we should only pass the
282 // API a buffer of at most MAX_PATH.
283 wchar_t file_name[MAX_PATH];
284 base::wcslcpy(file_name, file_part.c_str(), arraysize(file_name));
286 OPENFILENAME save_as;
287 // We must do this otherwise the ofn's FlagsEx may be initialized to random
288 // junk in release builds which can cause the Places Bar not to show up!
289 ZeroMemory(&save_as, sizeof(save_as));
290 save_as.lStructSize = sizeof(OPENFILENAME);
291 save_as.hwndOwner = owner;
292 save_as.hInstance = NULL;
294 save_as.lpstrFilter = filter.empty() ? NULL : filter.c_str();
296 save_as.lpstrCustomFilter = NULL;
297 save_as.nMaxCustFilter = 0;
298 save_as.nFilterIndex = *index;
299 save_as.lpstrFile = file_name;
300 save_as.nMaxFile = arraysize(file_name);
301 save_as.lpstrFileTitle = NULL;
302 save_as.nMaxFileTitle = 0;
304 // Set up the initial directory for the dialog.
305 std::wstring directory;
306 if (!suggested_name.empty()) {
307 if (IsDirectory(suggested_path)) {
308 directory = suggested_path.value();
309 file_part.clear();
310 } else {
311 directory = suggested_path.DirName().value();
315 save_as.lpstrInitialDir = directory.c_str();
316 save_as.lpstrTitle = NULL;
317 save_as.Flags = OFN_OVERWRITEPROMPT | OFN_EXPLORER | OFN_ENABLESIZING |
318 OFN_NOCHANGEDIR | OFN_PATHMUSTEXIST;
319 save_as.lpstrDefExt = &def_ext[0];
320 save_as.lCustData = NULL;
322 if (base::win::GetVersion() < base::win::VERSION_VISTA) {
323 // The save as on Windows XP remembers its last position,
324 // and if the screen resolution changed, it will be off screen.
325 save_as.Flags |= OFN_ENABLEHOOK;
326 save_as.lpfnHook = &SaveAsDialogHook;
329 // Must be NULL or 0.
330 save_as.pvReserved = NULL;
331 save_as.dwReserved = 0;
333 if (!CallGetSaveFileName(&save_as)) {
334 // Zero means the dialog was closed, otherwise we had an error.
335 DWORD error_code = CommDlgExtendedError();
336 if (error_code != 0) {
337 NOTREACHED() << "GetSaveFileName failed with code: " << error_code;
339 return false;
342 // Return the user's choice.
343 final_name->assign(save_as.lpstrFile);
344 *index = save_as.nFilterIndex;
346 // Figure out what filter got selected from the vector with embedded nulls.
347 // NOTE: The filter contains a string with embedded nulls, such as:
348 // JPG Image\0*.jpg\0All files\0*.*\0\0
349 // The filter index is 1-based index for which pair got selected. So, using
350 // the example above, if the first index was selected we need to skip 1
351 // instance of null to get to "*.jpg".
352 std::vector<std::wstring> filters;
353 if (!filter.empty() && save_as.nFilterIndex > 0)
354 base::SplitString(filter, '\0', &filters);
355 std::wstring filter_selected;
356 if (!filters.empty())
357 filter_selected = filters[(2 * (save_as.nFilterIndex - 1)) + 1];
359 // Get the extension that was suggested to the user (when the Save As dialog
360 // was opened). For saving web pages, we skip this step since there may be
361 // 'extension characters' in the title of the web page.
362 std::wstring suggested_ext;
363 if (!ignore_suggested_ext)
364 suggested_ext = GetExtensionWithoutLeadingDot(suggested_path.Extension());
366 // If we can't get the extension from the suggested_name, we use the default
367 // extension passed in. This is to cover cases like when saving a web page,
368 // where we get passed in a name without an extension and a default extension
369 // along with it.
370 if (suggested_ext.empty())
371 suggested_ext = def_ext;
373 *final_name =
374 ui::AppendExtensionIfNeeded(*final_name, filter_selected, suggested_ext);
375 return true;
378 // Prompt the user for location to save a file. 'suggested_name' is a full path
379 // that gives the dialog box a hint as to how to initialize itself.
380 // For example, a 'suggested_name' of:
381 // "C:\Documents and Settings\jojo\My Documents\picture.png"
382 // will start the dialog in the "C:\Documents and Settings\jojo\My Documents\"
383 // directory, and filter for .png file types.
384 // 'owner' is the window to which the dialog box is modal, NULL for a modeless
385 // dialog box.
386 // On success, returns true and 'final_name' contains the full path of the file
387 // that the user chose. On error, returns false, and 'final_name' is not
388 // modified.
389 bool SaveFileAs(HWND owner,
390 const std::wstring& suggested_name,
391 std::wstring* final_name) {
392 std::wstring file_ext =
393 base::FilePath(suggested_name).Extension().insert(0, L"*");
394 std::wstring filter = FormatFilterForExtensions(
395 std::vector<std::wstring>(1, file_ext),
396 std::vector<std::wstring>(),
397 true);
398 unsigned index = 1;
399 return SaveFileAsWithFilter(owner,
400 suggested_name,
401 filter,
402 L"",
403 false,
404 &index,
405 final_name);
408 // Implementation of SelectFileDialog that shows a Windows common dialog for
409 // choosing a file or folder.
410 class SelectFileDialogImpl : public ui::SelectFileDialog,
411 public ui::BaseShellDialogImpl {
412 public:
413 explicit SelectFileDialogImpl(Listener* listener,
414 ui::SelectFilePolicy* policy);
416 // BaseShellDialog implementation:
417 virtual bool IsRunning(gfx::NativeWindow owning_hwnd) const OVERRIDE;
418 virtual void ListenerDestroyed() OVERRIDE;
420 protected:
421 // SelectFileDialog implementation:
422 virtual void SelectFileImpl(
423 Type type,
424 const string16& title,
425 const base::FilePath& default_path,
426 const FileTypeInfo* file_types,
427 int file_type_index,
428 const base::FilePath::StringType& default_extension,
429 gfx::NativeWindow owning_window,
430 void* params) OVERRIDE;
432 private:
433 virtual ~SelectFileDialogImpl();
435 // A struct for holding all the state necessary for displaying a Save dialog.
436 struct ExecuteSelectParams {
437 ExecuteSelectParams(Type type,
438 const std::wstring& title,
439 const base::FilePath& default_path,
440 const FileTypeInfo* file_types,
441 int file_type_index,
442 const std::wstring& default_extension,
443 RunState run_state,
444 HWND owner,
445 void* params)
446 : type(type),
447 title(title),
448 default_path(default_path),
449 file_type_index(file_type_index),
450 default_extension(default_extension),
451 run_state(run_state),
452 ui_proxy(MessageLoopForUI::current()->message_loop_proxy()),
453 owner(owner),
454 params(params) {
455 if (file_types)
456 this->file_types = *file_types;
458 SelectFileDialog::Type type;
459 std::wstring title;
460 base::FilePath default_path;
461 FileTypeInfo file_types;
462 int file_type_index;
463 std::wstring default_extension;
464 RunState run_state;
465 scoped_refptr<base::MessageLoopProxy> ui_proxy;
466 HWND owner;
467 void* params;
470 // Shows the file selection dialog modal to |owner| and calls the result
471 // back on the ui thread. Run on the dialog thread.
472 void ExecuteSelectFile(const ExecuteSelectParams& params);
474 // Notifies the listener that a folder was chosen. Run on the ui thread.
475 void FileSelected(const base::FilePath& path, int index,
476 void* params, RunState run_state);
478 // Notifies listener that multiple files were chosen. Run on the ui thread.
479 void MultiFilesSelected(const std::vector<base::FilePath>& paths,
480 void* params,
481 RunState run_state);
483 // Notifies the listener that no file was chosen (the action was canceled).
484 // Run on the ui thread.
485 void FileNotSelected(void* params, RunState run_state);
487 // Runs a Folder selection dialog box, passes back the selected folder in
488 // |path| and returns true if the user clicks OK. If the user cancels the
489 // dialog box the value in |path| is not modified and returns false. |title|
490 // is the user-supplied title text to show for the dialog box. Run on the
491 // dialog thread.
492 bool RunSelectFolderDialog(const std::wstring& title,
493 HWND owner,
494 base::FilePath* path);
496 // Runs an Open file dialog box, with similar semantics for input paramaters
497 // as RunSelectFolderDialog.
498 bool RunOpenFileDialog(const std::wstring& title,
499 const std::wstring& filters,
500 HWND owner,
501 base::FilePath* path);
503 // Runs an Open file dialog box that supports multi-select, with similar
504 // semantics for input paramaters as RunOpenFileDialog.
505 bool RunOpenMultiFileDialog(const std::wstring& title,
506 const std::wstring& filter,
507 HWND owner,
508 std::vector<base::FilePath>* paths);
510 // The callback function for when the select folder dialog is opened.
511 static int CALLBACK BrowseCallbackProc(HWND window, UINT message,
512 LPARAM parameter,
513 LPARAM data);
515 virtual bool HasMultipleFileTypeChoicesImpl() OVERRIDE;
517 // Returns the filter to be used while displaying the open/save file dialog.
518 // This is computed from the extensions for the file types being opened.
519 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(
537 Type type,
538 const string16& title,
539 const base::FilePath& default_path,
540 const FileTypeInfo* file_types,
541 int file_type_index,
542 const base::FilePath::StringType& default_extension,
543 gfx::NativeWindow owning_window,
544 void* params) {
545 has_multiple_file_type_choices_ =
546 file_types ? file_types->extensions.size() > 1 : true;
547 #if defined(USE_AURA)
548 // If the owning_window passed in is in metro then we need to forward the
549 // file open/save operations to metro.
550 if (GetShellDialogsDelegate() &&
551 GetShellDialogsDelegate()->IsWindowInMetro(owning_window)) {
552 if (type == SELECT_SAVEAS_FILE) {
553 aura::HandleSaveFile(
554 UTF16ToWide(title),
555 default_path,
556 GetFilterForFileTypes(*file_types),
557 file_type_index,
558 default_extension,
559 base::Bind(&ui::SelectFileDialog::Listener::FileSelected,
560 base::Unretained(listener_)));
561 return;
562 } else if (type == SELECT_OPEN_FILE) {
563 aura::HandleOpenFile(
564 UTF16ToWide(title),
565 default_path,
566 GetFilterForFileTypes(*file_types),
567 base::Bind(&ui::SelectFileDialog::Listener::FileSelected,
568 base::Unretained(listener_)));
569 return;
570 } else if (type == SELECT_OPEN_MULTI_FILE) {
571 aura::HandleOpenMultipleFiles(
572 UTF16ToWide(title),
573 default_path,
574 GetFilterForFileTypes(*file_types),
575 base::Bind(&ui::SelectFileDialog::Listener::MultiFilesSelected,
576 base::Unretained(listener_)));
577 return;
580 HWND owner = owning_window
581 ? owning_window->GetRootWindow()->GetAcceleratedWidget() : NULL;
582 #else
583 HWND owner = owning_window;
584 #endif
585 ExecuteSelectParams execute_params(type, UTF16ToWide(title), default_path,
586 file_types, file_type_index,
587 default_extension, BeginRun(owner),
588 owner, params);
589 execute_params.run_state.dialog_thread->message_loop()->PostTask(
590 FROM_HERE,
591 base::Bind(&SelectFileDialogImpl::ExecuteSelectFile, this,
592 execute_params));
595 bool SelectFileDialogImpl::HasMultipleFileTypeChoicesImpl() {
596 return has_multiple_file_type_choices_;
599 bool SelectFileDialogImpl::IsRunning(gfx::NativeWindow owning_hwnd) const {
600 #if defined(USE_AURA)
601 HWND owner = owning_hwnd->GetRootWindow()->GetAcceleratedWidget();
602 #else
603 HWND owner = owning_hwnd;
604 #endif
605 return listener_ && IsRunningDialogForOwner(owner);
608 void SelectFileDialogImpl::ListenerDestroyed() {
609 // Our associated listener has gone away, so we shouldn't call back to it if
610 // our worker thread returns after the listener is dead.
611 listener_ = NULL;
614 void SelectFileDialogImpl::ExecuteSelectFile(
615 const ExecuteSelectParams& params) {
616 string16 filter = GetFilterForFileTypes(params.file_types);
618 base::FilePath path = params.default_path;
619 bool success = false;
620 unsigned filter_index = params.file_type_index;
621 if (params.type == SELECT_FOLDER) {
622 success = RunSelectFolderDialog(params.title,
623 params.run_state.owner,
624 &path);
625 } else if (params.type == SELECT_SAVEAS_FILE) {
626 std::wstring path_as_wstring = path.value();
627 success = SaveFileAsWithFilter(params.run_state.owner,
628 params.default_path.value(), filter,
629 params.default_extension, false, &filter_index, &path_as_wstring);
630 if (success)
631 path = base::FilePath(path_as_wstring);
632 DisableOwner(params.run_state.owner);
633 } else if (params.type == SELECT_OPEN_FILE) {
634 success = RunOpenFileDialog(params.title, filter,
635 params.run_state.owner, &path);
636 } else if (params.type == SELECT_OPEN_MULTI_FILE) {
637 std::vector<base::FilePath> paths;
638 if (RunOpenMultiFileDialog(params.title, filter,
639 params.run_state.owner, &paths)) {
640 params.ui_proxy->PostTask(
641 FROM_HERE,
642 base::Bind(&SelectFileDialogImpl::MultiFilesSelected, this, paths,
643 params.params, params.run_state));
644 return;
648 if (success) {
649 params.ui_proxy->PostTask(
650 FROM_HERE,
651 base::Bind(&SelectFileDialogImpl::FileSelected, this, path,
652 filter_index, params.params, params.run_state));
653 } else {
654 params.ui_proxy->PostTask(
655 FROM_HERE,
656 base::Bind(&SelectFileDialogImpl::FileNotSelected, this, params.params,
657 params.run_state));
661 void SelectFileDialogImpl::FileSelected(const base::FilePath& selected_folder,
662 int index,
663 void* params,
664 RunState run_state) {
665 if (listener_)
666 listener_->FileSelected(selected_folder, index, params);
667 EndRun(run_state);
670 void SelectFileDialogImpl::MultiFilesSelected(
671 const std::vector<base::FilePath>& selected_files,
672 void* params,
673 RunState run_state) {
674 if (listener_)
675 listener_->MultiFilesSelected(selected_files, params);
676 EndRun(run_state);
679 void SelectFileDialogImpl::FileNotSelected(void* params, RunState run_state) {
680 if (listener_)
681 listener_->FileSelectionCanceled(params);
682 EndRun(run_state);
685 int CALLBACK SelectFileDialogImpl::BrowseCallbackProc(HWND window,
686 UINT message,
687 LPARAM parameter,
688 LPARAM data) {
689 if (message == BFFM_INITIALIZED) {
690 // WParam is TRUE since passing a path.
691 // data lParam member of the BROWSEINFO structure.
692 SendMessage(window, BFFM_SETSELECTION, TRUE, (LPARAM)data);
694 return 0;
697 bool SelectFileDialogImpl::RunSelectFolderDialog(const std::wstring& title,
698 HWND owner,
699 base::FilePath* path) {
700 DCHECK(path);
702 wchar_t dir_buffer[MAX_PATH + 1];
704 bool result = false;
705 BROWSEINFO browse_info = {0};
706 browse_info.hwndOwner = owner;
707 browse_info.lpszTitle = title.c_str();
708 browse_info.pszDisplayName = dir_buffer;
709 browse_info.ulFlags = BIF_USENEWUI | BIF_RETURNONLYFSDIRS;
711 if (path->value().length()) {
712 // Highlight the current value.
713 browse_info.lParam = (LPARAM)path->value().c_str();
714 browse_info.lpfn = &BrowseCallbackProc;
717 LPITEMIDLIST list = SHBrowseForFolder(&browse_info);
718 DisableOwner(owner);
719 if (list) {
720 STRRET out_dir_buffer;
721 ZeroMemory(&out_dir_buffer, sizeof(out_dir_buffer));
722 out_dir_buffer.uType = STRRET_WSTR;
723 base::win::ScopedComPtr<IShellFolder> shell_folder;
724 if (SHGetDesktopFolder(shell_folder.Receive()) == NOERROR) {
725 HRESULT hr = shell_folder->GetDisplayNameOf(list, SHGDN_FORPARSING,
726 &out_dir_buffer);
727 if (SUCCEEDED(hr) && out_dir_buffer.uType == STRRET_WSTR) {
728 *path = base::FilePath(out_dir_buffer.pOleStr);
729 CoTaskMemFree(out_dir_buffer.pOleStr);
730 result = true;
731 } else {
732 // Use old way if we don't get what we want.
733 wchar_t old_out_dir_buffer[MAX_PATH + 1];
734 if (SHGetPathFromIDList(list, old_out_dir_buffer)) {
735 *path = base::FilePath(old_out_dir_buffer);
736 result = true;
740 // According to MSDN, win2000 will not resolve shortcuts, so we do it
741 // ourself.
742 base::win::ResolveShortcut(*path, path, NULL);
744 CoTaskMemFree(list);
746 return result;
749 bool SelectFileDialogImpl::RunOpenFileDialog(
750 const std::wstring& title,
751 const std::wstring& filter,
752 HWND owner,
753 base::FilePath* path) {
754 OPENFILENAME ofn;
755 // We must do this otherwise the ofn's FlagsEx may be initialized to random
756 // junk in release builds which can cause the Places Bar not to show up!
757 ZeroMemory(&ofn, sizeof(ofn));
758 ofn.lStructSize = sizeof(ofn);
759 ofn.hwndOwner = owner;
761 wchar_t filename[MAX_PATH];
762 // According to http://support.microsoft.com/?scid=kb;en-us;222003&x=8&y=12,
763 // The lpstrFile Buffer MUST be NULL Terminated.
764 filename[0] = 0;
765 // Define the dir in here to keep the string buffer pointer pointed to
766 // ofn.lpstrInitialDir available during the period of running the
767 // GetOpenFileName.
768 base::FilePath dir;
769 // Use lpstrInitialDir to specify the initial directory
770 if (!path->empty()) {
771 if (IsDirectory(*path)) {
772 ofn.lpstrInitialDir = path->value().c_str();
773 } else {
774 dir = path->DirName();
775 ofn.lpstrInitialDir = dir.value().c_str();
776 // Only pure filename can be put in lpstrFile field.
777 base::wcslcpy(filename, path->BaseName().value().c_str(),
778 arraysize(filename));
782 ofn.lpstrFile = filename;
783 ofn.nMaxFile = MAX_PATH;
785 // We use OFN_NOCHANGEDIR so that the user can rename or delete the directory
786 // without having to close Chrome first.
787 ofn.Flags = OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR;
789 if (!filter.empty())
790 ofn.lpstrFilter = filter.c_str();
791 bool success = CallGetOpenFileName(&ofn);
792 DisableOwner(owner);
793 if (success)
794 *path = base::FilePath(filename);
795 return success;
798 bool SelectFileDialogImpl::RunOpenMultiFileDialog(
799 const std::wstring& title,
800 const std::wstring& filter,
801 HWND owner,
802 std::vector<base::FilePath>* paths) {
803 OPENFILENAME ofn;
804 // We must do this otherwise the ofn's FlagsEx may be initialized to random
805 // junk in release builds which can cause the Places Bar not to show up!
806 ZeroMemory(&ofn, sizeof(ofn));
807 ofn.lStructSize = sizeof(ofn);
808 ofn.hwndOwner = owner;
810 scoped_ptr<wchar_t[]> filename(new wchar_t[UNICODE_STRING_MAX_CHARS]);
811 filename[0] = 0;
813 ofn.lpstrFile = filename.get();
814 ofn.nMaxFile = UNICODE_STRING_MAX_CHARS;
815 // We use OFN_NOCHANGEDIR so that the user can rename or delete the directory
816 // without having to close Chrome first.
817 ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_EXPLORER
818 | OFN_HIDEREADONLY | OFN_ALLOWMULTISELECT;
820 if (!filter.empty()) {
821 ofn.lpstrFilter = filter.c_str();
824 bool success = CallGetOpenFileName(&ofn);
825 DisableOwner(owner);
826 if (success) {
827 std::vector<base::FilePath> files;
828 const wchar_t* selection = ofn.lpstrFile;
829 while (*selection) { // Empty string indicates end of list.
830 files.push_back(base::FilePath(selection));
831 // Skip over filename and null-terminator.
832 selection += files.back().value().length() + 1;
834 if (files.empty()) {
835 success = false;
836 } else if (files.size() == 1) {
837 // When there is one file, it contains the path and filename.
838 paths->swap(files);
839 } else {
840 // Otherwise, the first string is the path, and the remainder are
841 // filenames.
842 std::vector<base::FilePath>::iterator path = files.begin();
843 for (std::vector<base::FilePath>::iterator file = path + 1;
844 file != files.end(); ++file) {
845 paths->push_back(path->Append(*file));
849 return success;
852 string16 SelectFileDialogImpl::GetFilterForFileTypes(
853 const FileTypeInfo& file_types) {
854 std::vector<string16> exts;
855 for (size_t i = 0; i < file_types.extensions.size(); ++i) {
856 const std::vector<string16>& inner_exts = file_types.extensions[i];
857 string16 ext_string;
858 for (size_t j = 0; j < inner_exts.size(); ++j) {
859 if (!ext_string.empty())
860 ext_string.push_back(L';');
861 ext_string.append(L"*.");
862 ext_string.append(inner_exts[j]);
864 exts.push_back(ext_string);
866 return FormatFilterForExtensions(
867 exts,
868 file_types.extension_description_overrides,
869 file_types.include_all_files);
872 } // namespace
874 namespace ui {
876 // This function takes the output of a SaveAs dialog: a filename, a filter and
877 // the extension originally suggested to the user (shown in the dialog box) and
878 // returns back the filename with the appropriate extension tacked on. If the
879 // user requests an unknown extension and is not using the 'All files' filter,
880 // the suggested extension will be appended, otherwise we will leave the
881 // filename unmodified. |filename| should contain the filename selected in the
882 // SaveAs dialog box and may include the path, |filter_selected| should be
883 // '*.something', for example '*.*' or it can be blank (which is treated as
884 // *.*). |suggested_ext| should contain the extension without the dot (.) in
885 // front, for example 'jpg'.
886 std::wstring AppendExtensionIfNeeded(
887 const std::wstring& filename,
888 const std::wstring& filter_selected,
889 const std::wstring& suggested_ext) {
890 DCHECK(!filename.empty());
891 std::wstring return_value = filename;
893 // If we wanted a specific extension, but the user's filename deleted it or
894 // changed it to something that the system doesn't understand, re-append.
895 // Careful: Checking net::GetMimeTypeFromExtension() will only find
896 // extensions with a known MIME type, which many "known" extensions on Windows
897 // don't have. So we check directly for the "known extension" registry key.
898 std::wstring file_extension(
899 GetExtensionWithoutLeadingDot(base::FilePath(filename).Extension()));
900 std::wstring key(L"." + file_extension);
901 if (!(filter_selected.empty() || filter_selected == L"*.*") &&
902 !base::win::RegKey(HKEY_CLASSES_ROOT, key.c_str(), KEY_READ).Valid() &&
903 file_extension != suggested_ext) {
904 if (return_value[return_value.length() - 1] != L'.')
905 return_value.append(L".");
906 return_value.append(suggested_ext);
909 // Strip any trailing dots, which Windows doesn't allow.
910 size_t index = return_value.find_last_not_of(L'.');
911 if (index < return_value.size() - 1)
912 return_value.resize(index + 1);
914 return return_value;
917 SelectFileDialog* CreateWinSelectFileDialog(
918 SelectFileDialog::Listener* listener,
919 SelectFilePolicy* policy) {
920 return new SelectFileDialogImpl(listener, policy);
923 } // namespace ui