platform_util_win.cc 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  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/stl_util.h"
  21. #include "base/strings/escape.h"
  22. #include "base/strings/string_util.h"
  23. #include "base/strings/utf_string_conversions.h"
  24. #include "base/task/thread_pool.h"
  25. #include "base/threading/scoped_blocking_call.h"
  26. #include "base/win/registry.h"
  27. #include "base/win/scoped_co_mem.h"
  28. #include "base/win/scoped_com_initializer.h"
  29. #include "base/win/windows_version.h"
  30. #include "content/public/browser/browser_task_traits.h"
  31. #include "content/public/browser/browser_thread.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 nullptr, 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(base::EscapeExternalHandlerValue(url.spec())) +
  218. L"\"";
  219. std::wstring working_dir = options.working_dir.value();
  220. SHELLEXECUTEINFO info = {};
  221. info.cbSize = sizeof(SHELLEXECUTEINFO);
  222. info.fMask = SEE_MASK_NOASYNC | SEE_MASK_FLAG_NO_UI;
  223. info.lpVerb = L"open";
  224. info.lpFile = escaped_url.c_str();
  225. info.lpDirectory = working_dir.empty() ? nullptr : working_dir.c_str();
  226. info.nShow = SW_SHOWNORMAL;
  227. if (options.log_usage) {
  228. info.fMask |= SEE_MASK_FLAG_LOG_USAGE;
  229. }
  230. if (!ShellExecuteEx(&info)) {
  231. return "Failed to open: " +
  232. logging::SystemErrorCodeToString(logging::GetLastSystemErrorCode());
  233. }
  234. return "";
  235. }
  236. void ShowItemInFolderOnWorkerThread(const base::FilePath& full_path) {
  237. base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
  238. base::BlockingType::MAY_BLOCK);
  239. base::win::ScopedCOMInitializer com_initializer;
  240. if (!com_initializer.Succeeded())
  241. return;
  242. base::FilePath dir = full_path.DirName().AsEndingWithSeparator();
  243. // ParseDisplayName will fail if the directory is "C:", it must be "C:\\".
  244. if (dir.empty())
  245. return;
  246. Microsoft::WRL::ComPtr<IShellFolder> desktop;
  247. HRESULT hr = SHGetDesktopFolder(&desktop);
  248. if (FAILED(hr))
  249. return;
  250. base::win::ScopedCoMem<ITEMIDLIST> dir_item;
  251. hr = desktop->ParseDisplayName(nullptr, nullptr,
  252. const_cast<wchar_t*>(dir.value().c_str()),
  253. nullptr, &dir_item, nullptr);
  254. if (FAILED(hr))
  255. return;
  256. base::win::ScopedCoMem<ITEMIDLIST> file_item;
  257. hr = desktop->ParseDisplayName(
  258. nullptr, nullptr, const_cast<wchar_t*>(full_path.value().c_str()),
  259. nullptr, &file_item, nullptr);
  260. if (FAILED(hr))
  261. return;
  262. const ITEMIDLIST* highlight[] = {file_item};
  263. hr = SHOpenFolderAndSelectItems(dir_item, std::size(highlight), highlight, 0);
  264. if (FAILED(hr)) {
  265. // On some systems, the above call mysteriously fails with "file not
  266. // found" even though the file is there. In these cases, ShellExecute()
  267. // seems to work as a fallback (although it won't select the file).
  268. if (hr == ERROR_FILE_NOT_FOUND) {
  269. ShellExecute(nullptr, L"open", dir.value().c_str(), nullptr, nullptr,
  270. SW_SHOW);
  271. } else {
  272. LOG(WARNING) << " " << __func__ << "(): Can't open full_path = \""
  273. << full_path.value() << "\""
  274. << " hr = " << logging::SystemErrorCodeToString(hr);
  275. }
  276. }
  277. }
  278. std::string OpenPathOnThread(const base::FilePath& full_path) {
  279. // May result in an interactive dialog.
  280. base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
  281. base::BlockingType::MAY_BLOCK);
  282. bool success;
  283. if (base::DirectoryExists(full_path))
  284. success = ui::win::OpenFolderViaShell(full_path);
  285. else
  286. success = ui::win::OpenFileViaShell(full_path);
  287. return success ? "" : "Failed to open path";
  288. }
  289. } // namespace
  290. namespace platform_util {
  291. void ShowItemInFolder(const base::FilePath& full_path) {
  292. base::ThreadPool::CreateCOMSTATaskRunner(
  293. {base::MayBlock(), base::TaskPriority::USER_BLOCKING})
  294. ->PostTask(FROM_HERE,
  295. base::BindOnce(&ShowItemInFolderOnWorkerThread, full_path));
  296. }
  297. void OpenPath(const base::FilePath& full_path, OpenCallback callback) {
  298. DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
  299. base::ThreadPool::CreateCOMSTATaskRunner(
  300. {base::MayBlock(), base::TaskPriority::USER_BLOCKING})
  301. ->PostTaskAndReplyWithResult(FROM_HERE,
  302. base::BindOnce(&OpenPathOnThread, full_path),
  303. std::move(callback));
  304. }
  305. void OpenExternal(const GURL& url,
  306. const OpenExternalOptions& options,
  307. OpenCallback callback) {
  308. base::ThreadPool::CreateCOMSTATaskRunner(
  309. {base::MayBlock(), base::TaskPriority::USER_BLOCKING})
  310. ->PostTaskAndReplyWithResult(
  311. FROM_HERE, base::BindOnce(&OpenExternalOnWorkerThread, url, options),
  312. std::move(callback));
  313. }
  314. bool MoveItemToTrashWithError(const base::FilePath& path,
  315. bool delete_on_fail,
  316. std::string* error) {
  317. Microsoft::WRL::ComPtr<IFileOperation> pfo;
  318. if (FAILED(::CoCreateInstance(CLSID_FileOperation, nullptr, CLSCTX_ALL,
  319. IID_PPV_ARGS(&pfo)))) {
  320. *error = "Failed to create FileOperation instance";
  321. return false;
  322. }
  323. // Elevation prompt enabled for UAC protected files. This overrides the
  324. // SILENT, NO_UI and NOERRORUI flags.
  325. if (FAILED(pfo->SetOperationFlags(
  326. FOF_NO_UI | FOFX_ADDUNDORECORD | FOF_NOERRORUI | FOF_SILENT |
  327. FOFX_SHOWELEVATIONPROMPT | FOFX_RECYCLEONDELETE))) {
  328. *error = "Failed to set operation flags";
  329. return false;
  330. }
  331. // Create an IShellItem from the supplied source path.
  332. Microsoft::WRL::ComPtr<IShellItem> delete_item;
  333. if (FAILED(SHCreateItemFromParsingName(path.value().c_str(), nullptr,
  334. IID_PPV_ARGS(&delete_item)))) {
  335. *error = "Failed to parse path";
  336. return false;
  337. }
  338. Microsoft::WRL::ComPtr<IFileOperationProgressSink> delete_sink(
  339. new DeleteFileProgressSink);
  340. if (!delete_sink) {
  341. *error = "Failed to create delete sink";
  342. return false;
  343. }
  344. BOOL pfAnyOperationsAborted;
  345. // Processes the queued command DeleteItem. This will trigger
  346. // the DeleteFileProgressSink to check for Recycle Bin.
  347. if (!SUCCEEDED(pfo->DeleteItem(delete_item.Get(), delete_sink.Get()))) {
  348. *error = "Failed to enqueue DeleteItem command";
  349. return false;
  350. }
  351. if (!SUCCEEDED(pfo->PerformOperations())) {
  352. *error = "Failed to perform delete operation";
  353. return false;
  354. }
  355. if (!SUCCEEDED(pfo->GetAnyOperationsAborted(&pfAnyOperationsAborted))) {
  356. *error = "Failed to check operation status";
  357. return false;
  358. }
  359. if (pfAnyOperationsAborted) {
  360. *error = "Operation was aborted";
  361. return false;
  362. }
  363. return true;
  364. }
  365. namespace internal {
  366. bool PlatformTrashItem(const base::FilePath& full_path, std::string* error) {
  367. return MoveItemToTrashWithError(full_path, false, error);
  368. }
  369. } // namespace internal
  370. bool GetFolderPath(int key, base::FilePath* result) {
  371. wchar_t system_buffer[MAX_PATH];
  372. switch (key) {
  373. case electron::DIR_RECENT:
  374. if (FAILED(SHGetFolderPath(nullptr, CSIDL_RECENT, nullptr,
  375. SHGFP_TYPE_CURRENT, system_buffer))) {
  376. return false;
  377. }
  378. *result = base::FilePath(system_buffer);
  379. break;
  380. }
  381. return true;
  382. }
  383. void Beep() {
  384. MessageBeep(MB_OK);
  385. }
  386. } // namespace platform_util