platform_util_win.cc 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  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 <shellapi.h>
  11. #include <shlobj.h>
  12. #include "base/bind.h"
  13. #include "base/bind_helpers.h"
  14. #include "base/files/file_path.h"
  15. #include "base/files/file_util.h"
  16. #include "base/logging.h"
  17. #include "base/strings/string_util.h"
  18. #include "base/strings/utf_string_conversions.h"
  19. #include "base/win/registry.h"
  20. #include "base/win/scoped_co_mem.h"
  21. #include "base/win/scoped_com_initializer.h"
  22. #include "base/win/scoped_comptr.h"
  23. #include "base/win/windows_version.h"
  24. #include "ui/base/win/shell.h"
  25. #include "url/gurl.h"
  26. namespace {
  27. // Old ShellExecute crashes the process when the command for a given scheme
  28. // is empty. This function tells if it is.
  29. bool ValidateShellCommandForScheme(const std::string& scheme) {
  30. base::win::RegKey key;
  31. base::string16 registry_path = base::ASCIIToUTF16(scheme) +
  32. L"\\shell\\open\\command";
  33. key.Open(HKEY_CLASSES_ROOT, registry_path.c_str(), KEY_READ);
  34. if (!key.Valid())
  35. return false;
  36. DWORD size = 0;
  37. key.ReadValue(NULL, NULL, &size, NULL);
  38. if (size <= 2)
  39. return false;
  40. return true;
  41. }
  42. // Required COM implementation of IFileOperationProgressSink so we can
  43. // precheck files before deletion to make sure they can be move to the
  44. // Recycle Bin.
  45. class DeleteFileProgressSink : public IFileOperationProgressSink {
  46. public:
  47. DeleteFileProgressSink();
  48. private:
  49. ULONG STDMETHODCALLTYPE AddRef(void);
  50. ULONG STDMETHODCALLTYPE Release(void);
  51. HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, LPVOID* ppvObj);
  52. HRESULT STDMETHODCALLTYPE StartOperations(void);
  53. HRESULT STDMETHODCALLTYPE FinishOperations(HRESULT);
  54. HRESULT STDMETHODCALLTYPE PreRenameItem(
  55. DWORD, IShellItem*, LPCWSTR);
  56. HRESULT STDMETHODCALLTYPE PostRenameItem(
  57. DWORD, IShellItem*, LPCWSTR, HRESULT, IShellItem*);
  58. HRESULT STDMETHODCALLTYPE PreMoveItem(
  59. DWORD, IShellItem*, IShellItem*, LPCWSTR);
  60. HRESULT STDMETHODCALLTYPE PostMoveItem(
  61. DWORD, IShellItem*, IShellItem*, LPCWSTR, HRESULT, IShellItem*);
  62. HRESULT STDMETHODCALLTYPE PreCopyItem(
  63. DWORD, IShellItem*, IShellItem*, LPCWSTR);
  64. HRESULT STDMETHODCALLTYPE PostCopyItem(
  65. DWORD, IShellItem*, IShellItem*, LPCWSTR, HRESULT, IShellItem*);
  66. HRESULT STDMETHODCALLTYPE PreDeleteItem(DWORD, IShellItem*);
  67. HRESULT STDMETHODCALLTYPE PostDeleteItem(
  68. DWORD, IShellItem*, HRESULT, IShellItem*);
  69. HRESULT STDMETHODCALLTYPE PreNewItem(
  70. DWORD, IShellItem*, LPCWSTR);
  71. HRESULT STDMETHODCALLTYPE PostNewItem(
  72. DWORD, IShellItem*, LPCWSTR, LPCWSTR, DWORD, HRESULT, IShellItem*);
  73. HRESULT STDMETHODCALLTYPE UpdateProgress(UINT, UINT);
  74. HRESULT STDMETHODCALLTYPE ResetTimer(void);
  75. HRESULT STDMETHODCALLTYPE PauseTimer(void);
  76. HRESULT STDMETHODCALLTYPE ResumeTimer(void);
  77. ULONG m_cRef;
  78. };
  79. DeleteFileProgressSink::DeleteFileProgressSink() {
  80. m_cRef = 0;
  81. }
  82. HRESULT DeleteFileProgressSink::PreDeleteItem(DWORD dwFlags, IShellItem*) {
  83. if (!(dwFlags & TSF_DELETE_RECYCLE_IF_POSSIBLE)) {
  84. // TSF_DELETE_RECYCLE_IF_POSSIBLE will not be set for items that cannot be
  85. // recycled. In this case, we abort the delete operation. This bubbles
  86. // up and stops the Delete in IFileOperation.
  87. return E_ABORT;
  88. }
  89. // Returns S_OK if successful, or an error value otherwise. In the case of an
  90. // error value, the delete operation and all subsequent operations pending
  91. // from the call to IFileOperation are canceled.
  92. return S_OK;
  93. }
  94. HRESULT DeleteFileProgressSink::QueryInterface(REFIID riid, LPVOID* ppvObj) {
  95. // Always set out parameter to NULL, validating it first.
  96. if (!ppvObj)
  97. return E_INVALIDARG;
  98. *ppvObj = nullptr;
  99. if (riid == IID_IUnknown || riid == IID_IFileOperationProgressSink) {
  100. // Increment the reference count and return the pointer.
  101. *ppvObj = reinterpret_cast<IUnknown*>(this);
  102. AddRef();
  103. return NOERROR;
  104. }
  105. return E_NOINTERFACE;
  106. }
  107. ULONG DeleteFileProgressSink::AddRef() {
  108. InterlockedIncrement(&m_cRef);
  109. return m_cRef;
  110. }
  111. ULONG DeleteFileProgressSink::Release() {
  112. // Decrement the object's internal counter.
  113. ULONG ulRefCount = InterlockedDecrement(&m_cRef);
  114. if (0 == m_cRef) {
  115. delete this;
  116. }
  117. return ulRefCount;
  118. }
  119. HRESULT DeleteFileProgressSink::StartOperations() {
  120. return S_OK;
  121. }
  122. HRESULT DeleteFileProgressSink::FinishOperations(HRESULT) {
  123. return S_OK;
  124. }
  125. HRESULT DeleteFileProgressSink::PreRenameItem(DWORD, IShellItem*, LPCWSTR) {
  126. return S_OK;
  127. }
  128. HRESULT DeleteFileProgressSink::PostRenameItem(
  129. DWORD, IShellItem*, __RPC__in_string LPCWSTR, HRESULT, IShellItem*) {
  130. return E_NOTIMPL;
  131. }
  132. HRESULT DeleteFileProgressSink::PreMoveItem(
  133. DWORD, IShellItem*, IShellItem*, LPCWSTR) {
  134. return E_NOTIMPL;
  135. }
  136. HRESULT DeleteFileProgressSink::PostMoveItem(
  137. DWORD, IShellItem*, IShellItem*, LPCWSTR, HRESULT, IShellItem*) {
  138. return E_NOTIMPL;
  139. }
  140. HRESULT DeleteFileProgressSink::PreCopyItem(
  141. DWORD, IShellItem*, IShellItem*, LPCWSTR) {
  142. return E_NOTIMPL;
  143. }
  144. HRESULT DeleteFileProgressSink::PostCopyItem(
  145. DWORD, IShellItem*, IShellItem*, LPCWSTR, HRESULT, IShellItem*) {
  146. return E_NOTIMPL;
  147. }
  148. HRESULT DeleteFileProgressSink::PostDeleteItem(
  149. DWORD, IShellItem*, HRESULT, IShellItem*) {
  150. return S_OK;
  151. }
  152. HRESULT DeleteFileProgressSink::PreNewItem(
  153. DWORD dwFlags, IShellItem*, LPCWSTR) {
  154. return E_NOTIMPL;
  155. }
  156. HRESULT DeleteFileProgressSink::PostNewItem(
  157. DWORD, IShellItem*, LPCWSTR, LPCWSTR, DWORD, HRESULT, IShellItem*) {
  158. return E_NOTIMPL;
  159. }
  160. HRESULT DeleteFileProgressSink::UpdateProgress(UINT, UINT) {
  161. return S_OK;
  162. }
  163. HRESULT DeleteFileProgressSink::ResetTimer() {
  164. return S_OK;
  165. }
  166. HRESULT DeleteFileProgressSink::PauseTimer() {
  167. return S_OK;
  168. }
  169. HRESULT DeleteFileProgressSink::ResumeTimer() {
  170. return S_OK;
  171. }
  172. } // namespace
  173. namespace platform_util {
  174. bool ShowItemInFolder(const base::FilePath& full_path) {
  175. base::win::ScopedCOMInitializer com_initializer;
  176. if (!com_initializer.succeeded())
  177. return false;
  178. base::FilePath dir = full_path.DirName().AsEndingWithSeparator();
  179. // ParseDisplayName will fail if the directory is "C:", it must be "C:\\".
  180. if (dir.empty())
  181. return false;
  182. typedef HRESULT (WINAPI *SHOpenFolderAndSelectItemsFuncPtr)(
  183. PCIDLIST_ABSOLUTE pidl_Folder,
  184. UINT cidl,
  185. PCUITEMID_CHILD_ARRAY pidls,
  186. DWORD flags);
  187. static SHOpenFolderAndSelectItemsFuncPtr open_folder_and_select_itemsPtr =
  188. NULL;
  189. static bool initialize_open_folder_proc = true;
  190. if (initialize_open_folder_proc) {
  191. initialize_open_folder_proc = false;
  192. // The SHOpenFolderAndSelectItems API is exposed by shell32 version 6
  193. // and does not exist in Win2K. We attempt to retrieve this function export
  194. // from shell32 and if it does not exist, we just invoke ShellExecute to
  195. // open the folder thus losing the functionality to select the item in
  196. // the process.
  197. HMODULE shell32_base = GetModuleHandle(L"shell32.dll");
  198. if (!shell32_base) {
  199. NOTREACHED() << " " << __FUNCTION__ << "(): Can't open shell32.dll";
  200. return false;
  201. }
  202. open_folder_and_select_itemsPtr =
  203. reinterpret_cast<SHOpenFolderAndSelectItemsFuncPtr>
  204. (GetProcAddress(shell32_base, "SHOpenFolderAndSelectItems"));
  205. }
  206. if (!open_folder_and_select_itemsPtr) {
  207. return ui::win::OpenFolderViaShell(dir);
  208. }
  209. base::win::ScopedComPtr<IShellFolder> desktop;
  210. HRESULT hr = SHGetDesktopFolder(desktop.Receive());
  211. if (FAILED(hr))
  212. return false;
  213. base::win::ScopedCoMem<ITEMIDLIST> dir_item;
  214. hr = desktop->ParseDisplayName(NULL, NULL,
  215. const_cast<wchar_t *>(dir.value().c_str()),
  216. NULL, &dir_item, NULL);
  217. if (FAILED(hr)) {
  218. return ui::win::OpenFolderViaShell(dir);
  219. }
  220. base::win::ScopedCoMem<ITEMIDLIST> file_item;
  221. hr = desktop->ParseDisplayName(NULL, NULL,
  222. const_cast<wchar_t *>(full_path.value().c_str()),
  223. NULL, &file_item, NULL);
  224. if (FAILED(hr)) {
  225. return ui::win::OpenFolderViaShell(dir);
  226. }
  227. const ITEMIDLIST* highlight[] = { file_item };
  228. hr = (*open_folder_and_select_itemsPtr)(dir_item, arraysize(highlight),
  229. highlight, NULL);
  230. if (!FAILED(hr))
  231. return true;
  232. // On some systems, the above call mysteriously fails with "file not
  233. // found" even though the file is there. In these cases, ShellExecute()
  234. // seems to work as a fallback (although it won't select the file).
  235. if (hr == ERROR_FILE_NOT_FOUND) {
  236. return ui::win::OpenFolderViaShell(dir);
  237. } else {
  238. LPTSTR message = NULL;
  239. DWORD message_length = FormatMessage(
  240. FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
  241. 0, hr, 0, reinterpret_cast<LPTSTR>(&message), 0, NULL);
  242. LOG(WARNING) << " " << __FUNCTION__
  243. << "(): Can't open full_path = \""
  244. << full_path.value() << "\""
  245. << " hr = " << hr
  246. << " " << reinterpret_cast<LPTSTR>(&message);
  247. if (message)
  248. LocalFree(message);
  249. return ui::win::OpenFolderViaShell(dir);
  250. }
  251. }
  252. bool OpenItem(const base::FilePath& full_path) {
  253. if (base::DirectoryExists(full_path))
  254. return ui::win::OpenFolderViaShell(full_path);
  255. else
  256. return ui::win::OpenFileViaShell(full_path);
  257. }
  258. bool OpenExternal(const base::string16& url, bool activate) {
  259. // Quote the input scheme to be sure that the command does not have
  260. // parameters unexpected by the external program. This url should already
  261. // have been escaped.
  262. base::string16 escaped_url = L"\"" + url + L"\"";
  263. if (reinterpret_cast<ULONG_PTR>(ShellExecuteW(NULL, L"open",
  264. escaped_url.c_str(), NULL, NULL,
  265. SW_SHOWNORMAL)) <= 32) {
  266. // We fail to execute the call. We could display a message to the user.
  267. // TODO(nsylvain): we should also add a dialog to warn on errors. See
  268. // bug 1136923.
  269. return false;
  270. }
  271. return true;
  272. }
  273. bool MoveItemToTrash(const base::FilePath& path) {
  274. base::win::ScopedCOMInitializer com_initializer;
  275. if (!com_initializer.succeeded())
  276. return false;
  277. base::win::ScopedComPtr<IFileOperation> pfo;
  278. if (FAILED(pfo.CreateInstance(CLSID_FileOperation)))
  279. return false;
  280. // Elevation prompt enabled for UAC protected files. This overrides the
  281. // SILENT, NO_UI and NOERRORUI flags.
  282. if (base::win::GetVersion() >= base::win::VERSION_WIN8) {
  283. // Windows 8 introduces the flag RECYCLEONDELETE and deprecates the
  284. // ALLOWUNDO in favor of ADDUNDORECORD.
  285. if (FAILED(pfo->SetOperationFlags(FOF_NO_UI |
  286. FOFX_ADDUNDORECORD |
  287. FOF_NOERRORUI |
  288. FOF_SILENT |
  289. FOFX_SHOWELEVATIONPROMPT |
  290. FOFX_RECYCLEONDELETE)))
  291. return false;
  292. } else {
  293. // For Windows 7 and Vista, RecycleOnDelete is the default behavior.
  294. if (FAILED(pfo->SetOperationFlags(FOF_NO_UI |
  295. FOF_ALLOWUNDO |
  296. FOF_NOERRORUI |
  297. FOF_SILENT |
  298. FOFX_SHOWELEVATIONPROMPT)))
  299. return false;
  300. }
  301. // Create an IShellItem from the supplied source path.
  302. base::win::ScopedComPtr<IShellItem> delete_item;
  303. if (FAILED(SHCreateItemFromParsingName(path.value().c_str(),
  304. NULL,
  305. IID_PPV_ARGS(delete_item.Receive()))))
  306. return false;
  307. base::win::ScopedComPtr<IFileOperationProgressSink> delete_sink(
  308. new DeleteFileProgressSink);
  309. if (!delete_sink)
  310. return false;
  311. // Processes the queued command DeleteItem. This will trigger
  312. // the DeleteFileProgressSink to check for Recycle Bin.
  313. return SUCCEEDED(pfo->DeleteItem(delete_item.get(), delete_sink.get())) &&
  314. SUCCEEDED(pfo->PerformOperations());
  315. }
  316. void Beep() {
  317. MessageBeep(MB_OK);
  318. }
  319. } // namespace platform_util