diff options
author | ananta@chromium.org <ananta@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98> | 2013-01-31 19:16:42 +0000 |
---|---|---|
committer | ananta@chromium.org <ananta@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98> | 2013-01-31 19:16:42 +0000 |
commit | c8ca6e1d2950f75867cc82da0792a10a76d59d79 (patch) | |
tree | 510edb50d84f23d741bb22d8efeb818fb47ec59a /win8/metro_driver | |
parent | 294b8d9992ef598c164c116641e948ebd3ddad05 (diff) | |
download | chromium_src-c8ca6e1d2950f75867cc82da0792a10a76d59d79.zip chromium_src-c8ca6e1d2950f75867cc82da0792a10a76d59d79.tar.gz chromium_src-c8ca6e1d2950f75867cc82da0792a10a76d59d79.tar.bz2 |
Add support for displaying the Windows 8 metro open/save file picker in Chrome ASH.
Added the following functions to the Aura namespace.
1. HandleOpenFile
2. HandleOpenMultipleFiles
3. HandleSaveFile
These functions are invoked from the windows implementation of SelectFileDialogImpl::SelectFileImpl
for AURA. Internally these functions forward off to the corresponding implementations in the singleton
instance of the RemoteRootWindowHostWin class which is instantiated for Chrome ASH on Windows.
These functions take in a callback object which is invoked when the file picker operations complete.
The SelectFileDialogImpl::SelectFileImpl function uses the newly added ShellDialogsDelegate interface to
determine if the owning native window is in Windows 8 metro. This interface is implemented by a global
object ShellDialogsDelegateWin which lives in the chrome_browser_main_extra_parts_ash.cc file. It uses the
IsNativeViewInAsh helper function to determine this.
Added the following IPC's which are sent from the browser to the metro viewer process.
1. MetroViewerHostMsg_DisplayFileOpen
2. MetroViewerHostMsg_DisplayFileSaveAs
The following IPC's are sent from the metro viewer to the browser process and inform the browser about the
status of the file open/file save operations along with the file names.
1. MetroViewerHostMsg_FileOpenDone
2. MetroViewerHostMsg_MultiFileOpenDone
3. MetroViewerHostMsg_FileSaveAsDone
The handlers for these IPCs live in the RemoteRootWindowHostWin class and invoke the callback objects which are
passed in.
In the metro driver the file_picker_ash.cc/.h files contain the code for displaying the metro style file pickers.
These sources are copied from the file_picker.cc/.h files which perform this functionality for regular Chrome metro.
BUG=170483
Review URL: https://codereview.chromium.org/12041089
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@179921 0039d316-1c4b-4281-b951-d872f2087c98
Diffstat (limited to 'win8/metro_driver')
-rw-r--r-- | win8/metro_driver/chrome_app_view_ash.cc | 133 | ||||
-rw-r--r-- | win8/metro_driver/chrome_app_view_ash.h | 30 | ||||
-rw-r--r-- | win8/metro_driver/file_picker_ash.cc | 546 | ||||
-rw-r--r-- | win8/metro_driver/file_picker_ash.h | 145 | ||||
-rw-r--r-- | win8/metro_driver/metro_driver.gyp | 2 | ||||
-rw-r--r-- | win8/metro_driver/stdafx.h | 2 |
6 files changed, 849 insertions, 9 deletions
diff --git a/win8/metro_driver/chrome_app_view_ash.cc b/win8/metro_driver/chrome_app_view_ash.cc index 3e4803b..d3c128d 100644 --- a/win8/metro_driver/chrome_app_view_ash.cc +++ b/win8/metro_driver/chrome_app_view_ash.cc @@ -20,6 +20,7 @@ #include "ipc/ipc_channel_proxy.h" #include "ipc/ipc_sender.h" #include "ui/metro_viewer/metro_viewer_messages.h" +#include "win8/metro_driver/file_picker_ash.h" #include "win8/metro_driver/metro_driver.h" #include "win8/metro_driver/winrt_utils.h" @@ -74,6 +75,10 @@ class ChromeChannelListener : public IPC::Listener { virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE { IPC_BEGIN_MESSAGE_MAP(ChromeChannelListener, message) IPC_MESSAGE_HANDLER(MetroViewerHostMsg_SetCursor, OnSetCursor) + IPC_MESSAGE_HANDLER(MetroViewerHostMsg_DisplayFileOpen, + OnDisplayFileOpenDialog) + IPC_MESSAGE_HANDLER(MetroViewerHostMsg_DisplayFileSaveAs, + OnDisplayFileSaveAsDialog) IPC_MESSAGE_UNHANDLED(__debugbreak()) IPC_END_MESSAGE_MAP() return true; @@ -85,15 +90,37 @@ class ChromeChannelListener : public IPC::Listener { } private: - void OnSetCursor(int64 cursor) { - ui_proxy_->PostTask(FROM_HERE, - base::Bind(&ChromeAppViewAsh::OnSetCursor, - base::Unretained(app_view_), - reinterpret_cast<HCURSOR>(cursor))); - } - - scoped_refptr<base::MessageLoopProxy> ui_proxy_; - ChromeAppViewAsh* app_view_; + void OnSetCursor(int64 cursor) { + ui_proxy_->PostTask(FROM_HERE, + base::Bind(&ChromeAppViewAsh::OnSetCursor, + base::Unretained(app_view_), + reinterpret_cast<HCURSOR>(cursor))); + } + + void OnDisplayFileOpenDialog(const string16& title, + const string16& filter, + const string16& default_path, + bool allow_multiple_files) { + ui_proxy_->PostTask(FROM_HERE, + base::Bind(&ChromeAppViewAsh::OnDisplayFileOpenDialog, + base::Unretained(app_view_), + title, + filter, + default_path, + allow_multiple_files)); + } + + void OnDisplayFileSaveAsDialog( + const MetroViewerHostMsg_SaveAsDialogParams& params) { + ui_proxy_->PostTask( + FROM_HERE, + base::Bind(&ChromeAppViewAsh::OnDisplayFileSaveAsDialog, + base::Unretained(app_view_), + params)); + } + + scoped_refptr<base::MessageLoopProxy> ui_proxy_; + ChromeAppViewAsh* app_view_; }; bool WaitForChromeIPCConnection(const std::string& channel_name) { @@ -374,10 +401,98 @@ ChromeAppViewAsh::Uninitialize() { return S_OK; } +// static +HRESULT ChromeAppViewAsh::Unsnap() { + mswr::ComPtr<winui::ViewManagement::IApplicationViewStatics> view_statics; + HRESULT hr = winrt_utils::CreateActivationFactory( + RuntimeClass_Windows_UI_ViewManagement_ApplicationView, + view_statics.GetAddressOf()); + CheckHR(hr); + + winui::ViewManagement::ApplicationViewState state = + winui::ViewManagement::ApplicationViewState_FullScreenLandscape; + hr = view_statics->get_Value(&state); + CheckHR(hr); + + if (state == winui::ViewManagement::ApplicationViewState_Snapped) { + boolean success = FALSE; + hr = view_statics->TryUnsnap(&success); + + if (FAILED(hr) || !success) { + LOG(ERROR) << "Failed to unsnap. Error 0x" << hr; + if (SUCCEEDED(hr)) + hr = E_UNEXPECTED; + } + } + return hr; +} + + void ChromeAppViewAsh::OnSetCursor(HCURSOR cursor) { ::SetCursor(HCURSOR(cursor)); } +void ChromeAppViewAsh::OnDisplayFileOpenDialog(const string16& title, + const string16& filter, + const string16& default_path, + bool allow_multiple_files) { + DVLOG(1) << __FUNCTION__; + + // The OpenFilePickerSession instance is deleted when we receive a + // callback from the OpenFilePickerSession class about the completion of the + // operation. + OpenFilePickerSession* open_file_picker = + new OpenFilePickerSession(this, + title, + filter, + default_path, + allow_multiple_files); + open_file_picker->Run(); +} + +void ChromeAppViewAsh::OnDisplayFileSaveAsDialog( + const MetroViewerHostMsg_SaveAsDialogParams& params) { + DVLOG(1) << __FUNCTION__; + + // The SaveFilePickerSession instance is deleted when we receive a + // callback from the OpenFilePickerSession class about the completion of the + // operation. + SaveFilePickerSession* save_file_picker = + new SaveFilePickerSession(this, params); + save_file_picker->Run(); +} + +void ChromeAppViewAsh::OnOpenFileCompleted( + OpenFilePickerSession* open_file_picker, + bool success) { + DVLOG(1) << __FUNCTION__; + DVLOG(1) << "Success: " << success; + if (ui_channel_) { + if (open_file_picker->allow_multi_select()) { + ui_channel_->Send(new MetroViewerHostMsg_MultiFileOpenDone( + success, open_file_picker->filenames())); + } else { + ui_channel_->Send(new MetroViewerHostMsg_FileOpenDone( + success, open_file_picker->result())); + } + } + delete open_file_picker; +} + +void ChromeAppViewAsh::OnSaveFileCompleted( + SaveFilePickerSession* save_file_picker, + bool success) { + DVLOG(1) << __FUNCTION__; + DVLOG(1) << "Success: " << success; + if (ui_channel_) { + ui_channel_->Send(new MetroViewerHostMsg_FileSaveAsDone( + success, + save_file_picker->result(), + save_file_picker->filter_index())); + } + delete save_file_picker; +} + HRESULT ChromeAppViewAsh::OnActivate( winapp::Core::ICoreApplicationView*, winapp::Activation::IActivatedEventArgs* args) { diff --git a/win8/metro_driver/chrome_app_view_ash.h b/win8/metro_driver/chrome_app_view_ash.h index ec06938..9dd0e60 100644 --- a/win8/metro_driver/chrome_app_view_ash.h +++ b/win8/metro_driver/chrome_app_view_ash.h @@ -11,6 +11,7 @@ #include <windows.ui.viewmanagement.h> #include "base/memory/scoped_ptr.h" +#include "base/string16.h" #include "ui/base/events/event_constants.h" #include "win8/metro_driver/direct3d_helper.h" @@ -19,6 +20,11 @@ namespace IPC { class ChannelProxy; } +class OpenFilePickerSession; +class SaveFilePickerSession; + +struct MetroViewerHostMsg_SaveAsDialogParams; + class ChromeAppViewAsh : public mswr::RuntimeClass<winapp::Core::IFrameworkView> { public: @@ -32,7 +38,31 @@ class ChromeAppViewAsh IFACEMETHOD(Run)(); IFACEMETHOD(Uninitialize)(); + // Helper function to unsnap the chrome metro app if it is snapped. + // Returns S_OK on success. + static HRESULT Unsnap(); + void OnSetCursor(HCURSOR cursor); + void OnDisplayFileOpenDialog(const string16& title, + const string16& filter, + const string16& default_path, + bool allow_multiple_files); + void OnDisplayFileSaveAsDialog( + const MetroViewerHostMsg_SaveAsDialogParams& params); + + // This function is invoked when the open file operation completes. The + // result of the operation is passed in along with the OpenFilePickerSession + // instance which is deleted after we read the required information from + // the OpenFilePickerSession class. + void OnOpenFileCompleted(OpenFilePickerSession* open_file_picker, + bool success); + + // This function is invoked when the save file operation completes. The + // result of the operation is passed in along with the SaveFilePickerSession + // instance which is deleted after we read the required information from + // the SaveFilePickerSession class. + void OnSaveFileCompleted(SaveFilePickerSession* save_file_picker, + bool success); private: HRESULT OnActivate(winapp::Core::ICoreApplicationView* view, diff --git a/win8/metro_driver/file_picker_ash.cc b/win8/metro_driver/file_picker_ash.cc new file mode 100644 index 0000000..4b73b90 --- /dev/null +++ b/win8/metro_driver/file_picker_ash.cc @@ -0,0 +1,546 @@ +// Copyright (c) 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "stdafx.h" +#include "win8/metro_driver/file_picker_ash.h" + +#include "base/bind.h" +#include "base/file_path.h" +#include "base/logging.h" +#include "base/message_loop.h" +#include "base/string_util.h" +#include "base/synchronization/waitable_event.h" +#include "base/win/scoped_comptr.h" +#include "base/win/metro.h" +#include "ui/metro_viewer/metro_viewer_messages.h" +#include "win8/metro_driver/chrome_app_view_ash.h" +#include "win8/metro_driver/winrt_utils.h" + +namespace { + +namespace winstorage = ABI::Windows::Storage; +typedef winfoundtn::Collections::IVector<HSTRING> StringVectorItf; + +// TODO(siggi): Complete this implementation and move it to a common place. +class StringVectorImpl : public mswr::RuntimeClass<StringVectorItf> { + public: + ~StringVectorImpl() { + std::for_each(strings_.begin(), strings_.end(), ::WindowsDeleteString); + } + + HRESULT RuntimeClassInitialize(const std::vector<string16>& list) { + for (size_t i = 0; i < list.size(); ++i) + strings_.push_back(MakeHString(list[i])); + + return S_OK; + } + + // IVector<HSTRING> implementation. + STDMETHOD(GetAt)(unsigned index, HSTRING* item) { + if (index >= strings_.size()) + return E_INVALIDARG; + + return ::WindowsDuplicateString(strings_[index], item); + } + STDMETHOD(get_Size)(unsigned *size) { + if (strings_.size() > UINT_MAX) + return E_UNEXPECTED; + *size = static_cast<unsigned>(strings_.size()); + return S_OK; + } + STDMETHOD(GetView)(winfoundtn::Collections::IVectorView<HSTRING> **view) { + return E_NOTIMPL; + } + STDMETHOD(IndexOf)(HSTRING value, unsigned *index, boolean *found) { + return E_NOTIMPL; + } + + // write methods + STDMETHOD(SetAt)(unsigned index, HSTRING item) { + return E_NOTIMPL; + } + STDMETHOD(InsertAt)(unsigned index, HSTRING item) { + return E_NOTIMPL; + } + STDMETHOD(RemoveAt)(unsigned index) { + return E_NOTIMPL; + } + STDMETHOD(Append)(HSTRING item) { + return E_NOTIMPL; + } + STDMETHOD(RemoveAtEnd)() { + return E_NOTIMPL; + } + STDMETHOD(Clear)() { + return E_NOTIMPL; + } + + private: + std::vector<HSTRING> strings_; +}; + +} // namespace + +FilePickerSessionBase::FilePickerSessionBase(ChromeAppViewAsh* app_view, + const string16& title, + const string16& filter, + const string16& default_path) + : app_view_(app_view), + title_(title), + filter_(filter), + default_path_(default_path), + success_(false) { +} + +bool FilePickerSessionBase::Run() { + if (!DoFilePicker()) + return false; + return success_; +} + +bool FilePickerSessionBase::DoFilePicker() { + // The file picker will fail if spawned from a snapped application, + // so let's attempt to unsnap first if we're in that state. + HRESULT hr = ChromeAppViewAsh::Unsnap(); + if (FAILED(hr)) { + LOG(ERROR) << "Failed to unsnap for file picker, error 0x" << hr; + return false; + } + hr = StartFilePicker(); + if (FAILED(hr)) { + LOG(ERROR) << "Failed to start file picker, error 0x" + << std::hex << hr; + return false; + } + return true; +} + +OpenFilePickerSession::OpenFilePickerSession(ChromeAppViewAsh* app_view, + const string16& title, + const string16& filter, + const string16& default_path, + bool allow_multi_select) + : FilePickerSessionBase(app_view, title, filter, default_path), + allow_multi_select_(allow_multi_select) { +} + +HRESULT OpenFilePickerSession::SinglePickerDone(SingleFileAsyncOp* async, + AsyncStatus status) { + if (status == Completed) { + mswr::ComPtr<winstorage::IStorageFile> file; + HRESULT hr = async->GetResults(file.GetAddressOf()); + + if (file) { + mswr::ComPtr<winstorage::IStorageItem> storage_item; + if (SUCCEEDED(hr)) + hr = file.As(&storage_item); + + mswrw::HString file_path; + if (SUCCEEDED(hr)) + hr = storage_item->get_Path(file_path.GetAddressOf()); + + if (SUCCEEDED(hr)) { + UINT32 path_len = 0; + const wchar_t* path_str = + ::WindowsGetStringRawBuffer(file_path.Get(), &path_len); + + result_ = path_str; + success_ = true; + } + } else { + LOG(ERROR) << "NULL IStorageItem"; + } + } else { + LOG(ERROR) << "Unexpected async status " << status; + } + app_view_->OnOpenFileCompleted(this, success_); + return S_OK; +} + +HRESULT OpenFilePickerSession::MultiPickerDone(MultiFileAsyncOp* async, + AsyncStatus status) { + if (status == Completed) { + mswr::ComPtr<StorageFileVectorCollection> files; + HRESULT hr = async->GetResults(files.GetAddressOf()); + + if (files) { + string16 result; + if (SUCCEEDED(hr)) + hr = ComposeMultiFileResult(files.Get(), &result); + + if (SUCCEEDED(hr)) { + success_ = true; + // The code below has been copied from the + // SelectFileDialogImpl::RunOpenMultiFileDialog function in + // select_file_dialog_win.cc. + // TODO(ananta) + // Consolidate this into a common place. + const wchar_t* selection = result.c_str(); + std::vector<FilePath> files; + + while (*selection) { // Empty string indicates end of list. + files.push_back(FilePath(selection)); + // Skip over filename and null-terminator. + selection += files.back().value().length() + 1; + } + if (files.empty()) { + success_ = false; + } else if (files.size() == 1) { + // When there is one file, it contains the path and filename. + filenames_ = files; + } else if (files.size() > 1) { + // Otherwise, the first string is the path, and the remainder are + // filenames. + std::vector<FilePath>::iterator path = files.begin(); + for (std::vector<FilePath>::iterator file = path + 1; + file != files.end(); ++file) { + filenames_.push_back(path->Append(*file)); + } + } + } + } else { + LOG(ERROR) << "NULL StorageFileVectorCollection"; + } + } else { + LOG(ERROR) << "Unexpected async status " << status; + } + app_view_->OnOpenFileCompleted(this, success_); + return S_OK; +} + +HRESULT OpenFilePickerSession::StartFilePicker() { + mswrw::HStringReference class_name( + RuntimeClass_Windows_Storage_Pickers_FileOpenPicker); + + // Create the file picker. + mswr::ComPtr<winstorage::Pickers::IFileOpenPicker> picker; + HRESULT hr = ::Windows::Foundation::ActivateInstance( + class_name.Get(), picker.GetAddressOf()); + CheckHR(hr); + + // Set the file type filter + mswr::ComPtr<winfoundtn::Collections::IVector<HSTRING>> filter; + hr = picker->get_FileTypeFilter(filter.GetAddressOf()); + if (FAILED(hr)) + return hr; + + if (filter_.empty()) { + hr = filter->Append(mswrw::HStringReference(L"*").Get()); + if (FAILED(hr)) + return hr; + } else { + // The filter is a concatenation of zero terminated string pairs, + // where each pair is {description, extension}. The concatenation ends + // with a zero length string - e.g. a double zero terminator. + const wchar_t* walk = filter_.c_str(); + while (*walk != L'\0') { + // Walk past the description. + walk += wcslen(walk) + 1; + + // We should have an extension, but bail on malformed filters. + if (*walk == L'\0') + break; + + // There can be a single extension, or a list of semicolon-separated ones. + std::vector<string16> extensions_win32_style; + size_t extension_count = Tokenize(walk, L";", &extensions_win32_style); + DCHECK_EQ(extension_count, extensions_win32_style.size()); + + // Metro wants suffixes only, not patterns. + mswrw::HString extension; + std::vector<string16> extensions; + for (size_t i = 0; i < extensions_win32_style.size(); ++i) { + if (extensions_win32_style[i] == L"*.*") { + // The wildcard filter is "*" for Metro. The string "*.*" produces + // an "invalid parameter" error. + hr = extension.Set(L"*"); + } else { + // Metro wants suffixes only, not patterns. + string16 ext = FilePath(extensions_win32_style[i]).Extension(); + if ((ext.size() < 2) || + (ext.find_first_of(L"*?") != string16::npos)) { + continue; + } + hr = extension.Set(ext.c_str()); + } + if (SUCCEEDED(hr)) + hr = filter->Append(extension.Get()); + if (FAILED(hr)) + return hr; + } + + // Walk past the extension. + walk += wcslen(walk) + 1; + } + } + + // Spin up a single or multi picker as appropriate. + if (allow_multi_select_) { + mswr::ComPtr<MultiFileAsyncOp> completion; + hr = picker->PickMultipleFilesAsync(&completion); + if (FAILED(hr)) + return hr; + + // Create the callback method. + typedef winfoundtn::IAsyncOperationCompletedHandler< + StorageFileVectorCollection*> HandlerDoneType; + mswr::ComPtr<HandlerDoneType> handler(mswr::Callback<HandlerDoneType>( + this, &OpenFilePickerSession::MultiPickerDone)); + DCHECK(handler.Get() != NULL); + hr = completion->put_Completed(handler.Get()); + + return hr; + } else { + mswr::ComPtr<SingleFileAsyncOp> completion; + hr = picker->PickSingleFileAsync(&completion); + if (FAILED(hr)) + return hr; + + // Create the callback method. + typedef winfoundtn::IAsyncOperationCompletedHandler< + winstorage::StorageFile*> HandlerDoneType; + mswr::ComPtr<HandlerDoneType> handler(mswr::Callback<HandlerDoneType>( + this, &OpenFilePickerSession::SinglePickerDone)); + DCHECK(handler.Get() != NULL); + hr = completion->put_Completed(handler.Get()); + + return hr; + } +} + +HRESULT OpenFilePickerSession::ComposeMultiFileResult( + StorageFileVectorCollection* files, string16* result) { + DCHECK(files != NULL); + DCHECK(result != NULL); + + // Empty the output string. + result->clear(); + + unsigned int num_files = 0; + HRESULT hr = files->get_Size(&num_files); + if (FAILED(hr)) + return hr; + + // Make sure we return an error on an empty collection. + if (num_files == 0) { + DLOG(ERROR) << "Empty collection on input."; + return E_UNEXPECTED; + } + + // This stores the base path that should be the parent of all the files. + FilePath base_path; + + // Iterate through the collection and append the file paths to the result. + for (unsigned int i = 0; i < num_files; ++i) { + mswr::ComPtr<winstorage::IStorageFile> file; + hr = files->GetAt(i, file.GetAddressOf()); + if (FAILED(hr)) + return hr; + + mswr::ComPtr<winstorage::IStorageItem> storage_item; + hr = file.As(&storage_item); + if (FAILED(hr)) + return hr; + + mswrw::HString file_path_str; + hr = storage_item->get_Path(file_path_str.GetAddressOf()); + if (FAILED(hr)) + return hr; + + FilePath file_path(MakeStdWString(file_path_str.Get())); + if (base_path.empty()) { + DCHECK(result->empty()); + base_path = file_path.DirName(); + + // Append the path, including the terminating zero. + // We do this only for the first file. + result->append(base_path.value().c_str(), base_path.value().size() + 1); + } + DCHECK(!result->empty()); + DCHECK(!base_path.empty()); + DCHECK(base_path == file_path.DirName()); + + // Append the base name, including the terminating zero. + FilePath base_name = file_path.BaseName(); + result->append(base_name.value().c_str(), base_name.value().size() + 1); + } + + DCHECK(!result->empty()); + + return S_OK; +} + +SaveFilePickerSession::SaveFilePickerSession( + ChromeAppViewAsh* app_view, + const MetroViewerHostMsg_SaveAsDialogParams& params) + : FilePickerSessionBase(app_view, + params.title, + params.filter, + params.suggested_name), + filter_index_(params.filter_index) { +} + +int SaveFilePickerSession::filter_index() const { + // TODO(ananta) + // Add support for returning the correct filter index. This does not work in + // regular Chrome metro on trunk as well. + // BUG: https://code.google.com/p/chromium/issues/detail?id=172704 + return filter_index_; +} + +HRESULT SaveFilePickerSession::StartFilePicker() { + mswrw::HStringReference class_name( + RuntimeClass_Windows_Storage_Pickers_FileSavePicker); + + // Create the file picker. + mswr::ComPtr<winstorage::Pickers::IFileSavePicker> picker; + HRESULT hr = ::Windows::Foundation::ActivateInstance( + class_name.Get(), picker.GetAddressOf()); + CheckHR(hr); + + typedef winfoundtn::Collections::IMap<HSTRING, StringVectorItf*> + StringVectorMap; + mswr::ComPtr<StringVectorMap> choices; + hr = picker->get_FileTypeChoices(choices.GetAddressOf()); + if (FAILED(hr)) + return hr; + + if (!filter_.empty()) { + // The filter is a concatenation of zero terminated string pairs, + // where each pair is {description, extension list}. The concatenation ends + // with a zero length string - e.g. a double zero terminator. + const wchar_t* walk = filter_.c_str(); + while (*walk != L'\0') { + mswrw::HString description; + hr = description.Set(walk); + if (FAILED(hr)) + return hr; + + // Walk past the description. + walk += wcslen(walk) + 1; + + // We should have an extension, but bail on malformed filters. + if (*walk == L'\0') + break; + + // There can be a single extension, or a list of semicolon-separated ones. + std::vector<string16> extensions_win32_style; + size_t extension_count = Tokenize(walk, L";", &extensions_win32_style); + DCHECK_EQ(extension_count, extensions_win32_style.size()); + + // Metro wants suffixes only, not patterns. Also, metro does not support + // the all files ("*") pattern in the save picker. + std::vector<string16> extensions; + for (size_t i = 0; i < extensions_win32_style.size(); ++i) { + string16 ext = FilePath(extensions_win32_style[i]).Extension(); + if ((ext.size() < 2) || + (ext.find_first_of(L"*?") != string16::npos)) + continue; + extensions.push_back(ext); + } + + if (!extensions.empty()) { + // Convert to a Metro collection class. + mswr::ComPtr<StringVectorItf> list; + hr = mswr::MakeAndInitialize<StringVectorImpl>( + list.GetAddressOf(), extensions); + if (FAILED(hr)) + return hr; + + // Finally set the filter. + boolean replaced = FALSE; + hr = choices->Insert(description.Get(), list.Get(), &replaced); + if (FAILED(hr)) + return hr; + DCHECK_EQ(FALSE, replaced); + } + + // Walk past the extension(s). + walk += wcslen(walk) + 1; + } + } + + // The save picker requires at least one choice. Callers are strongly advised + // to provide sensible choices. If none were given, fallback to .dat. + uint32 num_choices = 0; + hr = choices->get_Size(&num_choices); + if (FAILED(hr)) + return hr; + + if (num_choices == 0) { + mswrw::HString description; + // TODO(grt): Get a properly translated string. This can't be done from + // within metro_driver. Consider preprocessing the filter list in Chrome + // land to ensure it has this entry if all others are patterns. In that + // case, this whole block of code can be removed. + hr = description.Set(L"Data File"); + if (FAILED(hr)) + return hr; + + mswr::ComPtr<StringVectorItf> list; + hr = mswr::MakeAndInitialize<StringVectorImpl>( + list.GetAddressOf(), std::vector<string16>(1, L".dat")); + if (FAILED(hr)) + return hr; + + boolean replaced = FALSE; + hr = choices->Insert(description.Get(), list.Get(), &replaced); + if (FAILED(hr)) + return hr; + DCHECK_EQ(FALSE, replaced); + } + + if (!default_path_.empty()) { + hr = picker->put_SuggestedFileName( + mswrw::HStringReference(default_path_.c_str()).Get()); + if (FAILED(hr)) + return hr; + } + + mswr::ComPtr<SaveFileAsyncOp> completion; + hr = picker->PickSaveFileAsync(&completion); + if (FAILED(hr)) + return hr; + + // Create the callback method. + typedef winfoundtn::IAsyncOperationCompletedHandler< + winstorage::StorageFile*> HandlerDoneType; + mswr::ComPtr<HandlerDoneType> handler(mswr::Callback<HandlerDoneType>( + this, &SaveFilePickerSession::FilePickerDone)); + DCHECK(handler.Get() != NULL); + hr = completion->put_Completed(handler.Get()); + + return hr; +} + +HRESULT SaveFilePickerSession::FilePickerDone(SaveFileAsyncOp* async, + AsyncStatus status) { + if (status == Completed) { + mswr::ComPtr<winstorage::IStorageFile> file; + HRESULT hr = async->GetResults(file.GetAddressOf()); + + if (file) { + mswr::ComPtr<winstorage::IStorageItem> storage_item; + if (SUCCEEDED(hr)) + hr = file.As(&storage_item); + + mswrw::HString file_path; + if (SUCCEEDED(hr)) + hr = storage_item->get_Path(file_path.GetAddressOf()); + + if (SUCCEEDED(hr)) { + string16 path_str = MakeStdWString(file_path.Get()); + result_ = path_str; + success_ = true; + } + } else { + LOG(ERROR) << "NULL IStorageItem"; + } + } else { + LOG(ERROR) << "Unexpected async status " << status; + } + app_view_->OnSaveFileCompleted(this, success_); + return S_OK; +} + diff --git a/win8/metro_driver/file_picker_ash.h b/win8/metro_driver/file_picker_ash.h new file mode 100644 index 0000000..ec8cf6a --- /dev/null +++ b/win8/metro_driver/file_picker_ash.h @@ -0,0 +1,145 @@ +// Copyright (c) 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. +#ifndef CHROME_BROWSER_UI_METRO_DRIVER_FILE_PICKER_ASH_H_ +#define CHROME_BROWSER_UI_METRO_DRIVER_FILE_PICKER_ASH_H_ + +#include <vector> + +#include "base/basictypes.h" +#include "base/compiler_specific.h" +#include "base/string16.h" + +class FilePath; +class ChromeAppViewAsh; +struct MetroViewerHostMsg_SaveAsDialogParams; + +// Base class for the file pickers. +class FilePickerSessionBase { + public: + // Creates a file picker for open_file_name. + explicit FilePickerSessionBase(ChromeAppViewAsh* app_view, + const string16& title, + const string16& filter, + const string16& default_path); + + virtual ~FilePickerSessionBase() { + } + + // Runs the picker, returns true on success. + bool Run(); + + const string16& result() const { + return result_; + } + + bool success() const { + return success_; + } + + protected: + // Creates, configures and starts a file picker. + // If the HRESULT returned is a failure code the file picker has not started, + // so no callbacks should be expected. + virtual HRESULT StartFilePicker() = 0; + + // True iff a file picker has successfully finished. + bool success_; + + // The title of the file picker. + string16 title_; + + // The file type filter. + string16 filter_; + + // The starting directory/file name. + string16 default_path_; + + // Pointer to the ChromeAppViewAsh instance. We notify the ChromeAppViewAsh + // instance when the file open/save operations complete. + ChromeAppViewAsh* app_view_; + + string16 result_; + + private: + // Initiate a file picker, must be called on the main metro thread. + // Returns true on success. + bool DoFilePicker(); + + DISALLOW_COPY_AND_ASSIGN(FilePickerSessionBase); +}; + +// Provides functionality to display the open file/multiple open file pickers +// metro dialog. +class OpenFilePickerSession : public FilePickerSessionBase { + public: + explicit OpenFilePickerSession(ChromeAppViewAsh* app_view, + const string16& title, + const string16& filter, + const string16& default_path, + bool allow_multi_select); + + const std::vector<FilePath>& filenames() const { + return filenames_; + } + + const bool allow_multi_select() const { + return allow_multi_select_; + } + + private: + virtual HRESULT StartFilePicker() OVERRIDE; + + typedef winfoundtn::IAsyncOperation<winstorage::StorageFile*> + SingleFileAsyncOp; + typedef winfoundtn::Collections::IVectorView< + winstorage::StorageFile*> StorageFileVectorCollection; + typedef winfoundtn::IAsyncOperation<StorageFileVectorCollection*> + MultiFileAsyncOp; + + // Called asynchronously when a single file picker is done. + HRESULT SinglePickerDone(SingleFileAsyncOp* async, AsyncStatus status); + + // Called asynchronously when a multi file picker is done. + HRESULT MultiPickerDone(MultiFileAsyncOp* async, AsyncStatus status); + + // Composes a multi-file result string suitable for returning to a + // from a storage file collection. + static HRESULT ComposeMultiFileResult(StorageFileVectorCollection* files, + string16* result); + + private: + // True if the multi file picker is to be displayed. + bool allow_multi_select_; + // If multi select is true then this member contains the list of filenames + // to be returned back. + std::vector<FilePath> filenames_; + + DISALLOW_COPY_AND_ASSIGN(OpenFilePickerSession); +}; + +// Provides functionality to display the save file picker. +class SaveFilePickerSession : public FilePickerSessionBase { + public: + explicit SaveFilePickerSession( + ChromeAppViewAsh* app_view, + const MetroViewerHostMsg_SaveAsDialogParams& params); + + int SaveFilePickerSession::filter_index() const; + + private: + virtual HRESULT StartFilePicker() OVERRIDE; + + typedef winfoundtn::IAsyncOperation<winstorage::StorageFile*> + SaveFileAsyncOp; + + // Called asynchronously when the save file picker is done. + HRESULT FilePickerDone(SaveFileAsyncOp* async, AsyncStatus status); + + int filter_index_; + + DISALLOW_COPY_AND_ASSIGN(SaveFilePickerSession); +}; + +#endif // CHROME_BROWSER_UI_METRO_DRIVER_FILE_PICKER_ASH_H_ + diff --git a/win8/metro_driver/metro_driver.gyp b/win8/metro_driver/metro_driver.gyp index 0d0081b..f1f9892 100644 --- a/win8/metro_driver/metro_driver.gyp +++ b/win8/metro_driver/metro_driver.gyp @@ -77,6 +77,8 @@ 'chrome_app_view_ash.h', 'direct3d_helper.cc', 'direct3d_helper.h', + 'file_picker_ash.h', + 'file_picker_ash.cc', ], }, { # use_aura!=1 'sources': [ diff --git a/win8/metro_driver/stdafx.h b/win8/metro_driver/stdafx.h index a44c36f..1ce382c 100644 --- a/win8/metro_driver/stdafx.h +++ b/win8/metro_driver/stdafx.h @@ -21,6 +21,7 @@ #include <windows.applicationmodel.core.h> #include <windows.applicationModel.datatransfer.h> #include <windows.graphics.printing.h> +#include <windows.storage.pickers.h> #include <windows.ui.notifications.h> namespace mswr = Microsoft::WRL; @@ -34,5 +35,6 @@ namespace winfoundtn = ABI::Windows::Foundation; namespace wingfx = ABI::Windows::Graphics; namespace winui = ABI::Windows::UI; namespace winsys = ABI::Windows::System; +namespace winstorage = ABI::Windows::Storage; #endif // WIN8_METRO_DRIVER_STDAFX_H_ |