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