- add sources.
[platform/framework/web/crosswalk.git] / src / chrome / browser / chrome_process_finder_win.cc
1 // Copyright 2013 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 "chrome/browser/chrome_process_finder_win.h"
6
7 #include <shellapi.h>
8 #include <string>
9
10 #include "base/command_line.h"
11 #include "base/file_util.h"
12 #include "base/files/file_path.h"
13 #include "base/logging.h"
14 #include "base/process/process_handle.h"
15 #include "base/process/process_info.h"
16 #include "base/strings/string_number_conversions.h"
17 #include "base/strings/stringprintf.h"
18 #include "base/strings/utf_string_conversions.h"
19 #include "base/win/message_window.h"
20 #include "base/win/metro.h"
21 #include "base/win/scoped_handle.h"
22 #include "base/win/win_util.h"
23 #include "base/win/windows_version.h"
24 #include "chrome/browser/metro_utils/metro_chrome_win.h"
25 #include "chrome/common/chrome_constants.h"
26 #include "chrome/common/chrome_switches.h"
27
28
29 namespace {
30
31 const int kTimeoutInSeconds = 20;
32
33 // The following is copied from net/base/escape.cc. We don't want to depend on
34 // net here because this gets compiled into chrome.exe to facilitate
35 // fast-rendezvous (see https://codereview.chromium.org/14617003/).
36
37 // TODO(koz): Move these functions out of net/base/escape.cc into base/escape.cc
38 // so we can depend on it directly.
39
40 // BEGIN COPY from net/base/escape.cc
41
42 // A fast bit-vector map for ascii characters.
43 //
44 // Internally stores 256 bits in an array of 8 ints.
45 // Does quick bit-flicking to lookup needed characters.
46 struct Charmap {
47   bool Contains(unsigned char c) const {
48     return ((map[c >> 5] & (1 << (c & 31))) != 0);
49   }
50
51   uint32 map[8];
52 };
53
54 const char kHexString[] = "0123456789ABCDEF";
55 inline char IntToHex(int i) {
56   DCHECK_GE(i, 0) << i << " not a hex value";
57   DCHECK_LE(i, 15) << i << " not a hex value";
58   return kHexString[i];
59 }
60
61 // Given text to escape and a Charmap defining which values to escape,
62 // return an escaped string.  If use_plus is true, spaces are converted
63 // to +, otherwise, if spaces are in the charmap, they are converted to
64 // %20.
65 std::string Escape(const std::string& text, const Charmap& charmap,
66                    bool use_plus) {
67   std::string escaped;
68   escaped.reserve(text.length() * 3);
69   for (unsigned int i = 0; i < text.length(); ++i) {
70     unsigned char c = static_cast<unsigned char>(text[i]);
71     if (use_plus && ' ' == c) {
72       escaped.push_back('+');
73     } else if (charmap.Contains(c)) {
74       escaped.push_back('%');
75       escaped.push_back(IntToHex(c >> 4));
76       escaped.push_back(IntToHex(c & 0xf));
77     } else {
78       escaped.push_back(c);
79     }
80   }
81   return escaped;
82 }
83
84 // Everything except alphanumerics and !'()*-._~
85 // See RFC 2396 for the list of reserved characters.
86 static const Charmap kQueryCharmap = {{
87   0xffffffffL, 0xfc00987dL, 0x78000001L, 0xb8000001L,
88   0xffffffffL, 0xffffffffL, 0xffffffffL, 0xffffffffL
89 }};
90
91 std::string EscapeQueryParamValue(const std::string& text, bool use_plus) {
92   return Escape(text, kQueryCharmap, use_plus);
93 }
94
95 // END COPY from net/base/escape.cc
96
97 }  // namespace
98
99 namespace chrome {
100
101 HWND FindRunningChromeWindow(const base::FilePath& user_data_dir) {
102   return base::win::MessageWindow::FindWindow(user_data_dir.value());
103 }
104
105 NotifyChromeResult AttemptToNotifyRunningChrome(HWND remote_window,
106                                                 bool fast_start) {
107   DCHECK(remote_window);
108   static const char kSearchUrl[] =
109       "http://www.google.com/search?q=%s&sourceid=chrome&ie=UTF-8";
110   DWORD process_id = 0;
111   DWORD thread_id = GetWindowThreadProcessId(remote_window, &process_id);
112   if (!thread_id || !process_id)
113     return NOTIFY_FAILED;
114
115   if (base::win::IsMetroProcess()) {
116     // Interesting corner case. We are launched as a metro process but we
117     // found another chrome running. Since metro enforces single instance then
118     // the other chrome must be desktop chrome and this must be a search charm
119     // activation. This scenario is unique; other cases should be properly
120     // handled by the delegate_execute which will not activate a second chrome.
121     string16 terms;
122     base::win::MetroLaunchType launch = base::win::GetMetroLaunchParams(&terms);
123     if (launch != base::win::METRO_SEARCH) {
124       LOG(WARNING) << "In metro mode, but and launch is " << launch;
125     } else {
126       std::string query = EscapeQueryParamValue(UTF16ToUTF8(terms), true);
127       std::string url = base::StringPrintf(kSearchUrl, query.c_str());
128       SHELLEXECUTEINFOA sei = { sizeof(sei) };
129       sei.fMask = SEE_MASK_FLAG_LOG_USAGE;
130       sei.nShow = SW_SHOWNORMAL;
131       sei.lpFile = url.c_str();
132       OutputDebugStringA(sei.lpFile);
133       sei.lpDirectory = "";
134       ::ShellExecuteExA(&sei);
135     }
136     return NOTIFY_SUCCESS;
137   }
138
139   base::win::ScopedHandle process_handle;
140   if (base::win::GetVersion() >= base::win::VERSION_WIN8 &&
141       base::OpenProcessHandleWithAccess(
142           process_id, PROCESS_QUERY_INFORMATION,
143           process_handle.Receive()) &&
144       base::win::IsProcessImmersive(process_handle.Get())) {
145     chrome::ActivateMetroChrome();
146   }
147
148   CommandLine command_line(*CommandLine::ForCurrentProcess());
149   command_line.AppendSwitchASCII(
150       switches::kOriginalProcessStartTime,
151       base::Int64ToString(
152           base::CurrentProcessInfo::CreationTime().ToInternalValue()));
153
154   if (fast_start)
155     command_line.AppendSwitch(switches::kFastStart);
156
157   // Send the command line to the remote chrome window.
158   // Format is "START\0<<<current directory>>>\0<<<commandline>>>".
159   std::wstring to_send(L"START\0", 6);  // want the NULL in the string.
160   base::FilePath cur_dir;
161   if (!file_util::GetCurrentDirectory(&cur_dir))
162     return NOTIFY_FAILED;
163   to_send.append(cur_dir.value());
164   to_send.append(L"\0", 1);  // Null separator.
165   to_send.append(command_line.GetCommandLineString());
166   to_send.append(L"\0", 1);  // Null separator.
167
168   // Allow the current running browser window to make itself the foreground
169   // window (otherwise it will just flash in the taskbar).
170   ::AllowSetForegroundWindow(process_id);
171
172   COPYDATASTRUCT cds;
173   cds.dwData = 0;
174   cds.cbData = static_cast<DWORD>((to_send.length() + 1) * sizeof(wchar_t));
175   cds.lpData = const_cast<wchar_t*>(to_send.c_str());
176   DWORD_PTR result = 0;
177   if (::SendMessageTimeout(remote_window,
178                            WM_COPYDATA,
179                            NULL,
180                            reinterpret_cast<LPARAM>(&cds),
181                            SMTO_ABORTIFHUNG,
182                            kTimeoutInSeconds * 1000,
183                            &result)) {
184     return result ? NOTIFY_SUCCESS : NOTIFY_FAILED;
185   }
186
187   // It is possible that the process owning this window may have died by now.
188   if (!::IsWindow(remote_window))
189     return NOTIFY_FAILED;
190
191   // If the window couldn't be notified but still exists, assume it is hung.
192   return NOTIFY_WINDOW_HUNG;
193 }
194
195 }  // namespace chrome