select_file_dialog_win.cc revision 1e9bf3e0803691d0a228da41fc608347b6db4340
16d5ab866fc1492c12b1f2531bbe7dcdb55ac9e15Misha Brukman// Copyright (c) 2012 The Chromium Authors. All rights reserved.
26d5ab866fc1492c12b1f2531bbe7dcdb55ac9e15Misha Brukman// Use of this source code is governed by a BSD-style license that can be
36d5ab866fc1492c12b1f2531bbe7dcdb55ac9e15Misha Brukman// found in the LICENSE file.
46d5ab866fc1492c12b1f2531bbe7dcdb55ac9e15Misha Brukman
56d5ab866fc1492c12b1f2531bbe7dcdb55ac9e15Misha Brukman#include "ui/shell_dialogs/select_file_dialog_win.h"
66d5ab866fc1492c12b1f2531bbe7dcdb55ac9e15Misha Brukman
76d5ab866fc1492c12b1f2531bbe7dcdb55ac9e15Misha Brukman#include <windows.h>
86d5ab866fc1492c12b1f2531bbe7dcdb55ac9e15Misha Brukman#include <commdlg.h>
97a73b80b9052136c8cd2234eb3433a07df7cf38eJohn Criswell#include <shlobj.h>
107a73b80b9052136c8cd2234eb3433a07df7cf38eJohn Criswell
117a73b80b9052136c8cd2234eb3433a07df7cf38eJohn Criswell#include <algorithm>
12f1dd2004c07126944c9384d25e866215fd93c3bbBrian Gaeke#include <set>
136d5ab866fc1492c12b1f2531bbe7dcdb55ac9e15Misha Brukman
147a73b80b9052136c8cd2234eb3433a07df7cf38eJohn Criswell#include "base/bind.h"
15b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer#include "base/file_util.h"
16b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer#include "base/files/file_path.h"
17b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer#include "base/i18n/case_conversion.h"
18e1200219ec6f4d6ff7f54933ccad462c8dfdbb70Reid Spencer#include "base/message_loop/message_loop.h"
19b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer#include "base/message_loop/message_loop_proxy.h"
20b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer#include "base/strings/string_split.h"
21b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer#include "base/strings/utf_string_conversions.h"
22b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer#include "base/threading/thread.h"
23b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer#include "base/win/metro.h"
24b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer#include "base/win/registry.h"
25b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer#include "base/win/scoped_comptr.h"
26b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer#include "base/win/shortcut.h"
27b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer#include "base/win/windows_version.h"
28b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer#include "grit/ui_strings.h"
29b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer#include "ui/base/l10n/l10n_util.h"
30b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer#include "ui/gfx/native_widget_types.h"
31b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer#include "ui/shell_dialogs/base_shell_dialog_win.h"
32b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer#include "ui/shell_dialogs/shell_dialogs_delegate.h"
33b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer
34b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer#if defined(USE_AURA)
35b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer#include "ui/aura/remote_root_window_host_win.h"
36b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer#include "ui/aura/root_window.h"
37b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer#endif
38b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer
39b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencernamespace {
40b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer
41b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer// Given |extension|, if it's not empty, then remove the leading dot.
42b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencerstd::wstring GetExtensionWithoutLeadingDot(const std::wstring& extension) {
43b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer  DCHECK(extension.empty() || extension[0] == L'.');
44b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer  return extension.empty() ? extension : extension.substr(1);
45b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer}
46b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer
47b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer// Diverts to a metro-specific implementation as appropriate.
48153626a3c0598ea0b74b38e364184ab6c23ae1daReid Spencerbool CallGetOpenFileName(OPENFILENAME* ofn) {
49b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer  HMODULE metro_module = base::win::GetMetroModule();
50b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer  if (metro_module != NULL) {
51b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer    typedef BOOL (*MetroGetOpenFileName)(OPENFILENAME*);
52b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer    MetroGetOpenFileName metro_get_open_file_name =
53b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer        reinterpret_cast<MetroGetOpenFileName>(
54b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer            ::GetProcAddress(metro_module, "MetroGetOpenFileName"));
55b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer    if (metro_get_open_file_name == NULL) {
56b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer      NOTREACHED();
57b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer      return false;
58b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer    }
59b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer
60b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer    return metro_get_open_file_name(ofn) == TRUE;
61b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer  } else {
62b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer    return GetOpenFileName(ofn) == TRUE;
63b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer  }
64b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer}
65b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer
66b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer// Diverts to a metro-specific implementation as appropriate.
67b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencerbool CallGetSaveFileName(OPENFILENAME* ofn) {
68b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer  HMODULE metro_module = base::win::GetMetroModule();
69b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer  if (metro_module != NULL) {
70b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer    typedef BOOL (*MetroGetSaveFileName)(OPENFILENAME*);
71b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer    MetroGetSaveFileName metro_get_save_file_name =
72b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer        reinterpret_cast<MetroGetSaveFileName>(
73b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer            ::GetProcAddress(metro_module, "MetroGetSaveFileName"));
74b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer    if (metro_get_save_file_name == NULL) {
75b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer      NOTREACHED();
76b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer      return false;
77b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer    }
78b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer
79b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer    return metro_get_save_file_name(ofn) == TRUE;
80b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer  } else {
81b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer    return GetSaveFileName(ofn) == TRUE;
82b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer  }
83b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer}
84b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer
85b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer// Distinguish directories from regular files.
86b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencerbool IsDirectory(const base::FilePath& path) {
87b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer  base::PlatformFileInfo file_info;
88b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer  return file_util::GetFileInfo(path, &file_info) ?
89e1200219ec6f4d6ff7f54933ccad462c8dfdbb70Reid Spencer      file_info.is_directory : path.EndsWithSeparator();
90bbf7a8af5a7781cf0f721770ab81333f22c0f464Reid Spencer}
91bbf7a8af5a7781cf0f721770ab81333f22c0f464Reid Spencer
92bbf7a8af5a7781cf0f721770ab81333f22c0f464Reid Spencer// Get the file type description from the registry. This will be "Text Document"
93bbf7a8af5a7781cf0f721770ab81333f22c0f464Reid Spencer// for .txt files, "JPEG Image" for .jpg files, etc. If the registry doesn't
947a73b80b9052136c8cd2234eb3433a07df7cf38eJohn Criswell// have an entry for the file type, we return false, true if the description was
957a73b80b9052136c8cd2234eb3433a07df7cf38eJohn Criswell// found. 'file_ext' must be in form ".txt".
967a73b80b9052136c8cd2234eb3433a07df7cf38eJohn Criswellstatic bool GetRegistryDescriptionFromExtension(const std::wstring& file_ext,
977659545ceef542dc9951673e1f9085ef2d045699John Criswell                                                std::wstring* reg_description) {
987659545ceef542dc9951673e1f9085ef2d045699John Criswell  DCHECK(reg_description);
997659545ceef542dc9951673e1f9085ef2d045699John Criswell  base::win::RegKey reg_ext(HKEY_CLASSES_ROOT, file_ext.c_str(), KEY_READ);
10018224032d3b26cad39991fc569948f15cf5ed953Reid Spencer  std::wstring reg_app;
10118224032d3b26cad39991fc569948f15cf5ed953Reid Spencer  if (reg_ext.ReadValue(NULL, &reg_app) == ERROR_SUCCESS && !reg_app.empty()) {
10218224032d3b26cad39991fc569948f15cf5ed953Reid Spencer    base::win::RegKey reg_link(HKEY_CLASSES_ROOT, reg_app.c_str(), KEY_READ);
1035a870448d12a786098e9ec5018cd2bb3f5f673fdReid Spencer    if (reg_link.ReadValue(NULL, reg_description) == ERROR_SUCCESS)
1045a870448d12a786098e9ec5018cd2bb3f5f673fdReid Spencer      return true;
1055a870448d12a786098e9ec5018cd2bb3f5f673fdReid Spencer  }
1060021c31b60706f0a35f0858c112ebdc709f3d3e7John Criswell  return false;
1070021c31b60706f0a35f0858c112ebdc709f3d3e7John Criswell}
1080021c31b60706f0a35f0858c112ebdc709f3d3e7John Criswell
1097a73b80b9052136c8cd2234eb3433a07df7cf38eJohn Criswell// Set up a filter for a Save/Open dialog, which will consist of |file_ext| file
1107a73b80b9052136c8cd2234eb3433a07df7cf38eJohn Criswell// extensions (internally separated by semicolons), |ext_desc| as the text
1117a73b80b9052136c8cd2234eb3433a07df7cf38eJohn Criswell// descriptions of the |file_ext| types (optional), and (optionally) the default
1127a73b80b9052136c8cd2234eb3433a07df7cf38eJohn Criswell// 'All Files' view. The purpose of the filter is to show only files of a
113b5a2e40dd8f6b6550d4191f6d74edcb641d0153fMisha Brukman// particular type in a Windows Save/Open dialog box. The resulting filter is
1147a73b80b9052136c8cd2234eb3433a07df7cf38eJohn Criswell// returned. The filters created here are:
1157a73b80b9052136c8cd2234eb3433a07df7cf38eJohn Criswell//   1. only files that have 'file_ext' as their extension
116f1dd2004c07126944c9384d25e866215fd93c3bbBrian Gaeke//   2. all files (only added if 'include_all_files' is true)
117b812e76b56f96815c08b850fd688ff835862b22aJohn Criswell// Example:
11849bf862719c5ac24ddc9eafa35e51dd68904b1beJohn Criswell//   file_ext: { "*.txt", "*.htm;*.html" }
119f1dd2004c07126944c9384d25e866215fd93c3bbBrian Gaeke//   ext_desc: { "Text Document" }
1207a73b80b9052136c8cd2234eb3433a07df7cf38eJohn Criswell//   returned: "Text Document\0*.txt\0HTML Document\0*.htm;*.html\0"
1217a73b80b9052136c8cd2234eb3433a07df7cf38eJohn Criswell//             "All Files\0*.*\0\0" (in one big string)
122151f8ba3645defc371eb4b68427384e411305734Reid Spencer// If a description is not provided for a file extension, it will be retrieved
123e1200219ec6f4d6ff7f54933ccad462c8dfdbb70Reid Spencer// from the registry. If the file extension does not exist in the registry, it
1248a2d4718257aa1a97dad9f9f8cce719b539c694bReid Spencer// will be omitted from the filter, as it is likely a bogus extension.
1258a2d4718257aa1a97dad9f9f8cce719b539c694bReid Spencerstd::wstring FormatFilterForExtensions(
126e1200219ec6f4d6ff7f54933ccad462c8dfdbb70Reid Spencer    const std::vector<std::wstring>& file_ext,
127e1200219ec6f4d6ff7f54933ccad462c8dfdbb70Reid Spencer    const std::vector<std::wstring>& ext_desc,
128e1200219ec6f4d6ff7f54933ccad462c8dfdbb70Reid Spencer    bool include_all_files) {
129e1200219ec6f4d6ff7f54933ccad462c8dfdbb70Reid Spencer  const std::wstring all_ext = L"*.*";
130e1200219ec6f4d6ff7f54933ccad462c8dfdbb70Reid Spencer  const std::wstring all_desc =
131b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer      l10n_util::GetStringUTF16(IDS_APP_SAVEAS_ALL_FILES);
132e1200219ec6f4d6ff7f54933ccad462c8dfdbb70Reid Spencer
133e1200219ec6f4d6ff7f54933ccad462c8dfdbb70Reid Spencer  DCHECK(file_ext.size() >= ext_desc.size());
134e1200219ec6f4d6ff7f54933ccad462c8dfdbb70Reid Spencer
135e1200219ec6f4d6ff7f54933ccad462c8dfdbb70Reid Spencer  if (file_ext.empty())
136e1200219ec6f4d6ff7f54933ccad462c8dfdbb70Reid Spencer    include_all_files = true;
137e1200219ec6f4d6ff7f54933ccad462c8dfdbb70Reid Spencer
138e1200219ec6f4d6ff7f54933ccad462c8dfdbb70Reid Spencer  std::wstring result;
139e1200219ec6f4d6ff7f54933ccad462c8dfdbb70Reid Spencer
140b195d9d365e5f960c93ddfdf10638d5d147d9f6fReid Spencer  for (size_t i = 0; i < file_ext.size(); ++i) {
141e1200219ec6f4d6ff7f54933ccad462c8dfdbb70Reid Spencer    std::wstring ext = file_ext[i];
142e1200219ec6f4d6ff7f54933ccad462c8dfdbb70Reid Spencer    std::wstring desc;
143e1200219ec6f4d6ff7f54933ccad462c8dfdbb70Reid Spencer    if (i < ext_desc.size())
144e1200219ec6f4d6ff7f54933ccad462c8dfdbb70Reid Spencer      desc = ext_desc[i];
145e1200219ec6f4d6ff7f54933ccad462c8dfdbb70Reid Spencer
146e1200219ec6f4d6ff7f54933ccad462c8dfdbb70Reid Spencer    if (ext.empty()) {
147e1200219ec6f4d6ff7f54933ccad462c8dfdbb70Reid Spencer      // Force something reasonable to appear in the dialog box if there is no
148e1200219ec6f4d6ff7f54933ccad462c8dfdbb70Reid Spencer      // extension provided.
149e1200219ec6f4d6ff7f54933ccad462c8dfdbb70Reid Spencer      include_all_files = true;
150e1200219ec6f4d6ff7f54933ccad462c8dfdbb70Reid Spencer      continue;
1510fcb9410b9c51a179b3c7a80291f00dac344038cReid Spencer    }
152e1200219ec6f4d6ff7f54933ccad462c8dfdbb70Reid Spencer
1537a73b80b9052136c8cd2234eb3433a07df7cf38eJohn Criswell    if (desc.empty()) {
154b195d9d365e5f960c93ddfdf10638d5d147d9f6fReid Spencer      DCHECK(ext.find(L'.') != std::wstring::npos);
155b195d9d365e5f960c93ddfdf10638d5d147d9f6fReid Spencer      std::wstring first_extension = ext.substr(ext.find(L'.'));
1565a870448d12a786098e9ec5018cd2bb3f5f673fdReid Spencer      size_t first_separator_index = first_extension.find(L';');
1575a870448d12a786098e9ec5018cd2bb3f5f673fdReid Spencer      if (first_separator_index != std::wstring::npos)
1587908035f47ee637a2e9b585e3057b0f974dc75caReid Spencer        first_extension = first_extension.substr(0, first_separator_index);
1597908035f47ee637a2e9b585e3057b0f974dc75caReid Spencer
1607908035f47ee637a2e9b585e3057b0f974dc75caReid Spencer      // Find the extension name without the preceeding '.' character.
1617908035f47ee637a2e9b585e3057b0f974dc75caReid Spencer      std::wstring ext_name = first_extension;
1627a73b80b9052136c8cd2234eb3433a07df7cf38eJohn Criswell      size_t ext_index = ext_name.find_first_not_of(L'.');
1637a73b80b9052136c8cd2234eb3433a07df7cf38eJohn Criswell      if (ext_index != std::wstring::npos)
1647a73b80b9052136c8cd2234eb3433a07df7cf38eJohn Criswell        ext_name = ext_name.substr(ext_index);
165f1dd2004c07126944c9384d25e866215fd93c3bbBrian Gaeke
1667908035f47ee637a2e9b585e3057b0f974dc75caReid Spencer      if (!GetRegistryDescriptionFromExtension(first_extension, &desc)) {
1677908035f47ee637a2e9b585e3057b0f974dc75caReid Spencer        // The extension doesn't exist in the registry. Create a description
1687908035f47ee637a2e9b585e3057b0f974dc75caReid Spencer        // based on the unknown extension type (i.e. if the extension is .qqq,
1697908035f47ee637a2e9b585e3057b0f974dc75caReid Spencer        // the we create a description "QQQ File (.qqq)").
1707917d3af3f51a3584a87a44548d584a5ac253cfcReid Spencer        include_all_files = true;
1717917d3af3f51a3584a87a44548d584a5ac253cfcReid Spencer        desc = l10n_util::GetStringFUTF16(
172f1dd2004c07126944c9384d25e866215fd93c3bbBrian Gaeke            IDS_APP_SAVEAS_EXTENSION_FORMAT,
1737a73b80b9052136c8cd2234eb3433a07df7cf38eJohn Criswell            base::i18n::ToUpper(WideToUTF16(ext_name)),
1747a73b80b9052136c8cd2234eb3433a07df7cf38eJohn Criswell            ext_name);
1757a73b80b9052136c8cd2234eb3433a07df7cf38eJohn Criswell      }
1767f33695eac684bac5e925cf2039c8f9b001ceb7fJohn Criswell      if (desc.empty())
1777a73b80b9052136c8cd2234eb3433a07df7cf38eJohn Criswell        desc = L"*." + ext_name;
1787a73b80b9052136c8cd2234eb3433a07df7cf38eJohn Criswell    }
179f1dd2004c07126944c9384d25e866215fd93c3bbBrian Gaeke
1807a73b80b9052136c8cd2234eb3433a07df7cf38eJohn Criswell    result.append(desc.c_str(), desc.size() + 1);  // Append NULL too.
1817a73b80b9052136c8cd2234eb3433a07df7cf38eJohn Criswell    result.append(ext.c_str(), ext.size() + 1);
1827a73b80b9052136c8cd2234eb3433a07df7cf38eJohn Criswell  }
1837a73b80b9052136c8cd2234eb3433a07df7cf38eJohn Criswell
1847a73b80b9052136c8cd2234eb3433a07df7cf38eJohn Criswell  if (include_all_files) {
1857a73b80b9052136c8cd2234eb3433a07df7cf38eJohn Criswell    result.append(all_desc.c_str(), all_desc.size() + 1);
1866e96d81c874d19782b6c0942dd89d29eb1dbb75fReid Spencer    result.append(all_ext.c_str(), all_ext.size() + 1);
1876e96d81c874d19782b6c0942dd89d29eb1dbb75fReid Spencer  }
1886e96d81c874d19782b6c0942dd89d29eb1dbb75fReid Spencer
1896e96d81c874d19782b6c0942dd89d29eb1dbb75fReid Spencer  result.append(1, '\0');  // Double NULL required.
1906e96d81c874d19782b6c0942dd89d29eb1dbb75fReid Spencer  return result;
1917a73b80b9052136c8cd2234eb3433a07df7cf38eJohn Criswell}
1927a73b80b9052136c8cd2234eb3433a07df7cf38eJohn Criswell
1937a73b80b9052136c8cd2234eb3433a07df7cf38eJohn Criswell// Enforce visible dialog box.
1947a73b80b9052136c8cd2234eb3433a07df7cf38eJohn CriswellUINT_PTR CALLBACK SaveAsDialogHook(HWND dialog, UINT message,
195e1200219ec6f4d6ff7f54933ccad462c8dfdbb70Reid Spencer                                   WPARAM wparam, LPARAM lparam) {
196e1200219ec6f4d6ff7f54933ccad462c8dfdbb70Reid Spencer  static const UINT kPrivateMessage = 0x2F3F;
197e1200219ec6f4d6ff7f54933ccad462c8dfdbb70Reid Spencer  switch (message) {
198e9676508acff14a88bd45ef15b024c9b98773a5eMisha Brukman    case WM_INITDIALOG: {
1997a73b80b9052136c8cd2234eb3433a07df7cf38eJohn Criswell      // Do nothing here. Just post a message to defer actual processing.
2007a73b80b9052136c8cd2234eb3433a07df7cf38eJohn Criswell      PostMessage(dialog, kPrivateMessage, 0, 0);
2017a73b80b9052136c8cd2234eb3433a07df7cf38eJohn Criswell      return TRUE;
2027a73b80b9052136c8cd2234eb3433a07df7cf38eJohn Criswell    }
203b195d9d365e5f960c93ddfdf10638d5d147d9f6fReid Spencer    case kPrivateMessage: {
2047a73b80b9052136c8cd2234eb3433a07df7cf38eJohn Criswell      // The dialog box is the parent of the current handle.
20588aeace3189c214115e5170bcedf1888235c4c08Brian Gaeke      HWND real_dialog = GetParent(dialog);
20688aeace3189c214115e5170bcedf1888235c4c08Brian Gaeke
20788aeace3189c214115e5170bcedf1888235c4c08Brian Gaeke      // Retrieve the final size.
208e6d468f6f77b52e5ccc4592d1024829d8f5cf70bJohn Criswell      RECT dialog_rect;
209e6d468f6f77b52e5ccc4592d1024829d8f5cf70bJohn Criswell      GetWindowRect(real_dialog, &dialog_rect);
210e6d468f6f77b52e5ccc4592d1024829d8f5cf70bJohn Criswell
211b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer      // Verify that the upper left corner is visible.
212b2cb4861511692d8566b50fa34720eeb09ed617eReid Spencer      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.
258bool 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.
389bool 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.
410class 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_window) 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
526SelectFileDialogImpl::SelectFileDialogImpl(Listener* listener,
527                                           ui::SelectFilePolicy* policy)
528    : SelectFileDialog(listener, policy),
529      BaseShellDialogImpl(),
530      has_multiple_file_type_choices_(false) {
531}
532
533SelectFileDialogImpl::~SelectFileDialogImpl() {
534}
535
536void 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 && owning_window->GetRootWindow()
602               ? owning_window->GetDispatcher()->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
616bool SelectFileDialogImpl::HasMultipleFileTypeChoicesImpl() {
617  return has_multiple_file_type_choices_;
618}
619
620bool SelectFileDialogImpl::IsRunning(gfx::NativeWindow owning_window) const {
621#if defined(USE_AURA)
622  if (!owning_window->GetRootWindow())
623    return false;
624  HWND owner = owning_window->GetDispatcher()->GetAcceleratedWidget();
625#else
626  HWND owner = owning_window;
627#endif
628  return listener_ && IsRunningDialogForOwner(owner);
629}
630
631void SelectFileDialogImpl::ListenerDestroyed() {
632  // Our associated listener has gone away, so we shouldn't call back to it if
633  // our worker thread returns after the listener is dead.
634  listener_ = NULL;
635}
636
637void SelectFileDialogImpl::ExecuteSelectFile(
638    const ExecuteSelectParams& params) {
639  base::string16 filter = GetFilterForFileTypes(params.file_types);
640
641  base::FilePath path = params.default_path;
642  bool success = false;
643  unsigned filter_index = params.file_type_index;
644  if (params.type == SELECT_FOLDER || params.type == SELECT_UPLOAD_FOLDER) {
645    std::wstring title = params.title;
646    if (title.empty() && params.type == SELECT_UPLOAD_FOLDER) {
647      // If it's for uploading don't use default dialog title to
648      // make sure we clearly tell it's for uploading.
649      title = UTF16ToWide(
650          l10n_util::GetStringUTF16(IDS_SELECT_UPLOAD_FOLDER_DIALOG_TITLE));
651    }
652    success = RunSelectFolderDialog(title,
653                                    params.run_state.owner,
654                                    &path);
655  } else if (params.type == SELECT_SAVEAS_FILE) {
656    std::wstring path_as_wstring = path.value();
657    success = SaveFileAsWithFilter(params.run_state.owner,
658        params.default_path.value(), filter,
659        params.default_extension, false, &filter_index, &path_as_wstring);
660    if (success)
661      path = base::FilePath(path_as_wstring);
662    DisableOwner(params.run_state.owner);
663  } else if (params.type == SELECT_OPEN_FILE) {
664    success = RunOpenFileDialog(params.title, filter,
665                                params.run_state.owner, &path);
666  } else if (params.type == SELECT_OPEN_MULTI_FILE) {
667    std::vector<base::FilePath> paths;
668    if (RunOpenMultiFileDialog(params.title, filter,
669                               params.run_state.owner, &paths)) {
670      params.ui_proxy->PostTask(
671          FROM_HERE,
672          base::Bind(&SelectFileDialogImpl::MultiFilesSelected, this, paths,
673                     params.params, params.run_state));
674      return;
675    }
676  }
677
678  if (success) {
679      params.ui_proxy->PostTask(
680        FROM_HERE,
681        base::Bind(&SelectFileDialogImpl::FileSelected, this, path,
682                   filter_index, params.params, params.run_state));
683  } else {
684      params.ui_proxy->PostTask(
685        FROM_HERE,
686        base::Bind(&SelectFileDialogImpl::FileNotSelected, this, params.params,
687                   params.run_state));
688  }
689}
690
691void SelectFileDialogImpl::FileSelected(const base::FilePath& selected_folder,
692                                        int index,
693                                        void* params,
694                                        RunState run_state) {
695  if (listener_)
696    listener_->FileSelected(selected_folder, index, params);
697  EndRun(run_state);
698}
699
700void SelectFileDialogImpl::MultiFilesSelected(
701    const std::vector<base::FilePath>& selected_files,
702    void* params,
703    RunState run_state) {
704  if (listener_)
705    listener_->MultiFilesSelected(selected_files, params);
706  EndRun(run_state);
707}
708
709void SelectFileDialogImpl::FileNotSelected(void* params, RunState run_state) {
710  if (listener_)
711    listener_->FileSelectionCanceled(params);
712  EndRun(run_state);
713}
714
715int CALLBACK SelectFileDialogImpl::BrowseCallbackProc(HWND window,
716                                                      UINT message,
717                                                      LPARAM parameter,
718                                                      LPARAM data) {
719  if (message == BFFM_INITIALIZED) {
720    // WParam is TRUE since passing a path.
721    // data lParam member of the BROWSEINFO structure.
722    SendMessage(window, BFFM_SETSELECTION, TRUE, (LPARAM)data);
723  }
724  return 0;
725}
726
727bool SelectFileDialogImpl::RunSelectFolderDialog(const std::wstring& title,
728                                                 HWND owner,
729                                                 base::FilePath* path) {
730  DCHECK(path);
731
732  wchar_t dir_buffer[MAX_PATH + 1];
733
734  bool result = false;
735  BROWSEINFO browse_info = {0};
736  browse_info.hwndOwner = owner;
737  browse_info.lpszTitle = title.c_str();
738  browse_info.pszDisplayName = dir_buffer;
739  browse_info.ulFlags = BIF_USENEWUI | BIF_RETURNONLYFSDIRS;
740
741  if (path->value().length()) {
742    // Highlight the current value.
743    browse_info.lParam = (LPARAM)path->value().c_str();
744    browse_info.lpfn = &BrowseCallbackProc;
745  }
746
747  LPITEMIDLIST list = SHBrowseForFolder(&browse_info);
748  DisableOwner(owner);
749  if (list) {
750    STRRET out_dir_buffer;
751    ZeroMemory(&out_dir_buffer, sizeof(out_dir_buffer));
752    out_dir_buffer.uType = STRRET_WSTR;
753    base::win::ScopedComPtr<IShellFolder> shell_folder;
754    if (SHGetDesktopFolder(shell_folder.Receive()) == NOERROR) {
755      HRESULT hr = shell_folder->GetDisplayNameOf(list, SHGDN_FORPARSING,
756                                                  &out_dir_buffer);
757      if (SUCCEEDED(hr) && out_dir_buffer.uType == STRRET_WSTR) {
758        *path = base::FilePath(out_dir_buffer.pOleStr);
759        CoTaskMemFree(out_dir_buffer.pOleStr);
760        result = true;
761      } else {
762        // Use old way if we don't get what we want.
763        wchar_t old_out_dir_buffer[MAX_PATH + 1];
764        if (SHGetPathFromIDList(list, old_out_dir_buffer)) {
765          *path = base::FilePath(old_out_dir_buffer);
766          result = true;
767        }
768      }
769
770      // According to MSDN, win2000 will not resolve shortcuts, so we do it
771      // ourself.
772      base::win::ResolveShortcut(*path, path, NULL);
773    }
774    CoTaskMemFree(list);
775  }
776  return result;
777}
778
779bool SelectFileDialogImpl::RunOpenFileDialog(
780    const std::wstring& title,
781    const std::wstring& filter,
782    HWND owner,
783    base::FilePath* path) {
784  OPENFILENAME ofn;
785  // We must do this otherwise the ofn's FlagsEx may be initialized to random
786  // junk in release builds which can cause the Places Bar not to show up!
787  ZeroMemory(&ofn, sizeof(ofn));
788  ofn.lStructSize = sizeof(ofn);
789  ofn.hwndOwner = owner;
790
791  wchar_t filename[MAX_PATH];
792  // According to http://support.microsoft.com/?scid=kb;en-us;222003&x=8&y=12,
793  // The lpstrFile Buffer MUST be NULL Terminated.
794  filename[0] = 0;
795  // Define the dir in here to keep the string buffer pointer pointed to
796  // ofn.lpstrInitialDir available during the period of running the
797  // GetOpenFileName.
798  base::FilePath dir;
799  // Use lpstrInitialDir to specify the initial directory
800  if (!path->empty()) {
801    if (IsDirectory(*path)) {
802      ofn.lpstrInitialDir = path->value().c_str();
803    } else {
804      dir = path->DirName();
805      ofn.lpstrInitialDir = dir.value().c_str();
806      // Only pure filename can be put in lpstrFile field.
807      base::wcslcpy(filename, path->BaseName().value().c_str(),
808                    arraysize(filename));
809    }
810  }
811
812  ofn.lpstrFile = filename;
813  ofn.nMaxFile = MAX_PATH;
814
815  // We use OFN_NOCHANGEDIR so that the user can rename or delete the directory
816  // without having to close Chrome first.
817  ofn.Flags = OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR;
818
819  if (!filter.empty())
820    ofn.lpstrFilter = filter.c_str();
821  bool success = CallGetOpenFileName(&ofn);
822  DisableOwner(owner);
823  if (success)
824    *path = base::FilePath(filename);
825  return success;
826}
827
828bool SelectFileDialogImpl::RunOpenMultiFileDialog(
829    const std::wstring& title,
830    const std::wstring& filter,
831    HWND owner,
832    std::vector<base::FilePath>* paths) {
833  OPENFILENAME ofn;
834  // We must do this otherwise the ofn's FlagsEx may be initialized to random
835  // junk in release builds which can cause the Places Bar not to show up!
836  ZeroMemory(&ofn, sizeof(ofn));
837  ofn.lStructSize = sizeof(ofn);
838  ofn.hwndOwner = owner;
839
840  scoped_ptr<wchar_t[]> filename(new wchar_t[UNICODE_STRING_MAX_CHARS]);
841  filename[0] = 0;
842
843  ofn.lpstrFile = filename.get();
844  ofn.nMaxFile = UNICODE_STRING_MAX_CHARS;
845  // We use OFN_NOCHANGEDIR so that the user can rename or delete the directory
846  // without having to close Chrome first.
847  ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_EXPLORER
848               | OFN_HIDEREADONLY | OFN_ALLOWMULTISELECT;
849
850  if (!filter.empty()) {
851    ofn.lpstrFilter = filter.c_str();
852  }
853
854  bool success = CallGetOpenFileName(&ofn);
855  DisableOwner(owner);
856  if (success) {
857    std::vector<base::FilePath> files;
858    const wchar_t* selection = ofn.lpstrFile;
859    while (*selection) {  // Empty string indicates end of list.
860      files.push_back(base::FilePath(selection));
861      // Skip over filename and null-terminator.
862      selection += files.back().value().length() + 1;
863    }
864    if (files.empty()) {
865      success = false;
866    } else if (files.size() == 1) {
867      // When there is one file, it contains the path and filename.
868      paths->swap(files);
869    } else {
870      // Otherwise, the first string is the path, and the remainder are
871      // filenames.
872      std::vector<base::FilePath>::iterator path = files.begin();
873      for (std::vector<base::FilePath>::iterator file = path + 1;
874           file != files.end(); ++file) {
875        paths->push_back(path->Append(*file));
876      }
877    }
878  }
879  return success;
880}
881
882base::string16 SelectFileDialogImpl::GetFilterForFileTypes(
883    const FileTypeInfo& file_types) {
884  std::vector<base::string16> exts;
885  for (size_t i = 0; i < file_types.extensions.size(); ++i) {
886    const std::vector<base::string16>& inner_exts = file_types.extensions[i];
887    base::string16 ext_string;
888    for (size_t j = 0; j < inner_exts.size(); ++j) {
889      if (!ext_string.empty())
890        ext_string.push_back(L';');
891      ext_string.append(L"*.");
892      ext_string.append(inner_exts[j]);
893    }
894    exts.push_back(ext_string);
895  }
896  return FormatFilterForExtensions(
897      exts,
898      file_types.extension_description_overrides,
899      file_types.include_all_files);
900}
901
902}  // namespace
903
904namespace ui {
905
906// This function takes the output of a SaveAs dialog: a filename, a filter and
907// the extension originally suggested to the user (shown in the dialog box) and
908// returns back the filename with the appropriate extension tacked on. If the
909// user requests an unknown extension and is not using the 'All files' filter,
910// the suggested extension will be appended, otherwise we will leave the
911// filename unmodified. |filename| should contain the filename selected in the
912// SaveAs dialog box and may include the path, |filter_selected| should be
913// '*.something', for example '*.*' or it can be blank (which is treated as
914// *.*). |suggested_ext| should contain the extension without the dot (.) in
915// front, for example 'jpg'.
916std::wstring AppendExtensionIfNeeded(
917    const std::wstring& filename,
918    const std::wstring& filter_selected,
919    const std::wstring& suggested_ext) {
920  DCHECK(!filename.empty());
921  std::wstring return_value = filename;
922
923  // If we wanted a specific extension, but the user's filename deleted it or
924  // changed it to something that the system doesn't understand, re-append.
925  // Careful: Checking net::GetMimeTypeFromExtension() will only find
926  // extensions with a known MIME type, which many "known" extensions on Windows
927  // don't have.  So we check directly for the "known extension" registry key.
928  std::wstring file_extension(
929      GetExtensionWithoutLeadingDot(base::FilePath(filename).Extension()));
930  std::wstring key(L"." + file_extension);
931  if (!(filter_selected.empty() || filter_selected == L"*.*") &&
932      !base::win::RegKey(HKEY_CLASSES_ROOT, key.c_str(), KEY_READ).Valid() &&
933      file_extension != suggested_ext) {
934    if (return_value[return_value.length() - 1] != L'.')
935      return_value.append(L".");
936    return_value.append(suggested_ext);
937  }
938
939  // Strip any trailing dots, which Windows doesn't allow.
940  size_t index = return_value.find_last_not_of(L'.');
941  if (index < return_value.size() - 1)
942    return_value.resize(index + 1);
943
944  return return_value;
945}
946
947SelectFileDialog* CreateWinSelectFileDialog(
948    SelectFileDialog::Listener* listener,
949    SelectFilePolicy* policy) {
950  return new SelectFileDialogImpl(listener, policy);
951}
952
953}  // namespace ui
954