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_root_window_host_win.h"
36#include "ui/aura/root_window.h"
37#include "ui/aura/window.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::PlatformFileInfo 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(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  base::string16 GetFilterForFileTypes(const FileTypeInfo& file_types);
521
522  bool has_multiple_file_type_choices_;
523
524  DISALLOW_COPY_AND_ASSIGN(SelectFileDialogImpl);
525};
526
527SelectFileDialogImpl::SelectFileDialogImpl(Listener* listener,
528                                           ui::SelectFilePolicy* policy)
529    : SelectFileDialog(listener, policy),
530      BaseShellDialogImpl(),
531      has_multiple_file_type_choices_(false) {
532}
533
534SelectFileDialogImpl::~SelectFileDialogImpl() {
535}
536
537void SelectFileDialogImpl::SelectFileImpl(
538    Type type,
539    const base::string16& title,
540    const base::FilePath& default_path,
541    const FileTypeInfo* file_types,
542    int file_type_index,
543    const base::FilePath::StringType& default_extension,
544    gfx::NativeWindow owning_window,
545    void* params) {
546  has_multiple_file_type_choices_ =
547      file_types ? file_types->extensions.size() > 1 : true;
548#if defined(USE_AURA)
549  // If the owning_window passed in is in metro then we need to forward the
550  // file open/save operations to metro.
551  if (GetShellDialogsDelegate() &&
552      GetShellDialogsDelegate()->IsWindowInMetro(owning_window)) {
553    if (type == SELECT_SAVEAS_FILE) {
554      aura::HandleSaveFile(
555          UTF16ToWide(title),
556          default_path,
557          GetFilterForFileTypes(*file_types),
558          file_type_index,
559          default_extension,
560          base::Bind(&ui::SelectFileDialog::Listener::FileSelected,
561                     base::Unretained(listener_)),
562          base::Bind(&ui::SelectFileDialog::Listener::FileSelectionCanceled,
563                     base::Unretained(listener_)));
564      return;
565    } else if (type == SELECT_OPEN_FILE) {
566      aura::HandleOpenFile(
567          UTF16ToWide(title),
568          default_path,
569          GetFilterForFileTypes(*file_types),
570          base::Bind(&ui::SelectFileDialog::Listener::FileSelected,
571                     base::Unretained(listener_)),
572          base::Bind(&ui::SelectFileDialog::Listener::FileSelectionCanceled,
573                     base::Unretained(listener_)));
574      return;
575    } else if (type == SELECT_OPEN_MULTI_FILE) {
576      aura::HandleOpenMultipleFiles(
577          UTF16ToWide(title),
578          default_path,
579          GetFilterForFileTypes(*file_types),
580          base::Bind(&ui::SelectFileDialog::Listener::MultiFilesSelected,
581                     base::Unretained(listener_)),
582          base::Bind(&ui::SelectFileDialog::Listener::FileSelectionCanceled,
583                     base::Unretained(listener_)));
584      return;
585    } else if (type == SELECT_FOLDER || type == SELECT_UPLOAD_FOLDER) {
586      base::string16 title_string = title;
587      if (type == SELECT_UPLOAD_FOLDER && title_string.empty()) {
588        // If it's for uploading don't use default dialog title to
589        // make sure we clearly tell it's for uploading.
590        title_string = l10n_util::GetStringUTF16(
591            IDS_SELECT_UPLOAD_FOLDER_DIALOG_TITLE);
592      }
593      aura::HandleSelectFolder(
594          UTF16ToWide(title_string),
595          base::Bind(&ui::SelectFileDialog::Listener::FileSelected,
596                     base::Unretained(listener_)),
597          base::Bind(&ui::SelectFileDialog::Listener::FileSelectionCanceled,
598                     base::Unretained(listener_)));
599      return;
600    }
601  }
602  HWND owner = owning_window && owning_window->GetRootWindow()
603      ? owning_window->GetDispatcher()->host()->GetAcceleratedWidget() : NULL;
604#else
605  HWND owner = owning_window;
606#endif
607  ExecuteSelectParams execute_params(type, UTF16ToWide(title), default_path,
608                                     file_types, file_type_index,
609                                     default_extension, BeginRun(owner),
610                                     owner, params);
611  execute_params.run_state.dialog_thread->message_loop()->PostTask(
612      FROM_HERE,
613      base::Bind(&SelectFileDialogImpl::ExecuteSelectFile, this,
614                 execute_params));
615}
616
617bool SelectFileDialogImpl::HasMultipleFileTypeChoicesImpl() {
618  return has_multiple_file_type_choices_;
619}
620
621bool SelectFileDialogImpl::IsRunning(gfx::NativeWindow owning_window) const {
622#if defined(USE_AURA)
623  if (!owning_window->GetRootWindow())
624    return false;
625  HWND owner = owning_window->GetDispatcher()->host()->GetAcceleratedWidget();
626#else
627  HWND owner = owning_window;
628#endif
629  return listener_ && IsRunningDialogForOwner(owner);
630}
631
632void SelectFileDialogImpl::ListenerDestroyed() {
633  // Our associated listener has gone away, so we shouldn't call back to it if
634  // our worker thread returns after the listener is dead.
635  listener_ = NULL;
636}
637
638void SelectFileDialogImpl::ExecuteSelectFile(
639    const ExecuteSelectParams& params) {
640  base::string16 filter = GetFilterForFileTypes(params.file_types);
641
642  base::FilePath path = params.default_path;
643  bool success = false;
644  unsigned filter_index = params.file_type_index;
645  if (params.type == SELECT_FOLDER || params.type == SELECT_UPLOAD_FOLDER) {
646    std::wstring title = params.title;
647    if (title.empty() && params.type == SELECT_UPLOAD_FOLDER) {
648      // If it's for uploading don't use default dialog title to
649      // make sure we clearly tell it's for uploading.
650      title = UTF16ToWide(
651          l10n_util::GetStringUTF16(IDS_SELECT_UPLOAD_FOLDER_DIALOG_TITLE));
652    }
653    success = RunSelectFolderDialog(title,
654                                    params.run_state.owner,
655                                    &path);
656  } else if (params.type == SELECT_SAVEAS_FILE) {
657    std::wstring path_as_wstring = path.value();
658    success = SaveFileAsWithFilter(params.run_state.owner,
659        params.default_path.value(), filter,
660        params.default_extension, false, &filter_index, &path_as_wstring);
661    if (success)
662      path = base::FilePath(path_as_wstring);
663    DisableOwner(params.run_state.owner);
664  } else if (params.type == SELECT_OPEN_FILE) {
665    success = RunOpenFileDialog(params.title, filter,
666                                params.run_state.owner, &path);
667  } else if (params.type == SELECT_OPEN_MULTI_FILE) {
668    std::vector<base::FilePath> paths;
669    if (RunOpenMultiFileDialog(params.title, filter,
670                               params.run_state.owner, &paths)) {
671      params.ui_proxy->PostTask(
672          FROM_HERE,
673          base::Bind(&SelectFileDialogImpl::MultiFilesSelected, this, paths,
674                     params.params, params.run_state));
675      return;
676    }
677  }
678
679  if (success) {
680      params.ui_proxy->PostTask(
681        FROM_HERE,
682        base::Bind(&SelectFileDialogImpl::FileSelected, this, path,
683                   filter_index, params.params, params.run_state));
684  } else {
685      params.ui_proxy->PostTask(
686        FROM_HERE,
687        base::Bind(&SelectFileDialogImpl::FileNotSelected, this, params.params,
688                   params.run_state));
689  }
690}
691
692void SelectFileDialogImpl::FileSelected(const base::FilePath& selected_folder,
693                                        int index,
694                                        void* params,
695                                        RunState run_state) {
696  if (listener_)
697    listener_->FileSelected(selected_folder, index, params);
698  EndRun(run_state);
699}
700
701void SelectFileDialogImpl::MultiFilesSelected(
702    const std::vector<base::FilePath>& selected_files,
703    void* params,
704    RunState run_state) {
705  if (listener_)
706    listener_->MultiFilesSelected(selected_files, params);
707  EndRun(run_state);
708}
709
710void SelectFileDialogImpl::FileNotSelected(void* params, RunState run_state) {
711  if (listener_)
712    listener_->FileSelectionCanceled(params);
713  EndRun(run_state);
714}
715
716int CALLBACK SelectFileDialogImpl::BrowseCallbackProc(HWND window,
717                                                      UINT message,
718                                                      LPARAM parameter,
719                                                      LPARAM data) {
720  if (message == BFFM_INITIALIZED) {
721    // WParam is TRUE since passing a path.
722    // data lParam member of the BROWSEINFO structure.
723    SendMessage(window, BFFM_SETSELECTION, TRUE, (LPARAM)data);
724  }
725  return 0;
726}
727
728bool SelectFileDialogImpl::RunSelectFolderDialog(const std::wstring& title,
729                                                 HWND owner,
730                                                 base::FilePath* path) {
731  DCHECK(path);
732
733  wchar_t dir_buffer[MAX_PATH + 1];
734
735  bool result = false;
736  BROWSEINFO browse_info = {0};
737  browse_info.hwndOwner = owner;
738  browse_info.lpszTitle = title.c_str();
739  browse_info.pszDisplayName = dir_buffer;
740  browse_info.ulFlags = BIF_USENEWUI | BIF_RETURNONLYFSDIRS;
741
742  if (path->value().length()) {
743    // Highlight the current value.
744    browse_info.lParam = (LPARAM)path->value().c_str();
745    browse_info.lpfn = &BrowseCallbackProc;
746  }
747
748  LPITEMIDLIST list = SHBrowseForFolder(&browse_info);
749  DisableOwner(owner);
750  if (list) {
751    STRRET out_dir_buffer;
752    ZeroMemory(&out_dir_buffer, sizeof(out_dir_buffer));
753    out_dir_buffer.uType = STRRET_WSTR;
754    base::win::ScopedComPtr<IShellFolder> shell_folder;
755    if (SHGetDesktopFolder(shell_folder.Receive()) == NOERROR) {
756      HRESULT hr = shell_folder->GetDisplayNameOf(list, SHGDN_FORPARSING,
757                                                  &out_dir_buffer);
758      if (SUCCEEDED(hr) && out_dir_buffer.uType == STRRET_WSTR) {
759        *path = base::FilePath(out_dir_buffer.pOleStr);
760        CoTaskMemFree(out_dir_buffer.pOleStr);
761        result = true;
762      } else {
763        // Use old way if we don't get what we want.
764        wchar_t old_out_dir_buffer[MAX_PATH + 1];
765        if (SHGetPathFromIDList(list, old_out_dir_buffer)) {
766          *path = base::FilePath(old_out_dir_buffer);
767          result = true;
768        }
769      }
770
771      // According to MSDN, win2000 will not resolve shortcuts, so we do it
772      // ourself.
773      base::win::ResolveShortcut(*path, path, NULL);
774    }
775    CoTaskMemFree(list);
776  }
777  return result;
778}
779
780bool SelectFileDialogImpl::RunOpenFileDialog(
781    const std::wstring& title,
782    const std::wstring& filter,
783    HWND owner,
784    base::FilePath* path) {
785  OPENFILENAME ofn;
786  // We must do this otherwise the ofn's FlagsEx may be initialized to random
787  // junk in release builds which can cause the Places Bar not to show up!
788  ZeroMemory(&ofn, sizeof(ofn));
789  ofn.lStructSize = sizeof(ofn);
790  ofn.hwndOwner = owner;
791
792  wchar_t filename[MAX_PATH];
793  // According to http://support.microsoft.com/?scid=kb;en-us;222003&x=8&y=12,
794  // The lpstrFile Buffer MUST be NULL Terminated.
795  filename[0] = 0;
796  // Define the dir in here to keep the string buffer pointer pointed to
797  // ofn.lpstrInitialDir available during the period of running the
798  // GetOpenFileName.
799  base::FilePath dir;
800  // Use lpstrInitialDir to specify the initial directory
801  if (!path->empty()) {
802    if (IsDirectory(*path)) {
803      ofn.lpstrInitialDir = path->value().c_str();
804    } else {
805      dir = path->DirName();
806      ofn.lpstrInitialDir = dir.value().c_str();
807      // Only pure filename can be put in lpstrFile field.
808      base::wcslcpy(filename, path->BaseName().value().c_str(),
809                    arraysize(filename));
810    }
811  }
812
813  ofn.lpstrFile = filename;
814  ofn.nMaxFile = MAX_PATH;
815
816  // We use OFN_NOCHANGEDIR so that the user can rename or delete the directory
817  // without having to close Chrome first.
818  ofn.Flags = OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR;
819
820  if (!filter.empty())
821    ofn.lpstrFilter = filter.c_str();
822  bool success = CallGetOpenFileName(&ofn);
823  DisableOwner(owner);
824  if (success)
825    *path = base::FilePath(filename);
826  return success;
827}
828
829bool SelectFileDialogImpl::RunOpenMultiFileDialog(
830    const std::wstring& title,
831    const std::wstring& filter,
832    HWND owner,
833    std::vector<base::FilePath>* paths) {
834  OPENFILENAME ofn;
835  // We must do this otherwise the ofn's FlagsEx may be initialized to random
836  // junk in release builds which can cause the Places Bar not to show up!
837  ZeroMemory(&ofn, sizeof(ofn));
838  ofn.lStructSize = sizeof(ofn);
839  ofn.hwndOwner = owner;
840
841  scoped_ptr<wchar_t[]> filename(new wchar_t[UNICODE_STRING_MAX_CHARS]);
842  filename[0] = 0;
843
844  ofn.lpstrFile = filename.get();
845  ofn.nMaxFile = UNICODE_STRING_MAX_CHARS;
846  // We use OFN_NOCHANGEDIR so that the user can rename or delete the directory
847  // without having to close Chrome first.
848  ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_EXPLORER
849               | OFN_HIDEREADONLY | OFN_ALLOWMULTISELECT | OFN_NOCHANGEDIR;
850
851  if (!filter.empty()) {
852    ofn.lpstrFilter = filter.c_str();
853  }
854
855  bool success = CallGetOpenFileName(&ofn);
856  DisableOwner(owner);
857  if (success) {
858    std::vector<base::FilePath> files;
859    const wchar_t* selection = ofn.lpstrFile;
860    while (*selection) {  // Empty string indicates end of list.
861      files.push_back(base::FilePath(selection));
862      // Skip over filename and null-terminator.
863      selection += files.back().value().length() + 1;
864    }
865    if (files.empty()) {
866      success = false;
867    } else if (files.size() == 1) {
868      // When there is one file, it contains the path and filename.
869      paths->swap(files);
870    } else {
871      // Otherwise, the first string is the path, and the remainder are
872      // filenames.
873      std::vector<base::FilePath>::iterator path = files.begin();
874      for (std::vector<base::FilePath>::iterator file = path + 1;
875           file != files.end(); ++file) {
876        paths->push_back(path->Append(*file));
877      }
878    }
879  }
880  return success;
881}
882
883base::string16 SelectFileDialogImpl::GetFilterForFileTypes(
884    const FileTypeInfo& file_types) {
885  std::vector<base::string16> exts;
886  for (size_t i = 0; i < file_types.extensions.size(); ++i) {
887    const std::vector<base::string16>& inner_exts = file_types.extensions[i];
888    base::string16 ext_string;
889    for (size_t j = 0; j < inner_exts.size(); ++j) {
890      if (!ext_string.empty())
891        ext_string.push_back(L';');
892      ext_string.append(L"*.");
893      ext_string.append(inner_exts[j]);
894    }
895    exts.push_back(ext_string);
896  }
897  return FormatFilterForExtensions(
898      exts,
899      file_types.extension_description_overrides,
900      file_types.include_all_files);
901}
902
903}  // namespace
904
905namespace ui {
906
907// This function takes the output of a SaveAs dialog: a filename, a filter and
908// the extension originally suggested to the user (shown in the dialog box) and
909// returns back the filename with the appropriate extension tacked on. If the
910// user requests an unknown extension and is not using the 'All files' filter,
911// the suggested extension will be appended, otherwise we will leave the
912// filename unmodified. |filename| should contain the filename selected in the
913// SaveAs dialog box and may include the path, |filter_selected| should be
914// '*.something', for example '*.*' or it can be blank (which is treated as
915// *.*). |suggested_ext| should contain the extension without the dot (.) in
916// front, for example 'jpg'.
917std::wstring AppendExtensionIfNeeded(
918    const std::wstring& filename,
919    const std::wstring& filter_selected,
920    const std::wstring& suggested_ext) {
921  DCHECK(!filename.empty());
922  std::wstring return_value = filename;
923
924  // If we wanted a specific extension, but the user's filename deleted it or
925  // changed it to something that the system doesn't understand, re-append.
926  // Careful: Checking net::GetMimeTypeFromExtension() will only find
927  // extensions with a known MIME type, which many "known" extensions on Windows
928  // don't have.  So we check directly for the "known extension" registry key.
929  std::wstring file_extension(
930      GetExtensionWithoutLeadingDot(base::FilePath(filename).Extension()));
931  std::wstring key(L"." + file_extension);
932  if (!(filter_selected.empty() || filter_selected == L"*.*") &&
933      !base::win::RegKey(HKEY_CLASSES_ROOT, key.c_str(), KEY_READ).Valid() &&
934      file_extension != suggested_ext) {
935    if (return_value[return_value.length() - 1] != L'.')
936      return_value.append(L".");
937    return_value.append(suggested_ext);
938  }
939
940  // Strip any trailing dots, which Windows doesn't allow.
941  size_t index = return_value.find_last_not_of(L'.');
942  if (index < return_value.size() - 1)
943    return_value.resize(index + 1);
944
945  return return_value;
946}
947
948SelectFileDialog* CreateWinSelectFileDialog(
949    SelectFileDialog::Listener* listener,
950    SelectFilePolicy* policy) {
951  return new SelectFileDialogImpl(listener, policy);
952}
953
954}  // namespace ui
955