platform_util_win.cc 15 KB

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