Upstream version 5.34.92.0
[platform/framework/web/crosswalk.git] / src / win8 / delegate_execute / command_execute_impl.cc
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.
7
8 #include "win8/delegate_execute/command_execute_impl.h"
9
10 #include <shlguid.h>
11
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"
34
35 namespace {
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) {
39   DCHECK(shell_item);
40   DCHECK(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,
47                                          BHID_DataObject,
48                                          IID_IDataObject,
49                                          reinterpret_cast<void**>(&object));
50   if (SUCCEEDED(hr)) {
51     DCHECK(object);
52     if (ui::ClipboardUtil::GetPlainText(object, url))
53       return S_OK;
54   }
55
56   base::win::ScopedCoMem<wchar_t> name;
57   hr = shell_item->GetDisplayName(SIGDN_URL, &name);
58   if (hr != S_OK) {
59     AtlTrace("Failed to get display name\n");
60     return hr;
61   }
62
63   *url = static_cast<const wchar_t*>(name);
64   AtlTrace("Retrieved url from display name %ls\n", url->c_str());
65   return S_OK;
66 }
67
68 bool LaunchChromeBrowserProcess() {
69   base::FilePath delegate_exe_path;
70   if (!PathService::Get(base::FILE_EXE, &delegate_exe_path))
71     return false;
72
73   // First try and go up a level to find chrome.exe.
74   base::FilePath chrome_exe_path =
75       delegate_exe_path.DirName()
76                        .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.
81     chrome_exe_path =
82         delegate_exe_path.DirName()
83                          .Append(chrome::kBrowserProcessExecutableName);
84   }
85
86   if (!base::PathExists(chrome_exe_path)) {
87     AtlTrace("Could not locate chrome.exe at: %ls\n",
88              chrome_exe_path.value().c_str());
89     return false;
90   }
91
92   CommandLine cl(chrome_exe_path);
93
94   // Prevent a Chrome window from showing up on the desktop.
95   cl.AppendSwitch(switches::kSilentLaunch);
96
97   // Tell Chrome to connect to the Metro viewer process.
98   cl.AppendSwitch(switches::kViewerConnect);
99
100   base::LaunchOptions launch_options;
101   launch_options.start_hidden = true;
102
103   return base::LaunchProcess(cl, launch_options, NULL);
104 }
105
106 }  // namespace
107
108 bool CommandExecuteImpl::path_provider_initialized_ = false;
109
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.
118 //
119 // The general flow when chrome is the default browser is as follows:
120 //
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 the command line --force-xxx is present return that
139 //       ii) if the registry 'launch_mode' exists return that
140 //       iii) else return AHE_DESKTOP
141 // 6- If we returned AHE_IMMERSIVE in step 5 windows might not call us back
142 //    and simply activate chrome in metro by itself, however in some cases
143 //    it might proceed at step 7.
144 //    As far as we know if we return AHE_DESKTOP then step 7 always happens.
145 // 7- Windows calls CommandExecuteImpl::Execute()
146 //    Here we call GetLaunchMode() which returns the cached answer
147 //    computed at step 5c. which can be:
148 //    a) ECHUIM_DESKTOP then we call LaunchDesktopChrome() that calls
149 //       ::CreateProcess and we exit at this point even on failure.
150 //    b) else we call one of the IApplicationActivationManager activation
151 //       functions depending on the parameters passed in step 4.
152 //    c) If the activation returns E_APPLICATION_NOT_REGISTERED, then we fall
153 //       back to launching chrome on the desktop via LaunchDestopChrome().
154 //
155 // Note that if a command line --force-xxx is present we write that launch mode
156 // in the registry so next time the logic reaches 5c-ii it will use the same
157 // mode again.
158 //
159 CommandExecuteImpl::CommandExecuteImpl()
160     : parameters_(CommandLine::NO_PROGRAM),
161       launch_scheme_(INTERNET_SCHEME_DEFAULT),
162       integrity_level_(base::INTEGRITY_UNKNOWN) {
163   memset(&start_info_, 0, sizeof(start_info_));
164   start_info_.cb = sizeof(start_info_);
165
166   // We need to query the user data dir of chrome so we need chrome's
167   // path provider. We can be created multiplie times in a single instance
168   // however so make sure we do this only once.
169   if (!path_provider_initialized_) {
170     chrome::RegisterPathProvider();
171     path_provider_initialized_ = true;
172   }
173 }
174
175 // CommandExecuteImpl
176 STDMETHODIMP CommandExecuteImpl::SetKeyState(DWORD key_state) {
177   return S_OK;
178 }
179
180 STDMETHODIMP CommandExecuteImpl::SetParameters(LPCWSTR params) {
181   parameters_ = delegate_execute::CommandLineFromParameters(params);
182   return S_OK;
183 }
184
185 STDMETHODIMP CommandExecuteImpl::SetPosition(POINT pt) {
186   return S_OK;
187 }
188
189 STDMETHODIMP CommandExecuteImpl::SetShowWindow(int show) {
190   start_info_.wShowWindow = show;
191   start_info_.dwFlags |= STARTF_USESHOWWINDOW;
192   return S_OK;
193 }
194
195 STDMETHODIMP CommandExecuteImpl::SetNoShowUI(BOOL no_show_ui) {
196   return S_OK;
197 }
198
199 STDMETHODIMP CommandExecuteImpl::SetDirectory(LPCWSTR directory) {
200   return S_OK;
201 }
202
203 STDMETHODIMP CommandExecuteImpl::GetValue(enum AHE_TYPE* pahe) {
204   if (!GetLaunchScheme(&display_name_, &launch_scheme_)) {
205     AtlTrace("Failed to get scheme, E_FAIL\n");
206     return E_FAIL;
207   }
208
209   EC_HOST_UI_MODE mode = GetLaunchMode();
210   *pahe = (mode == ECHUIM_DESKTOP) ? AHE_DESKTOP : AHE_IMMERSIVE;
211
212   if (*pahe == AHE_IMMERSIVE && verb_ != win8::kMetroViewerConnectVerb)
213     LaunchChromeBrowserProcess();
214   return S_OK;
215 }
216
217 STDMETHODIMP CommandExecuteImpl::Execute() {
218   AtlTrace("In %hs\n", __FUNCTION__);
219
220   if (integrity_level_ == base::HIGH_INTEGRITY)
221     return LaunchDesktopChrome();
222
223   EC_HOST_UI_MODE mode = GetLaunchMode();
224   if (mode == ECHUIM_DESKTOP)
225     return LaunchDesktopChrome();
226
227   HRESULT hr = E_FAIL;
228   CComPtr<IApplicationActivationManager> activation_manager;
229   hr = activation_manager.CoCreateInstance(CLSID_ApplicationActivationManager);
230   if (!activation_manager) {
231     AtlTrace("Failed to get the activation manager, error 0x%x\n", hr);
232     return S_OK;
233   }
234
235   BrowserDistribution* distribution = BrowserDistribution::GetDistribution();
236   bool is_per_user_install = InstallUtil::IsPerUserInstall(
237       chrome_exe_.value().c_str());
238   base::string16 app_id = ShellUtil::GetBrowserModelId(
239       distribution, is_per_user_install);
240
241   DWORD pid = 0;
242   if (launch_scheme_ == INTERNET_SCHEME_FILE &&
243       display_name_.find(installer::kChromeExe) != base::string16::npos) {
244     AtlTrace("Activating for file\n");
245     hr = activation_manager->ActivateApplication(app_id.c_str(),
246                                                  verb_.c_str(),
247                                                  AO_NONE,
248                                                  &pid);
249   } else {
250     AtlTrace("Activating for protocol\n");
251     hr = activation_manager->ActivateForProtocol(app_id.c_str(),
252                                                  item_array_,
253                                                  &pid);
254   }
255   if (hr == E_APPLICATION_NOT_REGISTERED) {
256     AtlTrace("Metro chrome is not registered, launching in desktop\n");
257     return LaunchDesktopChrome();
258   }
259   AtlTrace("Metro Chrome launch, pid=%d, returned 0x%x\n", pid, hr);
260   return S_OK;
261 }
262
263 STDMETHODIMP CommandExecuteImpl::Initialize(LPCWSTR name,
264                                             IPropertyBag* bag) {
265   if (!FindChromeExe(&chrome_exe_))
266     return E_FAIL;
267   delegate_execute::UpdateChromeIfNeeded(chrome_exe_);
268
269   if (name) {
270     AtlTrace("Verb is %S\n", name);
271     verb_ = name;
272   }
273
274   base::GetProcessIntegrityLevel(base::GetCurrentProcessHandle(),
275                                  &integrity_level_);
276   return S_OK;
277 }
278
279 STDMETHODIMP CommandExecuteImpl::SetSelection(IShellItemArray* item_array) {
280   item_array_ = item_array;
281   return S_OK;
282 }
283
284 STDMETHODIMP CommandExecuteImpl::GetSelection(REFIID riid, void** selection) {
285   return S_OK;
286 }
287
288 STDMETHODIMP CommandExecuteImpl::AllowForegroundTransfer(void* reserved) {
289   return S_OK;
290 }
291
292 // Returns false if chrome.exe cannot be found.
293 // static
294 bool CommandExecuteImpl::FindChromeExe(base::FilePath* chrome_exe) {
295   // Look for chrome.exe one folder above delegate_execute.exe (as expected in
296   // Chrome installs). Failing that, look for it alonside delegate_execute.exe.
297   base::FilePath dir_exe;
298   if (!PathService::Get(base::DIR_EXE, &dir_exe)) {
299     AtlTrace("Failed to get current exe path\n");
300     return false;
301   }
302
303   *chrome_exe = dir_exe.DirName().Append(chrome::kBrowserProcessExecutableName);
304   if (!base::PathExists(*chrome_exe)) {
305     *chrome_exe = dir_exe.Append(chrome::kBrowserProcessExecutableName);
306     if (!base::PathExists(*chrome_exe)) {
307       AtlTrace("Failed to find chrome exe file\n");
308       return false;
309     }
310   }
311   return true;
312 }
313
314 bool CommandExecuteImpl::GetLaunchScheme(
315     base::string16* display_name, INTERNET_SCHEME* scheme) {
316   if (!item_array_)
317     return false;
318
319   ATLASSERT(display_name);
320   ATLASSERT(scheme);
321
322   DWORD count = 0;
323   item_array_->GetCount(&count);
324
325   if (count != 1) {
326     AtlTrace("Cannot handle %d elements in the IShellItemArray\n", count);
327     return false;
328   }
329
330   CComPtr<IEnumShellItems> items;
331   item_array_->EnumItems(&items);
332   CComPtr<IShellItem> shell_item;
333   HRESULT hr = items->Next(1, &shell_item, &count);
334   if (hr != S_OK) {
335     AtlTrace("Failed to read element from the IShellItemsArray\n");
336     return false;
337   }
338
339   hr = GetUrlFromShellItem(shell_item, display_name);
340   if (FAILED(hr)) {
341     AtlTrace("Failed to get url. Error 0x%x\n", hr);
342     return false;
343   }
344
345   wchar_t scheme_name[16];
346   URL_COMPONENTS components = {0};
347   components.lpszScheme = scheme_name;
348   components.dwSchemeLength = sizeof(scheme_name)/sizeof(scheme_name[0]);
349
350   components.dwStructSize = sizeof(components);
351   if (!InternetCrackUrlW(display_name->c_str(), 0, 0, &components)) {
352     AtlTrace("Failed to crack url %ls\n", display_name->c_str());
353     return false;
354   }
355
356   AtlTrace("Launch scheme is [%ls] (%d)\n", scheme_name, components.nScheme);
357   *scheme = components.nScheme;
358   return true;
359 }
360
361 HRESULT CommandExecuteImpl::LaunchDesktopChrome() {
362   base::string16 display_name = display_name_;
363
364   switch (launch_scheme_) {
365     case INTERNET_SCHEME_FILE:
366       // If anything other than chrome.exe is passed in the display name we
367       // should honor it. For e.g. If the user clicks on a html file when
368       // chrome is the default we should treat it as a parameter to be passed
369       // to chrome.
370       if (display_name.find(installer::kChromeExe) != base::string16::npos)
371         display_name.clear();
372       break;
373
374     default:
375       break;
376   }
377
378   CommandLine chrome(
379       delegate_execute::MakeChromeCommandLine(chrome_exe_, parameters_,
380                                               display_name));
381   base::string16 command_line(chrome.GetCommandLineString());
382
383   AtlTrace("Formatted command line is %ls\n", command_line.c_str());
384
385   PROCESS_INFORMATION temp_process_info = {};
386   BOOL ret = CreateProcess(chrome_exe_.value().c_str(),
387                            const_cast<LPWSTR>(command_line.c_str()),
388                            NULL, NULL, FALSE, 0, NULL, NULL, &start_info_,
389                            &temp_process_info);
390   if (ret) {
391     base::win::ScopedProcessInformation proc_info(temp_process_info);
392     AtlTrace("Process id is %d\n", proc_info.process_id());
393     AllowSetForegroundWindow(proc_info.process_id());
394   } else {
395     AtlTrace("Process launch failed, error %d\n", ::GetLastError());
396   }
397
398   return S_OK;
399 }
400
401 EC_HOST_UI_MODE CommandExecuteImpl::GetLaunchMode() {
402   // See the header file for an explanation of the mode selection logic.
403   static bool launch_mode_determined = false;
404   static EC_HOST_UI_MODE launch_mode = ECHUIM_DESKTOP;
405
406   const char* modes[] = { "Desktop", "Immersive", "SysLauncher", "??" };
407
408   if (launch_mode_determined)
409     return launch_mode;
410
411   if (integrity_level_ == base::HIGH_INTEGRITY) {
412     // Metro mode apps don't work in high integrity mode.
413     AtlTrace("High integrity: launching in desktop mode\n");
414     launch_mode = ECHUIM_DESKTOP;
415     launch_mode_determined = true;
416     return launch_mode;
417   }
418   if (GetAsyncKeyState(VK_SHIFT) && GetAsyncKeyState(VK_F11)) {
419     AtlTrace("Hotkey: launching in immersive mode\n");
420     launch_mode = ECHUIM_IMMERSIVE;
421     launch_mode_determined = true;
422     return launch_mode;
423   }
424
425   // From here on, if we can, we will write the outcome
426   // of this function to the registry.
427   if (parameters_.HasSwitch(switches::kForceImmersive)) {
428     launch_mode = ECHUIM_IMMERSIVE;
429     launch_mode_determined = true;
430     parameters_ = CommandLine(CommandLine::NO_PROGRAM);
431   } else if (parameters_.HasSwitch(switches::kForceDesktop)) {
432     launch_mode = ECHUIM_DESKTOP;
433     launch_mode_determined = true;
434     parameters_ = CommandLine(CommandLine::NO_PROGRAM);
435   }
436
437   base::win::RegKey reg_key;
438   LONG key_result = reg_key.Create(HKEY_CURRENT_USER,
439                                    chrome::kMetroRegistryPath,
440                                    KEY_ALL_ACCESS);
441   if (key_result != ERROR_SUCCESS) {
442     AtlTrace("Failed to open HKCU %ls key, error 0x%x\n",
443              chrome::kMetroRegistryPath,
444              key_result);
445     if (!launch_mode_determined) {
446       // If we cannot open the key and we don't know the
447       // launch mode we default to desktop mode.
448       launch_mode = ECHUIM_DESKTOP;
449       launch_mode_determined = true;
450     }
451     return launch_mode;
452   }
453
454   if (launch_mode_determined) {
455     AtlTrace("Launch mode forced by cmdline to %s\n", modes[launch_mode]);
456     reg_key.WriteValue(chrome::kLaunchModeValue,
457                        static_cast<DWORD>(launch_mode));
458     return launch_mode;
459   }
460
461   // Use the previous mode if available. Else launch in desktop mode.
462   DWORD reg_value;
463   if (reg_key.ReadValueDW(chrome::kLaunchModeValue,
464                           &reg_value) != ERROR_SUCCESS) {
465     launch_mode = ECHUIM_DESKTOP;
466     AtlTrace("Can't read registry, defaulting to %s\n", modes[launch_mode]);
467   } else if (reg_value >= ECHUIM_SYSTEM_LAUNCHER) {
468     AtlTrace("Invalid registry launch mode value %u\n", reg_value);
469     launch_mode = ECHUIM_DESKTOP;
470   } else {
471     launch_mode = static_cast<EC_HOST_UI_MODE>(reg_value);
472     AtlTrace("Launch mode forced by registry to %s\n", modes[launch_mode]);
473   }
474
475   launch_mode_determined = true;
476   return launch_mode;
477 }