Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(178)

Side by Side Diff: webkit/plugins/npapi/webplugin_delegate_impl_win.cc

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

Powered by Google App Engine
This is Rietveld 408576698