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