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/files/file_util.h"
13 #include "base/path_service.h"
14 #include "base/process/launch.h"
15 #include "base/strings/utf_string_conversions.h"
16 #include "base/win/registry.h"
17 #include "base/win/scoped_co_mem.h"
18 #include "base/win/scoped_handle.h"
19 #include "base/win/scoped_process_information.h"
20 #include "base/win/win_util.h"
21 #include "base/win/windows_version.h"
22 #include "chrome/common/chrome_constants.h"
23 #include "chrome/common/chrome_paths.h"
24 #include "chrome/common/chrome_switches.h"
25 #include "chrome/installer/util/browser_distribution.h"
26 #include "chrome/installer/util/install_util.h"
27 #include "chrome/installer/util/shell_util.h"
28 #include "chrome/installer/util/util_constants.h"
29 #include "ui/base/clipboard/clipboard_util_win.h"
30 #include "ui/base/ui_base_switches.h"
31 #include "ui/gfx/win/dpi.h"
32 #include "win8/delegate_execute/chrome_util.h"
33 #include "win8/delegate_execute/delegate_execute_util.h"
34 #include "win8/viewer/metro_viewer_constants.h"
37 // Helper function to retrieve the url from IShellItem interface passed in.
38 // Returns S_OK on success.
39 HRESULT
GetUrlFromShellItem(IShellItem
* shell_item
, base::string16
* url
) {
42 // First attempt to get the url from the underlying IDataObject if any. This
43 // ensures that we get the full url, i.e. including the anchor.
44 // If we fail to get the underlying IDataObject we retrieve the url via the
45 // IShellItem::GetDisplayName function.
46 CComPtr
<IDataObject
> object
;
47 HRESULT hr
= shell_item
->BindToHandler(NULL
,
50 reinterpret_cast<void**>(&object
));
53 if (ui::ClipboardUtil::GetPlainText(object
, url
))
57 base::win::ScopedCoMem
<wchar_t> name
;
58 hr
= shell_item
->GetDisplayName(SIGDN_URL
, &name
);
60 AtlTrace("Failed to get display name\n");
64 *url
= static_cast<const wchar_t*>(name
);
65 AtlTrace("Retrieved url from display name %ls\n", url
->c_str());
69 bool LaunchChromeBrowserProcess() {
70 base::FilePath delegate_exe_path
;
71 if (!PathService::Get(base::FILE_EXE
, &delegate_exe_path
))
74 // First try and go up a level to find chrome.exe.
75 base::FilePath chrome_exe_path
=
76 delegate_exe_path
.DirName()
78 .Append(chrome::kBrowserProcessExecutableName
);
79 if (!base::PathExists(chrome_exe_path
)) {
80 // Try looking in the current directory if we couldn't find it one up in
81 // order to support developer installs.
83 delegate_exe_path
.DirName()
84 .Append(chrome::kBrowserProcessExecutableName
);
87 if (!base::PathExists(chrome_exe_path
)) {
88 AtlTrace("Could not locate chrome.exe at: %ls\n",
89 chrome_exe_path
.value().c_str());
93 base::CommandLine
cl(chrome_exe_path
);
95 // Prevent a Chrome window from showing up on the desktop.
96 cl
.AppendSwitch(switches::kSilentLaunch
);
98 // Tell Chrome to connect to the Metro viewer process.
99 cl
.AppendSwitch(switches::kViewerConnect
);
101 base::LaunchOptions launch_options
;
102 launch_options
.start_hidden
= true;
104 return base::LaunchProcess(cl
, launch_options
).IsValid();
109 bool CommandExecuteImpl::path_provider_initialized_
= false;
111 // CommandExecuteImpl is responsible for activating chrome in Windows 8. The
112 // flow is complicated and this tries to highlight the important events.
113 // The current approach is to have a single instance of chrome either
114 // running in desktop or metro mode. If there is no current instance then
115 // the desktop shortcut launches desktop chrome and the metro tile or search
116 // charm launches metro chrome.
117 // If chrome is running then focus/activation is given to the existing one
118 // regardless of what launch point the user used.
120 // The general flow for activation is as follows:
122 // 1- User interacts with launch point (icon, tile, search, shellexec, etc)
123 // 2- Windows finds the appid for launch item and resolves it to chrome
124 // 3- Windows activates CommandExecuteImpl inside a surrogate process
125 // 4- Windows calls the following sequence of entry points:
126 // CommandExecuteImpl::SetShowWindow
127 // CommandExecuteImpl::SetPosition
128 // CommandExecuteImpl::SetDirectory
129 // CommandExecuteImpl::SetParameter
130 // CommandExecuteImpl::SetNoShowUI
131 // CommandExecuteImpl::SetSelection
132 // CommandExecuteImpl::Initialize
133 // Up to this point the code basically just gathers values passed in, like
134 // the launch scheme (or url) and the activation verb.
135 // 5- Windows calls CommandExecuteImpl::Getvalue()
136 // Here we need to return AHE_IMMERSIVE or AHE_DESKTOP. That depends on:
137 // a) if run in high-integrity return AHE_DESKTOP.
138 // b) else we return what GetLaunchMode() tells us, which is:
139 // i) if chrome is not the default browser, return AHE_DESKTOP
140 // ii) if the command line --force-xxx is present return that
141 // iii) if the registry 'launch_mode' exists return that
142 // iv) else return AHE_DESKTOP
143 // 6- If we returned AHE_IMMERSIVE in step 5 windows might not call us back
144 // and simply activate chrome in metro by itself, however in some cases
145 // it might proceed at step 7.
146 // As far as we know if we return AHE_DESKTOP then step 7 always happens.
147 // 7- Windows calls CommandExecuteImpl::Execute()
148 // Here we call GetLaunchMode() which returns the cached answer
149 // computed at step 5c. which can be:
150 // a) ECHUIM_DESKTOP then we call LaunchDesktopChrome() that calls
151 // ::CreateProcess and we exit at this point even on failure.
152 // b) else we call one of the IApplicationActivationManager activation
153 // functions depending on the parameters passed in step 4.
154 // c) If the activation returns E_APPLICATION_NOT_REGISTERED, then we fall
155 // back to launching chrome on the desktop via LaunchDestopChrome(). Note
156 // that this case can lead to strange behavior, because at this point we
157 // have pre-launched the browser with:
158 // --silent-launch --connect-to-metro-viewer.
159 // E_APPLICATION_NOT_REGISTERED is always returned if Chrome is not the
160 // default browser (this case will have already been checked for by
161 // GetLaunchMode() and AHE_DESKTOP returned), but we don't know if it can
162 // be returned for other reasons.
164 // Note that if a command line --force-xxx is present we write that launch mode
165 // in the registry so next time the logic reaches 5c-ii it will use the same
168 CommandExecuteImpl::CommandExecuteImpl()
169 : parameters_(base::CommandLine::NO_PROGRAM
),
170 launch_scheme_(INTERNET_SCHEME_DEFAULT
),
171 integrity_level_(base::INTEGRITY_UNKNOWN
) {
172 memset(&start_info_
, 0, sizeof(start_info_
));
173 start_info_
.cb
= sizeof(start_info_
);
175 // We need to query the user data dir of chrome so we need chrome's
176 // path provider. We can be created multiple times in a single instance
177 // however so make sure we do this only once.
178 if (!path_provider_initialized_
) {
179 chrome::RegisterPathProvider();
180 path_provider_initialized_
= true;
184 CommandExecuteImpl::~CommandExecuteImpl() {
187 // CommandExecuteImpl
188 STDMETHODIMP
CommandExecuteImpl::SetKeyState(DWORD key_state
) {
192 STDMETHODIMP
CommandExecuteImpl::SetParameters(LPCWSTR params
) {
193 parameters_
= delegate_execute::CommandLineFromParameters(params
);
197 STDMETHODIMP
CommandExecuteImpl::SetPosition(POINT pt
) {
201 STDMETHODIMP
CommandExecuteImpl::SetShowWindow(int show
) {
202 start_info_
.wShowWindow
= show
;
203 start_info_
.dwFlags
|= STARTF_USESHOWWINDOW
;
207 STDMETHODIMP
CommandExecuteImpl::SetNoShowUI(BOOL no_show_ui
) {
211 STDMETHODIMP
CommandExecuteImpl::SetDirectory(LPCWSTR directory
) {
215 STDMETHODIMP
CommandExecuteImpl::GetValue(enum AHE_TYPE
* pahe
) {
216 if (!GetLaunchScheme(&display_name_
, &launch_scheme_
)) {
217 AtlTrace("Failed to get scheme, E_FAIL\n");
221 EC_HOST_UI_MODE mode
= GetLaunchMode();
222 *pahe
= (mode
== ECHUIM_DESKTOP
) ? AHE_DESKTOP
: AHE_IMMERSIVE
;
224 // If we're going to return AHE_IMMERSIVE, then both the browser process and
225 // the metro viewer need to launch and connect before the user can start
226 // browsing. However we must not launch the metro viewer until we get a
227 // call to CommandExecuteImpl::Execute(). If we wait until then to launch
228 // the browser process as well, it will appear laggy while they connect to
229 // each other, so we pre-launch the browser process now.
230 if (*pahe
== AHE_IMMERSIVE
&& verb_
!= win8::kMetroViewerConnectVerb
) {
231 LaunchChromeBrowserProcess();
236 STDMETHODIMP
CommandExecuteImpl::Execute() {
237 AtlTrace("In %hs\n", __FUNCTION__
);
239 if (integrity_level_
== base::HIGH_INTEGRITY
)
240 return LaunchDesktopChrome();
242 EC_HOST_UI_MODE mode
= GetLaunchMode();
243 if (mode
== ECHUIM_DESKTOP
)
244 return LaunchDesktopChrome();
247 CComPtr
<IApplicationActivationManager
> activation_manager
;
248 hr
= activation_manager
.CoCreateInstance(CLSID_ApplicationActivationManager
);
249 if (!activation_manager
) {
250 AtlTrace("Failed to get the activation manager, error 0x%x\n", hr
);
254 BrowserDistribution
* distribution
= BrowserDistribution::GetDistribution();
255 bool is_per_user_install
= InstallUtil::IsPerUserInstall(chrome_exe_
);
256 base::string16 app_id
= ShellUtil::GetBrowserModelId(
257 distribution
, is_per_user_install
);
260 if (launch_scheme_
== INTERNET_SCHEME_FILE
&&
261 display_name_
.find(installer::kChromeExe
) != base::string16::npos
) {
262 AtlTrace("Activating for file\n");
263 hr
= activation_manager
->ActivateApplication(app_id
.c_str(),
268 AtlTrace("Activating for protocol\n");
269 hr
= activation_manager
->ActivateForProtocol(app_id
.c_str(),
273 if (hr
== E_APPLICATION_NOT_REGISTERED
) {
274 AtlTrace("Metro chrome is not registered, launching in desktop\n");
275 return LaunchDesktopChrome();
277 AtlTrace("Metro Chrome launch, pid=%d, returned 0x%x\n", pid
, hr
);
281 STDMETHODIMP
CommandExecuteImpl::Initialize(LPCWSTR name
,
283 if (!FindChromeExe(&chrome_exe_
))
285 delegate_execute::UpdateChromeIfNeeded(chrome_exe_
);
288 AtlTrace("Verb is %S\n", name
);
292 integrity_level_
= base::GetCurrentProcessIntegrityLevel();
296 STDMETHODIMP
CommandExecuteImpl::SetSelection(IShellItemArray
* item_array
) {
297 item_array_
= item_array
;
301 STDMETHODIMP
CommandExecuteImpl::GetSelection(REFIID riid
, void** selection
) {
305 STDMETHODIMP
CommandExecuteImpl::AllowForegroundTransfer(void* reserved
) {
309 // Returns false if chrome.exe cannot be found.
311 bool CommandExecuteImpl::FindChromeExe(base::FilePath
* chrome_exe
) {
312 // Look for chrome.exe one folder above delegate_execute.exe (as expected in
313 // Chrome installs). Failing that, look for it alonside delegate_execute.exe.
314 base::FilePath dir_exe
;
315 if (!PathService::Get(base::DIR_EXE
, &dir_exe
)) {
316 AtlTrace("Failed to get current exe path\n");
320 *chrome_exe
= dir_exe
.DirName().Append(chrome::kBrowserProcessExecutableName
);
321 if (!base::PathExists(*chrome_exe
)) {
322 *chrome_exe
= dir_exe
.Append(chrome::kBrowserProcessExecutableName
);
323 if (!base::PathExists(*chrome_exe
)) {
324 AtlTrace("Failed to find chrome exe file\n");
331 bool CommandExecuteImpl::GetLaunchScheme(
332 base::string16
* display_name
, INTERNET_SCHEME
* scheme
) {
336 ATLASSERT(display_name
);
340 item_array_
->GetCount(&count
);
343 AtlTrace("Cannot handle %d elements in the IShellItemArray\n", count
);
347 CComPtr
<IEnumShellItems
> items
;
348 item_array_
->EnumItems(&items
);
349 CComPtr
<IShellItem
> shell_item
;
350 HRESULT hr
= items
->Next(1, &shell_item
, &count
);
352 AtlTrace("Failed to read element from the IShellItemsArray\n");
356 hr
= GetUrlFromShellItem(shell_item
, display_name
);
358 AtlTrace("Failed to get url. Error 0x%x\n", hr
);
362 wchar_t scheme_name
[16];
363 URL_COMPONENTS components
= {0};
364 components
.lpszScheme
= scheme_name
;
365 components
.dwSchemeLength
= sizeof(scheme_name
)/sizeof(scheme_name
[0]);
367 components
.dwStructSize
= sizeof(components
);
368 if (!InternetCrackUrlW(display_name
->c_str(), 0, 0, &components
)) {
369 AtlTrace("Failed to crack url %ls\n", display_name
->c_str());
373 AtlTrace("Launch scheme is [%ls] (%d)\n", scheme_name
, components
.nScheme
);
374 *scheme
= components
.nScheme
;
378 HRESULT
CommandExecuteImpl::LaunchDesktopChrome() {
379 base::string16 display_name
= display_name_
;
381 switch (launch_scheme_
) {
382 case INTERNET_SCHEME_FILE
:
383 // If anything other than chrome.exe is passed in the display name we
384 // should honor it. For e.g. If the user clicks on a html file when
385 // chrome is the default we should treat it as a parameter to be passed
387 if (display_name
.find(installer::kChromeExe
) != base::string16::npos
)
388 display_name
.clear();
395 base::CommandLine
chrome(delegate_execute::MakeChromeCommandLine(
396 chrome_exe_
, parameters_
, display_name
));
397 base::string16
command_line(chrome
.GetCommandLineString());
399 AtlTrace("Formatted command line is %ls\n", command_line
.c_str());
401 PROCESS_INFORMATION temp_process_info
= {};
402 BOOL ret
= CreateProcess(chrome_exe_
.value().c_str(),
404 NULL
, NULL
, FALSE
, 0, NULL
, NULL
, &start_info_
,
407 base::win::ScopedProcessInformation
proc_info(temp_process_info
);
408 AtlTrace("Process id is %d\n", proc_info
.process_id());
409 AllowSetForegroundWindow(proc_info
.process_id());
411 AtlTrace("Process launch failed, error %d\n", ::GetLastError());
417 EC_HOST_UI_MODE
CommandExecuteImpl::GetLaunchMode() {
418 // See the header file for an explanation of the mode selection logic.
419 static bool launch_mode_determined
= false;
420 static EC_HOST_UI_MODE launch_mode
= ECHUIM_DESKTOP
;
422 const char* modes
[] = { "Desktop", "Immersive", "SysLauncher", "??" };
424 if (launch_mode_determined
)
427 if (integrity_level_
== base::HIGH_INTEGRITY
) {
428 // Metro mode apps don't work in high integrity mode.
429 AtlTrace("High integrity: launching in desktop mode\n");
430 launch_mode
= ECHUIM_DESKTOP
;
431 launch_mode_determined
= true;
435 base::FilePath chrome_exe
;
436 if (!FindChromeExe(&chrome_exe
) ||
437 ShellUtil::GetChromeDefaultStateFromPath(chrome_exe
) !=
438 ShellUtil::IS_DEFAULT
) {
439 AtlTrace("Chrome is not default: launching in desktop mode\n");
440 launch_mode
= ECHUIM_DESKTOP
;
441 launch_mode_determined
= true;
445 if (GetAsyncKeyState(VK_SHIFT
) && GetAsyncKeyState(VK_F11
)) {
446 AtlTrace("Hotkey: launching in immersive mode\n");
447 launch_mode
= ECHUIM_IMMERSIVE
;
448 launch_mode_determined
= true;
452 // From here on, if we can, we will write the outcome
453 // of this function to the registry.
454 if (parameters_
.HasSwitch(switches::kForceImmersive
)) {
455 launch_mode
= ECHUIM_IMMERSIVE
;
456 launch_mode_determined
= true;
457 parameters_
= base::CommandLine(base::CommandLine::NO_PROGRAM
);
458 } else if (parameters_
.HasSwitch(switches::kForceDesktop
)) {
459 launch_mode
= ECHUIM_DESKTOP
;
460 launch_mode_determined
= true;
461 parameters_
= base::CommandLine(base::CommandLine::NO_PROGRAM
);
464 base::win::RegKey reg_key
;
465 LONG key_result
= reg_key
.Create(HKEY_CURRENT_USER
,
466 chrome::kMetroRegistryPath
,
468 if (key_result
!= ERROR_SUCCESS
) {
469 AtlTrace("Failed to open HKCU %ls key, error 0x%x\n",
470 chrome::kMetroRegistryPath
,
472 if (!launch_mode_determined
) {
473 // If we cannot open the key and we don't know the
474 // launch mode we default to desktop mode.
475 launch_mode
= ECHUIM_DESKTOP
;
476 launch_mode_determined
= true;
481 if (launch_mode_determined
) {
482 AtlTrace("Launch mode forced by cmdline to %s\n", modes
[launch_mode
]);
483 reg_key
.WriteValue(chrome::kLaunchModeValue
,
484 static_cast<DWORD
>(launch_mode
));
488 // As of now ActivateApplication fails on Windows 10 (Build 9926).
489 // Until there is some clarity on special status of browser in metro mode on
490 // Windows 10, we just disable Chrome metro mode so that browser remains
492 if (base::win::GetVersion() >= base::win::VERSION_WIN10
) {
493 launch_mode
= ECHUIM_DESKTOP
;
494 launch_mode_determined
= true;
498 // Use the previous mode if available. Else launch in desktop mode.
500 if (reg_key
.ReadValueDW(chrome::kLaunchModeValue
,
501 ®_value
) != ERROR_SUCCESS
) {
502 launch_mode
= ECHUIM_DESKTOP
;
503 AtlTrace("Can't read registry, defaulting to %s\n", modes
[launch_mode
]);
504 } else if (reg_value
>= ECHUIM_SYSTEM_LAUNCHER
) {
505 AtlTrace("Invalid registry launch mode value %u\n", reg_value
);
506 launch_mode
= ECHUIM_DESKTOP
;
508 launch_mode
= static_cast<EC_HOST_UI_MODE
>(reg_value
);
509 AtlTrace("Launch mode forced by registry to %s\n", modes
[launch_mode
]);
512 launch_mode_determined
= true;