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