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