diff options
author | robertshield@chromium.org <robertshield@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98> | 2012-09-07 19:17:08 +0000 |
---|---|---|
committer | robertshield@chromium.org <robertshield@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98> | 2012-09-07 19:17:08 +0000 |
commit | 5b963d0f04a1e4baf5bf9a371890bbb698520f7d (patch) | |
tree | 9c020c289fa550d28b6b67789ee199a77ef759fb /win8/delegate_execute | |
parent | d13928d51c251bdcc76b961c1ad8bb9339da9917 (diff) | |
download | chromium_src-5b963d0f04a1e4baf5bf9a371890bbb698520f7d.zip chromium_src-5b963d0f04a1e4baf5bf9a371890bbb698520f7d.tar.gz chromium_src-5b963d0f04a1e4baf5bf9a371890bbb698520f7d.tar.bz2 |
Integrate the Windows 8 code into the Chromium tree (take 2).
This time, also: fix invalid path in metro_driver.gyp. Also, set executable bit on check_sdk_patch.py and post_build.bat.
This reverts "Revert 155429 - Integrate the Windows 8 code into the Chromium tree."
Original CL: https://chromiumcodereview.appspot.com/10875008
BUG=127799
TEST=A Chromium build can run as the immersive browser on Windows 8.
TBR=ben
Review URL: https://chromiumcodereview.appspot.com/10912152
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@155444 0039d316-1c4b-4281-b951-d872f2087c98
Diffstat (limited to 'win8/delegate_execute')
-rw-r--r-- | win8/delegate_execute/chrome_util.cc | 267 | ||||
-rw-r--r-- | win8/delegate_execute/chrome_util.h | 22 | ||||
-rw-r--r-- | win8/delegate_execute/command_execute_impl.cc | 440 | ||||
-rw-r--r-- | win8/delegate_execute/command_execute_impl.h | 105 | ||||
-rw-r--r-- | win8/delegate_execute/command_execute_impl.rgs | 10 | ||||
-rw-r--r-- | win8/delegate_execute/delegate_execute.cc | 120 | ||||
-rw-r--r-- | win8/delegate_execute/delegate_execute.gyp | 46 | ||||
-rw-r--r-- | win8/delegate_execute/delegate_execute.rgs | 3 | ||||
-rw-r--r-- | win8/delegate_execute/delegate_execute_operation.cc | 37 | ||||
-rw-r--r-- | win8/delegate_execute/delegate_execute_operation.h | 52 | ||||
-rwxr-xr-x | win8/delegate_execute/post_build.bat | 3 | ||||
-rw-r--r-- | win8/delegate_execute/resource.h | 22 |
12 files changed, 1127 insertions, 0 deletions
diff --git a/win8/delegate_execute/chrome_util.cc b/win8/delegate_execute/chrome_util.cc new file mode 100644 index 0000000..701f2e8 --- /dev/null +++ b/win8/delegate_execute/chrome_util.cc @@ -0,0 +1,267 @@ +// Copyright (c) 2012 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 "win8/delegate_execute/chrome_util.h" + +#include <atlbase.h> +#include <shlobj.h> +#include <windows.h> + +#include <algorithm> +#include <limits> +#include <string> + +#include "base/file_path.h" +#include "base/file_util.h" +#include "base/md5.h" +#include "base/process_util.h" +#include "base/string_util.h" +#include "base/utf_string_conversions.h" +#include "base/win/registry.h" +#include "base/win/scoped_comptr.h" +#include "base/win/scoped_handle.h" +#include "base/win/win_util.h" +#include "google_update/google_update_idl.h" + +namespace { + +#if defined(GOOGLE_CHROME_BUILD) +const wchar_t kAppUserModelId[] = L"Chrome"; +#else // GOOGLE_CHROME_BUILD +const wchar_t kAppUserModelId[] = L"Chromium"; +#endif // GOOGLE_CHROME_BUILD + +#if defined(GOOGLE_CHROME_BUILD) + +// TODO(grt): These constants live in installer_util. Consider moving them +// into common_constants to allow for reuse. +const FilePath::CharType kNewChromeExe[] = FILE_PATH_LITERAL("new_chrome.exe"); +const wchar_t kRenameCommandValue[] = L"cmd"; +const wchar_t kChromeAppGuid[] = L"{8A69D345-D564-463c-AFF1-A69D9E530F96}"; +const wchar_t kRegPathChromeClient[] = + L"Software\\Google\\Update\\Clients\\" + L"{8A69D345-D564-463c-AFF1-A69D9E530F96}"; +const int kExitCodeRenameSuccessful = 23; + +// Returns the name of the global event used to detect if |chrome_exe| is in +// use by a browser process. +// TODO(grt): Move this somewhere central so it can be used by both this +// IsBrowserRunning (below) and IsBrowserAlreadyRunning (browser_util_win.cc). +string16 GetEventName(const FilePath& chrome_exe) { + static wchar_t const kEventPrefix[] = L"Global\\"; + const size_t prefix_len = arraysize(kEventPrefix) - 1; + string16 name; + name.reserve(prefix_len + chrome_exe.value().size()); + name.assign(kEventPrefix, prefix_len); + name.append(chrome_exe.value()); + std::replace(name.begin() + prefix_len, name.end(), '\\', '!'); + std::transform(name.begin() + prefix_len, name.end(), + name.begin() + prefix_len, tolower); + return name; +} + +// Returns true if |chrome_exe| is in use by a browser process. In this case, +// "in use" means past ChromeBrowserMainParts::PreMainMessageLoopRunImpl. +bool IsBrowserRunning(const FilePath& chrome_exe) { + base::win::ScopedHandle handle(::OpenEvent( + SYNCHRONIZE, FALSE, GetEventName(chrome_exe).c_str())); + if (handle.IsValid()) + return true; + DWORD last_error = ::GetLastError(); + if (last_error != ERROR_FILE_NOT_FOUND) { + AtlTrace("%hs. Failed to open browser event; error %u.\n", __FUNCTION__, + last_error); + } + return false; +} + +// Returns true if the file new_chrome.exe exists in the same directory as +// |chrome_exe|. +bool NewChromeExeExists(const FilePath& chrome_exe) { + FilePath new_chrome_exe(chrome_exe.DirName().Append(kNewChromeExe)); + return file_util::PathExists(new_chrome_exe); +} + +bool GetUpdateCommand(bool is_per_user, string16* update_command) { + const HKEY root = is_per_user ? HKEY_CURRENT_USER : HKEY_LOCAL_MACHINE; + base::win::RegKey key(root, kRegPathChromeClient, KEY_QUERY_VALUE); + + return key.ReadValue(kRenameCommandValue, update_command) == ERROR_SUCCESS; +} + +#endif // GOOGLE_CHROME_BUILD + +// TODO(grt): This code also lives in installer_util. Refactor for reuse. +bool IsPerUserInstall(const FilePath& chrome_exe) { + wchar_t program_files_path[MAX_PATH] = {0}; + if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_PROGRAM_FILES, NULL, + SHGFP_TYPE_CURRENT, program_files_path))) { + return !StartsWith(chrome_exe.value().c_str(), program_files_path, false); + } else { + NOTREACHED(); + } + return true; +} + +// TODO(gab): This code also lives in shell_util. Refactor for reuse. +string16 ByteArrayToBase32(const uint8* bytes, size_t size) { + static const char kEncoding[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; + + // Eliminate special cases first. + if (size == 0) { + return string16(); + } else if (size == 1) { + string16 ret; + ret.push_back(kEncoding[(bytes[0] & 0xf8) >> 3]); + ret.push_back(kEncoding[(bytes[0] & 0x07) << 2]); + return ret; + } else if (size >= std::numeric_limits<size_t>::max() / 8) { + // If |size| is too big, the calculation of |encoded_length| below will + // overflow. + AtlTrace("%hs. Byte array is too long.\n", __FUNCTION__); + return string16(); + } + + // Overestimate the number of bits in the string by 4 so that dividing by 5 + // is the equivalent of rounding up the actual number of bits divided by 5. + const size_t encoded_length = (size * 8 + 4) / 5; + + string16 ret; + ret.reserve(encoded_length); + + // A bit stream which will be read from the left and appended to from the + // right as it's emptied. + uint16 bit_stream = (bytes[0] << 8) + bytes[1]; + size_t next_byte_index = 2; + int free_bits = 0; + while (free_bits < 16) { + // Extract the 5 leftmost bits in the stream + ret.push_back(kEncoding[(bit_stream & 0xf800) >> 11]); + bit_stream <<= 5; + free_bits += 5; + + // If there is enough room in the bit stream, inject another byte (if there + // are any left...). + if (free_bits >= 8 && next_byte_index < size) { + free_bits -= 8; + bit_stream += bytes[next_byte_index++] << free_bits; + } + } + + if (ret.length() != encoded_length) { + AtlTrace("%hs. Encoding doesn't match expected length.\n", __FUNCTION__); + return string16(); + } + return ret; +} + +// TODO(gab): This code also lives in shell_util. Refactor for reuse. +bool GetUserSpecificRegistrySuffix(string16* suffix) { + string16 user_sid; + if (!base::win::GetUserSidString(&user_sid)) { + AtlTrace("%hs. GetUserSidString failed.\n", __FUNCTION__); + return false; + } + COMPILE_ASSERT(sizeof(base::MD5Digest) == 16, size_of_MD5_not_as_expected_); + base::MD5Digest md5_digest; + std::string user_sid_ascii(UTF16ToASCII(user_sid)); + base::MD5Sum(user_sid_ascii.c_str(), user_sid_ascii.length(), &md5_digest); + const string16 base32_md5( + ByteArrayToBase32(md5_digest.a, arraysize(md5_digest.a))); + // The value returned by the base32 algorithm above must never change and must + // always be 26 characters long (i.e. if someone ever moves this to base and + // implements the full base32 algorithm (i.e. with appended '=' signs in the + // output), they must provide a flag to allow this method to still request + // the output with no appended '=' signs). + if (base32_md5.length() != 26U) { + AtlTrace("%hs. Base32 encoding of md5 hash is incorrect.\n", __FUNCTION__); + return false; + } + suffix->reserve(base32_md5.length() + 1); + suffix->assign(1, L'.'); + suffix->append(base32_md5); + return true; +} + +} // namespace + +namespace delegate_execute { + +void UpdateChromeIfNeeded(const FilePath& chrome_exe) { +#if defined(GOOGLE_CHROME_BUILD) + // Nothing to do if a browser is already running or if there's no + // new_chrome.exe. + if (IsBrowserRunning(chrome_exe) || !NewChromeExeExists(chrome_exe)) + return; + + base::ProcessHandle process_handle = base::kNullProcessHandle; + + if (IsPerUserInstall(chrome_exe)) { + // Read the update command from the registry. + string16 update_command; + if (!GetUpdateCommand(true, &update_command)) { + AtlTrace("%hs. Failed to read update command from registry.\n", + __FUNCTION__); + } else { + // Run the update command. + base::LaunchOptions launch_options; + launch_options.start_hidden = true; + if (!base::LaunchProcess(update_command, launch_options, + &process_handle)) { + AtlTrace("%hs. Failed to launch command to finalize update; " + "error %u.\n", __FUNCTION__, ::GetLastError()); + process_handle = base::kNullProcessHandle; + } + } + } else { + // Run the update command via Google Update. + HRESULT hr = S_OK; + base::win::ScopedComPtr<IProcessLauncher> process_launcher; + hr = process_launcher.CreateInstance(__uuidof(ProcessLauncherClass)); + if (FAILED(hr)) { + AtlTrace("%hs. Failed to Create ProcessLauncher; hr=0x%X.\n", + __FUNCTION__, hr); + } else { + ULONG_PTR handle = 0; + hr = process_launcher->LaunchCmdElevated( + kChromeAppGuid, kRenameCommandValue, GetCurrentProcessId(), &handle); + if (FAILED(hr)) { + AtlTrace("%hs. Failed to launch command to finalize update; " + "hr=0x%X.\n", __FUNCTION__, hr); + } else { + process_handle = reinterpret_cast<base::ProcessHandle>(handle); + } + } + } + + // Wait for the update to complete and report the results. + if (process_handle != base::kNullProcessHandle) { + int exit_code = 0; + // WaitForExitCode will close the handle in all cases. + if (!base::WaitForExitCode(process_handle, &exit_code)) { + AtlTrace("%hs. Failed to get result when finalizing update.\n", + __FUNCTION__); + } else if (exit_code != kExitCodeRenameSuccessful) { + AtlTrace("%hs. Failed to finalize update with exit code %d.\n", + __FUNCTION__, exit_code); + } else { + AtlTrace("%hs. Finalized pending update.\n", __FUNCTION__); + } + } +#endif +} + +// TODO(gab): This code also lives in shell_util. Refactor for reuse. +string16 GetAppId(const FilePath& chrome_exe) { + string16 app_id(kAppUserModelId); + string16 suffix; + if (IsPerUserInstall(chrome_exe) && + !GetUserSpecificRegistrySuffix(&suffix)) { + AtlTrace("%hs. GetUserSpecificRegistrySuffix failed.\n", + __FUNCTION__); + } + return app_id.append(suffix); +} + +} // delegate_execute diff --git a/win8/delegate_execute/chrome_util.h b/win8/delegate_execute/chrome_util.h new file mode 100644 index 0000000..634ce6c --- /dev/null +++ b/win8/delegate_execute/chrome_util.h @@ -0,0 +1,22 @@ +// Copyright (c) 2012 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 WIN8_DELEGATE_EXECUTE_CHROME_UTIL_H_ +#define WIN8_DELEGATE_EXECUTE_CHROME_UTIL_H_ + +#include "base/string16.h" + +class FilePath; + +namespace delegate_execute { + +// Finalizes a previously updated installation. +void UpdateChromeIfNeeded(const FilePath& chrome_exe); + +// Returns the appid of the Chrome pointed to by |chrome_exe|. +string16 GetAppId(const FilePath& chrome_exe); + +} // namespace delegate_execute + +#endif // WIN8_DELEGATE_EXECUTE_CHROME_UTIL_H_ diff --git a/win8/delegate_execute/command_execute_impl.cc b/win8/delegate_execute/command_execute_impl.cc new file mode 100644 index 0000000..ef1378a --- /dev/null +++ b/win8/delegate_execute/command_execute_impl.cc @@ -0,0 +1,440 @@ +// Copyright (c) 2012 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. +// Implementation of the CommandExecuteImpl class which implements the +// IExecuteCommand and related interfaces for handling ShellExecute based +// launches of the Chrome browser. + +#include "win8/delegate_execute/command_execute_impl.h" + +#include "base/file_util.h" +#include "base/path_service.h" +#include "base/utf_string_conversions.h" +#include "base/win/scoped_co_mem.h" +#include "base/win/scoped_handle.h" +#include "chrome/common/chrome_constants.h" +#include "chrome/common/chrome_paths.h" +#include "chrome/common/chrome_switches.h" +#include "win8/delegate_execute/chrome_util.h" + +// CommandExecuteImpl is resposible for activating chrome in Windows 8. The +// flow is complicated and this tries to highlight the important events. +// The current approach is to have a single instance of chrome either +// running in desktop or metro mode. If there is no current instance then +// the desktop shortcut launches desktop chrome and the metro tile or search +// charm launches metro chrome. +// If chrome is running then focus/activation is given to the existing one +// regarless of what launch point the user used. +// +// The general flow when chrome is the default browser is as follows: +// +// 1- User interacts with launch point (icon, tile, search, shellexec, etc) +// 2- Windows finds the appid for launch item and resolves it to chrome +// 3- Windows activates CommandExecuteImpl inside a surrogate process +// 4- Windows calls the following sequence of entry points: +// CommandExecuteImpl::SetShowWindow +// CommandExecuteImpl::SetPosition +// CommandExecuteImpl::SetDirectory +// CommandExecuteImpl::SetParameter +// CommandExecuteImpl::SetNoShowUI +// CommandExecuteImpl::SetSelection +// CommandExecuteImpl::Initialize +// Up to this point the code basically just gathers values passed in, like +// the launch scheme (or url) and the activation verb. +// 5- Windows calls CommandExecuteImpl::Getvalue() +// Here we need to return AHE_IMMERSIVE or AHE_DESKTOP. That depends on: +// a) if run in high-integrity return AHE_DESKTOP +// b) if chrome is running return the AHE_ mode of chrome +// c) if the current process is inmmersive return AHE_IMMERSIVE +// d) if the protocol is file and IExecuteCommandHost::GetUIMode() is not +// ECHUIM_DESKTOP then return AHE_IMMERSIVE +// e) if none of the above return AHE_DESKTOP +// 6- If we returned AHE_DESKTOP in step 5 then CommandExecuteImpl::Execute() +// is called, here we call GetLaunchMode() which: +// a) if chrome is running return the mode of chrome or +// b) return IExecuteCommandHost::GetUIMode() +// 7- If GetLaunchMode() returns +// a) ECHUIM_DESKTOP we call LaunchDestopChrome() that calls ::CreateProcess +// b) else we call one of the IApplicationActivationManager activation +// functions depending on the parameters passed in step 4. +// +// Some examples will help clarify the common cases. +// +// I - No chrome running, taskbar icon launch: +// a) Scheme is 'file', Verb is 'open' +// b) GetValue() returns at e) step : AHE_DESKTOP +// c) Execute() calls LaunchDestopChrome() +// --> desktop chrome runs +// II- No chrome running, tile activation launch: +// a) Scheme is 'file', Verb is 'open' +// b) GetValue() returns at d) step : AHE_IMMERSIVE +// c) Windows does not call us back and just activates chrome +// --> metro chrome runs +// III- No chrome running, url link click on metro app: +// a) Scheme is 'http', Verb is 'open' +// b) Getvalue() returns at e) step : AHE_DESKTOP +// c) Execute() calls IApplicationActivationManager::ActivateForProtocol +// --> metro chrome runs +// +CommandExecuteImpl::CommandExecuteImpl() + : integrity_level_(base::INTEGRITY_UNKNOWN), + launch_scheme_(INTERNET_SCHEME_DEFAULT), + chrome_mode_(ECHUIM_SYSTEM_LAUNCHER) { + memset(&start_info_, 0, sizeof(start_info_)); + start_info_.cb = sizeof(start_info_); + // We need to query the user data dir of chrome so we need chrome's + // path provider. + chrome::RegisterPathProvider(); +} + +// CommandExecuteImpl +STDMETHODIMP CommandExecuteImpl::SetKeyState(DWORD key_state) { + AtlTrace("In %hs\n", __FUNCTION__); + return S_OK; +} + +STDMETHODIMP CommandExecuteImpl::SetParameters(LPCWSTR params) { + AtlTrace("In %hs [%S]\n", __FUNCTION__, params); + if (params) { + parameters_ = params; + } + return S_OK; +} + +STDMETHODIMP CommandExecuteImpl::SetPosition(POINT pt) { + AtlTrace("In %hs\n", __FUNCTION__); + return S_OK; +} + +STDMETHODIMP CommandExecuteImpl::SetShowWindow(int show) { + AtlTrace("In %hs show=%d\n", __FUNCTION__, show); + start_info_.wShowWindow = show; + start_info_.dwFlags |= STARTF_USESHOWWINDOW; + return S_OK; +} + +STDMETHODIMP CommandExecuteImpl::SetNoShowUI(BOOL no_show_ui) { + AtlTrace("In %hs no_show=%d\n", __FUNCTION__, no_show_ui); + return S_OK; +} + +STDMETHODIMP CommandExecuteImpl::SetDirectory(LPCWSTR directory) { + AtlTrace("In %hs\n", __FUNCTION__); + return S_OK; +} + +STDMETHODIMP CommandExecuteImpl::GetValue(enum AHE_TYPE* pahe) { + AtlTrace("In %hs\n", __FUNCTION__); + + if (!GetLaunchScheme(&display_name_, &launch_scheme_)) { + AtlTrace("Failed to get scheme, E_FAIL\n"); + return E_FAIL; + } + + if (integrity_level_ == base::HIGH_INTEGRITY) { + // Metro mode apps don't work in high integrity mode. + AtlTrace("High integrity, AHE_DESKTOP\n"); + *pahe = AHE_DESKTOP; + return S_OK; + } + + FilePath user_data_dir; + if (!PathService::Get(chrome::DIR_USER_DATA, &user_data_dir)) { + AtlTrace("Failed to get chrome's data dir path, E_FAIL\n"); + return E_FAIL; + } + + HWND chrome_window = ::FindWindowEx(HWND_MESSAGE, NULL, + chrome::kMessageWindowClass, + user_data_dir.value().c_str()); + if (chrome_window) { + AtlTrace("Found chrome window %p\n", chrome_window); + // The failure cases below are deemed to happen due to the inherently racy + // procedure of going from chrome's window to process handle during which + // chrome might have exited. Failing here would probably just cause the + // user to retry at which point we would do the right thing. + DWORD chrome_pid = 0; + ::GetWindowThreadProcessId(chrome_window, &chrome_pid); + if (!chrome_pid) { + AtlTrace("Failed to get chrome's PID, E_FAIL\n"); + return E_FAIL; + } + base::win::ScopedHandle process( + ::OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, chrome_pid)); + if (!process.IsValid()) { + AtlTrace("Failed to open chrome's process [%d], E_FAIL\n", chrome_pid); + return E_FAIL; + } + if (IsImmersiveProcess(process.Get())) { + AtlTrace("Chrome [%d] is inmmersive, AHE_IMMERSIVE\n", chrome_pid); + chrome_mode_ = ECHUIM_IMMERSIVE; + *pahe = AHE_IMMERSIVE; + } else { + AtlTrace("Chrome [%d] is Desktop, AHE_DESKTOP\n"); + chrome_mode_ = ECHUIM_DESKTOP; + *pahe = AHE_DESKTOP; + } + return S_OK; + } + + if (IsImmersiveProcess(GetCurrentProcess())) { + AtlTrace("Current process is inmmersive, AHE_IMMERSIVE\n"); + *pahe = AHE_IMMERSIVE; + return S_OK; + } + + if ((launch_scheme_ == INTERNET_SCHEME_FILE) && + (GetLaunchMode() != ECHUIM_DESKTOP)) { + AtlTrace("INTERNET_SCHEME_FILE, mode != ECHUIM_DESKTOP, AHE_IMMERSIVE\n"); + *pahe = AHE_IMMERSIVE; + return S_OK; + } + + AtlTrace("Fallback is AHE_DESKTOP\n"); + *pahe = AHE_DESKTOP; + return S_OK; +} + +STDMETHODIMP CommandExecuteImpl::Execute() { + AtlTrace("In %hs\n", __FUNCTION__); + + if (integrity_level_ == base::HIGH_INTEGRITY) + return LaunchDesktopChrome(); + + EC_HOST_UI_MODE mode = GetLaunchMode(); + if (mode == ECHUIM_DESKTOP) + return LaunchDesktopChrome(); + + HRESULT hr = E_FAIL; + CComPtr<IApplicationActivationManager> activation_manager; + hr = activation_manager.CoCreateInstance(CLSID_ApplicationActivationManager); + if (!activation_manager) { + AtlTrace("Failed to get the activation manager, error 0x%x\n", hr); + return S_OK; + } + + string16 app_id = delegate_execute::GetAppId(chrome_exe_); + + DWORD pid = 0; + if (launch_scheme_ == INTERNET_SCHEME_FILE) { + AtlTrace("Activating for file\n"); + hr = activation_manager->ActivateApplication(app_id.c_str(), + verb_.c_str(), + AO_NOERRORUI, + &pid); + } else { + AtlTrace("Activating for protocol\n"); + hr = activation_manager->ActivateForProtocol(app_id.c_str(), + item_array_, + &pid); + } + if (hr == E_APPLICATION_NOT_REGISTERED) { + AtlTrace("Metro chrome is not registered, launching in desktop\n"); + return LaunchDesktopChrome(); + } + AtlTrace("Metro Chrome launch, pid=%d, returned 0x%x\n", pid, hr); + return S_OK; +} + +STDMETHODIMP CommandExecuteImpl::Initialize(LPCWSTR name, + IPropertyBag* bag) { + AtlTrace("In %hs\n", __FUNCTION__); + if (!FindChromeExe(&chrome_exe_)) + return E_FAIL; + delegate_execute::UpdateChromeIfNeeded(chrome_exe_); + if (name) { + AtlTrace("Verb is %S\n", name); + verb_ = name; + } + + base::GetProcessIntegrityLevel(base::GetCurrentProcessHandle(), + &integrity_level_); + if (integrity_level_ == base::HIGH_INTEGRITY) { + AtlTrace("Delegate execute launched in high integrity level\n"); + } + return S_OK; +} + +STDMETHODIMP CommandExecuteImpl::SetSelection(IShellItemArray* item_array) { + AtlTrace("In %hs\n", __FUNCTION__); + item_array_ = item_array; + return S_OK; +} + +STDMETHODIMP CommandExecuteImpl::GetSelection(REFIID riid, void** selection) { + AtlTrace("In %hs\n", __FUNCTION__); + return S_OK; +} + +STDMETHODIMP CommandExecuteImpl::AllowForegroundTransfer(void* reserved) { + AtlTrace("In %hs\n", __FUNCTION__); + return S_OK; +} + +// Returns false if chrome.exe cannot be found. +// static +bool CommandExecuteImpl::FindChromeExe(FilePath* chrome_exe) { + AtlTrace("In %hs\n", __FUNCTION__); + // Look for chrome.exe one folder above delegate_execute.exe (as expected in + // Chrome installs). Failing that, look for it alonside delegate_execute.exe. + FilePath dir_exe; + if (!PathService::Get(base::DIR_EXE, &dir_exe)) { + AtlTrace("Failed to get current exe path\n"); + return false; + } + + *chrome_exe = dir_exe.DirName().Append(chrome::kBrowserProcessExecutableName); + if (!file_util::PathExists(*chrome_exe)) { + *chrome_exe = dir_exe.Append(chrome::kBrowserProcessExecutableName); + if (!file_util::PathExists(*chrome_exe)) { + AtlTrace("Failed to find chrome exe file\n"); + return false; + } + } + + AtlTrace("Got chrome exe path as %ls\n", chrome_exe->value().c_str()); + return true; +} + +bool CommandExecuteImpl::GetLaunchScheme( + string16* display_name, INTERNET_SCHEME* scheme) { + if (!item_array_) + return false; + + ATLASSERT(display_name); + ATLASSERT(scheme); + + DWORD count = 0; + item_array_->GetCount(&count); + + if (count != 1) { + AtlTrace("Cannot handle %d elements in the IShellItemArray\n", count); + return false; + } + + CComPtr<IEnumShellItems> items; + item_array_->EnumItems(&items); + CComPtr<IShellItem> shell_item; + HRESULT hr = items->Next(1, &shell_item, &count); + if (hr != S_OK) { + AtlTrace("Failed to read element from the IShellItemsArray\n"); + return false; + } + + base::win::ScopedCoMem<wchar_t> name; + hr = shell_item->GetDisplayName(SIGDN_URL, &name); + if (hr != S_OK) { + AtlTrace("Failed to get display name\n"); + return false; + } + + AtlTrace("Display name is [%ls]\n", name); + + wchar_t scheme_name[16]; + URL_COMPONENTS components = {0}; + components.lpszScheme = scheme_name; + components.dwSchemeLength = sizeof(scheme_name)/sizeof(scheme_name[0]); + + components.dwStructSize = sizeof(components); + if (!InternetCrackUrlW(name, 0, 0, &components)) { + AtlTrace("Failed to crack url %ls\n", name); + return false; + } + + AtlTrace("Launch scheme is [%ls] (%d)\n", scheme_name, components.nScheme); + *display_name = name; + *scheme = components.nScheme; + return true; +} + +HRESULT CommandExecuteImpl::LaunchDesktopChrome() { + AtlTrace("In %hs\n", __FUNCTION__); + string16 display_name = display_name_; + + switch (launch_scheme_) { + case INTERNET_SCHEME_FILE: + // If anything other than chrome.exe is passed in the display name we + // should honor it. For e.g. If the user clicks on a html file when + // chrome is the default we should treat it as a parameter to be passed + // to chrome. + if (display_name.find(L"chrome.exe") != string16::npos) + display_name.clear(); + break; + + default: + break; + } + + string16 command_line = L"\""; + command_line += chrome_exe_.value(); + command_line += L"\""; + + if (!parameters_.empty()) { + AtlTrace("Adding parameters %ls to command line\n", parameters_.c_str()); + command_line += L" "; + command_line += parameters_.c_str(); + } + + if (!display_name.empty()) { + command_line += L" -- "; + command_line += display_name; + } + + AtlTrace("Formatted command line is %ls\n", command_line.c_str()); + + PROCESS_INFORMATION proc_info = {0}; + BOOL ret = CreateProcess(NULL, const_cast<LPWSTR>(command_line.c_str()), + NULL, NULL, FALSE, 0, NULL, NULL, &start_info_, + &proc_info); + if (ret) { + AtlTrace("Process id is %d\n", proc_info.dwProcessId); + CloseHandle(proc_info.hProcess); + CloseHandle(proc_info.hThread); + } else { + AtlTrace("Process launch failed, error %d\n", ::GetLastError()); + } + + return S_OK; +} + +EC_HOST_UI_MODE CommandExecuteImpl::GetLaunchMode() { + // We are to return chrome's mode if chrome exists else we query our embedder + // IServiceProvider and learn the mode from them. + static bool launch_mode_determined = false; + static EC_HOST_UI_MODE launch_mode = ECHUIM_DESKTOP; + + const char* modes[] = { "Desktop", "Inmmersive", "SysLauncher", "??" }; + + if (launch_mode_determined) + return launch_mode; + + if (chrome_mode_ != ECHUIM_SYSTEM_LAUNCHER) { + launch_mode = chrome_mode_; + AtlTrace("Launch mode is that of chrome, %s\n", modes[launch_mode]); + launch_mode_determined = true; + return launch_mode; + } + + if (parameters_ == ASCIIToWide(switches::kForceImmersive)) { + launch_mode = ECHUIM_IMMERSIVE; + AtlTrace("Launch mode forced to %s\n", modes[launch_mode]); + launch_mode_determined = true; + return launch_mode; + } + + CComPtr<IExecuteCommandHost> host; + CComQIPtr<IServiceProvider> service_provider = m_spUnkSite; + if (service_provider) { + service_provider->QueryService(IID_IExecuteCommandHost, &host); + if (host) { + host->GetUIMode(&launch_mode); + } else { + AtlTrace("Failed to get IID_IExecuteCommandHost. Assuming desktop\n"); + } + } else { + AtlTrace("Failed to get IServiceProvider. Assuming desktop mode\n"); + } + AtlTrace("Launch mode is %s\n", modes[launch_mode]); + launch_mode_determined = true; + return launch_mode; +} diff --git a/win8/delegate_execute/command_execute_impl.h b/win8/delegate_execute/command_execute_impl.h new file mode 100644 index 0000000..5a1a95c --- /dev/null +++ b/win8/delegate_execute/command_execute_impl.h @@ -0,0 +1,105 @@ +// Copyright (c) 2012 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 <atlbase.h> +#include <atlcom.h> +#include <atlctl.h> +#include <ShObjIdl.h> +#include <WinInet.h> + +#include <string> + +#include "base/file_path.h" +#include "base/process_util.h" +#include "win8/delegate_execute/resource.h" // main symbols + +using namespace ATL; + +EXTERN_C const GUID CLSID_CommandExecuteImpl; + +// CommandExecuteImpl +// This class implements the IExecuteCommand and related interfaces for +// handling ShellExecute launches of the Chrome browser, i.e. whether to +// launch Chrome in metro mode or desktop mode. +#if defined(GOOGLE_CHROME_BUILD) +class ATL_NO_VTABLE DECLSPEC_UUID("5C65F4B0-3651-4514-B207-D10CB699B14B") + CommandExecuteImpl +#else // GOOGLE_CHROME_BUILD +class ATL_NO_VTABLE DECLSPEC_UUID("A2DF06F9-A21A-44A8-8A99-8B9C84F29160") + CommandExecuteImpl +#endif // GOOGLE_CHROME_BUILD + : public CComObjectRootEx<CComSingleThreadModel>, + public CComCoClass<CommandExecuteImpl, &CLSID_CommandExecuteImpl>, + public IExecuteCommand, + public IObjectWithSiteImpl<CommandExecuteImpl>, + public IInitializeCommand, + public IObjectWithSelection, + public IExecuteCommandApplicationHostEnvironment, + public IForegroundTransfer { + public: + CommandExecuteImpl(); + + DECLARE_REGISTRY_RESOURCEID(IDR_COMMANDEXECUTEIMPL) + + BEGIN_COM_MAP(CommandExecuteImpl) + COM_INTERFACE_ENTRY(IExecuteCommand) + COM_INTERFACE_ENTRY(IObjectWithSite) + COM_INTERFACE_ENTRY(IInitializeCommand) + COM_INTERFACE_ENTRY(IObjectWithSelection) + COM_INTERFACE_ENTRY(IExecuteCommandApplicationHostEnvironment) + COM_INTERFACE_ENTRY(IForegroundTransfer) + END_COM_MAP() + + DECLARE_PROTECT_FINAL_CONSTRUCT() + + HRESULT FinalConstruct() { + return S_OK; + } + + void FinalRelease() { + } + + public: + // IExecuteCommand + STDMETHOD(SetKeyState)(DWORD key_state); + STDMETHOD(SetParameters)(LPCWSTR params); + STDMETHOD(SetPosition)(POINT pt); + STDMETHOD(SetShowWindow)(int show); + STDMETHOD(SetNoShowUI)(BOOL no_show_ui); + STDMETHOD(SetDirectory)(LPCWSTR directory); + STDMETHOD(Execute)(void); + + // IInitializeCommand + STDMETHOD(Initialize)(LPCWSTR name, IPropertyBag* bag); + + // IObjectWithSelection + STDMETHOD(SetSelection)(IShellItemArray* item_array); + STDMETHOD(GetSelection)(REFIID riid, void** selection); + + // IExecuteCommandApplicationHostEnvironment + STDMETHOD(GetValue)(enum AHE_TYPE* pahe); + + // IForegroundTransfer + STDMETHOD(AllowForegroundTransfer)(void* reserved); + + private: + static bool FindChromeExe(FilePath* chrome_exe); + bool GetLaunchScheme(string16* display_name, INTERNET_SCHEME* scheme); + HRESULT LaunchDesktopChrome(); + // Returns the launch mode, i.e. desktop launch/metro launch, etc. + EC_HOST_UI_MODE GetLaunchMode(); + + CComPtr<IShellItemArray> item_array_; + string16 parameters_; + FilePath chrome_exe_; + STARTUPINFO start_info_; + string16 verb_; + string16 display_name_; + INTERNET_SCHEME launch_scheme_; + + base::IntegrityLevel integrity_level_; + EC_HOST_UI_MODE chrome_mode_; +}; + +OBJECT_ENTRY_AUTO(__uuidof(CommandExecuteImpl), CommandExecuteImpl) diff --git a/win8/delegate_execute/command_execute_impl.rgs b/win8/delegate_execute/command_execute_impl.rgs new file mode 100644 index 0000000..4f1aba3 --- /dev/null +++ b/win8/delegate_execute/command_execute_impl.rgs @@ -0,0 +1,10 @@ +HKCR { + NoRemove CLSID { + ForceRemove '%DELEGATE_EXECUTE_CLSID%' = s 'CommandExecuteImpl Class' { + ForceRemove Programmable + LocalServer32 = s '%MODULE%' { + val ServerExecutable = s '%MODULE_RAW%' + } + } + } +} diff --git a/win8/delegate_execute/delegate_execute.cc b/win8/delegate_execute/delegate_execute.cc new file mode 100644 index 0000000..9f3430c --- /dev/null +++ b/win8/delegate_execute/delegate_execute.cc @@ -0,0 +1,120 @@ +// Copyright (c) 2012 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 <atlbase.h> +#include <atlcom.h> +#include <atlctl.h> +#include <initguid.h> +#include <shellapi.h> + +#include "base/at_exit.h" +#include "base/command_line.h" +#include "base/file_util.h" +#include "base/string16.h" +#include "base/string_number_conversions.h" +#include "base/utf_string_conversions.h" +#include "base/win/scoped_com_initializer.h" +#include "base/win/scoped_handle.h" +#include "chrome/common/chrome_switches.h" +#include "command_execute_impl.h" +#include "win8/delegate_execute/delegate_execute_operation.h" +#include "win8/delegate_execute/resource.h" + +using namespace ATL; + +class DelegateExecuteModule + : public ATL::CAtlExeModuleT< DelegateExecuteModule > { + public : + typedef ATL::CAtlExeModuleT<DelegateExecuteModule> ParentClass; + + DECLARE_REGISTRY_APPID_RESOURCEID(IDR_DELEGATEEXECUTE, + "{B1935DA1-112F-479A-975B-AB8588ABA636}") + + virtual HRESULT AddCommonRGSReplacements(IRegistrarBase* registrar) throw() { + AtlTrace(L"In %hs\n", __FUNCTION__); + HRESULT hr = ParentClass::AddCommonRGSReplacements(registrar); + if (FAILED(hr)) + return hr; + + wchar_t delegate_execute_clsid[MAX_PATH] = {0}; + if (!StringFromGUID2(__uuidof(CommandExecuteImpl), delegate_execute_clsid, + ARRAYSIZE(delegate_execute_clsid))) { + ATLASSERT(false); + return E_FAIL; + } + + hr = registrar->AddReplacement(L"DELEGATE_EXECUTE_CLSID", + delegate_execute_clsid); + ATLASSERT(SUCCEEDED(hr)); + return hr; + } +}; + +DelegateExecuteModule _AtlModule; + +// Relaunch metro Chrome by ShellExecute on |shortcut| with --force-immersive. +// |handle_value| is an optional handle on which this function will wait before +// performing the relaunch. +int RelaunchChrome(const FilePath& shortcut, const string16& handle_value) { + base::win::ScopedHandle handle; + + if (!handle_value.empty()) { + uint32 the_handle = 0; + if (!base::StringToUint(handle_value, &the_handle)) { + // Failed to parse the handle value. Skip the wait but proceed with the + // relaunch. + AtlTrace(L"Failed to parse handle value %ls\n", handle_value.c_str()); + } else { + handle.Set(reinterpret_cast<HANDLE>(the_handle)); + } + } + + if (handle.IsValid()) { + AtlTrace(L"Waiting for chrome.exe to exit.\n"); + DWORD result = ::WaitForSingleObject(handle, 10 * 1000); + AtlTrace(L"And we're back.\n"); + if (result != WAIT_OBJECT_0) { + AtlTrace(L"Failed to wait for parent to exit; result=%u.\n", result); + // This could mean that Chrome has hung. Conservatively proceed with + // the relaunch anyway. + } + handle.Close(); + } + + base::win::ScopedCOMInitializer com_initializer; + + AtlTrace(L"Launching Chrome via %ls.\n", shortcut.value().c_str()); + int ser = reinterpret_cast<int>( + ::ShellExecute(NULL, NULL, shortcut.value().c_str(), + ASCIIToWide(switches::kForceImmersive).c_str(), NULL, + SW_SHOWNORMAL)); + AtlTrace(L"ShellExecute returned %d.\n", ser); + return ser <= 32; +} + +// +extern "C" int WINAPI _tWinMain(HINSTANCE , HINSTANCE, + LPTSTR, int nShowCmd) { + using delegate_execute::DelegateExecuteOperation; + base::AtExitManager exit_manager; + + CommandLine::Init(0, NULL); + CommandLine* cmd_line = CommandLine::ForCurrentProcess(); + DelegateExecuteOperation operation; + + operation.Initialize(cmd_line); + switch (operation.operation_type()) { + case DelegateExecuteOperation::EXE_MODULE: + return _AtlModule.WinMain(nShowCmd); + + case DelegateExecuteOperation::RELAUNCH_CHROME: + return RelaunchChrome(operation.relaunch_shortcut(), + cmd_line->GetSwitchValueNative(switches::kWaitForHandle)); + + default: + NOTREACHED(); + } + + return 1; +} diff --git a/win8/delegate_execute/delegate_execute.gyp b/win8/delegate_execute/delegate_execute.gyp new file mode 100644 index 0000000..e4feff4 --- /dev/null +++ b/win8/delegate_execute/delegate_execute.gyp @@ -0,0 +1,46 @@ +# Copyright (c) 2012 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. +{ + 'variables': { + 'chromium_code': 1, + }, + 'includes': [ + '../../build/win_precompile.gypi', + ], + 'targets': [ + { + 'target_name': 'delegate_execute', + 'type': 'executable', + 'dependencies': [ + '../../base/base.gyp:base', + '../../chrome/chrome.gyp:installer_util', + '../../google_update/google_update.gyp:google_update', + '../../win8/win8.gyp:check_sdk_patch', + ], + 'sources': [ + 'chrome_util.cc', + 'chrome_util.h', + 'command_execute_impl.cc', + 'command_execute_impl.h', + 'command_execute_impl.rgs', + 'delegate_execute.cc', + 'delegate_execute.rc', + 'delegate_execute.rgs', + 'delegate_execute_operation.cc', + 'delegate_execute_operation.h', + 'resource.h', + ], + 'defines': [ + # This define is required to pull in the new Win8 interfaces from + # system headers like ShObjIdl.h + 'NTDDI_VERSION=0x06020000', + ], + 'msvs_settings': { + 'VCLinkerTool': { + 'SubSystem': '2', # Set /SUBSYSTEM:WINDOWS + }, + }, + }, + ], +} diff --git a/win8/delegate_execute/delegate_execute.rgs b/win8/delegate_execute/delegate_execute.rgs new file mode 100644 index 0000000..e7d3740 --- /dev/null +++ b/win8/delegate_execute/delegate_execute.rgs @@ -0,0 +1,3 @@ +HKCR +{ +} diff --git a/win8/delegate_execute/delegate_execute_operation.cc b/win8/delegate_execute/delegate_execute_operation.cc new file mode 100644 index 0000000..e6823f0 --- /dev/null +++ b/win8/delegate_execute/delegate_execute_operation.cc @@ -0,0 +1,37 @@ +// Copyright (c) 2012 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 "win8/delegate_execute/delegate_execute_operation.h" + +#include "base/command_line.h" +#include "chrome/common/chrome_switches.h" + +namespace delegate_execute { + +DelegateExecuteOperation::DelegateExecuteOperation() + : operation_type_(EXE_MODULE) { +} + +DelegateExecuteOperation::~DelegateExecuteOperation() { + Clear(); +} + +void DelegateExecuteOperation::Initialize(const CommandLine* command_line) { + Clear(); + + // --relaunch-shortcut=PathToShortcut triggers the relaunch Chrome operation. + FilePath shortcut( + command_line->GetSwitchValuePath(switches::kRelaunchShortcut)); + if (!shortcut.empty()) { + relaunch_shortcut_ = shortcut; + operation_type_ = RELAUNCH_CHROME; + } +} + +void DelegateExecuteOperation::Clear() { + operation_type_ = EXE_MODULE; + relaunch_shortcut_.clear(); +} + +} // namespace delegate_execute diff --git a/win8/delegate_execute/delegate_execute_operation.h b/win8/delegate_execute/delegate_execute_operation.h new file mode 100644 index 0000000..59acfd7a --- /dev/null +++ b/win8/delegate_execute/delegate_execute_operation.h @@ -0,0 +1,52 @@ +// Copyright (c) 2012 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 WIN8_DELEGATE_EXECUTE_DELEGATE_EXECUTE_OPERATION_H_ +#define WIN8_DELEGATE_EXECUTE_DELEGATE_EXECUTE_OPERATION_H_ + +#include <atldef.h> + +#include "base/basictypes.h" +#include "base/file_path.h" + +class CommandLine; + +namespace delegate_execute { + +// Parses a portion of the DelegateExecute handler's command line to determine +// the desired operation. +class DelegateExecuteOperation { + public: + enum OperationType { + EXE_MODULE, + RELAUNCH_CHROME, + }; + + DelegateExecuteOperation(); + ~DelegateExecuteOperation(); + + void Initialize(const CommandLine* command_line); + + OperationType operation_type() const { + return operation_type_; + } + + // Returns the argument to the --relaunch-shortcut switch. Valid only when + // the operation is RELAUNCH_CHROME. + const FilePath& relaunch_shortcut() const { + ATLASSERT(operation_type_ == RELAUNCH_CHROME); + return relaunch_shortcut_; + } + + private: + void Clear(); + + OperationType operation_type_; + FilePath relaunch_shortcut_; + DISALLOW_COPY_AND_ASSIGN(DelegateExecuteOperation); +}; + +} // namespace delegate_execute + +#endif // WIN8_DELEGATE_EXECUTE_DELEGATE_EXECUTE_OPERATION_H_ diff --git a/win8/delegate_execute/post_build.bat b/win8/delegate_execute/post_build.bat new file mode 100755 index 0000000..8aa9a76 --- /dev/null +++ b/win8/delegate_execute/post_build.bat @@ -0,0 +1,3 @@ +REM invoke as: post_build.bat OUTPUT_PATH_TO_EXE PATH_TO_CHROME_ROOT CONFIGURATION
+mkdir %2\build\%3
+copy %1 %2\build\%3\
diff --git a/win8/delegate_execute/resource.h b/win8/delegate_execute/resource.h new file mode 100644 index 0000000..cb81bf0 --- /dev/null +++ b/win8/delegate_execute/resource.h @@ -0,0 +1,22 @@ +// Copyright (c) 2012 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. + +// {{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by DelegateExecute.rc +// +#define IDS_PROJNAME 100 +#define IDR_DELEGATEEXECUTE 101 +#define IDR_COMMANDEXECUTEIMPL 106 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 201 +#define _APS_NEXT_COMMAND_VALUE 32768 +#define _APS_NEXT_CONTROL_VALUE 201 +#define _APS_NEXT_SYMED_VALUE 107 +#endif +#endif |