1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 // Implementation of the CommandExecuteImpl class which implements the
5 // IExecuteCommand and related interfaces for handling ShellExecute based
6 // launches of the Chrome browser.
8 #include "win8/delegate_execute/command_execute_impl.h"
12 #include "base/file_util.h"
13 #include "base/path_service.h"
14 #include "base/process/launch.h"
15 #include "base/process/process_handle.h"
16 #include "base/strings/utf_string_conversions.h"
17 #include "base/win/message_window.h"
18 #include "base/win/registry.h"
19 #include "base/win/scoped_co_mem.h"
20 #include "base/win/scoped_handle.h"
21 #include "base/win/scoped_process_information.h"
22 #include "base/win/win_util.h"
23 #include "chrome/common/chrome_constants.h"
24 #include "chrome/common/chrome_paths.h"
25 #include "chrome/common/chrome_switches.h"
26 #include "chrome/installer/util/browser_distribution.h"
27 #include "chrome/installer/util/install_util.h"
28 #include "chrome/installer/util/shell_util.h"
29 #include "chrome/installer/util/util_constants.h"
30 #include "ui/base/clipboard/clipboard_util_win.h"
31 #include "win8/delegate_execute/chrome_util.h"
32 #include "win8/delegate_execute/delegate_execute_util.h"
33 #include "win8/viewer/metro_viewer_constants.h"
36 // Helper function to retrieve the url from IShellItem interface passed in.
37 // Returns S_OK on success.
38 HRESULT
GetUrlFromShellItem(IShellItem
* shell_item
, base::string16
* url
) {
41 // First attempt to get the url from the underlying IDataObject if any. This
42 // ensures that we get the full url, i.e. including the anchor.
43 // If we fail to get the underlying IDataObject we retrieve the url via the
44 // IShellItem::GetDisplayName function.
45 CComPtr
<IDataObject
> object
;
46 HRESULT hr
= shell_item
->BindToHandler(NULL
,
49 reinterpret_cast<void**>(&object
));
52 if (ui::ClipboardUtil::GetPlainText(object
, url
))
56 base::win::ScopedCoMem
<wchar_t> name
;
57 hr
= shell_item
->GetDisplayName(SIGDN_URL
, &name
);
59 AtlTrace("Failed to get display name\n");
63 *url
= static_cast<const wchar_t*>(name
);
64 AtlTrace("Retrieved url from display name %ls\n", url
->c_str());
68 bool LaunchChromeBrowserProcess() {
69 base::FilePath delegate_exe_path
;
70 if (!PathService::Get(base::FILE_EXE
, &delegate_exe_path
))
73 // First try and go up a level to find chrome.exe.
74 base::FilePath chrome_exe_path
=
75 delegate_exe_path
.DirName()
77 .Append(chrome::kBrowserProcessExecutableName
);
78 if (!base::PathExists(chrome_exe_path
)) {
79 // Try looking in the current directory if we couldn't find it one up in
80 // order to support developer installs.
82 delegate_exe_path
.DirName()
83 .Append(chrome::kBrowserProcessExecutableName
);
86 if (!base::PathExists(chrome_exe_path
)) {
87 AtlTrace("Could not locate chrome.exe at: %ls\n",
88 chrome_exe_path
.value().c_str());
92 CommandLine
cl(chrome_exe_path
);
94 // Prevent a Chrome window from showing up on the desktop.
95 cl
.AppendSwitch(switches::kSilentLaunch
);
97 // Tell Chrome to connect to the Metro viewer process.
98 cl
.AppendSwitch(switches::kViewerConnect
);
100 base::LaunchOptions launch_options
;
101 launch_options
.start_hidden
= true;
103 return base::LaunchProcess(cl
, launch_options
, NULL
);
108 bool CommandExecuteImpl::path_provider_initialized_
= false;
110 // CommandExecuteImpl is resposible for activating chrome in Windows 8. The
111 // flow is complicated and this tries to highlight the important events.
112 // The current approach is to have a single instance of chrome either
113 // running in desktop or metro mode. If there is no current instance then
114 // the desktop shortcut launches desktop chrome and the metro tile or search
115 // charm launches metro chrome.
116 // If chrome is running then focus/activation is given to the existing one
117 // regarless of what launch point the user used.
119 // The general flow for activation is as follows:
121 // 1- User interacts with launch point (icon, tile, search, shellexec, etc)
122 // 2- Windows finds the appid for launch item and resolves it to chrome
123 // 3- Windows activates CommandExecuteImpl inside a surrogate process
124 // 4- Windows calls the following sequence of entry points:
125 // CommandExecuteImpl::SetShowWindow
126 // CommandExecuteImpl::SetPosition
127 // CommandExecuteImpl::SetDirectory
128 // CommandExecuteImpl::SetParameter
129 // CommandExecuteImpl::SetNoShowUI
130 // CommandExecuteImpl::SetSelection
131 // CommandExecuteImpl::Initialize
132 // Up to this point the code basically just gathers values passed in, like
133 // the launch scheme (or url) and the activation verb.
134 // 5- Windows calls CommandExecuteImpl::Getvalue()
135 // Here we need to return AHE_IMMERSIVE or AHE_DESKTOP. That depends on:
136 // a) if run in high-integrity return AHE_DESKTOP.
137 // b) else we return what GetLaunchMode() tells us, which is:
138 // i) if chrome is not the default browser, return AHE_DESKTOP
139 // ii) if the command line --force-xxx is present return that
140 // iii) if the registry 'launch_mode' exists return that
141 // iv) else return AHE_DESKTOP
142 // 6- If we returned AHE_IMMERSIVE in step 5 windows might not call us back
143 // and simply activate chrome in metro by itself, however in some cases
144 // it might proceed at step 7.
145 // As far as we know if we return AHE_DESKTOP then step 7 always happens.
146 // 7- Windows calls CommandExecuteImpl::Execute()
147 // Here we call GetLaunchMode() which returns the cached answer
148 // computed at step 5c. which can be:
149 // a) ECHUIM_DESKTOP then we call LaunchDesktopChrome() that calls
150 // ::CreateProcess and we exit at this point even on failure.
151 // b) else we call one of the IApplicationActivationManager activation
152 // functions depending on the parameters passed in step 4.
153 // c) If the activation returns E_APPLICATION_NOT_REGISTERED, then we fall
154 // back to launching chrome on the desktop via LaunchDestopChrome(). Note
155 // that this case can lead to strange behavior, because at this point we
156 // have pre-launched the browser with --silent-launch --viewer-connect.
157 // E_APPLICATION_NOT_REGISTERED is always returned if Chrome is not the
158 // default browser (this case will have already been checked for by
159 // GetLaunchMode() and AHE_DESKTOP returned), but we don't know if it can
160 // be returned for other reasons.
162 // Note that if a command line --force-xxx is present we write that launch mode
163 // in the registry so next time the logic reaches 5c-ii it will use the same
166 CommandExecuteImpl::CommandExecuteImpl()
167 : parameters_(CommandLine::NO_PROGRAM
),
168 launch_scheme_(INTERNET_SCHEME_DEFAULT
),
169 integrity_level_(base::INTEGRITY_UNKNOWN
) {
170 memset(&start_info_
, 0, sizeof(start_info_
));
171 start_info_
.cb
= sizeof(start_info_
);
173 // We need to query the user data dir of chrome so we need chrome's
174 // path provider. We can be created multiplie times in a single instance
175 // however so make sure we do this only once.
176 if (!path_provider_initialized_
) {
177 chrome::RegisterPathProvider();
178 path_provider_initialized_
= true;
182 // CommandExecuteImpl
183 STDMETHODIMP
CommandExecuteImpl::SetKeyState(DWORD key_state
) {
187 STDMETHODIMP
CommandExecuteImpl::SetParameters(LPCWSTR params
) {
188 parameters_
= delegate_execute::CommandLineFromParameters(params
);
192 STDMETHODIMP
CommandExecuteImpl::SetPosition(POINT pt
) {
196 STDMETHODIMP
CommandExecuteImpl::SetShowWindow(int show
) {
197 start_info_
.wShowWindow
= show
;
198 start_info_
.dwFlags
|= STARTF_USESHOWWINDOW
;
202 STDMETHODIMP
CommandExecuteImpl::SetNoShowUI(BOOL no_show_ui
) {
206 STDMETHODIMP
CommandExecuteImpl::SetDirectory(LPCWSTR directory
) {
210 STDMETHODIMP
CommandExecuteImpl::GetValue(enum AHE_TYPE
* pahe
) {
211 if (!GetLaunchScheme(&display_name_
, &launch_scheme_
)) {
212 AtlTrace("Failed to get scheme, E_FAIL\n");
216 EC_HOST_UI_MODE mode
= GetLaunchMode();
217 *pahe
= (mode
== ECHUIM_DESKTOP
) ? AHE_DESKTOP
: AHE_IMMERSIVE
;
219 // If we're going to return AHE_IMMERSIVE, then both the browser process and
220 // the metro viewer need to launch and connect before the user can start
221 // browsing. However we must not launch the metro viewer until we get a
222 // call to CommandExecuteImpl::Execute(). If we wait until then to launch
223 // the browser process as well, it will appear laggy while they connect to
224 // each other, so we pre-launch the browser process now.
225 if (*pahe
== AHE_IMMERSIVE
&& verb_
!= win8::kMetroViewerConnectVerb
)
226 LaunchChromeBrowserProcess();
230 STDMETHODIMP
CommandExecuteImpl::Execute() {
231 AtlTrace("In %hs\n", __FUNCTION__
);
233 if (integrity_level_
== base::HIGH_INTEGRITY
)
234 return LaunchDesktopChrome();
236 EC_HOST_UI_MODE mode
= GetLaunchMode();
237 if (mode
== ECHUIM_DESKTOP
)
238 return LaunchDesktopChrome();
241 CComPtr
<IApplicationActivationManager
> activation_manager
;
242 hr
= activation_manager
.CoCreateInstance(CLSID_ApplicationActivationManager
);
243 if (!activation_manager
) {
244 AtlTrace("Failed to get the activation manager, error 0x%x\n", hr
);
248 BrowserDistribution
* distribution
= BrowserDistribution::GetDistribution();
249 bool is_per_user_install
= InstallUtil::IsPerUserInstall(
250 chrome_exe_
.value().c_str());
251 base::string16 app_id
= ShellUtil::GetBrowserModelId(
252 distribution
, is_per_user_install
);
255 if (launch_scheme_
== INTERNET_SCHEME_FILE
&&
256 display_name_
.find(installer::kChromeExe
) != base::string16::npos
) {
257 AtlTrace("Activating for file\n");
258 hr
= activation_manager
->ActivateApplication(app_id
.c_str(),
263 AtlTrace("Activating for protocol\n");
264 hr
= activation_manager
->ActivateForProtocol(app_id
.c_str(),
268 if (hr
== E_APPLICATION_NOT_REGISTERED
) {
269 AtlTrace("Metro chrome is not registered, launching in desktop\n");
270 return LaunchDesktopChrome();
272 AtlTrace("Metro Chrome launch, pid=%d, returned 0x%x\n", pid
, hr
);
276 STDMETHODIMP
CommandExecuteImpl::Initialize(LPCWSTR name
,
278 if (!FindChromeExe(&chrome_exe_
))
280 delegate_execute::UpdateChromeIfNeeded(chrome_exe_
);
283 AtlTrace("Verb is %S\n", name
);
287 base::GetProcessIntegrityLevel(base::GetCurrentProcessHandle(),
292 STDMETHODIMP
CommandExecuteImpl::SetSelection(IShellItemArray
* item_array
) {
293 item_array_
= item_array
;
297 STDMETHODIMP
CommandExecuteImpl::GetSelection(REFIID riid
, void** selection
) {
301 STDMETHODIMP
CommandExecuteImpl::AllowForegroundTransfer(void* reserved
) {
305 // Returns false if chrome.exe cannot be found.
307 bool CommandExecuteImpl::FindChromeExe(base::FilePath
* chrome_exe
) {
308 // Look for chrome.exe one folder above delegate_execute.exe (as expected in
309 // Chrome installs). Failing that, look for it alonside delegate_execute.exe.
310 base::FilePath dir_exe
;
311 if (!PathService::Get(base::DIR_EXE
, &dir_exe
)) {
312 AtlTrace("Failed to get current exe path\n");
316 *chrome_exe
= dir_exe
.DirName().Append(chrome::kBrowserProcessExecutableName
);
317 if (!base::PathExists(*chrome_exe
)) {
318 *chrome_exe
= dir_exe
.Append(chrome::kBrowserProcessExecutableName
);
319 if (!base::PathExists(*chrome_exe
)) {
320 AtlTrace("Failed to find chrome exe file\n");
327 bool CommandExecuteImpl::GetLaunchScheme(
328 base::string16
* display_name
, INTERNET_SCHEME
* scheme
) {
332 ATLASSERT(display_name
);
336 item_array_
->GetCount(&count
);
339 AtlTrace("Cannot handle %d elements in the IShellItemArray\n", count
);
343 CComPtr
<IEnumShellItems
> items
;
344 item_array_
->EnumItems(&items
);
345 CComPtr
<IShellItem
> shell_item
;
346 HRESULT hr
= items
->Next(1, &shell_item
, &count
);
348 AtlTrace("Failed to read element from the IShellItemsArray\n");
352 hr
= GetUrlFromShellItem(shell_item
, display_name
);
354 AtlTrace("Failed to get url. Error 0x%x\n", hr
);
358 wchar_t scheme_name
[16];
359 URL_COMPONENTS components
= {0};
360 components
.lpszScheme
= scheme_name
;
361 components
.dwSchemeLength
= sizeof(scheme_name
)/sizeof(scheme_name
[0]);
363 components
.dwStructSize
= sizeof(components
);
364 if (!InternetCrackUrlW(display_name
->c_str(), 0, 0, &components
)) {
365 AtlTrace("Failed to crack url %ls\n", display_name
->c_str());
369 AtlTrace("Launch scheme is [%ls] (%d)\n", scheme_name
, components
.nScheme
);
370 *scheme
= components
.nScheme
;
374 HRESULT
CommandExecuteImpl::LaunchDesktopChrome() {
375 base::string16 display_name
= display_name_
;
377 switch (launch_scheme_
) {
378 case INTERNET_SCHEME_FILE
:
379 // If anything other than chrome.exe is passed in the display name we
380 // should honor it. For e.g. If the user clicks on a html file when
381 // chrome is the default we should treat it as a parameter to be passed
383 if (display_name
.find(installer::kChromeExe
) != base::string16::npos
)
384 display_name
.clear();
392 delegate_execute::MakeChromeCommandLine(chrome_exe_
, parameters_
,
394 base::string16
command_line(chrome
.GetCommandLineString());
396 AtlTrace("Formatted command line is %ls\n", command_line
.c_str());
398 PROCESS_INFORMATION temp_process_info
= {};
399 BOOL ret
= CreateProcess(chrome_exe_
.value().c_str(),
400 const_cast<LPWSTR
>(command_line
.c_str()),
401 NULL
, NULL
, FALSE
, 0, NULL
, NULL
, &start_info_
,
404 base::win::ScopedProcessInformation
proc_info(temp_process_info
);
405 AtlTrace("Process id is %d\n", proc_info
.process_id());
406 AllowSetForegroundWindow(proc_info
.process_id());
408 AtlTrace("Process launch failed, error %d\n", ::GetLastError());
414 EC_HOST_UI_MODE
CommandExecuteImpl::GetLaunchMode() {
415 // See the header file for an explanation of the mode selection logic.
416 static bool launch_mode_determined
= false;
417 static EC_HOST_UI_MODE launch_mode
= ECHUIM_DESKTOP
;
419 const char* modes
[] = { "Desktop", "Immersive", "SysLauncher", "??" };
421 if (launch_mode_determined
)
424 if (integrity_level_
== base::HIGH_INTEGRITY
) {
425 // Metro mode apps don't work in high integrity mode.
426 AtlTrace("High integrity: launching in desktop mode\n");
427 launch_mode
= ECHUIM_DESKTOP
;
428 launch_mode_determined
= true;
432 base::FilePath chrome_exe
;
433 if (!FindChromeExe(&chrome_exe
) ||
434 ShellUtil::GetChromeDefaultStateFromPath(chrome_exe
) !=
435 ShellUtil::IS_DEFAULT
) {
436 AtlTrace("Chrome is not default: launching in desktop mode\n");
437 launch_mode
= ECHUIM_DESKTOP
;
438 launch_mode_determined
= true;
442 if (GetAsyncKeyState(VK_SHIFT
) && GetAsyncKeyState(VK_F11
)) {
443 AtlTrace("Hotkey: launching in immersive mode\n");
444 launch_mode
= ECHUIM_IMMERSIVE
;
445 launch_mode_determined
= true;
449 // From here on, if we can, we will write the outcome
450 // of this function to the registry.
451 if (parameters_
.HasSwitch(switches::kForceImmersive
)) {
452 launch_mode
= ECHUIM_IMMERSIVE
;
453 launch_mode_determined
= true;
454 parameters_
= CommandLine(CommandLine::NO_PROGRAM
);
455 } else if (parameters_
.HasSwitch(switches::kForceDesktop
)) {
456 launch_mode
= ECHUIM_DESKTOP
;
457 launch_mode_determined
= true;
458 parameters_
= CommandLine(CommandLine::NO_PROGRAM
);
461 base::win::RegKey reg_key
;
462 LONG key_result
= reg_key
.Create(HKEY_CURRENT_USER
,
463 chrome::kMetroRegistryPath
,
465 if (key_result
!= ERROR_SUCCESS
) {
466 AtlTrace("Failed to open HKCU %ls key, error 0x%x\n",
467 chrome::kMetroRegistryPath
,
469 if (!launch_mode_determined
) {
470 // If we cannot open the key and we don't know the
471 // launch mode we default to desktop mode.
472 launch_mode
= ECHUIM_DESKTOP
;
473 launch_mode_determined
= true;
478 if (launch_mode_determined
) {
479 AtlTrace("Launch mode forced by cmdline to %s\n", modes
[launch_mode
]);
480 reg_key
.WriteValue(chrome::kLaunchModeValue
,
481 static_cast<DWORD
>(launch_mode
));
485 // Use the previous mode if available. Else launch in desktop mode.
487 if (reg_key
.ReadValueDW(chrome::kLaunchModeValue
,
488 ®_value
) != ERROR_SUCCESS
) {
489 launch_mode
= ECHUIM_DESKTOP
;
490 AtlTrace("Can't read registry, defaulting to %s\n", modes
[launch_mode
]);
491 } else if (reg_value
>= ECHUIM_SYSTEM_LAUNCHER
) {
492 AtlTrace("Invalid registry launch mode value %u\n", reg_value
);
493 launch_mode
= ECHUIM_DESKTOP
;
495 launch_mode
= static_cast<EC_HOST_UI_MODE
>(reg_value
);
496 AtlTrace("Launch mode forced by registry to %s\n", modes
[launch_mode
]);
499 launch_mode_determined
= true;