platform_util_win.cc 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  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/bind_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. base::string16 escaped_url =
  217. L"\"" + base::UTF8ToUTF16(net::EscapeExternalHandlerValue(url.spec())) +
  218. L"\"";
  219. base::string16 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. }
  226. return "";
  227. }
  228. void ShowItemInFolderOnWorkerThread(const base::FilePath& full_path) {
  229. base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
  230. base::BlockingType::MAY_BLOCK);
  231. base::win::ScopedCOMInitializer com_initializer;
  232. if (!com_initializer.Succeeded())
  233. return;
  234. base::FilePath dir = full_path.DirName().AsEndingWithSeparator();
  235. // ParseDisplayName will fail if the directory is "C:", it must be "C:\\".
  236. if (dir.empty())
  237. return;
  238. Microsoft::WRL::ComPtr<IShellFolder> desktop;
  239. HRESULT hr = SHGetDesktopFolder(desktop.GetAddressOf());
  240. if (FAILED(hr))
  241. return;
  242. base::win::ScopedCoMem<ITEMIDLIST> dir_item;
  243. hr = desktop->ParseDisplayName(NULL, NULL,
  244. const_cast<wchar_t*>(dir.value().c_str()),
  245. NULL, &dir_item, NULL);
  246. if (FAILED(hr))
  247. return;
  248. base::win::ScopedCoMem<ITEMIDLIST> file_item;
  249. hr = desktop->ParseDisplayName(
  250. NULL, NULL, const_cast<wchar_t*>(full_path.value().c_str()), NULL,
  251. &file_item, NULL);
  252. if (FAILED(hr))
  253. return;
  254. const ITEMIDLIST* highlight[] = {file_item};
  255. hr = SHOpenFolderAndSelectItems(dir_item, base::size(highlight), highlight,
  256. NULL);
  257. if (FAILED(hr)) {
  258. // On some systems, the above call mysteriously fails with "file not
  259. // found" even though the file is there. In these cases, ShellExecute()
  260. // seems to work as a fallback (although it won't select the file).
  261. if (hr == ERROR_FILE_NOT_FOUND) {
  262. ShellExecute(NULL, L"open", dir.value().c_str(), NULL, NULL, SW_SHOW);
  263. } else {
  264. LOG(WARNING) << " " << __func__ << "(): Can't open full_path = \""
  265. << full_path.value() << "\""
  266. << " hr = " << logging::SystemErrorCodeToString(hr);
  267. }
  268. }
  269. }
  270. std::string OpenPathOnThread(const base::FilePath& full_path) {
  271. // May result in an interactive dialog.
  272. base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
  273. base::BlockingType::MAY_BLOCK);
  274. bool success;
  275. if (base::DirectoryExists(full_path))
  276. success = ui::win::OpenFolderViaShell(full_path);
  277. else
  278. success = ui::win::OpenFileViaShell(full_path);
  279. return success ? "" : "Failed to open path";
  280. }
  281. } // namespace
  282. namespace platform_util {
  283. void ShowItemInFolder(const base::FilePath& full_path) {
  284. base::ThreadPool::CreateCOMSTATaskRunner(
  285. {base::MayBlock(), base::TaskPriority::USER_BLOCKING})
  286. ->PostTask(FROM_HERE,
  287. base::BindOnce(&ShowItemInFolderOnWorkerThread, full_path));
  288. }
  289. void OpenPath(const base::FilePath& full_path, OpenCallback callback) {
  290. DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
  291. base::PostTaskAndReplyWithResult(
  292. base::ThreadPool::CreateCOMSTATaskRunner(
  293. {base::MayBlock(), base::TaskPriority::USER_BLOCKING})
  294. .get(),
  295. FROM_HERE, base::BindOnce(&OpenPathOnThread, full_path),
  296. std::move(callback));
  297. }
  298. void OpenExternal(const GURL& url,
  299. const OpenExternalOptions& options,
  300. OpenCallback callback) {
  301. base::PostTaskAndReplyWithResult(
  302. base::ThreadPool::CreateCOMSTATaskRunner(
  303. {base::MayBlock(), base::TaskPriority::USER_BLOCKING})
  304. .get(),
  305. FROM_HERE, base::BindOnce(&OpenExternalOnWorkerThread, url, options),
  306. std::move(callback));
  307. }
  308. bool MoveItemToTrash(const base::FilePath& path, bool delete_on_fail) {
  309. base::win::ScopedCOMInitializer com_initializer;
  310. if (!com_initializer.Succeeded())
  311. return false;
  312. Microsoft::WRL::ComPtr<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. Microsoft::WRL::ComPtr<IShellItem> delete_item;
  334. if (FAILED(SHCreateItemFromParsingName(
  335. path.value().c_str(), NULL,
  336. IID_PPV_ARGS(delete_item.GetAddressOf()))))
  337. return false;
  338. Microsoft::WRL::ComPtr<IFileOperationProgressSink> delete_sink(
  339. new DeleteFileProgressSink);
  340. if (!delete_sink)
  341. return false;
  342. BOOL pfAnyOperationsAborted;
  343. // Processes the queued command DeleteItem. This will trigger
  344. // the DeleteFileProgressSink to check for Recycle Bin.
  345. return SUCCEEDED(pfo->DeleteItem(delete_item.Get(), delete_sink.Get())) &&
  346. SUCCEEDED(pfo->PerformOperations()) &&
  347. SUCCEEDED(pfo->GetAnyOperationsAborted(&pfAnyOperationsAborted)) &&
  348. !pfAnyOperationsAborted;
  349. }
  350. bool GetFolderPath(int key, base::FilePath* result) {
  351. wchar_t system_buffer[MAX_PATH];
  352. switch (key) {
  353. case electron::DIR_RECENT:
  354. if (FAILED(SHGetFolderPath(NULL, CSIDL_RECENT, NULL, SHGFP_TYPE_CURRENT,
  355. system_buffer))) {
  356. return false;
  357. }
  358. *result = base::FilePath(system_buffer);
  359. break;
  360. }
  361. return true;
  362. }
  363. void Beep() {
  364. MessageBeep(MB_OK);
  365. }
  366. } // namespace platform_util