platform_util_win.cc 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. // Copyright (c) 2013 GitHub, Inc.
  2. // Use of this source code is governed by the MIT license that can be
  3. // found in the LICENSE file.
  4. #include "atom/common/platform_util.h"
  5. #include <windows.h> // windows.h must be included first
  6. #include <atlbase.h>
  7. #include <comdef.h>
  8. #include <commdlg.h>
  9. #include <dwmapi.h>
  10. #include <objbase.h>
  11. #include <shellapi.h>
  12. #include <shlobj.h>
  13. #include "base/bind.h"
  14. #include "base/bind_helpers.h"
  15. #include "base/files/file_path.h"
  16. #include "base/files/file_util.h"
  17. #include "base/logging.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_com_initializer.h"
  23. #include "base/win/scoped_comptr.h"
  24. #include "base/win/windows_version.h"
  25. #include "ui/base/win/shell.h"
  26. #include "url/gurl.h"
  27. namespace {
  28. // Old ShellExecute crashes the process when the command for a given scheme
  29. // is empty. This function tells if it is.
  30. bool ValidateShellCommandForScheme(const std::string& scheme) {
  31. base::win::RegKey key;
  32. base::string16 registry_path =
  33. base::ASCIIToUTF16(scheme) + L"\\shell\\open\\command";
  34. key.Open(HKEY_CLASSES_ROOT, registry_path.c_str(), KEY_READ);
  35. if (!key.Valid())
  36. return false;
  37. DWORD size = 0;
  38. key.ReadValue(NULL, NULL, &size, NULL);
  39. if (size <= 2)
  40. return false;
  41. return true;
  42. }
  43. // Required COM implementation of IFileOperationProgressSink so we can
  44. // precheck files before deletion to make sure they can be move to the
  45. // Recycle Bin.
  46. class DeleteFileProgressSink : public IFileOperationProgressSink {
  47. public:
  48. DeleteFileProgressSink();
  49. private:
  50. ULONG STDMETHODCALLTYPE AddRef(void);
  51. ULONG STDMETHODCALLTYPE Release(void);
  52. HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, LPVOID* ppvObj);
  53. HRESULT STDMETHODCALLTYPE StartOperations(void);
  54. HRESULT STDMETHODCALLTYPE FinishOperations(HRESULT);
  55. HRESULT STDMETHODCALLTYPE PreRenameItem(DWORD, IShellItem*, LPCWSTR);
  56. HRESULT STDMETHODCALLTYPE
  57. PostRenameItem(DWORD, IShellItem*, LPCWSTR, HRESULT, IShellItem*);
  58. HRESULT STDMETHODCALLTYPE PreMoveItem(DWORD,
  59. IShellItem*,
  60. IShellItem*,
  61. LPCWSTR);
  62. HRESULT STDMETHODCALLTYPE
  63. PostMoveItem(DWORD, IShellItem*, IShellItem*, LPCWSTR, HRESULT, IShellItem*);
  64. HRESULT STDMETHODCALLTYPE PreCopyItem(DWORD,
  65. IShellItem*,
  66. IShellItem*,
  67. LPCWSTR);
  68. HRESULT STDMETHODCALLTYPE
  69. PostCopyItem(DWORD, IShellItem*, IShellItem*, LPCWSTR, HRESULT, IShellItem*);
  70. HRESULT STDMETHODCALLTYPE PreDeleteItem(DWORD, IShellItem*);
  71. HRESULT STDMETHODCALLTYPE PostDeleteItem(DWORD,
  72. IShellItem*,
  73. HRESULT,
  74. IShellItem*);
  75. HRESULT STDMETHODCALLTYPE PreNewItem(DWORD, IShellItem*, LPCWSTR);
  76. HRESULT STDMETHODCALLTYPE PostNewItem(DWORD,
  77. IShellItem*,
  78. LPCWSTR,
  79. LPCWSTR,
  80. DWORD,
  81. HRESULT,
  82. IShellItem*);
  83. HRESULT STDMETHODCALLTYPE UpdateProgress(UINT, UINT);
  84. HRESULT STDMETHODCALLTYPE ResetTimer(void);
  85. HRESULT STDMETHODCALLTYPE PauseTimer(void);
  86. HRESULT STDMETHODCALLTYPE ResumeTimer(void);
  87. ULONG m_cRef;
  88. };
  89. DeleteFileProgressSink::DeleteFileProgressSink() {
  90. m_cRef = 0;
  91. }
  92. HRESULT DeleteFileProgressSink::PreDeleteItem(DWORD dwFlags, IShellItem*) {
  93. if (!(dwFlags & TSF_DELETE_RECYCLE_IF_POSSIBLE)) {
  94. // TSF_DELETE_RECYCLE_IF_POSSIBLE will not be set for items that cannot be
  95. // recycled. In this case, we abort the delete operation. This bubbles
  96. // up and stops the Delete in IFileOperation.
  97. return E_ABORT;
  98. }
  99. // Returns S_OK if successful, or an error value otherwise. In the case of an
  100. // error value, the delete operation and all subsequent operations pending
  101. // from the call to IFileOperation are canceled.
  102. return S_OK;
  103. }
  104. HRESULT DeleteFileProgressSink::QueryInterface(REFIID riid, LPVOID* ppvObj) {
  105. // Always set out parameter to NULL, validating it first.
  106. if (!ppvObj)
  107. return E_INVALIDARG;
  108. *ppvObj = nullptr;
  109. if (riid == IID_IUnknown || riid == IID_IFileOperationProgressSink) {
  110. // Increment the reference count and return the pointer.
  111. *ppvObj = reinterpret_cast<IUnknown*>(this);
  112. AddRef();
  113. return NOERROR;
  114. }
  115. return E_NOINTERFACE;
  116. }
  117. ULONG DeleteFileProgressSink::AddRef() {
  118. InterlockedIncrement(&m_cRef);
  119. return m_cRef;
  120. }
  121. ULONG DeleteFileProgressSink::Release() {
  122. // Decrement the object's internal counter.
  123. ULONG ulRefCount = InterlockedDecrement(&m_cRef);
  124. if (0 == m_cRef) {
  125. delete this;
  126. }
  127. return ulRefCount;
  128. }
  129. HRESULT DeleteFileProgressSink::StartOperations() {
  130. return S_OK;
  131. }
  132. HRESULT DeleteFileProgressSink::FinishOperations(HRESULT) {
  133. return S_OK;
  134. }
  135. HRESULT DeleteFileProgressSink::PreRenameItem(DWORD, IShellItem*, LPCWSTR) {
  136. return S_OK;
  137. }
  138. HRESULT DeleteFileProgressSink::PostRenameItem(DWORD,
  139. IShellItem*,
  140. __RPC__in_string LPCWSTR,
  141. HRESULT,
  142. IShellItem*) {
  143. return E_NOTIMPL;
  144. }
  145. HRESULT DeleteFileProgressSink::PreMoveItem(DWORD,
  146. IShellItem*,
  147. IShellItem*,
  148. LPCWSTR) {
  149. return E_NOTIMPL;
  150. }
  151. HRESULT DeleteFileProgressSink::PostMoveItem(DWORD,
  152. IShellItem*,
  153. IShellItem*,
  154. LPCWSTR,
  155. HRESULT,
  156. IShellItem*) {
  157. return E_NOTIMPL;
  158. }
  159. HRESULT DeleteFileProgressSink::PreCopyItem(DWORD,
  160. IShellItem*,
  161. IShellItem*,
  162. LPCWSTR) {
  163. return E_NOTIMPL;
  164. }
  165. HRESULT DeleteFileProgressSink::PostCopyItem(DWORD,
  166. IShellItem*,
  167. IShellItem*,
  168. LPCWSTR,
  169. HRESULT,
  170. IShellItem*) {
  171. return E_NOTIMPL;
  172. }
  173. HRESULT DeleteFileProgressSink::PostDeleteItem(DWORD,
  174. IShellItem*,
  175. HRESULT,
  176. IShellItem*) {
  177. return S_OK;
  178. }
  179. HRESULT DeleteFileProgressSink::PreNewItem(DWORD dwFlags,
  180. IShellItem*,
  181. LPCWSTR) {
  182. return E_NOTIMPL;
  183. }
  184. HRESULT DeleteFileProgressSink::PostNewItem(DWORD,
  185. IShellItem*,
  186. LPCWSTR,
  187. LPCWSTR,
  188. DWORD,
  189. HRESULT,
  190. IShellItem*) {
  191. return E_NOTIMPL;
  192. }
  193. HRESULT DeleteFileProgressSink::UpdateProgress(UINT, UINT) {
  194. return S_OK;
  195. }
  196. HRESULT DeleteFileProgressSink::ResetTimer() {
  197. return S_OK;
  198. }
  199. HRESULT DeleteFileProgressSink::PauseTimer() {
  200. return S_OK;
  201. }
  202. HRESULT DeleteFileProgressSink::ResumeTimer() {
  203. return S_OK;
  204. }
  205. } // namespace
  206. namespace platform_util {
  207. bool ShowItemInFolder(const base::FilePath& full_path) {
  208. base::win::ScopedCOMInitializer com_initializer;
  209. if (!com_initializer.succeeded())
  210. return false;
  211. base::FilePath dir = full_path.DirName().AsEndingWithSeparator();
  212. // ParseDisplayName will fail if the directory is "C:", it must be "C:\\".
  213. if (dir.empty())
  214. return false;
  215. typedef HRESULT(WINAPI * SHOpenFolderAndSelectItemsFuncPtr)(
  216. PCIDLIST_ABSOLUTE pidl_Folder, UINT cidl, PCUITEMID_CHILD_ARRAY pidls,
  217. DWORD flags);
  218. static SHOpenFolderAndSelectItemsFuncPtr open_folder_and_select_itemsPtr =
  219. NULL;
  220. static bool initialize_open_folder_proc = true;
  221. if (initialize_open_folder_proc) {
  222. initialize_open_folder_proc = false;
  223. // The SHOpenFolderAndSelectItems API is exposed by shell32 version 6
  224. // and does not exist in Win2K. We attempt to retrieve this function export
  225. // from shell32 and if it does not exist, we just invoke ShellExecute to
  226. // open the folder thus losing the functionality to select the item in
  227. // the process.
  228. HMODULE shell32_base = GetModuleHandle(L"shell32.dll");
  229. if (!shell32_base) {
  230. NOTREACHED() << " " << __FUNCTION__ << "(): Can't open shell32.dll";
  231. return false;
  232. }
  233. open_folder_and_select_itemsPtr =
  234. reinterpret_cast<SHOpenFolderAndSelectItemsFuncPtr>(
  235. GetProcAddress(shell32_base, "SHOpenFolderAndSelectItems"));
  236. }
  237. if (!open_folder_and_select_itemsPtr) {
  238. return ui::win::OpenFolderViaShell(dir);
  239. }
  240. base::win::ScopedComPtr<IShellFolder> desktop;
  241. HRESULT hr = SHGetDesktopFolder(desktop.GetAddressOf());
  242. if (FAILED(hr))
  243. return false;
  244. base::win::ScopedCoMem<ITEMIDLIST> dir_item;
  245. hr = desktop->ParseDisplayName(NULL, NULL,
  246. const_cast<wchar_t*>(dir.value().c_str()),
  247. NULL, &dir_item, NULL);
  248. if (FAILED(hr)) {
  249. return ui::win::OpenFolderViaShell(dir);
  250. }
  251. base::win::ScopedCoMem<ITEMIDLIST> file_item;
  252. hr = desktop->ParseDisplayName(
  253. NULL, NULL, const_cast<wchar_t*>(full_path.value().c_str()), NULL,
  254. &file_item, NULL);
  255. if (FAILED(hr)) {
  256. return ui::win::OpenFolderViaShell(dir);
  257. }
  258. const ITEMIDLIST* highlight[] = {file_item};
  259. hr = (*open_folder_and_select_itemsPtr)(dir_item, arraysize(highlight),
  260. highlight, NULL);
  261. if (!FAILED(hr))
  262. return true;
  263. // On some systems, the above call mysteriously fails with "file not
  264. // found" even though the file is there. In these cases, ShellExecute()
  265. // seems to work as a fallback (although it won't select the file).
  266. if (hr == ERROR_FILE_NOT_FOUND) {
  267. return ui::win::OpenFolderViaShell(dir);
  268. } else {
  269. LPTSTR message = NULL;
  270. DWORD message_length = FormatMessage(
  271. FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, 0, hr, 0,
  272. reinterpret_cast<LPTSTR>(&message), 0, NULL);
  273. LOG(WARNING) << " " << __FUNCTION__ << "(): Can't open full_path = \""
  274. << full_path.value() << "\""
  275. << " hr = " << hr << " " << reinterpret_cast<LPTSTR>(&message);
  276. if (message)
  277. LocalFree(message);
  278. return ui::win::OpenFolderViaShell(dir);
  279. }
  280. }
  281. bool OpenItem(const base::FilePath& full_path) {
  282. if (base::DirectoryExists(full_path))
  283. return ui::win::OpenFolderViaShell(full_path);
  284. else
  285. return ui::win::OpenFileViaShell(full_path);
  286. }
  287. bool OpenExternal(const base::string16& url, bool activate) {
  288. // Quote the input scheme to be sure that the command does not have
  289. // parameters unexpected by the external program. This url should already
  290. // have been escaped.
  291. base::string16 escaped_url = L"\"" + url + L"\"";
  292. if (reinterpret_cast<ULONG_PTR>(ShellExecuteW(
  293. NULL, L"open", escaped_url.c_str(), NULL, NULL, SW_SHOWNORMAL)) <=
  294. 32) {
  295. // We fail to execute the call. We could display a message to the user.
  296. // TODO(nsylvain): we should also add a dialog to warn on errors. See
  297. // bug 1136923.
  298. return false;
  299. }
  300. return true;
  301. }
  302. void OpenExternal(const base::string16& url,
  303. bool activate,
  304. const OpenExternalCallback& callback) {
  305. // TODO(gabriel): Implement async open if callback is specified
  306. callback.Run(OpenExternal(url, activate) ? "" : "Failed to open");
  307. }
  308. bool MoveItemToTrash(const base::FilePath& path) {
  309. base::win::ScopedCOMInitializer com_initializer;
  310. if (!com_initializer.succeeded())
  311. return false;
  312. base::win::ScopedComPtr<IFileOperation> pfo;
  313. if (FAILED(::CoCreateInstance(CLSID_FileOperation, nullptr, CLSCTX_ALL,
  314. IID_PPV_ARGS(&pfo))))
  315. return false;
  316. // Elevation prompt enabled for UAC protected files. This overrides the
  317. // SILENT, NO_UI and NOERRORUI flags.
  318. if (base::win::GetVersion() >= base::win::VERSION_WIN8) {
  319. // Windows 8 introduces the flag RECYCLEONDELETE and deprecates the
  320. // ALLOWUNDO in favor of ADDUNDORECORD.
  321. if (FAILED(pfo->SetOperationFlags(
  322. FOF_NO_UI | FOFX_ADDUNDORECORD | FOF_NOERRORUI | FOF_SILENT |
  323. FOFX_SHOWELEVATIONPROMPT | FOFX_RECYCLEONDELETE)))
  324. return false;
  325. } else {
  326. // For Windows 7 and Vista, RecycleOnDelete is the default behavior.
  327. if (FAILED(pfo->SetOperationFlags(FOF_NO_UI | FOF_ALLOWUNDO |
  328. FOF_NOERRORUI | FOF_SILENT |
  329. FOFX_SHOWELEVATIONPROMPT)))
  330. return false;
  331. }
  332. // Create an IShellItem from the supplied source path.
  333. base::win::ScopedComPtr<IShellItem> delete_item;
  334. if (FAILED(SHCreateItemFromParsingName(
  335. path.value().c_str(), NULL,
  336. IID_PPV_ARGS(delete_item.GetAddressOf()))))
  337. return false;
  338. base::win::ScopedComPtr<IFileOperationProgressSink> delete_sink(
  339. new DeleteFileProgressSink);
  340. if (!delete_sink)
  341. return false;
  342. // Processes the queued command DeleteItem. This will trigger
  343. // the DeleteFileProgressSink to check for Recycle Bin.
  344. return SUCCEEDED(pfo->DeleteItem(delete_item.Get(), delete_sink.Get())) &&
  345. SUCCEEDED(pfo->PerformOperations());
  346. }
  347. void Beep() {
  348. MessageBeep(MB_OK);
  349. }
  350. } // namespace platform_util