- add sources.
[platform/framework/web/crosswalk.git] / src / content / child / npapi / webplugin_delegate_impl_win.cc
1 // Copyright (c) 2012 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 "content/child/npapi/webplugin_delegate_impl.h"
6
7 #include <map>
8 #include <set>
9 #include <string>
10 #include <vector>
11
12 #include "base/bind.h"
13 #include "base/compiler_specific.h"
14 #include "base/lazy_instance.h"
15 #include "base/memory/scoped_ptr.h"
16 #include "base/message_loop/message_loop.h"
17 #include "base/metrics/stats_counters.h"
18 #include "base/strings/string_util.h"
19 #include "base/strings/stringprintf.h"
20 #include "base/synchronization/lock.h"
21 #include "base/version.h"
22 #include "base/win/iat_patch_function.h"
23 #include "base/win/registry.h"
24 #include "base/win/windows_version.h"
25 #include "content/child/npapi/plugin_instance.h"
26 #include "content/child/npapi/plugin_lib.h"
27 #include "content/child/npapi/plugin_stream_url.h"
28 #include "content/child/npapi/webplugin.h"
29 #include "content/child/npapi/webplugin_ime_win.h"
30 #include "content/common/plugin_constants_win.h"
31 #include "content/public/common/content_constants.h"
32 #include "skia/ext/platform_canvas.h"
33 #include "third_party/WebKit/public/web/WebInputEvent.h"
34 #include "ui/gfx/win/dpi.h"
35 #include "ui/gfx/win/hwnd_util.h"
36 #include "webkit/common/cursors/webcursor.h"
37
38 using WebKit::WebKeyboardEvent;
39 using WebKit::WebInputEvent;
40 using WebKit::WebMouseEvent;
41
42 namespace content {
43
44 namespace {
45
46 const wchar_t kWebPluginDelegateProperty[] = L"WebPluginDelegateProperty";
47 const wchar_t kPluginFlashThrottle[] = L"FlashThrottle";
48
49 // The fastest we are willing to process WM_USER+1 events for Flash.
50 // Flash can easily exceed the limits of our CPU if we don't throttle it.
51 // The throttle has been chosen by testing various delays and compromising
52 // on acceptable Flash performance and reasonable CPU consumption.
53 //
54 // I'd like to make the throttle delay variable, based on the amount of
55 // time currently required to paint Flash plugins.  There isn't a good
56 // way to count the time spent in aggregate plugin painting, however, so
57 // this seems to work well enough.
58 const int kFlashWMUSERMessageThrottleDelayMs = 5;
59
60 // Flash displays popups in response to user clicks by posting a WM_USER
61 // message to the plugin window. The handler for this message displays
62 // the popup. To ensure that the popups allowed state is sent correctly
63 // to the renderer we reset the popups allowed state in a timer.
64 const int kWindowedPluginPopupTimerMs = 50;
65
66 // The current instance of the plugin which entered the modal loop.
67 WebPluginDelegateImpl* g_current_plugin_instance = NULL;
68
69 typedef std::deque<MSG> ThrottleQueue;
70 base::LazyInstance<ThrottleQueue> g_throttle_queue = LAZY_INSTANCE_INITIALIZER;
71
72 base::LazyInstance<std::map<HWND, WNDPROC> > g_window_handle_proc_map =
73     LAZY_INSTANCE_INITIALIZER;
74
75 // Helper object for patching the TrackPopupMenu API.
76 base::LazyInstance<base::win::IATPatchFunction> g_iat_patch_track_popup_menu =
77     LAZY_INSTANCE_INITIALIZER;
78
79 // Helper object for patching the SetCursor API.
80 base::LazyInstance<base::win::IATPatchFunction> g_iat_patch_set_cursor =
81     LAZY_INSTANCE_INITIALIZER;
82
83 // Helper object for patching the RegEnumKeyExW API.
84 base::LazyInstance<base::win::IATPatchFunction> g_iat_patch_reg_enum_key_ex_w =
85     LAZY_INSTANCE_INITIALIZER;
86
87 // Helper object for patching the GetProcAddress API.
88 base::LazyInstance<base::win::IATPatchFunction> g_iat_patch_get_proc_address =
89     LAZY_INSTANCE_INITIALIZER;
90
91 // http://crbug.com/16114
92 // Enforces providing a valid device context in NPWindow, so that NPP_SetWindow
93 // is never called with NPNWindoTypeDrawable and NPWindow set to NULL.
94 // Doing so allows removing NPP_SetWindow call during painting a windowless
95 // plugin, which otherwise could trigger layout change while painting by
96 // invoking NPN_Evaluate. Which would cause bad, bad crashes. Bad crashes.
97 // TODO(dglazkov): If this approach doesn't produce regressions, move class to
98 // webplugin_delegate_impl.h and implement for other platforms.
99 class DrawableContextEnforcer {
100  public:
101   explicit DrawableContextEnforcer(NPWindow* window)
102       : window_(window),
103         disposable_dc_(window && !window->window) {
104     // If NPWindow is NULL, create a device context with monochrome 1x1 surface
105     // and stuff it to NPWindow.
106     if (disposable_dc_)
107       window_->window = CreateCompatibleDC(NULL);
108   }
109
110   ~DrawableContextEnforcer() {
111     if (!disposable_dc_)
112       return;
113
114     DeleteDC(static_cast<HDC>(window_->window));
115     window_->window = NULL;
116   }
117
118  private:
119   NPWindow* window_;
120   bool disposable_dc_;
121 };
122
123 // These are from ntddk.h
124 typedef LONG NTSTATUS;
125
126 #ifndef STATUS_SUCCESS
127 #define STATUS_SUCCESS ((NTSTATUS)0x00000000L)
128 #endif
129
130 #ifndef STATUS_BUFFER_TOO_SMALL
131 #define STATUS_BUFFER_TOO_SMALL ((NTSTATUS)0xC0000023L)
132 #endif
133
134 typedef enum _KEY_INFORMATION_CLASS {
135   KeyBasicInformation,
136   KeyNodeInformation,
137   KeyFullInformation,
138   KeyNameInformation,
139   KeyCachedInformation,
140   KeyVirtualizationInformation
141 } KEY_INFORMATION_CLASS;
142
143 typedef struct _KEY_NAME_INFORMATION {
144   ULONG NameLength;
145   WCHAR Name[1];
146 } KEY_NAME_INFORMATION, *PKEY_NAME_INFORMATION;
147
148 typedef DWORD (__stdcall *ZwQueryKeyType)(
149     HANDLE  key_handle,
150     int key_information_class,
151     PVOID  key_information,
152     ULONG  length,
153     PULONG  result_length);
154
155 // Returns a key's full path.
156 std::wstring GetKeyPath(HKEY key) {
157   if (key == NULL)
158     return L"";
159
160   HMODULE dll = GetModuleHandle(L"ntdll.dll");
161   if (dll == NULL)
162     return L"";
163
164   ZwQueryKeyType func = reinterpret_cast<ZwQueryKeyType>(
165       ::GetProcAddress(dll, "ZwQueryKey"));
166   if (func == NULL)
167     return L"";
168
169   DWORD size = 0;
170   DWORD result = 0;
171   result = func(key, KeyNameInformation, 0, 0, &size);
172   if (result != STATUS_BUFFER_TOO_SMALL)
173     return L"";
174
175   scoped_ptr<char[]> buffer(new char[size]);
176   if (buffer.get() == NULL)
177     return L"";
178
179   result = func(key, KeyNameInformation, buffer.get(), size, &size);
180   if (result != STATUS_SUCCESS)
181     return L"";
182
183   KEY_NAME_INFORMATION* info =
184       reinterpret_cast<KEY_NAME_INFORMATION*>(buffer.get());
185   return std::wstring(info->Name, info->NameLength / sizeof(wchar_t));
186 }
187
188 int GetPluginMajorVersion(const WebPluginInfo& plugin_info) {
189   Version plugin_version;
190   WebPluginInfo::CreateVersionFromString(plugin_info.version, &plugin_version);
191
192   int major_version = 0;
193   if (plugin_version.IsValid())
194     major_version = plugin_version.components()[0];
195
196   return major_version;
197 }
198
199 }  // namespace
200
201 LRESULT CALLBACK WebPluginDelegateImpl::HandleEventMessageFilterHook(
202     int code, WPARAM wParam, LPARAM lParam) {
203   if (g_current_plugin_instance) {
204     g_current_plugin_instance->OnModalLoopEntered();
205   } else {
206     NOTREACHED();
207   }
208   return CallNextHookEx(NULL, code, wParam, lParam);
209 }
210
211 LRESULT CALLBACK WebPluginDelegateImpl::MouseHookProc(
212     int code, WPARAM wParam, LPARAM lParam) {
213   if (code == HC_ACTION) {
214     MOUSEHOOKSTRUCT* hook_struct = reinterpret_cast<MOUSEHOOKSTRUCT*>(lParam);
215     if (hook_struct)
216       HandleCaptureForMessage(hook_struct->hwnd, wParam);
217   }
218
219   return CallNextHookEx(NULL, code, wParam, lParam);
220 }
221
222 WebPluginDelegateImpl::WebPluginDelegateImpl(
223     WebPlugin* plugin,
224     PluginInstance* instance)
225     : instance_(instance),
226       quirks_(0),
227       plugin_(plugin),
228       windowless_(false),
229       windowed_handle_(NULL),
230       windowed_did_set_window_(false),
231       plugin_wnd_proc_(NULL),
232       last_message_(0),
233       is_calling_wndproc(false),
234       dummy_window_for_activation_(NULL),
235       dummy_window_parent_(NULL),
236       old_dummy_window_proc_(NULL),
237       handle_event_message_filter_hook_(NULL),
238       handle_event_pump_messages_event_(NULL),
239       user_gesture_message_posted_(false),
240       user_gesture_msg_factory_(this),
241       handle_event_depth_(0),
242       mouse_hook_(NULL),
243       first_set_window_call_(true),
244       plugin_has_focus_(false),
245       has_webkit_focus_(false),
246       containing_view_has_focus_(true),
247       creation_succeeded_(false) {
248   memset(&window_, 0, sizeof(window_));
249
250   const WebPluginInfo& plugin_info = instance_->plugin_lib()->plugin_info();
251   std::wstring filename =
252       StringToLowerASCII(plugin_info.path.BaseName().value());
253
254   if (instance_->mime_type() == kFlashPluginSwfMimeType ||
255       filename == kFlashPlugin) {
256     // Flash only requests windowless plugins if we return a Mozilla user
257     // agent.
258     instance_->set_use_mozilla_user_agent();
259     quirks_ |= PLUGIN_QUIRK_THROTTLE_WM_USER_PLUS_ONE;
260     quirks_ |= PLUGIN_QUIRK_PATCH_SETCURSOR;
261     quirks_ |= PLUGIN_QUIRK_ALWAYS_NOTIFY_SUCCESS;
262     quirks_ |= PLUGIN_QUIRK_HANDLE_MOUSE_CAPTURE;
263     quirks_ |= PLUGIN_QUIRK_EMULATE_IME;
264   } else if (filename == kAcrobatReaderPlugin) {
265     // Check for the version number above or equal 9.
266     int major_version = GetPluginMajorVersion(plugin_info);
267     if (major_version >= 9) {
268       quirks_ |= PLUGIN_QUIRK_DIE_AFTER_UNLOAD;
269       // 9.2 needs this.
270       quirks_ |= PLUGIN_QUIRK_SETWINDOW_TWICE;
271     }
272     quirks_ |= PLUGIN_QUIRK_BLOCK_NONSTANDARD_GETURL_REQUESTS;
273   } else if (plugin_info.name.find(L"Windows Media Player") !=
274              std::wstring::npos) {
275     // Windows Media Player needs two NPP_SetWindow calls.
276     quirks_ |= PLUGIN_QUIRK_SETWINDOW_TWICE;
277
278     // Windowless mode doesn't work in the WMP NPAPI plugin.
279     quirks_ |= PLUGIN_QUIRK_NO_WINDOWLESS;
280
281     // The media player plugin sets its size on the first NPP_SetWindow call
282     // and never updates its size. We should call the underlying NPP_SetWindow
283     // only when we have the correct size.
284     quirks_ |= PLUGIN_QUIRK_IGNORE_FIRST_SETWINDOW_CALL;
285
286     if (filename == kOldWMPPlugin) {
287       // Non-admin users on XP couldn't modify the key to force the new UI.
288       quirks_ |= PLUGIN_QUIRK_PATCH_REGENUMKEYEXW;
289     }
290   } else if (instance_->mime_type() == "audio/x-pn-realaudio-plugin" ||
291              filename == kRealPlayerPlugin) {
292     quirks_ |= PLUGIN_QUIRK_DONT_CALL_WND_PROC_RECURSIVELY;
293   } else if (plugin_info.name.find(L"VLC Multimedia Plugin") !=
294              std::wstring::npos ||
295              plugin_info.name.find(L"VLC Multimedia Plug-in") !=
296              std::wstring::npos) {
297     // VLC hangs on NPP_Destroy if we call NPP_SetWindow with a null window
298     // handle
299     quirks_ |= PLUGIN_QUIRK_DONT_SET_NULL_WINDOW_HANDLE_ON_DESTROY;
300     int major_version = GetPluginMajorVersion(plugin_info);
301     if (major_version == 0) {
302       // VLC 0.8.6d and 0.8.6e crash if multiple instances are created.
303       quirks_ |= PLUGIN_QUIRK_DONT_ALLOW_MULTIPLE_INSTANCES;
304     }
305   } else if (filename == kSilverlightPlugin) {
306     // Explanation for this quirk can be found in
307     // WebPluginDelegateImpl::Initialize.
308     quirks_ |= PLUGIN_QUIRK_PATCH_SETCURSOR;
309   } else if (plugin_info.name.find(L"DivX Web Player") !=
310              std::wstring::npos) {
311     // The divx plugin sets its size on the first NPP_SetWindow call and never
312     // updates its size. We should call the underlying NPP_SetWindow only when
313     // we have the correct size.
314     quirks_ |= PLUGIN_QUIRK_IGNORE_FIRST_SETWINDOW_CALL;
315   }
316 }
317
318 WebPluginDelegateImpl::~WebPluginDelegateImpl() {
319   if (::IsWindow(dummy_window_for_activation_)) {
320     WNDPROC current_wnd_proc = reinterpret_cast<WNDPROC>(
321         GetWindowLongPtr(dummy_window_for_activation_, GWLP_WNDPROC));
322     if (current_wnd_proc == DummyWindowProc) {
323       SetWindowLongPtr(dummy_window_for_activation_,
324                        GWLP_WNDPROC,
325                        reinterpret_cast<LONG_PTR>(old_dummy_window_proc_));
326     }
327     ::DestroyWindow(dummy_window_for_activation_);
328   }
329
330   DestroyInstance();
331
332   if (!windowless_)
333     WindowedDestroyWindow();
334
335   if (handle_event_pump_messages_event_) {
336     CloseHandle(handle_event_pump_messages_event_);
337   }
338 }
339
340 bool WebPluginDelegateImpl::PlatformInitialize() {
341   plugin_->SetWindow(windowed_handle_);
342
343   if (windowless_) {
344     CreateDummyWindowForActivation();
345     handle_event_pump_messages_event_ = CreateEvent(NULL, TRUE, FALSE, NULL);
346     plugin_->SetWindowlessData(
347         handle_event_pump_messages_event_,
348         reinterpret_cast<gfx::NativeViewId>(dummy_window_for_activation_));
349   }
350
351   // Windowless plugins call the WindowFromPoint API and passes the result of
352   // that to the TrackPopupMenu API call as the owner window. This causes the
353   // API to fail as the API expects the window handle to live on the same
354   // thread as the caller. It works in the other browsers as the plugin lives
355   // on the browser thread. Our workaround is to intercept the TrackPopupMenu
356   // API and replace the window handle with the dummy activation window.
357   if (windowless_ && !g_iat_patch_track_popup_menu.Pointer()->is_patched()) {
358     g_iat_patch_track_popup_menu.Pointer()->Patch(
359         GetPluginPath().value().c_str(), "user32.dll", "TrackPopupMenu",
360         WebPluginDelegateImpl::TrackPopupMenuPatch);
361   }
362
363   // Windowless plugins can set cursors by calling the SetCursor API. This
364   // works because the thread inputs of the browser UI thread and the plugin
365   // thread are attached. We intercept the SetCursor API for windowless
366   // plugins and remember the cursor being set. This is shipped over to the
367   // browser in the HandleEvent call, which ensures that the cursor does not
368   // change when a windowless plugin instance changes the cursor
369   // in a background tab.
370   if (windowless_ && !g_iat_patch_set_cursor.Pointer()->is_patched() &&
371       (quirks_ & PLUGIN_QUIRK_PATCH_SETCURSOR)) {
372     g_iat_patch_set_cursor.Pointer()->Patch(
373         GetPluginPath().value().c_str(), "user32.dll", "SetCursor",
374         WebPluginDelegateImpl::SetCursorPatch);
375   }
376
377   // The windowed flash plugin has a bug which occurs when the plugin enters
378   // fullscreen mode. It basically captures the mouse on WM_LBUTTONDOWN and
379   // does not release capture correctly causing it to stop receiving
380   // subsequent mouse events. This problem is also seen in Safari where there
381   // is code to handle this in the wndproc. However the plugin subclasses the
382   // window again in WM_LBUTTONDOWN before entering full screen. As a result
383   // Safari does not receive the WM_LBUTTONUP message. To workaround this
384   // issue we use a per thread mouse hook. This bug does not occur in Firefox
385   // and opera. Firefox has code similar to Safari. It could well be a bug in
386   // the flash plugin, which only occurs in webkit based browsers.
387   if (quirks_ & PLUGIN_QUIRK_HANDLE_MOUSE_CAPTURE) {
388     mouse_hook_ = SetWindowsHookEx(WH_MOUSE, MouseHookProc, NULL,
389                                     GetCurrentThreadId());
390   }
391
392   // On XP, WMP will use its old UI unless a registry key under HKLM has the
393   // name of the current process.  We do it in the installer for admin users,
394   // for the rest patch this function.
395   if ((quirks_ & PLUGIN_QUIRK_PATCH_REGENUMKEYEXW) &&
396       base::win::GetVersion() == base::win::VERSION_XP &&
397       (base::win::RegKey().Open(HKEY_LOCAL_MACHINE,
398           L"SOFTWARE\\Microsoft\\MediaPlayer\\ShimInclusionList\\chrome.exe",
399           KEY_READ) != ERROR_SUCCESS) &&
400       !g_iat_patch_reg_enum_key_ex_w.Pointer()->is_patched()) {
401     g_iat_patch_reg_enum_key_ex_w.Pointer()->Patch(
402         L"wmpdxm.dll", "advapi32.dll", "RegEnumKeyExW",
403         WebPluginDelegateImpl::RegEnumKeyExWPatch);
404   }
405
406   // Flash retrieves the pointers to IMM32 functions with GetProcAddress() calls
407   // and use them to retrieve IME data. We add a patch to this function so we
408   // can dispatch these IMM32 calls to the WebPluginIMEWin class, which emulates
409   // IMM32 functions for Flash.
410   if (!g_iat_patch_get_proc_address.Pointer()->is_patched() &&
411       (quirks_ & PLUGIN_QUIRK_EMULATE_IME)) {
412     g_iat_patch_get_proc_address.Pointer()->Patch(
413         GetPluginPath().value().c_str(), "kernel32.dll", "GetProcAddress",
414         GetProcAddressPatch);
415   }
416
417   return true;
418 }
419
420 void WebPluginDelegateImpl::PlatformDestroyInstance() {
421   if (!instance_->plugin_lib())
422     return;
423
424   // Unpatch if this is the last plugin instance.
425   if (instance_->plugin_lib()->instance_count() != 1)
426     return;
427
428   if (g_iat_patch_set_cursor.Pointer()->is_patched())
429     g_iat_patch_set_cursor.Pointer()->Unpatch();
430
431   if (g_iat_patch_track_popup_menu.Pointer()->is_patched())
432     g_iat_patch_track_popup_menu.Pointer()->Unpatch();
433
434   if (g_iat_patch_reg_enum_key_ex_w.Pointer()->is_patched())
435     g_iat_patch_reg_enum_key_ex_w.Pointer()->Unpatch();
436
437   if (mouse_hook_) {
438     UnhookWindowsHookEx(mouse_hook_);
439     mouse_hook_ = NULL;
440   }
441 }
442
443 void WebPluginDelegateImpl::Paint(SkCanvas* canvas, const gfx::Rect& rect) {
444   if (windowless_ && skia::SupportsPlatformPaint(canvas)) {
445     skia::ScopedPlatformPaint scoped_platform_paint(canvas);
446     HDC hdc = scoped_platform_paint.GetPlatformSurface();
447     WindowlessPaint(hdc, rect);
448   }
449 }
450
451 bool WebPluginDelegateImpl::WindowedCreatePlugin() {
452   DCHECK(!windowed_handle_);
453
454   RegisterNativeWindowClass();
455
456   // The window will be sized and shown later.
457   windowed_handle_ = CreateWindowEx(
458       WS_EX_LEFT | WS_EX_LTRREADING | WS_EX_RIGHTSCROLLBAR,
459       kNativeWindowClassName,
460       0,
461       WS_POPUP | WS_CLIPCHILDREN | WS_CLIPSIBLINGS,
462       0,
463       0,
464       0,
465       0,
466       GetDesktopWindow(),
467       0,
468       GetModuleHandle(NULL),
469       0);
470   if (windowed_handle_ == 0)
471     return false;
472
473     // This is a tricky workaround for Issue 2673 in chromium "Flash: IME not
474     // available". To use IMEs in this window, we have to make Windows attach
475   // IMEs to this window (i.e. load IME DLLs, attach them to this process, and
476   // add their message hooks to this window). Windows attaches IMEs while this
477   // process creates a top-level window. On the other hand, to layout this
478   // window correctly in the given parent window (RenderWidgetHostViewWin or
479   // RenderWidgetHostViewAura), this window should be a child window of the
480   // parent window. To satisfy both of the above conditions, this code once
481   // creates a top-level window and change it to a child window of the parent
482   // window (in the browser process).
483     SetWindowLongPtr(windowed_handle_, GWL_STYLE,
484                      WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS);
485
486   BOOL result = SetProp(windowed_handle_, kWebPluginDelegateProperty, this);
487   DCHECK(result == TRUE) << "SetProp failed, last error = " << GetLastError();
488   // Get the name and version of the plugin, create atoms and set them in a
489   // window property. Use atoms so that other processes can access the name and
490   // version of the plugin that this window is hosting.
491   if (instance_ != NULL) {
492     PluginLib* plugin_lib = instance()->plugin_lib();
493     if (plugin_lib != NULL) {
494       std::wstring plugin_name = plugin_lib->plugin_info().name;
495       if (!plugin_name.empty()) {
496         ATOM plugin_name_atom = GlobalAddAtomW(plugin_name.c_str());
497         DCHECK_NE(0, plugin_name_atom);
498         result = SetProp(windowed_handle_,
499             kPluginNameAtomProperty,
500             reinterpret_cast<HANDLE>(plugin_name_atom));
501         DCHECK(result == TRUE) << "SetProp failed, last error = " <<
502             GetLastError();
503       }
504       base::string16 plugin_version = plugin_lib->plugin_info().version;
505       if (!plugin_version.empty()) {
506         ATOM plugin_version_atom = GlobalAddAtomW(plugin_version.c_str());
507         DCHECK_NE(0, plugin_version_atom);
508         result = SetProp(windowed_handle_,
509             kPluginVersionAtomProperty,
510             reinterpret_cast<HANDLE>(plugin_version_atom));
511         DCHECK(result == TRUE) << "SetProp failed, last error = " <<
512             GetLastError();
513       }
514     }
515   }
516
517   // Calling SetWindowLongPtrA here makes the window proc ASCII, which is
518   // required by at least the Shockwave Director plug-in.
519   SetWindowLongPtrA(windowed_handle_,
520                     GWLP_WNDPROC,
521                     reinterpret_cast<LONG_PTR>(DefWindowProcA));
522
523   return true;
524 }
525
526 void WebPluginDelegateImpl::WindowedDestroyWindow() {
527   if (windowed_handle_ != NULL) {
528     // Unsubclass the window.
529     WNDPROC current_wnd_proc = reinterpret_cast<WNDPROC>(
530         GetWindowLongPtr(windowed_handle_, GWLP_WNDPROC));
531     if (current_wnd_proc == NativeWndProc) {
532       SetWindowLongPtr(windowed_handle_,
533                        GWLP_WNDPROC,
534                        reinterpret_cast<LONG_PTR>(plugin_wnd_proc_));
535     }
536
537     plugin_->WillDestroyWindow(windowed_handle_);
538
539     DestroyWindow(windowed_handle_);
540     windowed_handle_ = 0;
541   }
542 }
543
544 // Erase all messages in the queue destined for a particular window.
545 // When windows are closing, callers should use this function to clear
546 // the queue.
547 // static
548 void WebPluginDelegateImpl::ClearThrottleQueueForWindow(HWND window) {
549   ThrottleQueue* throttle_queue = g_throttle_queue.Pointer();
550
551   ThrottleQueue::iterator it;
552   for (it = throttle_queue->begin(); it != throttle_queue->end(); ) {
553     if (it->hwnd == window) {
554       it = throttle_queue->erase(it);
555     } else {
556       it++;
557     }
558   }
559 }
560
561 // Delayed callback for processing throttled messages.
562 // Throttled messages are aggregated globally across all plugins.
563 // static
564 void WebPluginDelegateImpl::OnThrottleMessage() {
565   // The current algorithm walks the list and processes the first
566   // message it finds for each plugin.  It is important to service
567   // all active plugins with each pass through the throttle, otherwise
568   // we see video jankiness.  Copy the set to notify before notifying
569   // since we may re-enter OnThrottleMessage from CallWindowProc!
570   ThrottleQueue* throttle_queue = g_throttle_queue.Pointer();
571   ThrottleQueue notify_queue;
572   std::set<HWND> processed;
573
574   ThrottleQueue::iterator it = throttle_queue->begin();
575   while (it != throttle_queue->end()) {
576     const MSG& msg = *it;
577     if (processed.find(msg.hwnd) == processed.end()) {
578       processed.insert(msg.hwnd);
579       notify_queue.push_back(msg);
580       it = throttle_queue->erase(it);
581     } else {
582       it++;
583     }
584   }
585
586   // Due to re-entrancy, we must save our queue state now.  Otherwise, we may
587   // self-post below, and *also* start up another delayed task when the first
588   // entry is pushed onto the queue in ThrottleMessage().
589   bool throttle_queue_was_empty = throttle_queue->empty();
590
591   for (it = notify_queue.begin(); it != notify_queue.end(); ++it) {
592     const MSG& msg = *it;
593     WNDPROC proc = reinterpret_cast<WNDPROC>(msg.time);
594     // It is possible that the window was closed after we queued
595     // this message.  This is a rare event; just verify the window
596     // is alive.  (see also bug 1259488)
597     if (IsWindow(msg.hwnd))
598       CallWindowProc(proc, msg.hwnd, msg.message, msg.wParam, msg.lParam);
599   }
600
601   if (!throttle_queue_was_empty) {
602     base::MessageLoop::current()->PostDelayedTask(
603         FROM_HERE,
604         base::Bind(&WebPluginDelegateImpl::OnThrottleMessage),
605         base::TimeDelta::FromMilliseconds(kFlashWMUSERMessageThrottleDelayMs));
606   }
607 }
608
609 // Schedule a windows message for delivery later.
610 // static
611 void WebPluginDelegateImpl::ThrottleMessage(WNDPROC proc, HWND hwnd,
612                                             UINT message, WPARAM wParam,
613                                             LPARAM lParam) {
614   MSG msg;
615   msg.time = reinterpret_cast<DWORD>(proc);
616   msg.hwnd = hwnd;
617   msg.message = message;
618   msg.wParam = wParam;
619   msg.lParam = lParam;
620
621   ThrottleQueue* throttle_queue = g_throttle_queue.Pointer();
622
623   throttle_queue->push_back(msg);
624
625   if (throttle_queue->size() == 1) {
626     base::MessageLoop::current()->PostDelayedTask(
627         FROM_HERE,
628         base::Bind(&WebPluginDelegateImpl::OnThrottleMessage),
629         base::TimeDelta::FromMilliseconds(kFlashWMUSERMessageThrottleDelayMs));
630   }
631 }
632
633 // We go out of our way to find the hidden windows created by Flash for
634 // windowless plugins.  We throttle the rate at which they deliver messages
635 // so that they will not consume outrageous amounts of CPU.
636 // static
637 LRESULT CALLBACK WebPluginDelegateImpl::FlashWindowlessWndProc(
638     HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam) {
639   std::map<HWND, WNDPROC>::iterator index =
640       g_window_handle_proc_map.Get().find(hwnd);
641
642   WNDPROC old_proc = (*index).second;
643   DCHECK(old_proc);
644
645   switch (message) {
646     case WM_NCDESTROY: {
647       WebPluginDelegateImpl::ClearThrottleQueueForWindow(hwnd);
648       g_window_handle_proc_map.Get().erase(index);
649       break;
650     }
651     // Flash may flood the message queue with WM_USER+1 message causing 100% CPU
652     // usage.  See https://bugzilla.mozilla.org/show_bug.cgi?id=132759.  We
653     // prevent this by throttling the messages.
654     case WM_USER + 1: {
655       WebPluginDelegateImpl::ThrottleMessage(old_proc, hwnd, message, wparam,
656                                              lparam);
657       return TRUE;
658     }
659
660     default: {
661       break;
662     }
663   }
664   return CallWindowProc(old_proc, hwnd, message, wparam, lparam);
665 }
666
667 LRESULT CALLBACK WebPluginDelegateImpl::DummyWindowProc(
668     HWND hwnd, UINT message, WPARAM w_param, LPARAM l_param) {
669   WebPluginDelegateImpl* delegate = reinterpret_cast<WebPluginDelegateImpl*>(
670       GetProp(hwnd, kWebPluginDelegateProperty));
671   CHECK(delegate);
672   if (message == WM_WINDOWPOSCHANGING) {
673     // We need to know when the dummy window is parented because windowless
674     // plugins need the parent window for things like menus. There's no message
675     // for a parent being changed, but a WM_WINDOWPOSCHANGING is sent so we
676     // check every time we get it.
677     // For non-aura builds, this never changes since RenderWidgetHostViewWin's
678     // window is constant. For aura builds, this changes every time the tab gets
679     // dragged to a new window.
680     HWND parent = GetParent(hwnd);
681     if (parent != delegate->dummy_window_parent_) {
682       delegate->dummy_window_parent_ = parent;
683
684       // Set the containing window handle as the instance window handle. This is
685       // what Safari does. Not having a valid window handle causes subtle bugs
686       // with plugins which retrieve the window handle and use it for things
687       // like context menus. The window handle can be retrieved via
688       // NPN_GetValue of NPNVnetscapeWindow.
689       delegate->instance_->set_window_handle(parent);
690
691       // The plugin caches the result of NPNVnetscapeWindow when we originally
692       // called NPP_SetWindow, so force it to get the new value.
693       delegate->WindowlessSetWindow();
694     }
695   } else if (message == WM_NCDESTROY) {
696     RemoveProp(hwnd, kWebPluginDelegateProperty);
697   }
698   return CallWindowProc(
699       delegate->old_dummy_window_proc_, hwnd, message, w_param, l_param);
700 }
701
702 // Callback for enumerating the Flash windows.
703 BOOL CALLBACK EnumFlashWindows(HWND window, LPARAM arg) {
704   WNDPROC wnd_proc = reinterpret_cast<WNDPROC>(arg);
705   TCHAR class_name[1024];
706   if (!RealGetWindowClass(window, class_name,
707                           sizeof(class_name)/sizeof(TCHAR))) {
708     LOG(ERROR) << "RealGetWindowClass failure: " << GetLastError();
709     return FALSE;
710   }
711
712   if (wcscmp(class_name, L"SWFlash_PlaceholderX"))
713     return TRUE;
714
715   WNDPROC current_wnd_proc = reinterpret_cast<WNDPROC>(
716         GetWindowLongPtr(window, GWLP_WNDPROC));
717   if (current_wnd_proc != wnd_proc) {
718     WNDPROC old_flash_proc = reinterpret_cast<WNDPROC>(SetWindowLongPtr(
719         window, GWLP_WNDPROC,
720         reinterpret_cast<LONG_PTR>(wnd_proc)));
721     DCHECK(old_flash_proc);
722     g_window_handle_proc_map.Get()[window] = old_flash_proc;
723   }
724
725   return TRUE;
726 }
727
728 bool WebPluginDelegateImpl::CreateDummyWindowForActivation() {
729   DCHECK(!dummy_window_for_activation_);
730
731   dummy_window_for_activation_ = CreateWindowEx(
732     0,
733     L"Static",
734     kDummyActivationWindowName,
735     WS_CHILD,
736     0,
737     0,
738     0,
739     0,
740     // We don't know the parent of the dummy window yet, so just set it to the
741     // desktop and it'll get parented by the browser.
742     GetDesktopWindow(),
743     0,
744     GetModuleHandle(NULL),
745     0);
746
747   if (dummy_window_for_activation_ == 0)
748     return false;
749
750   BOOL result = SetProp(dummy_window_for_activation_,
751                         kWebPluginDelegateProperty, this);
752   DCHECK(result == TRUE) << "SetProp failed, last error = " << GetLastError();
753   old_dummy_window_proc_ = reinterpret_cast<WNDPROC>(SetWindowLongPtr(
754       dummy_window_for_activation_, GWLP_WNDPROC,
755       reinterpret_cast<LONG_PTR>(DummyWindowProc)));
756
757   // Flash creates background windows which use excessive CPU in our
758   // environment; we wrap these windows and throttle them so that they don't
759   // get out of hand.
760   if (!EnumThreadWindows(::GetCurrentThreadId(), EnumFlashWindows,
761       reinterpret_cast<LPARAM>(
762       &WebPluginDelegateImpl::FlashWindowlessWndProc))) {
763     // Log that this happened.  Flash will still work; it just means the
764     // throttle isn't installed (and Flash will use more CPU).
765     NOTREACHED();
766     LOG(ERROR) << "Failed to wrap all windowless Flash windows";
767   }
768   return true;
769 }
770
771 bool WebPluginDelegateImpl::WindowedReposition(
772     const gfx::Rect& window_rect_in_dip,
773     const gfx::Rect& clip_rect_in_dip) {
774   if (!windowed_handle_) {
775     NOTREACHED();
776     return false;
777   }
778
779   gfx::Rect window_rect = gfx::win::DIPToScreenRect(window_rect_in_dip);
780   gfx::Rect clip_rect = gfx::win::DIPToScreenRect(clip_rect_in_dip);
781   if (window_rect_ == window_rect && clip_rect_ == clip_rect)
782     return false;
783
784   // We only set the plugin's size here.  Its position is moved elsewhere, which
785   // allows the window moves/scrolling/clipping to be synchronized with the page
786   // and other windows.
787   // If the plugin window has no parent, then don't focus it because it isn't
788   // being displayed anywhere. See:
789   // http://code.google.com/p/chromium/issues/detail?id=32658
790   if (window_rect.size() != window_rect_.size()) {
791     UINT flags = SWP_NOMOVE | SWP_NOZORDER;
792     if (!GetParent(windowed_handle_))
793       flags |= SWP_NOACTIVATE;
794     ::SetWindowPos(windowed_handle_,
795                    NULL,
796                    0,
797                    0,
798                    window_rect.width(),
799                    window_rect.height(),
800                    flags);
801   }
802
803   window_rect_ = window_rect;
804   clip_rect_ = clip_rect;
805
806   // Ensure that the entire window gets repainted.
807   ::InvalidateRect(windowed_handle_, NULL, FALSE);
808
809   return true;
810 }
811
812 void WebPluginDelegateImpl::WindowedSetWindow() {
813   if (!instance_)
814     return;
815
816   if (!windowed_handle_) {
817     NOTREACHED();
818     return;
819   }
820
821   instance()->set_window_handle(windowed_handle_);
822
823   DCHECK(!instance()->windowless());
824
825   window_.clipRect.top = std::max(0, clip_rect_.y());
826   window_.clipRect.left = std::max(0, clip_rect_.x());
827   window_.clipRect.bottom = std::max(0, clip_rect_.y() + clip_rect_.height());
828   window_.clipRect.right = std::max(0, clip_rect_.x() + clip_rect_.width());
829   window_.height = window_rect_.height();
830   window_.width = window_rect_.width();
831   window_.x = 0;
832   window_.y = 0;
833
834   window_.window = windowed_handle_;
835   window_.type = NPWindowTypeWindow;
836
837   // Reset this flag before entering the instance in case of side-effects.
838   windowed_did_set_window_ = true;
839
840   NPError err = instance()->NPP_SetWindow(&window_);
841   if (quirks_ & PLUGIN_QUIRK_SETWINDOW_TWICE)
842     instance()->NPP_SetWindow(&window_);
843
844   WNDPROC current_wnd_proc = reinterpret_cast<WNDPROC>(
845         GetWindowLongPtr(windowed_handle_, GWLP_WNDPROC));
846   if (current_wnd_proc != NativeWndProc) {
847     plugin_wnd_proc_ = reinterpret_cast<WNDPROC>(
848         SetWindowLongPtr(windowed_handle_,
849                          GWLP_WNDPROC,
850                          reinterpret_cast<LONG_PTR>(NativeWndProc)));
851   }
852 }
853
854 ATOM WebPluginDelegateImpl::RegisterNativeWindowClass() {
855   static bool have_registered_window_class = false;
856   if (have_registered_window_class == true)
857     return true;
858
859   have_registered_window_class = true;
860
861   WNDCLASSEX wcex;
862   wcex.cbSize         = sizeof(WNDCLASSEX);
863   wcex.style          = CS_DBLCLKS;
864   wcex.lpfnWndProc    = WrapperWindowProc;
865   wcex.cbClsExtra     = 0;
866   wcex.cbWndExtra     = 0;
867   wcex.hInstance      = GetModuleHandle(NULL);
868   wcex.hIcon          = 0;
869   wcex.hCursor        = 0;
870   // Some plugins like windows media player 11 create child windows parented
871   // by our plugin window, where the media content is rendered. These plugins
872   // dont implement WM_ERASEBKGND, which causes painting issues, when the
873   // window where the media is rendered is moved around. DefWindowProc does
874   // implement WM_ERASEBKGND correctly if we have a valid background brush.
875   wcex.hbrBackground  = reinterpret_cast<HBRUSH>(COLOR_WINDOW+1);
876   wcex.lpszMenuName   = 0;
877   wcex.lpszClassName  = kNativeWindowClassName;
878   wcex.hIconSm        = 0;
879
880   return RegisterClassEx(&wcex);
881 }
882
883 LRESULT CALLBACK WebPluginDelegateImpl::WrapperWindowProc(
884     HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
885   // This is another workaround for Issue 2673 in chromium "Flash: IME not
886   // available". Somehow, the CallWindowProc() function does not dispatch
887   // window messages when its first parameter is a handle representing the
888   // DefWindowProc() function. To avoid this problem, this code creates a
889   // wrapper function which just encapsulates the DefWindowProc() function
890   // and set it as the window procedure of a windowed plug-in.
891   return DefWindowProc(hWnd, message, wParam, lParam);
892 }
893
894 // Returns true if the message passed in corresponds to a user gesture.
895 static bool IsUserGestureMessage(unsigned int message) {
896   switch (message) {
897     case WM_LBUTTONDOWN:
898     case WM_LBUTTONUP:
899     case WM_RBUTTONDOWN:
900     case WM_RBUTTONUP:
901     case WM_MBUTTONDOWN:
902     case WM_MBUTTONUP:
903     case WM_KEYDOWN:
904     case WM_KEYUP:
905       return true;
906
907     default:
908       break;
909   }
910
911   return false;
912 }
913
914 LRESULT CALLBACK WebPluginDelegateImpl::NativeWndProc(
915     HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam) {
916   WebPluginDelegateImpl* delegate = reinterpret_cast<WebPluginDelegateImpl*>(
917       GetProp(hwnd, kWebPluginDelegateProperty));
918   if (!delegate) {
919     NOTREACHED();
920     return 0;
921   }
922
923   if (message == delegate->last_message_ &&
924       delegate->GetQuirks() & PLUGIN_QUIRK_DONT_CALL_WND_PROC_RECURSIVELY &&
925       delegate->is_calling_wndproc) {
926     // Real may go into a state where it recursively dispatches the same event
927     // when subclassed.  See https://bugzilla.mozilla.org/show_bug.cgi?id=192914
928     // We only do the recursive check for Real because it's possible and valid
929     // for a plugin to synchronously dispatch a message to itself such that it
930     // looks like it's in recursion.
931     return TRUE;
932   }
933
934   // Flash may flood the message queue with WM_USER+1 message causing 100% CPU
935   // usage.  See https://bugzilla.mozilla.org/show_bug.cgi?id=132759.  We
936   // prevent this by throttling the messages.
937   if (message == WM_USER + 1 &&
938       delegate->GetQuirks() & PLUGIN_QUIRK_THROTTLE_WM_USER_PLUS_ONE) {
939     WebPluginDelegateImpl::ThrottleMessage(delegate->plugin_wnd_proc_, hwnd,
940                                            message, wparam, lparam);
941     return FALSE;
942   }
943
944   LRESULT result;
945   uint32 old_message = delegate->last_message_;
946   delegate->last_message_ = message;
947
948   static UINT custom_msg = RegisterWindowMessage(kPaintMessageName);
949   if (message == custom_msg) {
950     // Get the invalid rect which is in screen coordinates and convert to
951     // window coordinates.
952     gfx::Rect invalid_rect;
953     invalid_rect.set_x(static_cast<short>(LOWORD(wparam)));
954     invalid_rect.set_y(static_cast<short>(HIWORD(wparam)));
955     invalid_rect.set_width(static_cast<short>(LOWORD(lparam)));
956     invalid_rect.set_height(static_cast<short>(HIWORD(lparam)));
957
958     RECT window_rect;
959     GetWindowRect(hwnd, &window_rect);
960     invalid_rect.Offset(-window_rect.left, -window_rect.top);
961
962     // The plugin window might have non-client area.   If we don't pass in
963     // RDW_FRAME then the children don't receive WM_NCPAINT messages while
964     // scrolling, which causes painting problems (http://b/issue?id=923945).
965     uint32 flags = RDW_INVALIDATE | RDW_ALLCHILDREN | RDW_FRAME;
966
967     // If a plugin (like Google Earth or Java) has child windows that are hosted
968     // in a different process, then RedrawWindow with UPDATENOW will
969     // synchronously wait for this call to complete.  Some messages are pumped
970     // but not others, which could lead to a deadlock.  So avoid reentrancy by
971     // only synchronously calling RedrawWindow once at a time.
972     if (old_message != custom_msg)
973       flags |= RDW_UPDATENOW;
974     RECT rect = invalid_rect.ToRECT();
975     RedrawWindow(hwnd, &rect, NULL, flags);
976     result = FALSE;
977   } else {
978     delegate->is_calling_wndproc = true;
979
980     if (!delegate->user_gesture_message_posted_ &&
981         IsUserGestureMessage(message)) {
982       delegate->user_gesture_message_posted_ = true;
983
984       delegate->instance()->PushPopupsEnabledState(true);
985
986       base::MessageLoop::current()->PostDelayedTask(
987           FROM_HERE,
988           base::Bind(&WebPluginDelegateImpl::OnUserGestureEnd,
989                      delegate->user_gesture_msg_factory_.GetWeakPtr()),
990           base::TimeDelta::FromMilliseconds(kWindowedPluginPopupTimerMs));
991     }
992
993     HandleCaptureForMessage(hwnd, message);
994
995     // Maintain a local/global stack for the g_current_plugin_instance variable
996     // as this may be a nested invocation.
997     WebPluginDelegateImpl* last_plugin_instance = g_current_plugin_instance;
998
999     g_current_plugin_instance = delegate;
1000
1001     result = CallWindowProc(
1002         delegate->plugin_wnd_proc_, hwnd, message, wparam, lparam);
1003
1004     delegate->is_calling_wndproc = false;
1005     g_current_plugin_instance = last_plugin_instance;
1006
1007     if (message == WM_NCDESTROY) {
1008       RemoveProp(hwnd, kWebPluginDelegateProperty);
1009       ATOM plugin_name_atom = reinterpret_cast<ATOM>(
1010           RemoveProp(hwnd, kPluginNameAtomProperty));
1011       if (plugin_name_atom != 0)
1012         GlobalDeleteAtom(plugin_name_atom);
1013       ATOM plugin_version_atom = reinterpret_cast<ATOM>(
1014           RemoveProp(hwnd, kPluginVersionAtomProperty));
1015       if (plugin_version_atom != 0)
1016         GlobalDeleteAtom(plugin_version_atom);
1017       ClearThrottleQueueForWindow(hwnd);
1018     }
1019   }
1020   delegate->last_message_ = old_message;
1021   return result;
1022 }
1023
1024 void WebPluginDelegateImpl::WindowlessUpdateGeometry(
1025     const gfx::Rect& window_rect,
1026     const gfx::Rect& clip_rect) {
1027   bool window_rect_changed = (window_rect_ != window_rect);
1028   // Only resend to the instance if the geometry has changed.
1029   if (!window_rect_changed && clip_rect == clip_rect_)
1030     return;
1031
1032   clip_rect_ = clip_rect;
1033   window_rect_ = window_rect;
1034
1035   WindowlessSetWindow();
1036
1037   if (window_rect_changed) {
1038     WINDOWPOS win_pos = {0};
1039     win_pos.x = window_rect_.x();
1040     win_pos.y = window_rect_.y();
1041     win_pos.cx = window_rect_.width();
1042     win_pos.cy = window_rect_.height();
1043
1044     NPEvent pos_changed_event;
1045     pos_changed_event.event = WM_WINDOWPOSCHANGED;
1046     pos_changed_event.wParam = 0;
1047     pos_changed_event.lParam = PtrToUlong(&win_pos);
1048
1049     instance()->NPP_HandleEvent(&pos_changed_event);
1050   }
1051 }
1052
1053 void WebPluginDelegateImpl::WindowlessPaint(HDC hdc,
1054                                             const gfx::Rect& damage_rect) {
1055   DCHECK(hdc);
1056
1057   RECT damage_rect_win;
1058   damage_rect_win.left   = damage_rect.x();  // + window_rect_.x();
1059   damage_rect_win.top    = damage_rect.y();  // + window_rect_.y();
1060   damage_rect_win.right  = damage_rect_win.left + damage_rect.width();
1061   damage_rect_win.bottom = damage_rect_win.top + damage_rect.height();
1062
1063   // Save away the old HDC as this could be a nested invocation.
1064   void* old_dc = window_.window;
1065   window_.window = hdc;
1066
1067   NPEvent paint_event;
1068   paint_event.event = WM_PAINT;
1069   // NOTE: NPAPI is not 64bit safe.  It puts pointers into 32bit values.
1070   paint_event.wParam = PtrToUlong(hdc);
1071   paint_event.lParam = PtrToUlong(&damage_rect_win);
1072   base::StatsRate plugin_paint("Plugin.Paint");
1073   base::StatsScope<base::StatsRate> scope(plugin_paint);
1074   instance()->NPP_HandleEvent(&paint_event);
1075   window_.window = old_dc;
1076 }
1077
1078 void WebPluginDelegateImpl::WindowlessSetWindow() {
1079   if (!instance())
1080     return;
1081
1082   if (window_rect_.IsEmpty())  // wait for geometry to be set.
1083     return;
1084
1085   DCHECK(instance()->windowless());
1086
1087   window_.clipRect.top = clip_rect_.y();
1088   window_.clipRect.left = clip_rect_.x();
1089   window_.clipRect.bottom = clip_rect_.y() + clip_rect_.height();
1090   window_.clipRect.right = clip_rect_.x() + clip_rect_.width();
1091   window_.height = window_rect_.height();
1092   window_.width = window_rect_.width();
1093   window_.x = window_rect_.x();
1094   window_.y = window_rect_.y();
1095   window_.type = NPWindowTypeDrawable;
1096   DrawableContextEnforcer enforcer(&window_);
1097
1098   NPError err = instance()->NPP_SetWindow(&window_);
1099   DCHECK(err == NPERR_NO_ERROR);
1100 }
1101
1102 bool WebPluginDelegateImpl::PlatformSetPluginHasFocus(bool focused) {
1103   DCHECK(instance()->windowless());
1104
1105   NPEvent focus_event;
1106   focus_event.event = focused ? WM_SETFOCUS : WM_KILLFOCUS;
1107   focus_event.wParam = 0;
1108   focus_event.lParam = 0;
1109
1110   instance()->NPP_HandleEvent(&focus_event);
1111   return true;
1112 }
1113
1114 static bool NPEventFromWebMouseEvent(const WebMouseEvent& event,
1115                                      NPEvent* np_event) {
1116   np_event->lParam = static_cast<uint32>(MAKELPARAM(event.windowX,
1117                                                    event.windowY));
1118   np_event->wParam = 0;
1119
1120   if (event.modifiers & WebInputEvent::ControlKey)
1121     np_event->wParam |= MK_CONTROL;
1122   if (event.modifiers & WebInputEvent::ShiftKey)
1123     np_event->wParam |= MK_SHIFT;
1124   if (event.modifiers & WebInputEvent::LeftButtonDown)
1125     np_event->wParam |= MK_LBUTTON;
1126   if (event.modifiers & WebInputEvent::MiddleButtonDown)
1127     np_event->wParam |= MK_MBUTTON;
1128   if (event.modifiers & WebInputEvent::RightButtonDown)
1129     np_event->wParam |= MK_RBUTTON;
1130
1131   switch (event.type) {
1132     case WebInputEvent::MouseMove:
1133     case WebInputEvent::MouseLeave:
1134     case WebInputEvent::MouseEnter:
1135       np_event->event = WM_MOUSEMOVE;
1136       return true;
1137     case WebInputEvent::MouseDown:
1138       switch (event.button) {
1139         case WebMouseEvent::ButtonLeft:
1140           np_event->event = WM_LBUTTONDOWN;
1141           break;
1142         case WebMouseEvent::ButtonMiddle:
1143           np_event->event = WM_MBUTTONDOWN;
1144           break;
1145         case WebMouseEvent::ButtonRight:
1146           np_event->event = WM_RBUTTONDOWN;
1147           break;
1148       }
1149       return true;
1150     case WebInputEvent::MouseUp:
1151       switch (event.button) {
1152         case WebMouseEvent::ButtonLeft:
1153           np_event->event = WM_LBUTTONUP;
1154           break;
1155         case WebMouseEvent::ButtonMiddle:
1156           np_event->event = WM_MBUTTONUP;
1157           break;
1158         case WebMouseEvent::ButtonRight:
1159           np_event->event = WM_RBUTTONUP;
1160           break;
1161       }
1162       return true;
1163     default:
1164       NOTREACHED();
1165       return false;
1166   }
1167 }
1168
1169 static bool NPEventFromWebKeyboardEvent(const WebKeyboardEvent& event,
1170                                         NPEvent* np_event) {
1171   np_event->wParam = event.windowsKeyCode;
1172
1173   switch (event.type) {
1174     case WebInputEvent::KeyDown:
1175       np_event->event = WM_KEYDOWN;
1176       np_event->lParam = 0;
1177       return true;
1178     case WebInputEvent::Char:
1179       np_event->event = WM_CHAR;
1180       np_event->lParam = 0;
1181       return true;
1182     case WebInputEvent::KeyUp:
1183       np_event->event = WM_KEYUP;
1184       np_event->lParam = 0x8000;
1185       return true;
1186     default:
1187       NOTREACHED();
1188       return false;
1189   }
1190 }
1191
1192 static bool NPEventFromWebInputEvent(const WebInputEvent& event,
1193                                      NPEvent* np_event) {
1194   switch (event.type) {
1195     case WebInputEvent::MouseMove:
1196     case WebInputEvent::MouseLeave:
1197     case WebInputEvent::MouseEnter:
1198     case WebInputEvent::MouseDown:
1199     case WebInputEvent::MouseUp:
1200       if (event.size < sizeof(WebMouseEvent)) {
1201         NOTREACHED();
1202         return false;
1203       }
1204       return NPEventFromWebMouseEvent(
1205           *static_cast<const WebMouseEvent*>(&event), np_event);
1206     case WebInputEvent::KeyDown:
1207     case WebInputEvent::Char:
1208     case WebInputEvent::KeyUp:
1209       if (event.size < sizeof(WebKeyboardEvent)) {
1210         NOTREACHED();
1211         return false;
1212       }
1213       return NPEventFromWebKeyboardEvent(
1214           *static_cast<const WebKeyboardEvent*>(&event), np_event);
1215     default:
1216       return false;
1217   }
1218 }
1219
1220 bool WebPluginDelegateImpl::PlatformHandleInputEvent(
1221     const WebInputEvent& event, WebCursor::CursorInfo* cursor_info) {
1222   DCHECK(cursor_info != NULL);
1223
1224   NPEvent np_event;
1225   if (!NPEventFromWebInputEvent(event, &np_event)) {
1226     return false;
1227   }
1228
1229   // Allow this plug-in to access this IME emulator through IMM32 API while the
1230   // plug-in is processing this event.
1231   if (GetQuirks() & PLUGIN_QUIRK_EMULATE_IME) {
1232     if (!plugin_ime_)
1233       plugin_ime_.reset(new WebPluginIMEWin);
1234   }
1235   WebPluginIMEWin::ScopedLock lock(
1236       event.isKeyboardEventType(event.type) ? plugin_ime_.get() : NULL);
1237
1238   HWND last_focus_window = NULL;
1239
1240   if (ShouldTrackEventForModalLoops(&np_event)) {
1241     // A windowless plugin can enter a modal loop in a NPP_HandleEvent call.
1242     // For e.g. Flash puts up a context menu when we right click on the
1243     // windowless plugin area. We detect this by setting up a message filter
1244     // hook pror to calling NPP_HandleEvent on the plugin and unhook on
1245     // return from NPP_HandleEvent. If the plugin does enter a modal loop
1246     // in that context we unhook on receiving the first notification in
1247     // the message filter hook.
1248     handle_event_message_filter_hook_ =
1249         SetWindowsHookEx(WH_MSGFILTER, HandleEventMessageFilterHook, NULL,
1250                          GetCurrentThreadId());
1251     // To ensure that the plugin receives keyboard events we set focus to the
1252     // dummy window.
1253     // TODO(iyengar) We need a framework in the renderer to identify which
1254     // windowless plugin is under the mouse and to handle this. This would
1255     // also require some changes in RenderWidgetHost to detect this in the
1256     // WM_MOUSEACTIVATE handler and inform the renderer accordingly.
1257     bool valid = GetParent(dummy_window_for_activation_) != GetDesktopWindow();
1258     if (valid) {
1259       last_focus_window = ::SetFocus(dummy_window_for_activation_);
1260     } else {
1261       NOTREACHED() << "Dummy window not parented";
1262     }
1263   }
1264
1265   bool old_task_reentrancy_state =
1266       base::MessageLoop::current()->NestableTasksAllowed();
1267
1268   // Maintain a local/global stack for the g_current_plugin_instance variable
1269   // as this may be a nested invocation.
1270   WebPluginDelegateImpl* last_plugin_instance = g_current_plugin_instance;
1271
1272   g_current_plugin_instance = this;
1273
1274   handle_event_depth_++;
1275
1276   bool popups_enabled = false;
1277
1278   if (IsUserGestureMessage(np_event.event)) {
1279     instance()->PushPopupsEnabledState(true);
1280     popups_enabled = true;
1281   }
1282
1283   bool ret = instance()->NPP_HandleEvent(&np_event) != 0;
1284
1285   if (popups_enabled) {
1286     instance()->PopPopupsEnabledState();
1287   }
1288
1289   // Flash and SilverLight always return false, even when they swallow the
1290   // event.  Flash does this because it passes the event to its window proc,
1291   // which is supposed to return 0 if an event was handled.  There are few
1292   // exceptions, such as IME, where it sometimes returns true.
1293   ret = true;
1294
1295   if (np_event.event == WM_MOUSEMOVE) {
1296     current_windowless_cursor_.InitFromExternalCursor(GetCursor());
1297     // Snag a reference to the current cursor ASAP in case the plugin modified
1298     // it. There is a nasty race condition here with the multiprocess browser
1299     // as someone might be setting the cursor in the main process as well.
1300     current_windowless_cursor_.GetCursorInfo(cursor_info);
1301   }
1302
1303   handle_event_depth_--;
1304
1305   g_current_plugin_instance = last_plugin_instance;
1306
1307   // We could have multiple NPP_HandleEvent calls nested together in case
1308   // the plugin enters a modal loop. Reset the pump messages event when
1309   // the outermost NPP_HandleEvent call unwinds.
1310   if (handle_event_depth_ == 0) {
1311     ResetEvent(handle_event_pump_messages_event_);
1312   }
1313
1314   if (::IsWindow(last_focus_window)) {
1315     // Restore the nestable tasks allowed state in the message loop and reset
1316     // the os modal loop state as the plugin returned from the TrackPopupMenu
1317     // API call.
1318     base::MessageLoop::current()->SetNestableTasksAllowed(
1319         old_task_reentrancy_state);
1320     base::MessageLoop::current()->set_os_modal_loop(false);
1321     // The Flash plugin at times sets focus to its hidden top level window
1322     // with class name SWFlash_PlaceholderX. This causes the chrome browser
1323     // window to receive a WM_ACTIVATEAPP message as a top level window from
1324     // another thread is now active. We end up in a state where the chrome
1325     // browser window is not active even though the user clicked on it.
1326     // Our workaround for this is to send over a raw
1327     // WM_LBUTTONDOWN/WM_LBUTTONUP combination to the last focus window, which
1328     // does the trick.
1329     if (dummy_window_for_activation_ != ::GetFocus()) {
1330       INPUT input_info = {0};
1331       input_info.type = INPUT_MOUSE;
1332       input_info.mi.dwFlags = MOUSEEVENTF_LEFTDOWN;
1333       ::SendInput(1, &input_info, sizeof(INPUT));
1334
1335       input_info.type = INPUT_MOUSE;
1336       input_info.mi.dwFlags = MOUSEEVENTF_LEFTUP;
1337       ::SendInput(1, &input_info, sizeof(INPUT));
1338     } else {
1339       ::SetFocus(last_focus_window);
1340     }
1341   }
1342   return ret;
1343 }
1344
1345
1346 void WebPluginDelegateImpl::OnModalLoopEntered() {
1347   DCHECK(handle_event_pump_messages_event_ != NULL);
1348   SetEvent(handle_event_pump_messages_event_);
1349
1350   base::MessageLoop::current()->SetNestableTasksAllowed(true);
1351   base::MessageLoop::current()->set_os_modal_loop(true);
1352
1353   UnhookWindowsHookEx(handle_event_message_filter_hook_);
1354   handle_event_message_filter_hook_ = NULL;
1355 }
1356
1357 bool WebPluginDelegateImpl::ShouldTrackEventForModalLoops(NPEvent* event) {
1358   if (event->event == WM_RBUTTONDOWN)
1359     return true;
1360   return false;
1361 }
1362
1363 void WebPluginDelegateImpl::OnUserGestureEnd() {
1364   user_gesture_message_posted_ = false;
1365   instance()->PopPopupsEnabledState();
1366 }
1367
1368 BOOL WINAPI WebPluginDelegateImpl::TrackPopupMenuPatch(
1369     HMENU menu, unsigned int flags, int x, int y, int reserved,
1370     HWND window, const RECT* rect) {
1371
1372   if (g_current_plugin_instance) {
1373     unsigned long window_process_id = 0;
1374     unsigned long window_thread_id =
1375         GetWindowThreadProcessId(window, &window_process_id);
1376     // TrackPopupMenu fails if the window passed in belongs to a different
1377     // thread.
1378     if (::GetCurrentThreadId() != window_thread_id) {
1379       bool valid =
1380           GetParent(g_current_plugin_instance->dummy_window_for_activation_) !=
1381               GetDesktopWindow();
1382       if (valid) {
1383         window = g_current_plugin_instance->dummy_window_for_activation_;
1384       } else {
1385         NOTREACHED() << "Dummy window not parented";
1386       }
1387     }
1388   }
1389
1390   BOOL result = TrackPopupMenu(menu, flags, x, y, reserved, window, rect);
1391   return result;
1392 }
1393
1394 HCURSOR WINAPI WebPluginDelegateImpl::SetCursorPatch(HCURSOR cursor) {
1395   // The windowless flash plugin periodically calls SetCursor in a wndproc
1396   // instantiated on the plugin thread. This causes annoying cursor flicker
1397   // when the mouse is moved on a foreground tab, with a windowless plugin
1398   // instance in a background tab. We just ignore the call here.
1399   if (!g_current_plugin_instance) {
1400     HCURSOR current_cursor = GetCursor();
1401     if (current_cursor != cursor) {
1402       ::SetCursor(cursor);
1403     }
1404     return current_cursor;
1405   }
1406   return ::SetCursor(cursor);
1407 }
1408
1409 LONG WINAPI WebPluginDelegateImpl::RegEnumKeyExWPatch(
1410     HKEY key, DWORD index, LPWSTR name, LPDWORD name_size, LPDWORD reserved,
1411     LPWSTR class_name, LPDWORD class_size, PFILETIME last_write_time) {
1412   DWORD orig_size = *name_size;
1413   LONG rv = RegEnumKeyExW(key, index, name, name_size, reserved, class_name,
1414                           class_size, last_write_time);
1415   if (rv == ERROR_SUCCESS &&
1416       GetKeyPath(key).find(L"Microsoft\\MediaPlayer\\ShimInclusionList") !=
1417           std::wstring::npos) {
1418     static const wchar_t kChromeExeName[] = L"chrome.exe";
1419     wcsncpy_s(name, orig_size, kChromeExeName, arraysize(kChromeExeName));
1420     *name_size =
1421         std::min(orig_size, static_cast<DWORD>(arraysize(kChromeExeName)));
1422   }
1423
1424   return rv;
1425 }
1426
1427 void WebPluginDelegateImpl::ImeCompositionUpdated(
1428     const base::string16& text,
1429     const std::vector<int>& clauses,
1430     const std::vector<int>& target,
1431     int cursor_position) {
1432   if (!plugin_ime_)
1433     plugin_ime_.reset(new WebPluginIMEWin);
1434
1435   plugin_ime_->CompositionUpdated(text, clauses, target, cursor_position);
1436   plugin_ime_->SendEvents(instance());
1437 }
1438
1439 void WebPluginDelegateImpl::ImeCompositionCompleted(
1440     const base::string16& text) {
1441   if (!plugin_ime_)
1442     plugin_ime_.reset(new WebPluginIMEWin);
1443   plugin_ime_->CompositionCompleted(text);
1444   plugin_ime_->SendEvents(instance());
1445 }
1446
1447 bool WebPluginDelegateImpl::GetIMEStatus(int* input_type,
1448                                          gfx::Rect* caret_rect) {
1449   if (!plugin_ime_)
1450     return false;
1451   return plugin_ime_->GetStatus(input_type, caret_rect);
1452 }
1453
1454 // static
1455 FARPROC WINAPI WebPluginDelegateImpl::GetProcAddressPatch(HMODULE module,
1456                                                           LPCSTR name) {
1457   FARPROC imm_function = WebPluginIMEWin::GetProcAddress(name);
1458   if (imm_function)
1459     return imm_function;
1460   return ::GetProcAddress(module, name);
1461 }
1462
1463 void WebPluginDelegateImpl::HandleCaptureForMessage(HWND window,
1464                                                     UINT message) {
1465   if (gfx::GetClassName(window) != base::string16(kNativeWindowClassName))
1466     return;
1467
1468   switch (message) {
1469     case WM_LBUTTONDOWN:
1470     case WM_MBUTTONDOWN:
1471     case WM_RBUTTONDOWN:
1472       ::SetCapture(window);
1473       // As per documentation the WM_PARENTNOTIFY message is sent to the parent
1474       // window chain if mouse input is received by the child window. However
1475       // the parent receives the WM_PARENTNOTIFY message only if we doubleclick
1476       // on the window. We send the WM_PARENTNOTIFY message for mouse input
1477       // messages to the parent to indicate that user action is expected.
1478       ::SendMessage(::GetParent(window), WM_PARENTNOTIFY, message, 0);
1479       break;
1480
1481     case WM_LBUTTONUP:
1482     case WM_MBUTTONUP:
1483     case WM_RBUTTONUP:
1484       ::ReleaseCapture();
1485       break;
1486
1487     default:
1488       break;
1489   }
1490 }
1491
1492 }  // namespace content