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 | |
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
-rw-r--r-- | chrome/browser/ui/views/ash/chrome_browser_main_extra_parts_ash.cc | 21 | ||||
-rw-r--r-- | ui/aura/remote_root_window_host_win.cc | 134 | ||||
-rw-r--r-- | ui/aura/remote_root_window_host_win.h | 75 | ||||
-rw-r--r-- | ui/metro_viewer/metro_viewer_messages.h | 51 | ||||
-rw-r--r-- | ui/shell_dialogs/select_file_dialog.cc | 13 | ||||
-rw-r--r-- | ui/shell_dialogs/select_file_dialog.h | 7 | ||||
-rw-r--r-- | ui/shell_dialogs/select_file_dialog_win.cc | 78 | ||||
-rw-r--r-- | ui/shell_dialogs/shell_dialogs_delegate.h | 24 | ||||
-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 |
14 files changed, 1233 insertions, 28 deletions
diff --git a/chrome/browser/ui/views/ash/chrome_browser_main_extra_parts_ash.cc b/chrome/browser/ui/views/ash/chrome_browser_main_extra_parts_ash.cc index bd06618..0ec81a4 100644 --- a/chrome/browser/ui/views/ash/chrome_browser_main_extra_parts_ash.cc +++ b/chrome/browser/ui/views/ash/chrome_browser_main_extra_parts_ash.cc @@ -5,6 +5,7 @@ #include "chrome/browser/ui/views/ash/chrome_browser_main_extra_parts_ash.h" #include "base/command_line.h" +#include "base/lazy_instance.h" #include "chrome/browser/chrome_browser_main.h" #include "chrome/browser/toolkit_extra_parts.h" #include "chrome/browser/ui/ash/ash_init.h" @@ -22,6 +23,11 @@ #endif #if !defined(OS_CHROMEOS) +#include "ui/shell_dialogs/select_file_dialog.h" +#include "ui/shell_dialogs/shell_dialogs_delegate.h" +#endif + +#if !defined(OS_CHROMEOS) class ScreenTypeDelegateWin : public gfx::ScreenTypeDelegate { public: ScreenTypeDelegateWin() {} @@ -34,6 +40,19 @@ class ScreenTypeDelegateWin : public gfx::ScreenTypeDelegate { private: DISALLOW_COPY_AND_ASSIGN(ScreenTypeDelegateWin); }; + +class ShellDialogsDelegateWin : public ui::ShellDialogsDelegate { + public: + ShellDialogsDelegateWin() {} + virtual bool IsWindowInMetro(gfx::NativeWindow window) OVERRIDE { + return chrome::IsNativeViewInAsh(window); + } + private: + DISALLOW_COPY_AND_ASSIGN(ShellDialogsDelegateWin); +}; + +base::LazyInstance<ShellDialogsDelegateWin> g_shell_dialogs_delegate; + #endif ChromeBrowserMainExtraPartsAsh::ChromeBrowserMainExtraPartsAsh() { @@ -52,6 +71,8 @@ void ChromeBrowserMainExtraPartsAsh::PreProfileInit() { } else { #if !defined(OS_CHROMEOS) gfx::Screen::SetScreenTypeDelegate(new ScreenTypeDelegateWin); + ui::SelectFileDialog::SetShellDialogsDelegate( + &g_shell_dialogs_delegate.Get()); #endif } diff --git a/ui/aura/remote_root_window_host_win.cc b/ui/aura/remote_root_window_host_win.cc index 18c1eed..9d1782d 100644 --- a/ui/aura/remote_root_window_host_win.cc +++ b/ui/aura/remote_root_window_host_win.cc @@ -31,6 +31,47 @@ const int kRemoteWindowTouchId = 10; } // namespace +void HandleOpenFile( + const string16& title, + const FilePath& default_path, + const string16& filter, + const OpenFileCompletion& callback) { + DCHECK(aura::RemoteRootWindowHostWin::Instance()); + aura::RemoteRootWindowHostWin::Instance()->HandleOpenFile(title, + default_path, + filter, + callback); +} + +void HandleOpenMultipleFiles( + const string16& title, + const FilePath& default_path, + const string16& filter, + const OpenMultipleFilesCompletion& callback) { + DCHECK(aura::RemoteRootWindowHostWin::Instance()); + aura::RemoteRootWindowHostWin::Instance()->HandleOpenMultipleFiles( + title, + default_path, + filter, + callback); +} + +void HandleSaveFile( + const string16& title, + const FilePath& default_path, + const string16& filter, + int filter_index, + const string16& default_extension, + const SaveFileCompletion& callback) { + DCHECK(aura::RemoteRootWindowHostWin::Instance()); + aura::RemoteRootWindowHostWin::Instance()->HandleSaveFile(title, + default_path, + filter, + filter_index, + default_extension, + callback); +} + RemoteRootWindowHostWin* g_instance = NULL; RemoteRootWindowHostWin* RemoteRootWindowHostWin::Instance() { @@ -77,11 +118,76 @@ bool RemoteRootWindowHostWin::OnMessageReceived(const IPC::Message& message) { OnTouchUp) IPC_MESSAGE_HANDLER(MetroViewerHostMsg_TouchMoved, OnTouchMoved) + IPC_MESSAGE_HANDLER(MetroViewerHostMsg_FileSaveAsDone, + OnFileSaveAsDone) + IPC_MESSAGE_HANDLER(MetroViewerHostMsg_FileOpenDone, + OnFileOpenDone) + IPC_MESSAGE_HANDLER(MetroViewerHostMsg_MultiFileOpenDone, + OnMultiFileOpenDone) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } +void RemoteRootWindowHostWin::HandleOpenFile( + const string16& title, + const FilePath& default_path, + const string16& filter, + const OpenFileCompletion& callback) { + if (!host_) + return; + + // Can only one of these operations in flight. + DCHECK(file_open_completion_callback_.is_null()); + file_open_completion_callback_ = callback; + + host_->Send(new MetroViewerHostMsg_DisplayFileOpen(title, + filter, + default_path.value(), + false)); +} + +void RemoteRootWindowHostWin::HandleOpenMultipleFiles( + const string16& title, + const FilePath& default_path, + const string16& filter, + const OpenMultipleFilesCompletion& callback) { + if (!host_) + return; + + // Can only one of these operations in flight. + DCHECK(multi_file_open_completion_callback_.is_null()); + multi_file_open_completion_callback_ = callback; + + host_->Send(new MetroViewerHostMsg_DisplayFileOpen(title, + filter, + default_path.value(), + true)); +} + +void RemoteRootWindowHostWin::HandleSaveFile( + const string16& title, + const FilePath& default_path, + const string16& filter, + int filter_index, + const string16& default_extension, + const SaveFileCompletion& callback) { + if (!host_) + return; + + MetroViewerHostMsg_SaveAsDialogParams params; + params.title = title; + params.default_extension = default_extension; + params.filter = filter; + params.filter_index = filter_index; + + // Can only one of these operations in flight. + DCHECK(file_saveas_completion_callback_.is_null()); + file_saveas_completion_callback_ = callback; + + host_->Send(new MetroViewerHostMsg_DisplayFileSaveAs(params)); +} + void RemoteRootWindowHostWin::SetDelegate(RootWindowHostDelegate* delegate) { delegate_ = delegate; } @@ -271,4 +377,32 @@ void RemoteRootWindowHostWin::OnTouchMoved(int32 x, delegate_->OnHostTouchEvent(&event); } +void RemoteRootWindowHostWin::OnFileSaveAsDone(bool success, + string16 filename, + int filter_index) { + if (success) { + file_saveas_completion_callback_.Run( + FilePath(filename), filter_index, NULL); + } + file_saveas_completion_callback_.Reset(); +} + + +void RemoteRootWindowHostWin::OnFileOpenDone(bool success, string16 filename) { + if (success) { + file_open_completion_callback_.Run( + FilePath(filename), 0, NULL); + } + file_open_completion_callback_.Reset(); +} + +void RemoteRootWindowHostWin::OnMultiFileOpenDone( + bool success, + const std::vector<FilePath>& files) { + if (success) { + multi_file_open_completion_callback_.Run(files, NULL); + } + multi_file_open_completion_callback_.Reset(); +} + } // namespace aura diff --git a/ui/aura/remote_root_window_host_win.h b/ui/aura/remote_root_window_host_win.h index d790015..de69eb2 100644 --- a/ui/aura/remote_root_window_host_win.h +++ b/ui/aura/remote_root_window_host_win.h @@ -7,9 +7,14 @@ #include <vector> +#include "base/callback.h" #include "base/compiler_specific.h" +#include "base/string16.h" #include "ui/aura/root_window_host.h" #include "ui/base/events/event_constants.h" +#include "ui/gfx/native_widget_types.h" + +class FilePath; namespace ui { class ViewProp; @@ -21,6 +26,44 @@ class Sender; } namespace aura { + +typedef base::Callback<void(const FilePath&, int, void*)> + OpenFileCompletion; + +typedef base::Callback<void(const std::vector<FilePath>&, void*)> + OpenMultipleFilesCompletion; + +typedef base::Callback<void(const FilePath&, int, void*)> + SaveFileCompletion; + +// Handles the open file operation for Metro Chrome Ash. The callback passed in +// is invoked when we receive the opened file name from the metro viewer. +AURA_EXPORT void HandleOpenFile( + const string16& title, + const FilePath& default_path, + const string16& filter, + const OpenFileCompletion& callback); + +// Handles the open multiple file operation for Metro Chrome Ash. The callback +// passed in is invoked when we receive the opened file names from the metro +// viewer. +AURA_EXPORT void HandleOpenMultipleFiles( + const string16& title, + const FilePath& default_path, + const string16& filter, + const OpenMultipleFilesCompletion& callback); + +// Handles the save file operation for Metro Chrome Ash. The callback passed in +// is invoked when we receive the saved file name from the metro viewer. +AURA_EXPORT void HandleSaveFile( + const string16& title, + const FilePath& default_path, + const string16& filter, + int filter_index, + const string16& default_extension, + const SaveFileCompletion& callback); + + // RootWindowHost implementaton that receives events from a different // process. In the case of Windows this is the Windows 8 (aka Metro) // frontend process, which forwards input events to this class. @@ -38,6 +81,26 @@ class AURA_EXPORT RemoteRootWindowHostWin : public RootWindowHost { // Called when we have a message from the remote process. bool OnMessageReceived(const IPC::Message& message); + void HandleOpenFile( + const string16& title, + const FilePath& default_path, + const string16& filter, + const OpenFileCompletion& callback); + + void HandleOpenMultipleFiles( + const string16& title, + const FilePath& default_path, + const string16& filter, + const OpenMultipleFilesCompletion& callback); + + void HandleSaveFile( + const string16& title, + const FilePath& default_path, + const string16& filter, + int filter_index, + const string16& default_extension, + const SaveFileCompletion& callback); + private: explicit RemoteRootWindowHostWin(const gfx::Rect& bounds); virtual ~RemoteRootWindowHostWin(); @@ -65,6 +128,12 @@ class AURA_EXPORT RemoteRootWindowHostWin : public RootWindowHost { void OnTouchDown(int32 x, int32 y, uint64 timestamp); void OnTouchUp(int32 x, int32 y, uint64 timestamp); void OnTouchMoved(int32 x, int32 y, uint64 timestamp); + void OnFileSaveAsDone(bool success, + string16 filename, + int filter_index); + void OnFileOpenDone(bool success, string16 filename); + void OnMultiFileOpenDone(bool success, + const std::vector<FilePath>& files); // RootWindowHost overrides: virtual void SetDelegate(RootWindowHostDelegate* delegate) OVERRIDE; @@ -99,6 +168,12 @@ class AURA_EXPORT RemoteRootWindowHostWin : public RootWindowHost { IPC::Sender* host_; scoped_ptr<ui::ViewProp> prop_; + // Saved callbacks which inform the caller about the result of the open file/ + // save file operations. + OpenFileCompletion file_open_completion_callback_; + OpenMultipleFilesCompletion multi_file_open_completion_callback_; + SaveFileCompletion file_saveas_completion_callback_; + DISALLOW_COPY_AND_ASSIGN(RemoteRootWindowHostWin); }; diff --git a/ui/metro_viewer/metro_viewer_messages.h b/ui/metro_viewer/metro_viewer_messages.h index 2b4a083..ec625f0 100644 --- a/ui/metro_viewer/metro_viewer_messages.h +++ b/ui/metro_viewer/metro_viewer_messages.h @@ -4,6 +4,8 @@ // Multiply-included message file, no include guard. +#include <vector> + #include "base/basictypes.h" #include "ipc/ipc_message_macros.h" #include "ui/base/events/event_constants.h" @@ -65,8 +67,57 @@ IPC_MESSAGE_CONTROL3(MetroViewerHostMsg_TouchMoved, int32, /* y-coordinate */ uint64) /* timestamp */ +// Informs the browser of the result of a file save as operation. +IPC_MESSAGE_CONTROL3(MetroViewerHostMsg_FileSaveAsDone, + bool, /* success */ + string16, /* filename */ + int) /* filter_index */ + +// Informs the browser of the result of a file open operation. +IPC_MESSAGE_CONTROL2(MetroViewerHostMsg_FileOpenDone, + bool, /* success */ + string16) /* filename */ + +IPC_MESSAGE_CONTROL2(MetroViewerHostMsg_MultiFileOpenDone, + bool, /* success */ + std::vector<FilePath>) /* filenames */ + + // Messages sent from the browser to the viewer: // Requests the viewer to change the pointer to a new cursor. IPC_MESSAGE_CONTROL1(MetroViewerHostMsg_SetCursor, int64 /* cursor */); + +// This structure contains the parameters sent to the viewer process to display +// the file save dialog. +IPC_STRUCT_BEGIN(MetroViewerHostMsg_SaveAsDialogParams) + + // The title of the file save dialog if any. + IPC_STRUCT_MEMBER(string16, title) + + // The suggested file name. + IPC_STRUCT_MEMBER(string16, suggested_name) + + // The save as filter to be used. + IPC_STRUCT_MEMBER(string16, filter) + + // The filter index. + IPC_STRUCT_MEMBER(uint32, filter_index) + + // The default extension. + IPC_STRUCT_MEMBER(string16, default_extension) + +IPC_STRUCT_END() + +// Requests the viewer to display the file save dialog. +IPC_MESSAGE_CONTROL1(MetroViewerHostMsg_DisplayFileSaveAs, + MetroViewerHostMsg_SaveAsDialogParams) + +// Requests the viewer to display the file open dialog. +IPC_MESSAGE_CONTROL4(MetroViewerHostMsg_DisplayFileOpen, + string16, /* title */ + string16, /* filter */ + string16, /* Default path */ + bool) /* allow_multi_select */ + diff --git a/ui/shell_dialogs/select_file_dialog.cc b/ui/shell_dialogs/select_file_dialog.cc index 2cf7d24..5423329 100644 --- a/ui/shell_dialogs/select_file_dialog.cc +++ b/ui/shell_dialogs/select_file_dialog.cc @@ -12,6 +12,7 @@ #include "ui/shell_dialogs/select_file_dialog_factory.h" #include "ui/shell_dialogs/select_file_policy.h" #include "ui/shell_dialogs/selected_file_info.h" +#include "ui/shell_dialogs/shell_dialogs_delegate.h" #if defined(OS_WIN) #include "ui/shell_dialogs/select_file_dialog_win.h" @@ -30,6 +31,9 @@ namespace { // Optional dialog factory. Leaked. ui::SelectFileDialogFactory* dialog_factory_ = NULL; +// The global shell dialogs delegate. +ui::ShellDialogsDelegate* g_shell_dialogs_delegate_ = NULL; + } // namespace namespace ui { @@ -127,6 +131,11 @@ bool SelectFileDialog::HasMultipleFileTypeChoices() { return HasMultipleFileTypeChoicesImpl(); } +// static +void SelectFileDialog::SetShellDialogsDelegate(ShellDialogsDelegate* delegate) { + g_shell_dialogs_delegate_ = delegate; +} + SelectFileDialog::SelectFileDialog(Listener* listener, ui::SelectFilePolicy* policy) : listener_(listener), @@ -141,4 +150,8 @@ void SelectFileDialog::CancelFileSelection(void* params) { listener_->FileSelectionCanceled(params); } +ShellDialogsDelegate* SelectFileDialog::GetShellDialogsDelegate() { + return g_shell_dialogs_delegate_; +} + } // namespace ui diff --git a/ui/shell_dialogs/select_file_dialog.h b/ui/shell_dialogs/select_file_dialog.h index 6478b6b..60b2462 100644 --- a/ui/shell_dialogs/select_file_dialog.h +++ b/ui/shell_dialogs/select_file_dialog.h @@ -23,6 +23,7 @@ namespace ui { class SelectFileDialogFactory; class SelectFilePolicy; struct SelectedFileInfo; +class ShellDialogsDelegate; // Shows a dialog box for selecting a file or a folder. class SHELL_DIALOGS_EXPORT SelectFileDialog @@ -157,6 +158,9 @@ class SHELL_DIALOGS_EXPORT SelectFileDialog void* params); bool HasMultipleFileTypeChoices(); + // Sets the global ShellDialogsDelegate. Defaults to NULL. + static void SetShellDialogsDelegate(ShellDialogsDelegate* delegate); + protected: friend class base::RefCountedThreadSafe<SelectFileDialog>; explicit SelectFileDialog(Listener* listener, @@ -176,6 +180,9 @@ class SHELL_DIALOGS_EXPORT SelectFileDialog gfx::NativeWindow owning_window, void* params) = 0; + // Returns the global ShellDialogsDelegate instance if any. + ShellDialogsDelegate* GetShellDialogsDelegate(); + // The listener to be notified of selection completion. Listener* listener_; diff --git a/ui/shell_dialogs/select_file_dialog_win.cc b/ui/shell_dialogs/select_file_dialog_win.cc index 7c31600..2ee4c0e 100644 --- a/ui/shell_dialogs/select_file_dialog_win.cc +++ b/ui/shell_dialogs/select_file_dialog_win.cc @@ -29,10 +29,11 @@ #include "ui/base/l10n/l10n_util.h" #include "ui/gfx/native_widget_types.h" #include "ui/shell_dialogs/base_shell_dialog_win.h" +#include "ui/shell_dialogs/shell_dialogs_delegate.h" #if defined(USE_AURA) +#include "ui/aura/remote_root_window_host_win.h" #include "ui/aura/root_window.h" -#include "ui/aura/window.h" #endif namespace { @@ -510,8 +511,11 @@ class SelectFileDialogImpl : public ui::SelectFileDialog, virtual bool HasMultipleFileTypeChoicesImpl() OVERRIDE; - bool has_multiple_file_type_choices_; + // Returns the filter to be used while displaying the open/save file dialog. + // This is computed from the extensions for the file types being opened. + string16 GetFilterForFileTypes(const FileTypeInfo& file_types); + bool has_multiple_file_type_choices_; DISALLOW_COPY_AND_ASSIGN(SelectFileDialogImpl); }; @@ -538,6 +542,38 @@ void SelectFileDialogImpl::SelectFileImpl( has_multiple_file_type_choices_ = file_types ? file_types->extensions.size() > 1 : true; #if defined(USE_AURA) + // If the owning_window passed in is in metro then we need to forward the + // file open/save operations to metro. + if (GetShellDialogsDelegate() && + GetShellDialogsDelegate()->IsWindowInMetro(owning_window)) { + if (type == SELECT_SAVEAS_FILE) { + aura::HandleSaveFile( + UTF16ToWide(title), + default_path, + GetFilterForFileTypes(*file_types), + file_type_index, + default_extension, + base::Bind(&ui::SelectFileDialog::Listener::FileSelected, + base::Unretained(listener_))); + return; + } else if (type == SELECT_OPEN_FILE) { + aura::HandleOpenFile( + UTF16ToWide(title), + default_path, + GetFilterForFileTypes(*file_types), + base::Bind(&ui::SelectFileDialog::Listener::FileSelected, + base::Unretained(listener_))); + return; + } else if (type == SELECT_OPEN_MULTI_FILE) { + aura::HandleOpenMultipleFiles( + UTF16ToWide(title), + default_path, + GetFilterForFileTypes(*file_types), + base::Bind(&ui::SelectFileDialog::Listener::MultiFilesSelected, + base::Unretained(listener_))); + return; + } + } HWND owner = owning_window->GetRootWindow()->GetAcceleratedWidget(); #else HWND owner = owning_window; @@ -573,23 +609,7 @@ void SelectFileDialogImpl::ListenerDestroyed() { void SelectFileDialogImpl::ExecuteSelectFile( const ExecuteSelectParams& params) { - std::vector<std::wstring> exts; - for (size_t i = 0; i < params.file_types.extensions.size(); ++i) { - const std::vector<std::wstring>& inner_exts = - params.file_types.extensions[i]; - std::wstring ext_string; - for (size_t j = 0; j < inner_exts.size(); ++j) { - if (!ext_string.empty()) - ext_string.push_back(L';'); - ext_string.append(L"*."); - ext_string.append(inner_exts[j]); - } - exts.push_back(ext_string); - } - std::wstring filter = FormatFilterForExtensions( - exts, - params.file_types.extension_description_overrides, - params.file_types.include_all_files); + string16 filter = GetFilterForFileTypes(params.file_types); FilePath path = params.default_path; bool success = false; @@ -825,6 +845,26 @@ bool SelectFileDialogImpl::RunOpenMultiFileDialog( return success; } +string16 SelectFileDialogImpl::GetFilterForFileTypes( + const FileTypeInfo& file_types) { + std::vector<string16> exts; + for (size_t i = 0; i < file_types.extensions.size(); ++i) { + const std::vector<string16>& inner_exts = file_types.extensions[i]; + string16 ext_string; + for (size_t j = 0; j < inner_exts.size(); ++j) { + if (!ext_string.empty()) + ext_string.push_back(L';'); + ext_string.append(L"*."); + ext_string.append(inner_exts[j]); + } + exts.push_back(ext_string); + } + return FormatFilterForExtensions( + exts, + file_types.extension_description_overrides, + file_types.include_all_files); +} + } // namespace namespace ui { diff --git a/ui/shell_dialogs/shell_dialogs_delegate.h b/ui/shell_dialogs/shell_dialogs_delegate.h new file mode 100644 index 0000000..ca2c57cf --- /dev/null +++ b/ui/shell_dialogs/shell_dialogs_delegate.h @@ -0,0 +1,24 @@ +// Copyright 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 UI_SHELL_DIALOGS_SELECT_FILE_DIALOG_DELEGATE_H_ +#define UI_SHELL_DIALOGS_SELECT_FILE_DIALOG_DELEGATE_H_ + +#include "ui/gfx/native_widget_types.h" +#include "ui/shell_dialogs/shell_dialogs_export.h" + +namespace ui { + +class SHELL_DIALOGS_EXPORT ShellDialogsDelegate { + public: + virtual ~ShellDialogsDelegate() {} + + // Returns true if the window passed in is in the Windows 8 metro + // environment. + virtual bool IsWindowInMetro(gfx::NativeWindow window) = 0; +}; + +} // namespace ui + +#endif // UI_SHELL_DIALOGS_SELECT_FILE_DIALOG_DELEGATE_H_ 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_ |