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