platform_util_win.cc 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  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 "shell/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 <wrl/client.h>
  14. #include "base/bind.h"
  15. #include "base/callback_helpers.h"
  16. #include "base/files/file_path.h"
  17. #include "base/files/file_util.h"
  18. #include "base/logging.h"
  19. #include "base/stl_util.h"
  20. #include "base/strings/string_util.h"
  21. #include "base/strings/utf_string_conversions.h"
  22. #include "base/task/post_task.h"
  23. #include "base/task/thread_pool.h"
  24. #include "base/threading/scoped_blocking_call.h"
  25. #include "base/win/registry.h"
  26. #include "base/win/scoped_co_mem.h"
  27. #include "base/win/scoped_com_initializer.h"
  28. #include "base/win/windows_version.h"
  29. #include "content/public/browser/browser_task_traits.h"
  30. #include "content/public/browser/browser_thread.h"
  31. #include "net/base/escape.h"
  32. #include "shell/common/electron_paths.h"
  33. #include "ui/base/win/shell.h"
  34. #include "url/gurl.h"
  35. namespace {
  36. // Required COM implementation of IFileOperationProgressSink so we can
  37. // precheck files before deletion to make sure they can be move to the
  38. // Recycle Bin.
  39. class DeleteFileProgressSink : public IFileOperationProgressSink {
  40. public:
  41. DeleteFileProgressSink();
  42. virtual ~DeleteFileProgressSink() = default;
  43. private:
  44. ULONG STDMETHODCALLTYPE AddRef(void) override;
  45. ULONG STDMETHODCALLTYPE Release(void) override;
  46. HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid,
  47. LPVOID* ppvObj) override;
  48. HRESULT STDMETHODCALLTYPE StartOperations(void) override;
  49. HRESULT STDMETHODCALLTYPE FinishOperations(HRESULT) override;
  50. HRESULT STDMETHODCALLTYPE PreRenameItem(DWORD, IShellItem*, LPCWSTR) override;
  51. HRESULT STDMETHODCALLTYPE
  52. PostRenameItem(DWORD, IShellItem*, LPCWSTR, HRESULT, IShellItem*) override;
  53. HRESULT STDMETHODCALLTYPE PreMoveItem(DWORD,
  54. IShellItem*,
  55. IShellItem*,
  56. LPCWSTR) override;
  57. HRESULT STDMETHODCALLTYPE PostMoveItem(DWORD,
  58. IShellItem*,
  59. IShellItem*,
  60. LPCWSTR,
  61. HRESULT,
  62. IShellItem*) override;
  63. HRESULT STDMETHODCALLTYPE PreCopyItem(DWORD,
  64. IShellItem*,
  65. IShellItem*,
  66. LPCWSTR) override;
  67. HRESULT STDMETHODCALLTYPE PostCopyItem(DWORD,
  68. IShellItem*,
  69. IShellItem*,
  70. LPCWSTR,
  71. HRESULT,
  72. IShellItem*) override;
  73. HRESULT STDMETHODCALLTYPE PreDeleteItem(DWORD, IShellItem*) override;
  74. HRESULT STDMETHODCALLTYPE PostDeleteItem(DWORD,
  75. IShellItem*,
  76. HRESULT,
  77. IShellItem*) override;
  78. HRESULT STDMETHODCALLTYPE PreNewItem(DWORD, IShellItem*, LPCWSTR) override;
  79. HRESULT STDMETHODCALLTYPE PostNewItem(DWORD,
  80. IShellItem*,
  81. LPCWSTR,
  82. LPCWSTR,
  83. DWORD,
  84. HRESULT,
  85. IShellItem*) override;
  86. HRESULT STDMETHODCALLTYPE UpdateProgress(UINT, UINT) override;
  87. HRESULT STDMETHODCALLTYPE ResetTimer(void) override;
  88. HRESULT STDMETHODCALLTYPE PauseTimer(void) override;
  89. HRESULT STDMETHODCALLTYPE ResumeTimer(void) override;
  90. ULONG m_cRef;
  91. };
  92. DeleteFileProgressSink::DeleteFileProgressSink() {
  93. m_cRef = 0;
  94. }
  95. HRESULT DeleteFileProgressSink::PreDeleteItem(DWORD dwFlags, IShellItem*) {
  96. if (!(dwFlags & TSF_DELETE_RECYCLE_IF_POSSIBLE)) {
  97. // TSF_DELETE_RECYCLE_IF_POSSIBLE will not be set for items that cannot be
  98. // recycled. In this case, we abort the delete operation. This bubbles
  99. // up and stops the Delete in IFileOperation.
  100. return E_ABORT;
  101. }
  102. // Returns S_OK if successful, or an error value otherwise. In the case of an
  103. // error value, the delete operation and all subsequent operations pending
  104. // from the call to IFileOperation are canceled.
  105. return S_OK;
  106. }
  107. HRESULT DeleteFileProgressSink::QueryInterface(REFIID riid, LPVOID* ppvObj) {
  108. // Always set out parameter to NULL, validating it first.
  109. if (!ppvObj)
  110. return E_INVALIDARG;
  111. *ppvObj = nullptr;
  112. if (riid == IID_IUnknown || riid == IID_IFileOperationProgressSink) {
  113. // Increment the reference count and return the pointer.
  114. *ppvObj = reinterpret_cast<IUnknown*>(this);
  115. AddRef();
  116. return NOERROR;
  117. }
  118. return E_NOINTERFACE;
  119. }
  120. ULONG DeleteFileProgressSink::AddRef() {
  121. InterlockedIncrement(&m_cRef);
  122. return m_cRef;
  123. }
  124. ULONG DeleteFileProgressSink::Release() {
  125. // Decrement the object's internal counter.
  126. ULONG ulRefCount = InterlockedDecrement(&m_cRef);
  127. if (0 == m_cRef) {
  128. delete this;
  129. }
  130. return ulRefCount;
  131. }
  132. HRESULT DeleteFileProgressSink::StartOperations() {
  133. return S_OK;
  134. }
  135. HRESULT DeleteFileProgressSink::FinishOperations(HRESULT) {
  136. return S_OK;
  137. }
  138. HRESULT DeleteFileProgressSink::PreRenameItem(DWORD, IShellItem*, LPCWSTR) {
  139. return S_OK;
  140. }
  141. HRESULT DeleteFileProgressSink::PostRenameItem(DWORD,
  142. IShellItem*,
  143. __RPC__in_string LPCWSTR,
  144. HRESULT,
  145. IShellItem*) {
  146. return E_NOTIMPL;
  147. }
  148. HRESULT DeleteFileProgressSink::PreMoveItem(DWORD,
  149. IShellItem*,
  150. IShellItem*,
  151. LPCWSTR) {
  152. return E_NOTIMPL;
  153. }
  154. HRESULT DeleteFileProgressSink::PostMoveItem(DWORD,
  155. IShellItem*,
  156. IShellItem*,
  157. LPCWSTR,
  158. HRESULT,
  159. IShellItem*) {
  160. return E_NOTIMPL;
  161. }
  162. HRESULT DeleteFileProgressSink::PreCopyItem(DWORD,
  163. IShellItem*,
  164. IShellItem*,
  165. LPCWSTR) {
  166. return E_NOTIMPL;
  167. }
  168. HRESULT DeleteFileProgressSink::PostCopyItem(DWORD,
  169. IShellItem*,
  170. IShellItem*,
  171. LPCWSTR,
  172. HRESULT,
  173. IShellItem*) {
  174. return E_NOTIMPL;
  175. }
  176. HRESULT DeleteFileProgressSink::PostDeleteItem(DWORD,
  177. IShellItem*,
  178. HRESULT,
  179. IShellItem*) {
  180. return S_OK;
  181. }
  182. HRESULT DeleteFileProgressSink::PreNewItem(DWORD dwFlags,
  183. IShellItem*,
  184. LPCWSTR) {
  185. return E_NOTIMPL;
  186. }
  187. HRESULT DeleteFileProgressSink::PostNewItem(DWORD,
  188. IShellItem*,
  189. LPCWSTR,
  190. LPCWSTR,
  191. DWORD,
  192. HRESULT,
  193. IShellItem*) {
  194. return E_NOTIMPL;
  195. }
  196. HRESULT DeleteFileProgressSink::UpdateProgress(UINT, UINT) {
  197. return S_OK;
  198. }
  199. HRESULT DeleteFileProgressSink::ResetTimer() {
  200. return S_OK;
  201. }
  202. HRESULT DeleteFileProgressSink::PauseTimer() {
  203. return S_OK;
  204. }
  205. HRESULT DeleteFileProgressSink::ResumeTimer() {
  206. return S_OK;
  207. }
  208. std::string OpenExternalOnWorkerThread(
  209. const GURL& url,
  210. const platform_util::OpenExternalOptions& options) {
  211. base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
  212. base::BlockingType::MAY_BLOCK);
  213. // Quote the input scheme to be sure that the command does not have
  214. // parameters unexpected by the external program. This url should already
  215. // have been escaped.
  216. std::wstring escaped_url =
  217. L"\"" + base::UTF8ToWide(net::EscapeExternalHandlerValue(url.spec())) +
  218. L"\"";
  219. std::wstring working_dir = options.working_dir.value();
  220. if (reinterpret_cast<ULONG_PTR>(
  221. ShellExecuteW(nullptr, L"open", escaped_url.c_str(), nullptr,
  222. working_dir.empty() ? nullptr : working_dir.c_str(),
  223. SW_SHOWNORMAL)) <= 32) {
  224. return "Failed to open: " +
  225. logging::SystemErrorCodeToString(logging::GetLastSystemErrorCode());
  226. }
  227. return "";
  228. }
  229. void ShowItemInFolderOnWorkerThread(const base::FilePath& full_path) {
  230. base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
  231. base::BlockingType::MAY_BLOCK);
  232. base::win::ScopedCOMInitializer com_initializer;
  233. if (!com_initializer.Succeeded())
  234. return;
  235. base::FilePath dir = full_path.DirName().AsEndingWithSeparator();
  236. // ParseDisplayName will fail if the directory is "C:", it must be "C:\\".
  237. if (dir.empty())
  238. return;
  239. Microsoft::WRL::ComPtr<IShellFolder> desktop;
  240. HRESULT hr = SHGetDesktopFolder(desktop.GetAddressOf());
  241. if (FAILED(hr))
  242. return;
  243. base::win::ScopedCoMem<ITEMIDLIST> dir_item;
  244. hr = desktop->ParseDisplayName(NULL, NULL,
  245. const_cast<wchar_t*>(dir.value().c_str()),
  246. NULL, &dir_item, NULL);
  247. if (FAILED(hr))
  248. return;
  249. base::win::ScopedCoMem<ITEMIDLIST> file_item;
  250. hr = desktop->ParseDisplayName(
  251. NULL, NULL, const_cast<wchar_t*>(full_path.value().c_str()), NULL,
  252. &file_item, NULL);
  253. if (FAILED(hr))
  254. return;
  255. const ITEMIDLIST* highlight[] = {file_item};
  256. hr = SHOpenFolderAndSelectItems(dir_item, base::size(highlight), highlight,
  257. NULL);
  258. if (FAILED(hr)) {
  259. // On some systems, the above call mysteriously fails with "file not
  260. // found" even though the file is there. In these cases, ShellExecute()
  261. // seems to work as a fallback (although it won't select the file).
  262. if (hr == ERROR_FILE_NOT_FOUND) {
  263. ShellExecute(NULL, L"open", dir.value().c_str(), NULL, NULL, SW_SHOW);
  264. } else {
  265. LOG(WARNING) << " " << __func__ << "(): Can't open full_path = \""
  266. << full_path.value() << "\""
  267. << " hr = " << logging::SystemErrorCodeToString(hr);
  268. }
  269. }
  270. }
  271. std::string OpenPathOnThread(const base::FilePath& full_path) {
  272. // May result in an interactive dialog.
  273. base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
  274. base::BlockingType::MAY_BLOCK);
  275. bool success;
  276. if (base::DirectoryExists(full_path))
  277. success = ui::win::OpenFolderViaShell(full_path);
  278. else
  279. success = ui::win::OpenFileViaShell(full_path);
  280. return success ? "" : "Failed to open path";
  281. }
  282. } // namespace
  283. namespace platform_util {
  284. void ShowItemInFolder(const base::FilePath& full_path) {
  285. base::ThreadPool::CreateCOMSTATaskRunner(
  286. {base::MayBlock(), base::TaskPriority::USER_BLOCKING})
  287. ->PostTask(FROM_HERE,
  288. base::BindOnce(&ShowItemInFolderOnWorkerThread, full_path));
  289. }
  290. void OpenPath(const base::FilePath& full_path, OpenCallback callback) {
  291. DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
  292. base::PostTaskAndReplyWithResult(
  293. base::ThreadPool::CreateCOMSTATaskRunner(
  294. {base::MayBlock(), base::TaskPriority::USER_BLOCKING})
  295. .get(),
  296. FROM_HERE, base::BindOnce(&OpenPathOnThread, full_path),
  297. std::move(callback));
  298. }
  299. void OpenExternal(const GURL& url,
  300. const OpenExternalOptions& options,
  301. OpenCallback callback) {
  302. base::PostTaskAndReplyWithResult(
  303. base::ThreadPool::CreateCOMSTATaskRunner(
  304. {base::MayBlock(), base::TaskPriority::USER_BLOCKING})
  305. .get(),
  306. FROM_HERE, base::BindOnce(&OpenExternalOnWorkerThread, url, options),
  307. std::move(callback));
  308. }
  309. bool MoveItemToTrashWithError(const base::FilePath& path,
  310. bool delete_on_fail,
  311. std::string* error) {
  312. Microsoft::WRL::ComPtr<IFileOperation> pfo;
  313. if (FAILED(::CoCreateInstance(CLSID_FileOperation, nullptr, CLSCTX_ALL,
  314. IID_PPV_ARGS(&pfo)))) {
  315. *error = "Failed to create FileOperation instance";
  316. return false;
  317. }
  318. // Elevation prompt enabled for UAC protected files. This overrides the
  319. // SILENT, NO_UI and NOERRORUI flags.
  320. if (base::win::GetVersion() >= base::win::Version::WIN8) {
  321. // Windows 8 introduces the flag RECYCLEONDELETE and deprecates the
  322. // ALLOWUNDO in favor of ADDUNDORECORD.
  323. if (FAILED(pfo->SetOperationFlags(
  324. FOF_NO_UI | FOFX_ADDUNDORECORD | FOF_NOERRORUI | FOF_SILENT |
  325. FOFX_SHOWELEVATIONPROMPT | FOFX_RECYCLEONDELETE))) {
  326. *error = "Failed to set operation flags";
  327. return false;
  328. }
  329. } else {
  330. // For Windows 7 and Vista, RecycleOnDelete is the default behavior.
  331. if (FAILED(pfo->SetOperationFlags(FOF_NO_UI | FOF_ALLOWUNDO |
  332. FOF_NOERRORUI | FOF_SILENT |
  333. FOFX_SHOWELEVATIONPROMPT))) {
  334. *error = "Failed to set operation flags";
  335. return false;
  336. }
  337. }
  338. // Create an IShellItem from the supplied source path.
  339. Microsoft::WRL::ComPtr<IShellItem> delete_item;
  340. if (FAILED(SHCreateItemFromParsingName(
  341. path.value().c_str(), NULL,
  342. IID_PPV_ARGS(delete_item.GetAddressOf())))) {
  343. *error = "Failed to parse path";
  344. return false;
  345. }
  346. Microsoft::WRL::ComPtr<IFileOperationProgressSink> delete_sink(
  347. new DeleteFileProgressSink);
  348. if (!delete_sink) {
  349. *error = "Failed to create delete sink";
  350. return false;
  351. }
  352. BOOL pfAnyOperationsAborted;
  353. // Processes the queued command DeleteItem. This will trigger
  354. // the DeleteFileProgressSink to check for Recycle Bin.
  355. if (!SUCCEEDED(pfo->DeleteItem(delete_item.Get(), delete_sink.Get()))) {
  356. *error = "Failed to enqueue DeleteItem command";
  357. return false;
  358. }
  359. if (!SUCCEEDED(pfo->PerformOperations())) {
  360. *error = "Failed to perform delete operation";
  361. return false;
  362. }
  363. if (!SUCCEEDED(pfo->GetAnyOperationsAborted(&pfAnyOperationsAborted))) {
  364. *error = "Failed to check operation status";
  365. return false;
  366. }
  367. if (pfAnyOperationsAborted) {
  368. *error = "Operation was aborted";
  369. return false;
  370. }
  371. return true;
  372. }
  373. namespace internal {
  374. bool PlatformTrashItem(const base::FilePath& full_path, std::string* error) {
  375. return MoveItemToTrashWithError(full_path, false, error);
  376. }
  377. } // namespace internal
  378. bool GetFolderPath(int key, base::FilePath* result) {
  379. wchar_t system_buffer[MAX_PATH];
  380. switch (key) {
  381. case electron::DIR_RECENT:
  382. if (FAILED(SHGetFolderPath(NULL, CSIDL_RECENT, NULL, SHGFP_TYPE_CURRENT,
  383. system_buffer))) {
  384. return false;
  385. }
  386. *result = base::FilePath(system_buffer);
  387. break;
  388. }
  389. return true;
  390. }
  391. void Beep() {
  392. MessageBeep(MB_OK);
  393. }
  394. } // namespace platform_util