platform_util_win.cc 15 KB

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