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