Upstream version 5.34.92.0
[platform/framework/web/crosswalk.git] / src / xwalk / runtime / browser / runtime_platform_util_win.cc
1 // Copyright (c) 2011 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "xwalk/runtime/browser/runtime_platform_util.h"
6
7 #include <commdlg.h>
8 #include <dwmapi.h>
9 #include <shellapi.h>
10 #include <shlobj.h>
11
12 #include "base/bind.h"
13 #include "base/bind_helpers.h"
14 #include "base/file_util.h"
15 #include "base/files/file_path.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_comptr.h"
22 #include "base/win/windows_version.h"
23 #include "content/public/browser/browser_thread.h"
24 #include "ui/base/win/shell.h"
25 #include "ui/gfx/native_widget_types.h"
26 #include "url/gurl.h"
27
28 using content::BrowserThread;
29
30 namespace {
31
32 void ShowItemInFolderOnFileThread(const base::FilePath& full_path) {
33   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
34   base::FilePath dir = full_path.DirName().AsEndingWithSeparator();
35   // ParseDisplayName will fail if the directory is "C:", it must be "C:\\".
36   if (dir.empty())
37     return;
38
39   typedef HRESULT (WINAPI *SHOpenFolderAndSelectItemsFuncPtr)(
40       PCIDLIST_ABSOLUTE pidl_Folder,
41       UINT cidl,
42       PCUITEMID_CHILD_ARRAY pidls,
43       DWORD flags);
44
45   static SHOpenFolderAndSelectItemsFuncPtr open_folder_and_select_itemsPtr =
46     NULL;
47   static bool initialize_open_folder_proc = true;
48   if (initialize_open_folder_proc) {
49     initialize_open_folder_proc = false;
50     // The SHOpenFolderAndSelectItems API is exposed by shell32 version 6
51     // and does not exist in Win2K. We attempt to retrieve this function export
52     // from shell32 and if it does not exist, we just invoke ShellExecute to
53     // open the folder thus losing the functionality to select the item in
54     // the process.
55     HMODULE shell32_base = GetModuleHandle(L"shell32.dll");
56     if (!shell32_base) {
57       NOTREACHED() << " " << __FUNCTION__ << "(): Can't open shell32.dll";
58       return;
59     }
60     open_folder_and_select_itemsPtr =
61         reinterpret_cast<SHOpenFolderAndSelectItemsFuncPtr>
62             (GetProcAddress(shell32_base, "SHOpenFolderAndSelectItems"));
63   }
64   if (!open_folder_and_select_itemsPtr) {
65     ShellExecute(NULL, L"open", dir.value().c_str(), NULL, NULL, SW_SHOW);
66     return;
67   }
68
69   base::win::ScopedComPtr<IShellFolder> desktop;
70   HRESULT hr = SHGetDesktopFolder(desktop.Receive());
71   if (FAILED(hr))
72     return;
73
74   base::win::ScopedCoMem<ITEMIDLIST> dir_item;
75   hr = desktop->ParseDisplayName(NULL, NULL,
76                                  const_cast<wchar_t *>(dir.value().c_str()),
77                                  NULL, &dir_item, NULL);
78   if (FAILED(hr))
79     return;
80
81   base::win::ScopedCoMem<ITEMIDLIST> file_item;
82   hr = desktop->ParseDisplayName(NULL, NULL,
83       const_cast<wchar_t *>(full_path.value().c_str()),
84       NULL, &file_item, NULL);
85   if (FAILED(hr))
86     return;
87
88   const ITEMIDLIST* highlight[] = {
89     {file_item},
90   };
91
92   hr = (*open_folder_and_select_itemsPtr)(dir_item, arraysize(highlight),
93                                           highlight, NULL);
94
95   if (FAILED(hr)) {
96     // On some systems, the above call mysteriously fails with "file not
97     // found" even though the file is there.  In these cases, ShellExecute()
98     // seems to work as a fallback (although it won't select the file).
99     if (hr == ERROR_FILE_NOT_FOUND) {
100       ShellExecute(NULL, L"open", dir.value().c_str(), NULL, NULL, SW_SHOW);
101     } else {
102       LPTSTR message = NULL;
103       DWORD message_length = FormatMessage(
104           FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
105           0, hr, 0, reinterpret_cast<LPTSTR>(&message), 0, NULL);
106       LOG(WARNING) << " " << __FUNCTION__
107                    << "(): Can't open full_path = \""
108                    << full_path.value() << "\""
109                    << " hr = " << hr
110                    << " " << reinterpret_cast<LPTSTR>(&message);
111       if (message)
112         LocalFree(message);
113     }
114   }
115 }
116
117 // Old ShellExecute crashes the process when the command for a given scheme
118 // is empty. This function tells if it is.
119 bool ValidateShellCommandForScheme(const std::string& scheme) {
120   base::win::RegKey key;
121   std::wstring registry_path = base::ASCIIToWide(scheme) +
122                                L"\\shell\\open\\command";
123   key.Open(HKEY_CLASSES_ROOT, registry_path.c_str(), KEY_READ);
124   if (!key.Valid())
125     return false;
126   DWORD size = 0;
127   key.ReadValue(NULL, NULL, &size, NULL);
128   if (size <= 2)
129     return false;
130   return true;
131 }
132
133 }  // namespace
134
135 namespace platform_util {
136
137 void ShowItemInFolder(const base::FilePath& full_path) {
138   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
139   BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
140       base::Bind(&ShowItemInFolderOnFileThread, full_path));
141 }
142
143 void OpenItem(const base::FilePath& full_path) {
144   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
145   BrowserThread::PostTask(
146       BrowserThread::FILE, FROM_HERE,
147       base::Bind(base::IgnoreResult(&ui::win::OpenItemViaShell), full_path));
148 }
149
150 void OpenExternal(const GURL& url) {
151   // Quote the input scheme to be sure that the command does not have
152   // parameters unexpected by the external program. This url should already
153   // have been escaped.
154   std::string escaped_url = url.spec();
155   escaped_url.insert(0, "\"");
156   escaped_url += "\"";
157
158   // According to Mozilla in uriloader/exthandler/win/nsOSHelperAppService.cpp:
159   // "Some versions of windows (Win2k before SP3, Win XP before SP1) crash in
160   // ShellExecute on long URLs (bug 161357 on bugzilla.mozilla.org). IE 5 and 6
161   // support URLS of 2083 chars in length, 2K is safe."
162   const size_t kMaxUrlLength = 2048;
163   if (escaped_url.length() > kMaxUrlLength) {
164     NOTREACHED();
165     return;
166   }
167
168   if (base::win::GetVersion() < base::win::VERSION_WIN7) {
169     if (!ValidateShellCommandForScheme(url.scheme()))
170       return;
171   }
172
173   if (reinterpret_cast<ULONG_PTR>(ShellExecuteA(NULL, "open",
174                                                 escaped_url.c_str(), NULL, NULL,
175                                                 SW_SHOWNORMAL)) <= 32) {
176     // We fail to execute the call. We could display a message to the user.
177     // TODO(nsylvain): we should also add a dialog to warn on errors. See
178     // bug 1136923.
179     return;
180   }
181 }
182
183 #if !defined(USE_AURA)
184 gfx::NativeWindow GetTopLevel(gfx::NativeView view) {
185   return ::GetAncestor(view, GA_ROOT);
186 }
187
188 gfx::NativeView GetParent(gfx::NativeView view) {
189   return ::GetParent(view);
190 }
191
192 bool IsWindowActive(gfx::NativeWindow window) {
193   return ::GetForegroundWindow() == window;
194 }
195
196 void ActivateWindow(gfx::NativeWindow window) {
197   ::SetForegroundWindow(window);
198 }
199
200 bool IsVisible(gfx::NativeView view) {
201   // MSVC complains if we don't include != 0.
202   return ::IsWindowVisible(view) != 0;
203 }
204 #endif
205
206 }  // namespace platform_util