Popular sites on the NTP: check that experiment group StartsWith (rather than IS...
[chromium-blink-merge.git] / chrome / browser / platform_util_win.cc
blob4e2d9f26fc5f06f7f8339fc2925cf2a856943898
1 // Copyright (c) 2011 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.
5 #include "chrome/browser/platform_util.h"
7 #include <commdlg.h>
8 #include <dwmapi.h>
9 #include <shellapi.h>
10 #include <shlobj.h>
12 #include "base/bind.h"
13 #include "base/bind_helpers.h"
14 #include "base/files/file_path.h"
15 #include "base/files/file_util.h"
16 #include "base/logging.h"
17 #include "base/metrics/field_trial.h"
18 #include "base/strings/string_util.h"
19 #include "base/strings/utf_string_conversions.h"
20 #include "base/win/registry.h"
21 #include "base/win/scoped_co_mem.h"
22 #include "base/win/scoped_comptr.h"
23 #include "base/win/windows_version.h"
24 #include "chrome/browser/lifetime/application_lifetime.h"
25 #include "chrome/browser/platform_util_internal.h"
26 #include "chrome/browser/ui/host_desktop.h"
27 #include "chrome/common/chrome_utility_messages.h"
28 #include "chrome/grit/generated_resources.h"
29 #include "content/public/browser/browser_thread.h"
30 #include "content/public/browser/utility_process_host.h"
31 #include "content/public/browser/utility_process_host_client.h"
32 #include "ui/base/l10n/l10n_util.h"
33 #include "ui/base/win/shell.h"
34 #include "ui/gfx/native_widget_types.h"
35 #include "url/gurl.h"
37 using content::BrowserThread;
39 namespace platform_util {
41 namespace {
43 // TODO(asanka): Move this to ui/base/win/shell.{h,cc} and invoke it from the
44 // utility process.
45 void ShowItemInFolderOnFileThread(const base::FilePath& full_path) {
46 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
47 base::FilePath dir = full_path.DirName().AsEndingWithSeparator();
48 // ParseDisplayName will fail if the directory is "C:", it must be "C:\\".
49 if (dir.empty())
50 return;
52 typedef HRESULT (WINAPI *SHOpenFolderAndSelectItemsFuncPtr)(
53 PCIDLIST_ABSOLUTE pidl_Folder,
54 UINT cidl,
55 PCUITEMID_CHILD_ARRAY pidls,
56 DWORD flags);
58 static SHOpenFolderAndSelectItemsFuncPtr open_folder_and_select_itemsPtr =
59 nullptr;
60 static bool initialize_open_folder_proc = true;
61 if (initialize_open_folder_proc) {
62 initialize_open_folder_proc = false;
63 // The SHOpenFolderAndSelectItems API is exposed by shell32 version 6
64 // and does not exist in Win2K. We attempt to retrieve this function export
65 // from shell32 and if it does not exist, we just invoke ShellExecute to
66 // open the folder thus losing the functionality to select the item in
67 // the process.
68 HMODULE shell32_base = GetModuleHandle(L"shell32.dll");
69 if (!shell32_base) {
70 NOTREACHED() << " " << __FUNCTION__ << "(): Can't open shell32.dll";
71 return;
73 open_folder_and_select_itemsPtr =
74 reinterpret_cast<SHOpenFolderAndSelectItemsFuncPtr>
75 (GetProcAddress(shell32_base, "SHOpenFolderAndSelectItems"));
77 if (!open_folder_and_select_itemsPtr) {
78 ShellExecute(NULL, L"open", dir.value().c_str(), NULL, NULL, SW_SHOW);
79 return;
82 base::win::ScopedComPtr<IShellFolder> desktop;
83 HRESULT hr = SHGetDesktopFolder(desktop.Receive());
84 if (FAILED(hr))
85 return;
87 base::win::ScopedCoMem<ITEMIDLIST> dir_item;
88 hr = desktop->ParseDisplayName(NULL, NULL,
89 const_cast<wchar_t *>(dir.value().c_str()),
90 NULL, &dir_item, NULL);
91 if (FAILED(hr))
92 return;
94 base::win::ScopedCoMem<ITEMIDLIST> file_item;
95 hr = desktop->ParseDisplayName(NULL, NULL,
96 const_cast<wchar_t *>(full_path.value().c_str()),
97 NULL, &file_item, NULL);
98 if (FAILED(hr))
99 return;
101 const ITEMIDLIST* highlight[] = { file_item };
103 hr = (*open_folder_and_select_itemsPtr)(dir_item, arraysize(highlight),
104 highlight, NULL);
106 if (FAILED(hr)) {
107 // On some systems, the above call mysteriously fails with "file not
108 // found" even though the file is there. In these cases, ShellExecute()
109 // seems to work as a fallback (although it won't select the file).
110 if (hr == ERROR_FILE_NOT_FOUND) {
111 ShellExecute(NULL, L"open", dir.value().c_str(), NULL, NULL, SW_SHOW);
112 } else {
113 LOG(WARNING) << " " << __FUNCTION__ << "(): Can't open full_path = \""
114 << full_path.value() << "\""
115 << " hr = " << logging::SystemErrorCodeToString(hr);
120 // Old ShellExecute crashes the process when the command for a given scheme
121 // is empty. This function tells if it is.
122 bool ValidateShellCommandForScheme(const std::string& scheme) {
123 base::win::RegKey key;
124 base::string16 registry_path = base::ASCIIToUTF16(scheme) +
125 L"\\shell\\open\\command";
126 key.Open(HKEY_CLASSES_ROOT, registry_path.c_str(), KEY_READ);
127 if (!key.Valid())
128 return false;
129 DWORD size = 0;
130 key.ReadValue(NULL, NULL, &size, NULL);
131 if (size <= 2)
132 return false;
133 return true;
136 void OpenExternalOnFileThread(const GURL& url) {
137 // Quote the input scheme to be sure that the command does not have
138 // parameters unexpected by the external program. This url should already
139 // have been escaped.
140 std::string escaped_url = url.spec();
141 escaped_url.insert(0, "\"");
142 escaped_url += "\"";
144 // According to Mozilla in uriloader/exthandler/win/nsOSHelperAppService.cpp:
145 // "Some versions of windows (Win2k before SP3, Win XP before SP1) crash in
146 // ShellExecute on long URLs (bug 161357 on bugzilla.mozilla.org). IE 5 and 6
147 // support URLS of 2083 chars in length, 2K is safe."
148 const size_t kMaxUrlLength = 2048;
149 if (escaped_url.length() > kMaxUrlLength) {
150 NOTREACHED();
151 return;
154 if (base::win::GetVersion() < base::win::VERSION_WIN7) {
155 if (!ValidateShellCommandForScheme(url.scheme()))
156 return;
159 if (reinterpret_cast<ULONG_PTR>(ShellExecuteA(NULL, "open",
160 escaped_url.c_str(), NULL, NULL,
161 SW_SHOWNORMAL)) <= 32) {
162 // We fail to execute the call. We could display a message to the user.
163 // TODO(nsylvain): we should also add a dialog to warn on errors. See
164 // bug 1136923.
165 return;
169 void OpenItemViaShellInUtilityProcess(const base::FilePath& full_path,
170 OpenItemType type) {
171 base::WeakPtr<content::UtilityProcessHost> utility_process_host(
172 content::UtilityProcessHost::Create(NULL, NULL)->AsWeakPtr());
173 utility_process_host->SetName(l10n_util::GetStringUTF16(
174 IDS_UTILITY_PROCESS_FILE_DIALOG_NAME));
175 utility_process_host->DisableSandbox();
176 switch (type) {
177 case OPEN_FILE:
178 utility_process_host->Send(
179 new ChromeUtilityMsg_OpenFileViaShell(full_path));
180 return;
182 case OPEN_FOLDER:
183 utility_process_host->Send(
184 new ChromeUtilityMsg_OpenFolderViaShell(full_path));
185 return;
189 void ActivateDesktopIfNecessary() {
190 DCHECK_CURRENTLY_ON(BrowserThread::UI);
191 if (chrome::GetActiveDesktop() == chrome::HOST_DESKTOP_TYPE_ASH)
192 chrome::ActivateDesktopHelper(chrome::ASH_KEEP_RUNNING);
195 } // namespace
197 void ShowItemInFolder(Profile* profile, const base::FilePath& full_path) {
198 ActivateDesktopIfNecessary();
199 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
200 base::Bind(&ShowItemInFolderOnFileThread, full_path));
203 namespace internal {
205 void PlatformOpenVerifiedItem(const base::FilePath& path, OpenItemType type) {
206 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
207 base::Bind(&ActivateDesktopIfNecessary));
209 if (base::FieldTrialList::FindFullName("IsolateShellOperations") ==
210 "Enabled") {
211 BrowserThread::PostTask(
212 BrowserThread::IO, FROM_HERE,
213 base::Bind(&OpenItemViaShellInUtilityProcess, path, type));
214 } else {
215 switch (type) {
216 case OPEN_FILE:
217 ui::win::OpenFileViaShell(path);
218 break;
220 case OPEN_FOLDER:
221 ui::win::OpenFolderViaShell(path);
222 break;
227 } // namespace internal
229 void OpenExternal(Profile* profile, const GURL& url) {
230 DCHECK_CURRENTLY_ON(BrowserThread::UI);
232 if (chrome::GetActiveDesktop() == chrome::HOST_DESKTOP_TYPE_ASH &&
233 !url.SchemeIsHTTPOrHTTPS())
234 chrome::ActivateDesktopHelper(chrome::ASH_KEEP_RUNNING);
236 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
237 base::Bind(&OpenExternalOnFileThread, url));
240 } // namespace platform_util