1 // Copyright (c) 2013 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.
6 #include "win8/metro_driver/file_picker_ash.h"
9 #include "base/logging.h"
10 #include "base/message_loop/message_loop.h"
11 #include "base/strings/string_util.h"
12 #include "base/synchronization/waitable_event.h"
13 #include "base/win/metro.h"
14 #include "base/win/scoped_comptr.h"
15 #include "ui/metro_viewer/metro_viewer_messages.h"
16 #include "win8/metro_driver/chrome_app_view_ash.h"
17 #include "win8/metro_driver/winrt_utils.h"
21 namespace winstorage
= ABI::Windows::Storage
;
22 typedef winfoundtn::Collections::IVector
<HSTRING
> StringVectorItf
;
24 // TODO(siggi): Complete this implementation and move it to a common place.
25 class StringVectorImpl
: public mswr::RuntimeClass
<StringVectorItf
> {
28 std::for_each(strings_
.begin(), strings_
.end(), ::WindowsDeleteString
);
31 HRESULT
RuntimeClassInitialize(const std::vector
<string16
>& list
) {
32 for (size_t i
= 0; i
< list
.size(); ++i
)
33 strings_
.push_back(MakeHString(list
[i
]));
38 // IVector<HSTRING> implementation.
39 STDMETHOD(GetAt
)(unsigned index
, HSTRING
* item
) {
40 if (index
>= strings_
.size())
43 return ::WindowsDuplicateString(strings_
[index
], item
);
45 STDMETHOD(get_Size
)(unsigned *size
) {
46 if (strings_
.size() > UINT_MAX
)
48 *size
= static_cast<unsigned>(strings_
.size());
51 STDMETHOD(GetView
)(winfoundtn::Collections::IVectorView
<HSTRING
> **view
) {
54 STDMETHOD(IndexOf
)(HSTRING value
, unsigned *index
, boolean
*found
) {
59 STDMETHOD(SetAt
)(unsigned index
, HSTRING item
) {
62 STDMETHOD(InsertAt
)(unsigned index
, HSTRING item
) {
65 STDMETHOD(RemoveAt
)(unsigned index
) {
68 STDMETHOD(Append
)(HSTRING item
) {
71 STDMETHOD(RemoveAtEnd
)() {
79 std::vector
<HSTRING
> strings_
;
84 FilePickerSessionBase::FilePickerSessionBase(ChromeAppViewAsh
* app_view
,
85 const string16
& title
,
86 const string16
& filter
,
87 const base::FilePath
& default_path
)
88 : app_view_(app_view
),
91 default_path_(default_path
),
95 bool FilePickerSessionBase::Run() {
101 bool FilePickerSessionBase::DoFilePicker() {
102 // The file picker will fail if spawned from a snapped application,
103 // so let's attempt to unsnap first if we're in that state.
104 HRESULT hr
= ChromeAppViewAsh::Unsnap();
106 LOG(ERROR
) << "Failed to unsnap for file picker, error 0x" << hr
;
109 hr
= StartFilePicker();
111 LOG(ERROR
) << "Failed to start file picker, error 0x"
118 OpenFilePickerSession::OpenFilePickerSession(
119 ChromeAppViewAsh
* app_view
,
120 const string16
& title
,
121 const string16
& filter
,
122 const base::FilePath
& default_path
,
123 bool allow_multi_select
)
124 : FilePickerSessionBase(app_view
, title
, filter
, default_path
),
125 allow_multi_select_(allow_multi_select
) {
128 HRESULT
OpenFilePickerSession::SinglePickerDone(SingleFileAsyncOp
* async
,
129 AsyncStatus status
) {
130 if (status
== Completed
) {
131 mswr::ComPtr
<winstorage::IStorageFile
> file
;
132 HRESULT hr
= async
->GetResults(file
.GetAddressOf());
135 mswr::ComPtr
<winstorage::IStorageItem
> storage_item
;
137 hr
= file
.As(&storage_item
);
139 mswrw::HString file_path
;
141 hr
= storage_item
->get_Path(file_path
.GetAddressOf());
145 const wchar_t* path_str
=
146 ::WindowsGetStringRawBuffer(file_path
.Get(), &path_len
);
152 LOG(ERROR
) << "NULL IStorageItem";
155 LOG(ERROR
) << "Unexpected async status " << status
;
157 app_view_
->OnOpenFileCompleted(this, success_
);
161 HRESULT
OpenFilePickerSession::MultiPickerDone(MultiFileAsyncOp
* async
,
162 AsyncStatus status
) {
163 if (status
== Completed
) {
164 mswr::ComPtr
<StorageFileVectorCollection
> files
;
165 HRESULT hr
= async
->GetResults(files
.GetAddressOf());
170 hr
= ComposeMultiFileResult(files
.Get(), &result
);
174 // The code below has been copied from the
175 // SelectFileDialogImpl::RunOpenMultiFileDialog function in
176 // select_file_dialog_win.cc.
178 // Consolidate this into a common place.
179 const wchar_t* selection
= result
.c_str();
180 std::vector
<base::FilePath
> files
;
182 while (*selection
) { // Empty string indicates end of list.
183 files
.push_back(base::FilePath(selection
));
184 // Skip over filename and null-terminator.
185 selection
+= files
.back().value().length() + 1;
189 } else if (files
.size() == 1) {
190 // When there is one file, it contains the path and filename.
192 } else if (files
.size() > 1) {
193 // Otherwise, the first string is the path, and the remainder are
195 std::vector
<base::FilePath
>::iterator path
= files
.begin();
196 for (std::vector
<base::FilePath
>::iterator file
= path
+ 1;
197 file
!= files
.end(); ++file
) {
198 filenames_
.push_back(path
->Append(*file
));
203 LOG(ERROR
) << "NULL StorageFileVectorCollection";
206 LOG(ERROR
) << "Unexpected async status " << status
;
208 app_view_
->OnOpenFileCompleted(this, success_
);
212 HRESULT
OpenFilePickerSession::StartFilePicker() {
213 mswrw::HStringReference
class_name(
214 RuntimeClass_Windows_Storage_Pickers_FileOpenPicker
);
216 // Create the file picker.
217 mswr::ComPtr
<winstorage::Pickers::IFileOpenPicker
> picker
;
218 HRESULT hr
= ::Windows::Foundation::ActivateInstance(
219 class_name
.Get(), picker
.GetAddressOf());
222 // Set the file type filter
223 mswr::ComPtr
<winfoundtn::Collections::IVector
<HSTRING
>> filter
;
224 hr
= picker
->get_FileTypeFilter(filter
.GetAddressOf());
228 if (filter_
.empty()) {
229 hr
= filter
->Append(mswrw::HStringReference(L
"*").Get());
233 // The filter is a concatenation of zero terminated string pairs,
234 // where each pair is {description, extension}. The concatenation ends
235 // with a zero length string - e.g. a double zero terminator.
236 const wchar_t* walk
= filter_
.c_str();
237 while (*walk
!= L
'\0') {
238 // Walk past the description.
239 walk
+= wcslen(walk
) + 1;
241 // We should have an extension, but bail on malformed filters.
245 // There can be a single extension, or a list of semicolon-separated ones.
246 std::vector
<string16
> extensions_win32_style
;
247 size_t extension_count
= Tokenize(walk
, L
";", &extensions_win32_style
);
248 DCHECK_EQ(extension_count
, extensions_win32_style
.size());
250 // Metro wants suffixes only, not patterns.
251 mswrw::HString extension
;
252 std::vector
<string16
> extensions
;
253 for (size_t i
= 0; i
< extensions_win32_style
.size(); ++i
) {
254 if (extensions_win32_style
[i
] == L
"*.*") {
255 // The wildcard filter is "*" for Metro. The string "*.*" produces
256 // an "invalid parameter" error.
257 hr
= extension
.Set(L
"*");
259 // Metro wants suffixes only, not patterns.
260 string16 ext
= base::FilePath(extensions_win32_style
[i
]).Extension();
261 if ((ext
.size() < 2) ||
262 (ext
.find_first_of(L
"*?") != string16::npos
)) {
265 hr
= extension
.Set(ext
.c_str());
268 hr
= filter
->Append(extension
.Get());
273 // Walk past the extension.
274 walk
+= wcslen(walk
) + 1;
278 // Spin up a single or multi picker as appropriate.
279 if (allow_multi_select_
) {
280 mswr::ComPtr
<MultiFileAsyncOp
> completion
;
281 hr
= picker
->PickMultipleFilesAsync(&completion
);
285 // Create the callback method.
286 typedef winfoundtn::IAsyncOperationCompletedHandler
<
287 StorageFileVectorCollection
*> HandlerDoneType
;
288 mswr::ComPtr
<HandlerDoneType
> handler(mswr::Callback
<HandlerDoneType
>(
289 this, &OpenFilePickerSession::MultiPickerDone
));
290 DCHECK(handler
.Get() != NULL
);
291 hr
= completion
->put_Completed(handler
.Get());
295 mswr::ComPtr
<SingleFileAsyncOp
> completion
;
296 hr
= picker
->PickSingleFileAsync(&completion
);
300 // Create the callback method.
301 typedef winfoundtn::IAsyncOperationCompletedHandler
<
302 winstorage::StorageFile
*> HandlerDoneType
;
303 mswr::ComPtr
<HandlerDoneType
> handler(mswr::Callback
<HandlerDoneType
>(
304 this, &OpenFilePickerSession::SinglePickerDone
));
305 DCHECK(handler
.Get() != NULL
);
306 hr
= completion
->put_Completed(handler
.Get());
312 HRESULT
OpenFilePickerSession::ComposeMultiFileResult(
313 StorageFileVectorCollection
* files
, string16
* result
) {
314 DCHECK(files
!= NULL
);
315 DCHECK(result
!= NULL
);
317 // Empty the output string.
320 unsigned int num_files
= 0;
321 HRESULT hr
= files
->get_Size(&num_files
);
325 // Make sure we return an error on an empty collection.
326 if (num_files
== 0) {
327 DLOG(ERROR
) << "Empty collection on input.";
331 // This stores the base path that should be the parent of all the files.
332 base::FilePath base_path
;
334 // Iterate through the collection and append the file paths to the result.
335 for (unsigned int i
= 0; i
< num_files
; ++i
) {
336 mswr::ComPtr
<winstorage::IStorageFile
> file
;
337 hr
= files
->GetAt(i
, file
.GetAddressOf());
341 mswr::ComPtr
<winstorage::IStorageItem
> storage_item
;
342 hr
= file
.As(&storage_item
);
346 mswrw::HString file_path_str
;
347 hr
= storage_item
->get_Path(file_path_str
.GetAddressOf());
351 base::FilePath
file_path(MakeStdWString(file_path_str
.Get()));
352 if (base_path
.empty()) {
353 DCHECK(result
->empty());
354 base_path
= file_path
.DirName();
356 // Append the path, including the terminating zero.
357 // We do this only for the first file.
358 result
->append(base_path
.value().c_str(), base_path
.value().size() + 1);
360 DCHECK(!result
->empty());
361 DCHECK(!base_path
.empty());
362 DCHECK(base_path
== file_path
.DirName());
364 // Append the base name, including the terminating zero.
365 base::FilePath base_name
= file_path
.BaseName();
366 result
->append(base_name
.value().c_str(), base_name
.value().size() + 1);
369 DCHECK(!result
->empty());
374 SaveFilePickerSession::SaveFilePickerSession(
375 ChromeAppViewAsh
* app_view
,
376 const MetroViewerHostMsg_SaveAsDialogParams
& params
)
377 : FilePickerSessionBase(app_view
,
380 params
.suggested_name
),
381 filter_index_(params
.filter_index
) {
384 int SaveFilePickerSession::filter_index() const {
386 // Add support for returning the correct filter index. This does not work in
387 // regular Chrome metro on trunk as well.
388 // BUG: https://code.google.com/p/chromium/issues/detail?id=172704
389 return filter_index_
;
392 HRESULT
SaveFilePickerSession::StartFilePicker() {
393 mswrw::HStringReference
class_name(
394 RuntimeClass_Windows_Storage_Pickers_FileSavePicker
);
396 // Create the file picker.
397 mswr::ComPtr
<winstorage::Pickers::IFileSavePicker
> picker
;
398 HRESULT hr
= ::Windows::Foundation::ActivateInstance(
399 class_name
.Get(), picker
.GetAddressOf());
402 typedef winfoundtn::Collections::IMap
<HSTRING
, StringVectorItf
*>
404 mswr::ComPtr
<StringVectorMap
> choices
;
405 hr
= picker
->get_FileTypeChoices(choices
.GetAddressOf());
409 if (!filter_
.empty()) {
410 // The filter is a concatenation of zero terminated string pairs,
411 // where each pair is {description, extension list}. The concatenation ends
412 // with a zero length string - e.g. a double zero terminator.
413 const wchar_t* walk
= filter_
.c_str();
414 while (*walk
!= L
'\0') {
415 mswrw::HString description
;
416 hr
= description
.Set(walk
);
420 // Walk past the description.
421 walk
+= wcslen(walk
) + 1;
423 // We should have an extension, but bail on malformed filters.
427 // There can be a single extension, or a list of semicolon-separated ones.
428 std::vector
<string16
> extensions_win32_style
;
429 size_t extension_count
= Tokenize(walk
, L
";", &extensions_win32_style
);
430 DCHECK_EQ(extension_count
, extensions_win32_style
.size());
432 // Metro wants suffixes only, not patterns. Also, metro does not support
433 // the all files ("*") pattern in the save picker.
434 std::vector
<string16
> extensions
;
435 for (size_t i
= 0; i
< extensions_win32_style
.size(); ++i
) {
436 string16 ext
= base::FilePath(extensions_win32_style
[i
]).Extension();
437 if ((ext
.size() < 2) ||
438 (ext
.find_first_of(L
"*?") != string16::npos
))
440 extensions
.push_back(ext
);
443 if (!extensions
.empty()) {
444 // Convert to a Metro collection class.
445 mswr::ComPtr
<StringVectorItf
> list
;
446 hr
= mswr::MakeAndInitialize
<StringVectorImpl
>(
447 list
.GetAddressOf(), extensions
);
451 // Finally set the filter.
452 boolean replaced
= FALSE
;
453 hr
= choices
->Insert(description
.Get(), list
.Get(), &replaced
);
456 DCHECK_EQ(FALSE
, replaced
);
459 // Walk past the extension(s).
460 walk
+= wcslen(walk
) + 1;
464 // The save picker requires at least one choice. Callers are strongly advised
465 // to provide sensible choices. If none were given, fallback to .dat.
466 uint32 num_choices
= 0;
467 hr
= choices
->get_Size(&num_choices
);
471 if (num_choices
== 0) {
472 mswrw::HString description
;
473 // TODO(grt): Get a properly translated string. This can't be done from
474 // within metro_driver. Consider preprocessing the filter list in Chrome
475 // land to ensure it has this entry if all others are patterns. In that
476 // case, this whole block of code can be removed.
477 hr
= description
.Set(L
"Data File");
481 mswr::ComPtr
<StringVectorItf
> list
;
482 hr
= mswr::MakeAndInitialize
<StringVectorImpl
>(
483 list
.GetAddressOf(), std::vector
<string16
>(1, L
".dat"));
487 boolean replaced
= FALSE
;
488 hr
= choices
->Insert(description
.Get(), list
.Get(), &replaced
);
491 DCHECK_EQ(FALSE
, replaced
);
494 if (!default_path_
.empty()) {
495 string16 file_part
= default_path_
.BaseName().value();
496 // If the suggested_name is a root directory, then don't set it as the
498 if (file_part
.size() == 1 && file_part
[0] == L
'\\')
500 hr
= picker
->put_SuggestedFileName(
501 mswrw::HStringReference(file_part
.c_str()).Get());
506 mswr::ComPtr
<SaveFileAsyncOp
> completion
;
507 hr
= picker
->PickSaveFileAsync(&completion
);
511 // Create the callback method.
512 typedef winfoundtn::IAsyncOperationCompletedHandler
<
513 winstorage::StorageFile
*> HandlerDoneType
;
514 mswr::ComPtr
<HandlerDoneType
> handler(mswr::Callback
<HandlerDoneType
>(
515 this, &SaveFilePickerSession::FilePickerDone
));
516 DCHECK(handler
.Get() != NULL
);
517 hr
= completion
->put_Completed(handler
.Get());
522 HRESULT
SaveFilePickerSession::FilePickerDone(SaveFileAsyncOp
* async
,
523 AsyncStatus status
) {
524 if (status
== Completed
) {
525 mswr::ComPtr
<winstorage::IStorageFile
> file
;
526 HRESULT hr
= async
->GetResults(file
.GetAddressOf());
529 mswr::ComPtr
<winstorage::IStorageItem
> storage_item
;
531 hr
= file
.As(&storage_item
);
533 mswrw::HString file_path
;
535 hr
= storage_item
->get_Path(file_path
.GetAddressOf());
538 string16 path_str
= MakeStdWString(file_path
.Get());
543 LOG(ERROR
) << "NULL IStorageItem";
546 LOG(ERROR
) << "Unexpected async status " << status
;
548 app_view_
->OnSaveFileCompleted(this, success_
);
552 FolderPickerSession::FolderPickerSession(ChromeAppViewAsh
* app_view
,
553 const string16
& title
)
554 : FilePickerSessionBase(app_view
, title
, L
"", base::FilePath()) {}
556 HRESULT
FolderPickerSession::StartFilePicker() {
557 mswrw::HStringReference
class_name(
558 RuntimeClass_Windows_Storage_Pickers_FolderPicker
);
560 // Create the folder picker.
561 mswr::ComPtr
<winstorage::Pickers::IFolderPicker
> picker
;
562 HRESULT hr
= ::Windows::Foundation::ActivateInstance(
563 class_name
.Get(), picker
.GetAddressOf());
566 // Set the file type filter
567 mswr::ComPtr
<winfoundtn::Collections::IVector
<HSTRING
>> filter
;
568 hr
= picker
->get_FileTypeFilter(filter
.GetAddressOf());
572 hr
= filter
->Append(mswrw::HStringReference(L
"*").Get());
576 mswr::ComPtr
<FolderPickerAsyncOp
> completion
;
577 hr
= picker
->PickSingleFolderAsync(&completion
);
581 // Create the callback method.
582 typedef winfoundtn::IAsyncOperationCompletedHandler
<
583 winstorage::StorageFolder
*> HandlerDoneType
;
584 mswr::ComPtr
<HandlerDoneType
> handler(mswr::Callback
<HandlerDoneType
>(
585 this, &FolderPickerSession::FolderPickerDone
));
586 DCHECK(handler
.Get() != NULL
);
587 hr
= completion
->put_Completed(handler
.Get());
591 HRESULT
FolderPickerSession::FolderPickerDone(FolderPickerAsyncOp
* async
,
592 AsyncStatus status
) {
593 if (status
== Completed
) {
594 mswr::ComPtr
<winstorage::IStorageFolder
> folder
;
595 HRESULT hr
= async
->GetResults(folder
.GetAddressOf());
598 mswr::ComPtr
<winstorage::IStorageItem
> storage_item
;
600 hr
= folder
.As(&storage_item
);
602 mswrw::HString file_path
;
604 hr
= storage_item
->get_Path(file_path
.GetAddressOf());
607 string16 path_str
= MakeStdWString(file_path
.Get());
612 LOG(ERROR
) << "NULL IStorageItem";
615 LOG(ERROR
) << "Unexpected async status " << status
;
617 app_view_
->OnFolderPickerCompleted(this, success_
);