platform_util_win.cc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  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 "atom/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/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 "base/win/windows_version.h"
  28. #include "content/public/browser/browser_task_traits.h"
  29. #include "ui/base/win/shell.h"
  30. #include "url/gurl.h"
  31. namespace {
  32. // Required COM implementation of IFileOperationProgressSink so we can
  33. // precheck files before deletion to make sure they can be move to the
  34. // Recycle Bin.
  35. class DeleteFileProgressSink : public IFileOperationProgressSink {
  36. public:
  37. DeleteFileProgressSink();
  38. virtual ~DeleteFileProgressSink() = default;
  39. private:
  40. ULONG STDMETHODCALLTYPE AddRef(void) override;
  41. ULONG STDMETHODCALLTYPE Release(void) override;
  42. HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid,
  43. LPVOID* ppvObj) override;
  44. HRESULT STDMETHODCALLTYPE StartOperations(void) override;
  45. HRESULT STDMETHODCALLTYPE FinishOperations(HRESULT) override;
  46. HRESULT STDMETHODCALLTYPE PreRenameItem(DWORD, IShellItem*, LPCWSTR) override;
  47. HRESULT STDMETHODCALLTYPE
  48. PostRenameItem(DWORD, IShellItem*, LPCWSTR, HRESULT, IShellItem*) override;
  49. HRESULT STDMETHODCALLTYPE PreMoveItem(DWORD,
  50. IShellItem*,
  51. IShellItem*,
  52. LPCWSTR) override;
  53. HRESULT STDMETHODCALLTYPE PostMoveItem(DWORD,
  54. IShellItem*,
  55. IShellItem*,
  56. LPCWSTR,
  57. HRESULT,
  58. IShellItem*) override;
  59. HRESULT STDMETHODCALLTYPE PreCopyItem(DWORD,
  60. IShellItem*,
  61. IShellItem*,
  62. LPCWSTR) override;
  63. HRESULT STDMETHODCALLTYPE PostCopyItem(DWORD,
  64. IShellItem*,
  65. IShellItem*,
  66. LPCWSTR,
  67. HRESULT,
  68. IShellItem*) override;
  69. HRESULT STDMETHODCALLTYPE PreDeleteItem(DWORD, IShellItem*) override;
  70. HRESULT STDMETHODCALLTYPE PostDeleteItem(DWORD,
  71. IShellItem*,
  72. HRESULT,
  73. IShellItem*) override;
  74. HRESULT STDMETHODCALLTYPE PreNewItem(DWORD, IShellItem*, LPCWSTR) override;
  75. HRESULT STDMETHODCALLTYPE PostNewItem(DWORD,
  76. IShellItem*,
  77. LPCWSTR,
  78. LPCWSTR,
  79. DWORD,
  80. HRESULT,
  81. IShellItem*) override;
  82. HRESULT STDMETHODCALLTYPE UpdateProgress(UINT, UINT) override;
  83. HRESULT STDMETHODCALLTYPE ResetTimer(void) override;
  84. HRESULT STDMETHODCALLTYPE PauseTimer(void) override;
  85. HRESULT STDMETHODCALLTYPE ResumeTimer(void) override;
  86. ULONG m_cRef;
  87. };
  88. DeleteFileProgressSink::DeleteFileProgressSink() {
  89. m_cRef = 0;
  90. }
  91. HRESULT DeleteFileProgressSink::PreDeleteItem(DWORD dwFlags, IShellItem*) {
  92. if (!(dwFlags & TSF_DELETE_RECYCLE_IF_POSSIBLE)) {
  93. // TSF_DELETE_RECYCLE_IF_POSSIBLE will not be set for items that cannot be
  94. // recycled. In this case, we abort the delete operation. This bubbles
  95. // up and stops the Delete in IFileOperation.
  96. return E_ABORT;
  97. }
  98. // Returns S_OK if successful, or an error value otherwise. In the case of an
  99. // error value, the delete operation and all subsequent operations pending
  100. // from the call to IFileOperation are canceled.
  101. return S_OK;
  102. }
  103. HRESULT DeleteFileProgressSink::QueryInterface(REFIID riid, LPVOID* ppvObj) {
  104. // Always set out parameter to NULL, validating it first.
  105. if (!ppvObj)
  106. return E_INVALIDARG;
  107. *ppvObj = nullptr;
  108. if (riid == IID_IUnknown || riid == IID_IFileOperationProgressSink) {
  109. // Increment the reference count and return the pointer.
  110. *ppvObj = reinterpret_cast<IUnknown*>(this);
  111. AddRef();
  112. return NOERROR;
  113. }
  114. return E_NOINTERFACE;
  115. }
  116. ULONG DeleteFileProgressSink::AddRef() {
  117. InterlockedIncrement(&m_cRef);
  118. return m_cRef;
  119. }
  120. ULONG DeleteFileProgressSink::Release() {
  121. // Decrement the object's internal counter.
  122. ULONG ulRefCount = InterlockedDecrement(&m_cRef);
  123. if (0 == m_cRef) {
  124. delete this;
  125. }
  126. return ulRefCount;
  127. }
  128. HRESULT DeleteFileProgressSink::StartOperations() {
  129. return S_OK;
  130. }
  131. HRESULT DeleteFileProgressSink::FinishOperations(HRESULT) {
  132. return S_OK;
  133. }
  134. HRESULT DeleteFileProgressSink::PreRenameItem(DWORD, IShellItem*, LPCWSTR) {
  135. return S_OK;
  136. }
  137. HRESULT DeleteFileProgressSink::PostRenameItem(DWORD,
  138. IShellItem*,
  139. __RPC__in_string LPCWSTR,
  140. HRESULT,
  141. IShellItem*) {
  142. return E_NOTIMPL;
  143. }
  144. HRESULT DeleteFileProgressSink::PreMoveItem(DWORD,
  145. IShellItem*,
  146. IShellItem*,
  147. LPCWSTR) {
  148. return E_NOTIMPL;
  149. }
  150. HRESULT DeleteFileProgressSink::PostMoveItem(DWORD,
  151. IShellItem*,
  152. IShellItem*,
  153. LPCWSTR,
  154. HRESULT,
  155. IShellItem*) {
  156. return E_NOTIMPL;
  157. }
  158. HRESULT DeleteFileProgressSink::PreCopyItem(DWORD,
  159. IShellItem*,
  160. IShellItem*,
  161. LPCWSTR) {
  162. return E_NOTIMPL;
  163. }
  164. HRESULT DeleteFileProgressSink::PostCopyItem(DWORD,
  165. IShellItem*,
  166. IShellItem*,
  167. LPCWSTR,
  168. HRESULT,
  169. IShellItem*) {
  170. return E_NOTIMPL;
  171. }
  172. HRESULT DeleteFileProgressSink::PostDeleteItem(DWORD,
  173. IShellItem*,
  174. HRESULT,
  175. IShellItem*) {
  176. return S_OK;
  177. }
  178. HRESULT DeleteFileProgressSink::PreNewItem(DWORD dwFlags,
  179. IShellItem*,
  180. LPCWSTR) {
  181. return E_NOTIMPL;
  182. }
  183. HRESULT DeleteFileProgressSink::PostNewItem(DWORD,
  184. IShellItem*,
  185. LPCWSTR,
  186. LPCWSTR,
  187. DWORD,
  188. HRESULT,
  189. IShellItem*) {
  190. return E_NOTIMPL;
  191. }
  192. HRESULT DeleteFileProgressSink::UpdateProgress(UINT, UINT) {
  193. return S_OK;
  194. }
  195. HRESULT DeleteFileProgressSink::ResetTimer() {
  196. return S_OK;
  197. }
  198. HRESULT DeleteFileProgressSink::PauseTimer() {
  199. return S_OK;
  200. }
  201. HRESULT DeleteFileProgressSink::ResumeTimer() {
  202. return S_OK;
  203. }
  204. void ShowItemInFolderOnWorkerThread(const base::FilePath& full_path) {
  205. base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
  206. base::BlockingType::MAY_BLOCK);
  207. base::win::ScopedCOMInitializer com_initializer;
  208. if (!com_initializer.Succeeded())
  209. return;
  210. base::FilePath dir = full_path.DirName().AsEndingWithSeparator();
  211. // ParseDisplayName will fail if the directory is "C:", it must be "C:\\".
  212. if (dir.empty())
  213. return;
  214. Microsoft::WRL::ComPtr<IShellFolder> desktop;
  215. HRESULT hr = SHGetDesktopFolder(desktop.GetAddressOf());
  216. if (FAILED(hr))
  217. return;
  218. base::win::ScopedCoMem<ITEMIDLIST> dir_item;
  219. hr = desktop->ParseDisplayName(NULL, NULL,
  220. const_cast<wchar_t*>(dir.value().c_str()),
  221. NULL, &dir_item, NULL);
  222. if (FAILED(hr)) {
  223. ui::win::OpenFolderViaShell(dir);
  224. return;
  225. }
  226. base::win::ScopedCoMem<ITEMIDLIST> file_item;
  227. hr = desktop->ParseDisplayName(
  228. NULL, NULL, const_cast<wchar_t*>(full_path.value().c_str()), NULL,
  229. &file_item, NULL);
  230. if (FAILED(hr)) {
  231. ui::win::OpenFolderViaShell(dir);
  232. return;
  233. }
  234. const ITEMIDLIST* highlight[] = {file_item};
  235. hr = SHOpenFolderAndSelectItems(dir_item, base::size(highlight), highlight,
  236. NULL);
  237. if (FAILED(hr)) {
  238. // On some systems, the above call mysteriously fails with "file not
  239. // found" even though the file is there. In these cases, ShellExecute()
  240. // seems to work as a fallback (although it won't select the file).
  241. if (hr == ERROR_FILE_NOT_FOUND) {
  242. ShellExecute(NULL, L"open", dir.value().c_str(), NULL, NULL, SW_SHOW);
  243. } else {
  244. LOG(WARNING) << " " << __func__ << "(): Can't open full_path = \""
  245. << full_path.value() << "\""
  246. << " hr = " << logging::SystemErrorCodeToString(hr);
  247. ui::win::OpenFolderViaShell(dir);
  248. }
  249. }
  250. }
  251. } // namespace
  252. namespace platform_util {
  253. void ShowItemInFolder(const base::FilePath& full_path) {
  254. base::CreateCOMSTATaskRunnerWithTraits(
  255. {base::MayBlock(), base::TaskPriority::USER_BLOCKING})
  256. ->PostTask(FROM_HERE,
  257. base::BindOnce(&ShowItemInFolderOnWorkerThread, full_path));
  258. }
  259. bool OpenItem(const base::FilePath& full_path) {
  260. if (base::DirectoryExists(full_path))
  261. return ui::win::OpenFolderViaShell(full_path);
  262. else
  263. return ui::win::OpenFileViaShell(full_path);
  264. }
  265. bool OpenExternal(const base::string16& url,
  266. const OpenExternalOptions& options) {
  267. // Quote the input scheme to be sure that the command does not have
  268. // parameters unexpected by the external program. This url should already
  269. // have been escaped.
  270. base::string16 escaped_url = L"\"" + url + L"\"";
  271. auto working_dir = options.working_dir.value();
  272. if (reinterpret_cast<ULONG_PTR>(
  273. ShellExecuteW(nullptr, L"open", escaped_url.c_str(), nullptr,
  274. working_dir.empty() ? nullptr : working_dir.c_str(),
  275. SW_SHOWNORMAL)) <= 32) {
  276. // We fail to execute the call. We could display a message to the user.
  277. // TODO(nsylvain): we should also add a dialog to warn on errors. See
  278. // bug 1136923.
  279. return false;
  280. }
  281. return true;
  282. }
  283. void OpenExternal(const base::string16& url,
  284. const OpenExternalOptions& options,
  285. OpenExternalCallback callback) {
  286. // TODO(gabriel): Implement async open if callback is specified
  287. std::move(callback).Run(OpenExternal(url, options) ? "" : "Failed to open");
  288. }
  289. bool MoveItemToTrash(const base::FilePath& path) {
  290. base::win::ScopedCOMInitializer com_initializer;
  291. if (!com_initializer.Succeeded())
  292. return false;
  293. Microsoft::WRL::ComPtr<IFileOperation> pfo;
  294. if (FAILED(::CoCreateInstance(CLSID_FileOperation, nullptr, CLSCTX_ALL,
  295. IID_PPV_ARGS(&pfo))))
  296. return false;
  297. // Elevation prompt enabled for UAC protected files. This overrides the
  298. // SILENT, NO_UI and NOERRORUI flags.
  299. if (base::win::GetVersion() >= base::win::Version::WIN8) {
  300. // Windows 8 introduces the flag RECYCLEONDELETE and deprecates the
  301. // ALLOWUNDO in favor of ADDUNDORECORD.
  302. if (FAILED(pfo->SetOperationFlags(
  303. FOF_NO_UI | FOFX_ADDUNDORECORD | FOF_NOERRORUI | FOF_SILENT |
  304. FOFX_SHOWELEVATIONPROMPT | FOFX_RECYCLEONDELETE)))
  305. return false;
  306. } else {
  307. // For Windows 7 and Vista, RecycleOnDelete is the default behavior.
  308. if (FAILED(pfo->SetOperationFlags(FOF_NO_UI | FOF_ALLOWUNDO |
  309. FOF_NOERRORUI | FOF_SILENT |
  310. FOFX_SHOWELEVATIONPROMPT)))
  311. return false;
  312. }
  313. // Create an IShellItem from the supplied source path.
  314. Microsoft::WRL::ComPtr<IShellItem> delete_item;
  315. if (FAILED(SHCreateItemFromParsingName(
  316. path.value().c_str(), NULL,
  317. IID_PPV_ARGS(delete_item.GetAddressOf()))))
  318. return false;
  319. Microsoft::WRL::ComPtr<IFileOperationProgressSink> delete_sink(
  320. new DeleteFileProgressSink);
  321. if (!delete_sink)
  322. return false;
  323. // Processes the queued command DeleteItem. This will trigger
  324. // the DeleteFileProgressSink to check for Recycle Bin.
  325. return SUCCEEDED(pfo->DeleteItem(delete_item.Get(), delete_sink.Get())) &&
  326. SUCCEEDED(pfo->PerformOperations());
  327. }
  328. void Beep() {
  329. MessageBeep(MB_OK);
  330. }
  331. } // namespace platform_util