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