Bug 451040 ? Passwords Manager Empty after convert to MozStorage. r=gavin
[wine-gecko.git] / layout / generic / nsObjectFrame.cpp
blob7b846a2d0e8bc6b47836f760baaf90f7e540bf24
1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 // vim:set ts=2 sts=2 sw=2 et cin:
3 /* ***** BEGIN LICENSE BLOCK *****
4 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
6 * The contents of this file are subject to the Mozilla Public License Version
7 * 1.1 (the "License"); you may not use this file except in compliance with
8 * the License. You may obtain a copy of the License at
9 * http://www.mozilla.org/MPL/
11 * Software distributed under the License is distributed on an "AS IS" basis,
12 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
13 * for the specific language governing rights and limitations under the
14 * License.
16 * The Original Code is Mozilla Communicator client code.
18 * The Initial Developer of the Original Code is
19 * Netscape Communications Corporation.
20 * Portions created by the Initial Developer are Copyright (C) 1998
21 * the Initial Developer. All Rights Reserved.
23 * Contributor(s):
24 * Pierre Phaneuf <pp@ludusdesign.com>
25 * Jacek Piskozub <piskozub@iopan.gda.pl>
26 * Leon Sha <leon.sha@sun.com>
27 * Roland Mainz <roland.mainz@informatik.med.uni-giessen.de>
28 * Robert O'Callahan <roc+moz@cs.cmu.edu>
29 * Christian Biesinger <cbiesinger@web.de>
30 * Josh Aas <josh@mozilla.com>
31 * Mats Palmgren <mats.palmgren@bredband.net>
33 * Alternatively, the contents of this file may be used under the terms of
34 * either of the GNU General Public License Version 2 or later (the "GPL"),
35 * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
36 * in which case the provisions of the GPL or the LGPL are applicable instead
37 * of those above. If you wish to allow use of your version of this file only
38 * under the terms of either the GPL or the LGPL, and not to allow others to
39 * use your version of this file under the terms of the MPL, indicate your
40 * decision by deleting the provisions above and replace them with the notice
41 * and other provisions required by the GPL or the LGPL. If you do not delete
42 * the provisions above, a recipient may use your version of this file under
43 * the terms of any one of the MPL, the GPL or the LGPL.
45 * ***** END LICENSE BLOCK ***** */
47 /* rendering objects for replaced elements implemented by a plugin */
49 #include "nscore.h"
50 #include "nsCOMPtr.h"
51 #include "nsPresContext.h"
52 #include "nsIPresShell.h"
53 #include "nsWidgetsCID.h"
54 #include "nsIView.h"
55 #include "nsIViewManager.h"
56 #include "nsIDOMKeyListener.h"
57 #ifdef MOZ_X11
58 #ifdef MOZ_WIDGET_QT
59 #include <QWidget>
60 #include <QX11Info>
61 #endif
62 #endif
63 #include "nsIPluginHost.h"
64 #include "nsplugin.h"
65 #include "nsString.h"
66 #include "nsReadableUtils.h"
67 #include "prmem.h"
68 #include "nsGkAtoms.h"
69 #include "nsIAppShell.h"
70 #include "nsIDocument.h"
71 #include "nsINodeInfo.h"
72 #include "nsIURL.h"
73 #include "nsNetUtil.h"
74 #include "nsIPluginInstanceOwner.h"
75 #include "plstr.h"
76 #include "nsILinkHandler.h"
77 #ifdef OJI
78 #include "nsIJVMPluginTagInfo.h"
79 #endif
80 #include "nsIEventListener.h"
81 #include "nsIScrollableView.h"
82 #include "nsIScrollPositionListener.h"
83 #include "nsITimer.h"
84 #include "nsIDocShellTreeItem.h"
85 #include "nsIDocShellTreeOwner.h"
86 #include "nsDocShellCID.h"
87 #include "nsIWebBrowserChrome.h"
88 #include "nsIDOMElement.h"
89 #include "nsIDOMNodeList.h"
90 #include "nsIDOMHTMLObjectElement.h"
91 #include "nsIDOMHTMLEmbedElement.h"
92 #include "nsIDOMHTMLAppletElement.h"
93 #include "nsIDOMWindow.h"
94 #include "nsIDOMDocumentEvent.h"
95 #include "nsIDOMMouseListener.h"
96 #include "nsIDOMMouseMotionListener.h"
97 #include "nsIDOMFocusListener.h"
98 #include "nsIDOMContextMenuListener.h"
99 #include "nsIDOMDragListener.h"
100 #include "nsIDOMEventTarget.h"
101 #include "nsIDOMNSEvent.h"
102 #include "nsIPrivateDOMEvent.h"
103 #include "nsIDocumentEncoder.h"
104 #include "nsXPIDLString.h"
105 #include "nsIDOMRange.h"
106 #include "nsIPluginWidget.h"
107 #include "nsGUIEvent.h"
108 #include "nsIRenderingContext.h"
109 #include "npapi.h"
110 #include "nsTransform2D.h"
111 #include "nsIImageLoadingContent.h"
112 #include "nsIObjectLoadingContent.h"
113 #include "nsPIDOMWindow.h"
114 #include "nsContentUtils.h"
115 #include "nsDisplayList.h"
116 #include "nsAttrName.h"
117 #include "nsDataHashtable.h"
118 #include "nsDOMClassInfo.h"
120 // headers for plugin scriptability
121 #include "nsIScriptGlobalObject.h"
122 #include "nsIScriptContext.h"
123 #include "nsIXPConnect.h"
124 #include "nsIXPCScriptable.h"
125 #include "nsIClassInfo.h"
127 #include "nsObjectFrame.h"
128 #include "nsIObjectFrame.h"
129 #include "nsPluginNativeWindow.h"
130 #include "nsPIPluginHost.h"
131 #include "nsIPluginDocument.h"
133 #include "nsThreadUtils.h"
135 #include "gfxContext.h"
137 #ifdef XP_WIN
138 #include "gfxWindowsNativeDrawing.h"
139 #endif
141 // accessibility support
142 #ifdef ACCESSIBILITY
143 #include "nsIAccessibilityService.h"
144 #endif
146 #ifdef MOZ_LOGGING
147 #define FORCE_PR_LOG 1 /* Allow logging in the release build */
148 #endif /* MOZ_LOGGING */
149 #include "prlog.h"
151 #include <errno.h>
153 #include "nsContentCID.h"
154 static NS_DEFINE_CID(kRangeCID, NS_RANGE_CID);
155 static NS_DEFINE_CID(kAppShellCID, NS_APPSHELL_CID);
157 #ifdef XP_MACOSX
158 #include "gfxQuartzNativeDrawing.h"
159 #endif
161 #ifdef MOZ_X11
162 #include <X11/Xlib.h>
163 /* X headers suck */
164 enum { XKeyPress = KeyPress };
165 #ifdef KeyPress
166 #undef KeyPress
167 #endif
168 #ifdef MOZ_WIDGET_GTK2
169 #include <gdk/gdkwindow.h>
170 #include <gdk/gdkx.h>
171 #endif
172 #endif
174 #ifdef MOZ_WIDGET_GTK2
175 #include "gfxGdkNativeRenderer.h"
176 #endif
178 #ifdef MOZ_WIDGET_QT
179 #include "gfxQtNativeRenderer.h"
180 #endif
182 #ifdef XP_WIN
183 #include <wtypes.h>
184 #include <winuser.h>
185 #endif
187 #ifdef CreateEvent // Thank you MS.
188 #undef CreateEvent
189 #endif
191 #ifdef PR_LOGGING
192 static PRLogModuleInfo *nsObjectFrameLM = PR_NewLogModule("nsObjectFrame");
193 #endif /* PR_LOGGING */
195 // 1020 / 60
196 #define NORMAL_PLUGIN_DELAY 17
198 // low enough to avoid audio skipping/delays
199 #define HIDDEN_PLUGIN_DELAY 100
201 // special class for handeling DOM context menu events because for
202 // some reason it starves other mouse events if implemented on the
203 // same class
204 class nsPluginDOMContextMenuListener : public nsIDOMContextMenuListener,
205 public nsIEventListener
207 public:
208 nsPluginDOMContextMenuListener();
209 virtual ~nsPluginDOMContextMenuListener();
211 NS_DECL_ISUPPORTS
213 NS_IMETHOD ContextMenu(nsIDOMEvent* aContextMenuEvent);
215 nsresult Init(nsIContent* aContent);
216 nsresult Destroy(nsIContent* aContent);
218 NS_IMETHOD HandleEvent(nsIDOMEvent* aEvent)
220 return NS_OK;
222 nsEventStatus ProcessEvent(const nsGUIEvent& anEvent)
224 return nsEventStatus_eConsumeNoDefault;
229 class nsPluginInstanceOwner : public nsIPluginInstanceOwner,
230 public nsIPluginTagInfo2,
231 #ifdef OJI
232 public nsIJVMPluginTagInfo,
233 #endif
234 public nsIEventListener,
235 public nsITimerCallback,
236 public nsIDOMMouseListener,
237 public nsIDOMMouseMotionListener,
238 public nsIDOMKeyListener,
239 public nsIDOMFocusListener,
240 public nsIScrollPositionListener,
241 public nsIDOMDragListener
244 public:
245 nsPluginInstanceOwner();
246 virtual ~nsPluginInstanceOwner();
248 NS_DECL_ISUPPORTS
250 //nsIPluginInstanceOwner interface
252 NS_IMETHOD SetInstance(nsIPluginInstance *aInstance);
254 NS_IMETHOD GetInstance(nsIPluginInstance *&aInstance);
256 NS_IMETHOD GetWindow(nsPluginWindow *&aWindow);
258 NS_IMETHOD GetMode(nsPluginMode *aMode);
260 NS_IMETHOD CreateWidget(void);
262 NS_IMETHOD GetURL(const char *aURL, const char *aTarget, void *aPostData,
263 PRUint32 aPostDataLen, void *aHeadersData,
264 PRUint32 aHeadersDataLen, PRBool isFile = PR_FALSE);
266 NS_IMETHOD ShowStatus(const char *aStatusMsg);
268 NS_IMETHOD ShowStatus(const PRUnichar *aStatusMsg);
270 NS_IMETHOD GetDocument(nsIDocument* *aDocument);
272 NS_IMETHOD InvalidateRect(nsPluginRect *invalidRect);
274 NS_IMETHOD InvalidateRegion(nsPluginRegion invalidRegion);
276 NS_IMETHOD ForceRedraw();
278 NS_IMETHOD GetValue(nsPluginInstancePeerVariable variable, void *value);
280 //nsIPluginTagInfo interface
282 NS_IMETHOD GetAttributes(PRUint16& n, const char*const*& names,
283 const char*const*& values);
285 NS_IMETHOD GetAttribute(const char* name, const char* *result);
287 //nsIPluginTagInfo2 interface
289 NS_IMETHOD GetTagType(nsPluginTagType *result);
291 NS_IMETHOD GetTagText(const char* *result);
293 NS_IMETHOD GetParameters(PRUint16& n, const char*const*& names, const char*const*& values);
295 NS_IMETHOD GetParameter(const char* name, const char* *result);
297 NS_IMETHOD GetDocumentBase(const char* *result);
299 NS_IMETHOD GetDocumentEncoding(const char* *result);
301 NS_IMETHOD GetAlignment(const char* *result);
303 NS_IMETHOD GetWidth(PRUint32 *result);
305 NS_IMETHOD GetHeight(PRUint32 *result);
307 NS_IMETHOD GetBorderVertSpace(PRUint32 *result);
309 NS_IMETHOD GetBorderHorizSpace(PRUint32 *result);
311 NS_IMETHOD GetUniqueID(PRUint32 *result);
313 NS_IMETHOD GetDOMElement(nsIDOMElement* *result);
315 #ifdef OJI
316 //nsIJVMPluginTagInfo interface
318 NS_IMETHOD GetCode(const char* *result);
320 NS_IMETHOD GetCodeBase(const char* *result);
322 NS_IMETHOD GetArchive(const char* *result);
324 NS_IMETHOD GetName(const char* *result);
326 NS_IMETHOD GetMayScript(PRBool *result);
328 #endif /* OJI */
330 /** nsIDOMMouseListener interfaces
331 * @see nsIDOMMouseListener
333 NS_IMETHOD MouseDown(nsIDOMEvent* aMouseEvent);
334 NS_IMETHOD MouseUp(nsIDOMEvent* aMouseEvent);
335 NS_IMETHOD MouseClick(nsIDOMEvent* aMouseEvent);
336 NS_IMETHOD MouseDblClick(nsIDOMEvent* aMouseEvent);
337 NS_IMETHOD MouseOver(nsIDOMEvent* aMouseEvent);
338 NS_IMETHOD MouseOut(nsIDOMEvent* aMouseEvent);
339 NS_IMETHOD HandleEvent(nsIDOMEvent* aEvent);
340 /* END interfaces from nsIDOMMouseListener*/
342 // nsIDOMMouseListener intefaces
343 NS_IMETHOD MouseMove(nsIDOMEvent* aMouseEvent);
344 NS_IMETHOD DragMove(nsIDOMEvent* aMouseEvent) { return NS_OK; }
346 // nsIDOMKeyListener interfaces
347 NS_IMETHOD KeyDown(nsIDOMEvent* aKeyEvent);
348 NS_IMETHOD KeyUp(nsIDOMEvent* aKeyEvent);
349 NS_IMETHOD KeyPress(nsIDOMEvent* aKeyEvent);
350 // end nsIDOMKeyListener interfaces
352 // nsIDOMFocuListener interfaces
353 NS_IMETHOD Focus(nsIDOMEvent * aFocusEvent);
354 NS_IMETHOD Blur(nsIDOMEvent * aFocusEvent);
356 // nsIDOMDragListener interfaces
357 NS_IMETHOD DragEnter(nsIDOMEvent* aMouseEvent);
358 NS_IMETHOD DragOver(nsIDOMEvent* aMouseEvent);
359 NS_IMETHOD DragExit(nsIDOMEvent* aMouseEvent);
360 NS_IMETHOD DragDrop(nsIDOMEvent* aMouseEvent);
361 NS_IMETHOD DragGesture(nsIDOMEvent* aMouseEvent);
362 NS_IMETHOD Drag(nsIDOMEvent* aMouseEvent);
363 NS_IMETHOD DragEnd(nsIDOMEvent* aMouseEvent);
366 nsresult Destroy();
368 void PrepareToStop(PRBool aDelayedStop);
370 //nsIEventListener interface
371 nsEventStatus ProcessEvent(const nsGUIEvent & anEvent);
373 #ifdef XP_WIN
374 void Paint(const nsRect& aDirtyRect, HDC ndc);
375 #elif defined(XP_MACOSX)
376 void Paint(const nsRect& aDirtyRect);
377 #elif defined(MOZ_X11) || defined(MOZ_DFB)
378 void Paint(gfxContext* aContext,
379 const gfxRect& aFrameRect,
380 const gfxRect& aDirtyRect);
381 #elif defined(XP_OS2)
382 void Paint(const nsRect& aDirtyRect, HPS aHPS);
383 #endif
385 // nsITimerCallback interface
386 NS_DECL_NSITIMERCALLBACK
388 void CancelTimer();
389 void StartTimer(unsigned int aDelay);
391 // nsIScrollPositionListener interface
392 NS_IMETHOD ScrollPositionWillChange(nsIScrollableView* aScrollable, nscoord aX, nscoord aY);
393 NS_IMETHOD ScrollPositionDidChange(nsIScrollableView* aScrollable, nscoord aX, nscoord aY);
395 //locals
397 nsresult Init(nsPresContext* aPresContext, nsObjectFrame* aFrame,
398 nsIContent* aContent);
400 nsPluginPort* GetPluginPort();
401 void ReleasePluginPort(nsPluginPort * pluginPort);
403 void SetPluginHost(nsIPluginHost* aHost);
405 #ifdef XP_MACOSX
406 NPDrawingModel GetDrawingModel();
407 WindowRef FixUpPluginWindow(PRInt32 inPaintState);
408 void GUItoMacEvent(const nsGUIEvent& anEvent, EventRecord* origEvent, EventRecord& aMacEvent);
409 #endif
411 void SetOwner(nsObjectFrame *aOwner)
413 mOwner = aOwner;
416 PRUint32 GetLastEventloopNestingLevel() const {
417 return mLastEventloopNestingLevel;
420 void ConsiderNewEventloopNestingLevel() {
421 nsCOMPtr<nsIAppShell> appShell = do_GetService(kAppShellCID);
422 if (appShell) {
423 PRUint32 currentLevel = 0;
424 appShell->GetEventloopNestingLevel(&currentLevel);
425 #ifdef XP_MACOSX
426 // Cocoa widget code doesn't process UI events through the normal appshell
427 // event loop, so it needs an additional count here.
428 currentLevel++;
429 #else
430 // No idea how this happens... but Linux doesn't consistently process UI
431 // events through the appshell event loop. If we get a 0 here on any
432 // platform we increment the level just in case so that we make sure we
433 // always tear the plugin down eventually.
434 if (!currentLevel) {
435 currentLevel++;
437 #endif
438 if (currentLevel < mLastEventloopNestingLevel) {
439 mLastEventloopNestingLevel = currentLevel;
444 const char* GetPluginName()
446 if (mInstance && mPluginHost) {
447 nsCOMPtr<nsPIPluginHost> piPluginHost = do_QueryInterface(mPluginHost);
448 const char* name = NULL;
449 if (NS_SUCCEEDED(piPluginHost->GetPluginName(mInstance, &name)) &&
450 name)
451 return name;
453 return "";
456 private:
457 void FixUpURLS(const nsString &name, nsAString &value);
459 nsPluginNativeWindow *mPluginWindow;
460 nsCOMPtr<nsIPluginInstance> mInstance;
461 nsObjectFrame *mOwner;
462 nsCOMPtr<nsIContent> mContent;
463 nsCString mDocumentBase;
464 char *mTagText;
465 nsCOMPtr<nsIWidget> mWidget;
466 nsCOMPtr<nsITimer> mPluginTimer;
467 nsCOMPtr<nsIPluginHost> mPluginHost;
469 // Initially, the event loop nesting level we were created on, it's updated
470 // if we detect the appshell is on a lower level as long as we're not stopped.
471 // We delay DoStopPlugin() until the appshell reaches this level or lower.
472 PRUint32 mLastEventloopNestingLevel;
473 PRPackedBool mContentFocused;
474 PRPackedBool mWidgetVisible; // used on Mac to store our widget's visible state
476 // If true, destroy the widget on destruction. Used when plugin stop
477 // is being delayed to a safer point in time.
478 PRPackedBool mDestroyWidget;
479 PRUint16 mNumCachedAttrs;
480 PRUint16 mNumCachedParams;
481 char **mCachedAttrParamNames;
482 char **mCachedAttrParamValues;
484 // pointer to wrapper for nsIDOMContextMenuListener
485 nsRefPtr<nsPluginDOMContextMenuListener> mCXMenuListener;
487 nsresult DispatchKeyToPlugin(nsIDOMEvent* aKeyEvent);
488 nsresult DispatchMouseToPlugin(nsIDOMEvent* aMouseEvent);
489 nsresult DispatchFocusToPlugin(nsIDOMEvent* aFocusEvent);
491 nsresult EnsureCachedAttrParamArrays();
493 #if defined(MOZ_WIDGET_GTK2)
494 class Renderer : public gfxGdkNativeRenderer {
495 public:
496 Renderer(nsPluginWindow* aWindow, nsIPluginInstance* aInstance,
497 const nsIntSize& aPluginSize, const nsIntRect& aDirtyRect)
498 : mWindow(aWindow), mInstance(aInstance),
499 mPluginSize(aPluginSize), mDirtyRect(aDirtyRect)
501 virtual nsresult NativeDraw(GdkDrawable * drawable, short offsetX,
502 short offsetY, GdkRectangle * clipRects, PRUint32 numClipRects);
503 private:
504 nsPluginWindow* mWindow;
505 nsIPluginInstance* mInstance;
506 const nsIntSize& mPluginSize;
507 const nsIntRect& mDirtyRect;
509 #elif defined(MOZ_WIDGET_QT)
510 class Renderer : public gfxQtNativeRenderer {
511 public:
512 Renderer(nsPluginWindow* aWindow, nsIPluginInstance* aInstance,
513 const nsIntSize& aPluginSize, const nsIntRect& aDirtyRect)
514 : mWindow(aWindow), mInstance(aInstance),
515 mPluginSize(aPluginSize), mDirtyRect(aDirtyRect)
517 virtual nsresult NativeDraw(QWidget * drawable, short offsetX,
518 short offsetY, QRect * clipRects, PRUint32 numClipRects);
519 private:
520 nsPluginWindow* mWindow;
521 nsIPluginInstance* mInstance;
522 const nsIntSize& mPluginSize;
523 const nsIntRect& mDirtyRect;
525 #endif
529 #if defined(XP_WIN) || (defined(DO_DIRTY_INTERSECT) && defined(XP_MACOSX)) || defined(XP_OS2)
530 static void ConvertAppUnitsToPixels(const nsPresContext& aPresContext, const nsRect& aTwipsRect, nsIntRect& aPixelRect);
531 #endif
533 // Mac specific code to fix up port position and clip during paint
534 #ifdef XP_MACOSX
536 #ifdef DO_DIRTY_INTERSECT
537 // convert relative coordinates to absolute
538 static void ConvertRelativeToWindowAbsolute(nsIFrame* aFrame, nsPoint& aRel, nsPoint& aAbs, nsIWidget *&aContainerWidget);
539 #endif
541 enum { ePluginPaintIgnore, ePluginPaintEnable, ePluginPaintDisable };
543 #endif // XP_MACOSX
545 nsObjectFrame::nsObjectFrame(nsStyleContext* aContext)
546 : nsObjectFrameSuper(aContext)
548 PR_LOG(nsObjectFrameLM, PR_LOG_DEBUG,
549 ("Created new nsObjectFrame %p\n", this));
552 nsObjectFrame::~nsObjectFrame()
554 PR_LOG(nsObjectFrameLM, PR_LOG_DEBUG,
555 ("nsObjectFrame %p deleted\n", this));
558 NS_IMETHODIMP
559 nsObjectFrame::QueryInterface(const nsIID& aIID, void** aInstancePtr)
561 NS_PRECONDITION(aInstancePtr, "null out param");
563 if (aIID.Equals(NS_GET_IID(nsIObjectFrame))) {
564 *aInstancePtr = static_cast<nsIObjectFrame*>(this);
565 return NS_OK;
568 return nsObjectFrameSuper::QueryInterface(aIID, aInstancePtr);
571 NS_IMETHODIMP_(nsrefcnt) nsObjectFrame::AddRef(void)
573 NS_WARNING("not supported for frames");
574 return 1;
577 NS_IMETHODIMP_(nsrefcnt) nsObjectFrame::Release(void)
579 NS_WARNING("not supported for frames");
580 return 1;
583 #ifdef ACCESSIBILITY
584 NS_IMETHODIMP nsObjectFrame::GetAccessible(nsIAccessible** aAccessible)
586 nsCOMPtr<nsIAccessibilityService> accService = do_GetService("@mozilla.org/accessibilityService;1");
588 if (accService) {
589 return accService->CreateHTMLObjectFrameAccessible(this, aAccessible);
592 return NS_ERROR_FAILURE;
595 #ifdef XP_WIN
596 NS_IMETHODIMP nsObjectFrame::GetPluginPort(HWND *aPort)
598 *aPort = (HWND) mInstanceOwner->GetPluginPort();
599 return NS_OK;
601 #endif
602 #endif
605 static NS_DEFINE_CID(kWidgetCID, NS_CHILD_CID);
606 static NS_DEFINE_CID(kCPluginManagerCID, NS_PLUGINMANAGER_CID);
608 // #define DO_DIRTY_INTERSECT 1 // enable dirty rect intersection during paint
610 NS_IMETHODIMP
611 nsObjectFrame::Init(nsIContent* aContent,
612 nsIFrame* aParent,
613 nsIFrame* aPrevInFlow)
615 mPreventInstantiation = PR_FALSE;
617 PR_LOG(nsObjectFrameLM, PR_LOG_DEBUG,
618 ("Initializing nsObjectFrame %p for content %p\n", this, aContent));
620 return nsObjectFrameSuper::Init(aContent, aParent, aPrevInFlow);
623 void
624 nsObjectFrame::Destroy()
626 NS_ASSERTION(!mPreventInstantiation, "about to crash due to bug 136927");
628 // we need to finish with the plugin before native window is destroyed
629 // doing this in the destructor is too late.
630 StopPluginInternal(PR_TRUE);
632 nsObjectFrameSuper::Destroy();
635 NS_IMETHODIMP
636 nsObjectFrame::DidSetStyleContext()
638 if (HasView()) {
639 nsIView* view = GetView();
640 nsIViewManager* vm = view->GetViewManager();
641 if (vm) {
642 nsViewVisibility visibility =
643 IsHidden() ? nsViewVisibility_kHide : nsViewVisibility_kShow;
644 vm->SetViewVisibility(view, visibility);
648 return nsObjectFrameSuper::DidSetStyleContext();
651 nsIAtom*
652 nsObjectFrame::GetType() const
654 return nsGkAtoms::objectFrame;
657 #ifdef DEBUG
658 NS_IMETHODIMP
659 nsObjectFrame::GetFrameName(nsAString& aResult) const
661 return MakeFrameName(NS_LITERAL_STRING("ObjectFrame"), aResult);
663 #endif
665 nsresult
666 nsObjectFrame::CreateWidgetForView(nsIView* aView)
668 // Bug 179822: Create widget and allow non-unicode SubClass
669 nsWidgetInitData initData;
670 initData.mUnicode = PR_FALSE;
671 return aView->CreateWidget(kWidgetCID, &initData);
674 nsresult
675 nsObjectFrame::CreateWidget(nscoord aWidth,
676 nscoord aHeight,
677 PRBool aViewOnly)
679 nsIView* view = GetView();
680 NS_ASSERTION(view, "Object frames must have views");
681 if (!view) {
682 return NS_OK; //XXX why OK? MMP
685 nsIViewManager* viewMan = view->GetViewManager();
686 // mark the view as hidden since we don't know the (x,y) until Paint
687 // XXX is the above comment correct?
688 viewMan->SetViewVisibility(view, nsViewVisibility_kHide);
690 //this is ugly. it was ripped off from didreflow(). MMP
691 // Position and size view relative to its parent, not relative to our
692 // parent frame (our parent frame may not have a view).
694 nsIView* parentWithView;
695 nsPoint origin;
696 nsRect r(0, 0, mRect.width, mRect.height);
698 GetOffsetFromView(origin, &parentWithView);
699 viewMan->ResizeView(view, r);
700 viewMan->MoveViewTo(view, origin.x, origin.y);
702 if (!aViewOnly && !view->HasWidget()) {
703 nsresult rv = CreateWidgetForView(view);
704 if (NS_FAILED(rv)) {
705 return NS_OK; //XXX why OK? MMP
710 // Here we set the background color for this widget because some plugins will use
711 // the child window background color when painting. If it's not set, it may default to gray
712 // Sometimes, a frame doesn't have a background color or is transparent. In this
713 // case, walk up the frame tree until we do find a frame with a background color
714 for (nsIFrame* frame = this; frame; frame = frame->GetParent()) {
715 const nsStyleBackground* background = frame->GetStyleBackground();
716 if (!background->IsTransparent()) { // make sure we got an actual color
717 nsIWidget* win = view->GetWidget();
718 if (win)
719 win->SetBackgroundColor(background->mBackgroundColor);
720 break;
726 if (!IsHidden()) {
727 viewMan->SetViewVisibility(view, nsViewVisibility_kShow);
730 return NS_OK;
733 #define EMBED_DEF_WIDTH 240
734 #define EMBED_DEF_HEIGHT 200
736 /* virtual */ nscoord
737 nsObjectFrame::GetMinWidth(nsIRenderingContext *aRenderingContext)
739 nscoord result = 0;
741 if (!IsHidden(PR_FALSE)) {
742 nsIAtom *atom = mContent->Tag();
743 if (atom == nsGkAtoms::applet || atom == nsGkAtoms::embed) {
744 result = nsPresContext::CSSPixelsToAppUnits(EMBED_DEF_WIDTH);
748 DISPLAY_MIN_WIDTH(this, result);
749 return result;
752 /* virtual */ nscoord
753 nsObjectFrame::GetPrefWidth(nsIRenderingContext *aRenderingContext)
755 return nsObjectFrame::GetMinWidth(aRenderingContext);
758 void
759 nsObjectFrame::GetDesiredSize(nsPresContext* aPresContext,
760 const nsHTMLReflowState& aReflowState,
761 nsHTMLReflowMetrics& aMetrics)
763 // By default, we have no area
764 aMetrics.width = 0;
765 aMetrics.height = 0;
767 if (IsHidden(PR_FALSE)) {
768 return;
771 aMetrics.width = aReflowState.ComputedWidth();
772 aMetrics.height = aReflowState.ComputedHeight();
774 // for EMBED and APPLET, default to 240x200 for compatibility
775 nsIAtom *atom = mContent->Tag();
776 if (atom == nsGkAtoms::applet || atom == nsGkAtoms::embed) {
777 if (aMetrics.width == NS_UNCONSTRAINEDSIZE) {
778 aMetrics.width = PR_MIN(PR_MAX(nsPresContext::CSSPixelsToAppUnits(EMBED_DEF_WIDTH),
779 aReflowState.mComputedMinWidth),
780 aReflowState.mComputedMaxWidth);
782 if (aMetrics.height == NS_UNCONSTRAINEDSIZE) {
783 aMetrics.height = PR_MIN(PR_MAX(nsPresContext::CSSPixelsToAppUnits(EMBED_DEF_HEIGHT),
784 aReflowState.mComputedMinHeight),
785 aReflowState.mComputedMaxHeight);
788 #if defined (MOZ_WIDGET_GTK2)
789 // We need to make sure that the size of the object frame does not
790 // exceed the maximum size of X coordinates. See bug #225357 for
791 // more information. In theory Gtk2 can handle large coordinates,
792 // but underlying plugins can't.
793 aMetrics.height = PR_MIN(aPresContext->DevPixelsToAppUnits(PR_INT16_MAX), aMetrics.height);
794 aMetrics.width = PR_MIN(aPresContext->DevPixelsToAppUnits(PR_INT16_MAX), aMetrics.width);
795 #endif
798 // At this point, the width has an unconstrained value only if we have
799 // nothing to go on (no width set, no information from the plugin, nothing).
800 // Make up a number.
801 if (aMetrics.width == NS_UNCONSTRAINEDSIZE) {
802 aMetrics.width =
803 (aReflowState.mComputedMinWidth != NS_UNCONSTRAINEDSIZE) ?
804 aReflowState.mComputedMinWidth : 0;
807 // At this point, the height has an unconstrained value only in two cases:
808 // a) We are in standards mode with percent heights and parent is auto-height
809 // b) We have no height information at all.
810 // In either case, we have to make up a number.
811 if (aMetrics.height == NS_UNCONSTRAINEDSIZE) {
812 aMetrics.height =
813 (aReflowState.mComputedMinHeight != NS_UNCONSTRAINEDSIZE) ?
814 aReflowState.mComputedMinHeight : 0;
817 // XXXbz don't add in the border and padding, because we screw up our
818 // plugin's size and positioning if we do... Eventually we _do_ want to
819 // paint borders, though! At that point, we will need to adjust the desired
820 // size either here or in Reflow.... Further, we will need to fix Paint() to
821 // call the superclass in all cases.
824 NS_IMETHODIMP
825 nsObjectFrame::Reflow(nsPresContext* aPresContext,
826 nsHTMLReflowMetrics& aMetrics,
827 const nsHTMLReflowState& aReflowState,
828 nsReflowStatus& aStatus)
830 DO_GLOBAL_REFLOW_COUNT("nsObjectFrame");
831 DISPLAY_REFLOW(aPresContext, this, aReflowState, aMetrics, aStatus);
833 // Get our desired size
834 GetDesiredSize(aPresContext, aReflowState, aMetrics);
835 aMetrics.mOverflowArea = nsRect(0, 0,
836 aMetrics.width, aMetrics.height);
838 // delay plugin instantiation until all children have
839 // arrived. Otherwise there may be PARAMs or other stuff that the
840 // plugin needs to see that haven't arrived yet.
841 if (!GetContent()->IsDoneAddingChildren()) {
842 aStatus = NS_FRAME_COMPLETE;
843 return NS_OK;
846 // if we are printing or print previewing, bail for now
847 if (aPresContext->Medium() == nsGkAtoms::print) {
848 aStatus = NS_FRAME_COMPLETE;
849 return NS_OK;
852 FixupWindow(nsSize(aMetrics.width, aMetrics.height));
854 aStatus = NS_FRAME_COMPLETE;
856 NS_FRAME_SET_TRUNCATION(aStatus, aReflowState, aMetrics);
857 return NS_OK;
860 nsresult
861 nsObjectFrame::InstantiatePlugin(nsIPluginHost* aPluginHost,
862 const char* aMimeType,
863 nsIURI* aURI)
865 NS_ASSERTION(mPreventInstantiation,
866 "Instantiation should be prevented here!");
868 // If you add early return(s), be sure to balance this call to
869 // appShell->SuspendNative() with additional call(s) to
870 // appShell->ReturnNative().
871 nsCOMPtr<nsIAppShell> appShell = do_GetService(kAppShellCID);
872 if (appShell) {
873 appShell->SuspendNative();
876 NS_ASSERTION(mContent, "We should have a content node.");
878 nsIDocument* doc = mContent->GetOwnerDoc();
879 nsCOMPtr<nsIPluginDocument> pDoc (do_QueryInterface(doc));
881 nsresult rv;
882 if (pDoc) { /* full-page mode */
883 nsCOMPtr<nsIStreamListener> stream;
884 rv = aPluginHost->InstantiateFullPagePlugin(aMimeType, aURI,
885 /* resulting stream listener */ *getter_AddRefs(stream),
886 mInstanceOwner);
887 if (NS_SUCCEEDED(rv))
888 pDoc->SetStreamListener(stream);
889 } else { /* embedded mode */
890 rv = aPluginHost->InstantiateEmbeddedPlugin(aMimeType, aURI,
891 mInstanceOwner);
894 // Note that |this| may very well be destroyed already!
896 if (appShell) {
897 appShell->ResumeNative();
900 return rv;
903 void
904 nsObjectFrame::FixupWindow(const nsSize& aSize)
906 nsPresContext* presContext = PresContext();
908 if (!mInstanceOwner)
909 return;
911 nsPluginWindow *window;
912 mInstanceOwner->GetWindow(window);
914 NS_ENSURE_TRUE(window, /**/);
916 #ifdef XP_MACOSX
917 mInstanceOwner->FixUpPluginWindow(ePluginPaintDisable);
918 #endif
920 PRBool windowless = (window->type == nsPluginWindowType_Drawable);
922 nsPoint origin = GetWindowOriginInPixels(windowless);
924 window->x = origin.x;
925 window->y = origin.y;
927 window->width = presContext->AppUnitsToDevPixels(aSize.width);
928 window->height = presContext->AppUnitsToDevPixels(aSize.height);
930 // on the Mac we need to set the clipRect to { 0, 0, 0, 0 } for now. This will keep
931 // us from drawing on screen until the widget is properly positioned, which will not
932 // happen until we have finished the reflow process.
933 window->clipRect.top = 0;
934 window->clipRect.left = 0;
935 #ifdef XP_MACOSX
936 window->clipRect.bottom = 0;
937 window->clipRect.right = 0;
938 #else
939 window->clipRect.bottom = presContext->AppUnitsToDevPixels(aSize.height);
940 window->clipRect.right = presContext->AppUnitsToDevPixels(aSize.width);
941 #endif
944 void
945 nsObjectFrame::CallSetWindow()
947 nsPluginWindow *win = nsnull;
949 nsresult rv;
950 nsCOMPtr<nsIPluginInstance> pi;
951 if (!mInstanceOwner ||
952 NS_FAILED(rv = mInstanceOwner->GetInstance(*getter_AddRefs(pi))) ||
953 !pi ||
954 NS_FAILED(rv = mInstanceOwner->GetWindow(win)) ||
955 !win)
956 return;
958 nsPluginNativeWindow *window = (nsPluginNativeWindow *)win;
960 #ifdef XP_MACOSX
961 mInstanceOwner->FixUpPluginWindow(ePluginPaintDisable);
962 #endif
964 if (IsHidden())
965 return;
967 PRBool windowless = (window->type == nsPluginWindowType_Drawable);
969 nsPoint origin = GetWindowOriginInPixels(windowless);
971 window->x = origin.x;
972 window->y = origin.y;
974 // refresh the plugin port as well
975 window->window = mInstanceOwner->GetPluginPort();
977 // this will call pi->SetWindow and take care of window subclassing
978 // if needed, see bug 132759.
979 window->CallSetWindow(pi);
981 mInstanceOwner->ReleasePluginPort((nsPluginPort *)window->window);
984 PRBool
985 nsObjectFrame::IsFocusable(PRInt32 *aTabIndex, PRBool aWithMouse)
987 if (aTabIndex)
988 *aTabIndex = -1;
989 return nsObjectFrameSuper::IsFocusable(aTabIndex, aWithMouse);
992 PRBool
993 nsObjectFrame::IsHidden(PRBool aCheckVisibilityStyle) const
995 if (aCheckVisibilityStyle) {
996 if (!GetStyleVisibility()->IsVisibleOrCollapsed())
997 return PR_TRUE;
1000 // only <embed> tags support the HIDDEN attribute
1001 if (mContent->Tag() == nsGkAtoms::embed) {
1002 // Yes, these are really the kooky ways that you could tell 4.x
1003 // not to hide the <embed> once you'd put the 'hidden' attribute
1004 // on the tag...
1006 // HIDDEN w/ no attributes gets translated as we are hidden for
1007 // compatibility w/ 4.x and IE so we don't create a non-painting
1008 // widget in layout. See bug 188959.
1009 nsAutoString hidden;
1010 if (mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::hidden, hidden) &&
1011 (hidden.IsEmpty() ||
1012 !hidden.LowerCaseEqualsLiteral("false") &&
1013 !hidden.LowerCaseEqualsLiteral("no") &&
1014 !hidden.LowerCaseEqualsLiteral("off"))) {
1015 return PR_TRUE;
1019 return PR_FALSE;
1022 nsPoint nsObjectFrame::GetWindowOriginInPixels(PRBool aWindowless)
1024 nsIView * parentWithView;
1025 nsPoint origin(0,0);
1027 GetOffsetFromView(origin, &parentWithView);
1029 // if it's windowless, let's make sure we have our origin set right
1030 // it may need to be corrected, like after scrolling
1031 if (aWindowless && parentWithView) {
1032 // XXX Should this be replaced by nsIView::GetNearestWidget?
1033 // The implementation below doesn't handle cases where the widget's origin
1034 // doesn't coincide with its view's origin.
1036 nsIViewManager* parentVM = parentWithView->GetViewManager();
1038 // Walk up all the views and add up their positions until we
1039 // reach the first view with a window (non-null widget). This will give us our
1040 // position relative to the containing window which is what we want to give the plugin
1041 nsIView* theView = parentWithView;
1042 while (theView && !theView->GetWidget()) {
1043 if (theView->GetViewManager() != parentVM)
1044 break;
1046 origin += theView->GetPosition();
1047 theView = theView->GetParent();
1051 origin.x = PresContext()->AppUnitsToDevPixels(origin.x);
1052 origin.y = PresContext()->AppUnitsToDevPixels(origin.y);
1054 return origin;
1057 NS_IMETHODIMP
1058 nsObjectFrame::DidReflow(nsPresContext* aPresContext,
1059 const nsHTMLReflowState* aReflowState,
1060 nsDidReflowStatus aStatus)
1062 // Do this check before calling the superclass, as that clears
1063 // NS_FRAME_FIRST_REFLOW
1064 if (aStatus == NS_FRAME_REFLOW_FINISHED &&
1065 (GetStateBits() & NS_FRAME_FIRST_REFLOW)) {
1066 nsCOMPtr<nsIObjectLoadingContent> objContent(do_QueryInterface(mContent));
1067 NS_ASSERTION(objContent, "Why not an object loading content?");
1068 objContent->HasNewFrame(this);
1071 nsresult rv = nsObjectFrameSuper::DidReflow(aPresContext, aReflowState, aStatus);
1073 // The view is created hidden; once we have reflowed it and it has been
1074 // positioned then we show it.
1075 if (aStatus != NS_FRAME_REFLOW_FINISHED)
1076 return rv;
1078 if (HasView()) {
1079 nsIView* view = GetView();
1080 nsIViewManager* vm = view->GetViewManager();
1081 if (vm)
1082 vm->SetViewVisibility(view, IsHidden() ? nsViewVisibility_kHide : nsViewVisibility_kShow);
1085 // WMP10 needs an additional SetWindow call here (bug 391261)
1086 CallSetWindow();
1088 return rv;
1091 /* static */ void
1092 nsObjectFrame::PaintPrintPlugin(nsIFrame* aFrame, nsIRenderingContext* aCtx,
1093 const nsRect& aDirtyRect, nsPoint aPt)
1095 // FIXME - Bug 385435: Doesn't aDirtyRect need translating too?
1096 nsIRenderingContext::AutoPushTranslation translate(aCtx, aPt.x, aPt.y);
1097 static_cast<nsObjectFrame*>(aFrame)->PrintPlugin(*aCtx, aDirtyRect);
1100 /*static */ void
1101 nsObjectFrame::PaintPlugin(nsIFrame* aFrame, nsIRenderingContext* aCtx,
1102 const nsRect& aDirtyRect, nsPoint aPt)
1104 static_cast<nsObjectFrame*>(aFrame)->PaintPlugin(*aCtx, aDirtyRect, aPt);
1107 NS_IMETHODIMP
1108 nsObjectFrame::BuildDisplayList(nsDisplayListBuilder* aBuilder,
1109 const nsRect& aDirtyRect,
1110 const nsDisplayListSet& aLists)
1112 // XXX why are we painting collapsed object frames?
1113 if (!IsVisibleOrCollapsedForPainting(aBuilder))
1114 return NS_OK;
1116 nsresult rv = DisplayBorderBackgroundOutline(aBuilder, aLists);
1117 NS_ENSURE_SUCCESS(rv, rv);
1119 nsPresContext::nsPresContextType type = PresContext()->Type();
1121 // If we are painting in Print Preview do nothing....
1122 if (type == nsPresContext::eContext_PrintPreview)
1123 return NS_OK;
1125 DO_GLOBAL_REFLOW_COUNT_DSP("nsObjectFrame");
1127 // determine if we are printing
1128 if (type == nsPresContext::eContext_Print)
1129 return aLists.Content()->AppendNewToTop(new (aBuilder)
1130 nsDisplayGeneric(this, PaintPrintPlugin, "PrintPlugin"));
1132 return aLists.Content()->AppendNewToTop(new (aBuilder)
1133 nsDisplayGeneric(this, PaintPlugin, "Plugin"));
1136 void
1137 nsObjectFrame::PrintPlugin(nsIRenderingContext& aRenderingContext,
1138 const nsRect& aDirtyRect)
1140 // if we are printing, we need to get the correct nsIPluginInstance
1141 // for THIS content node in order to call ->Print() on the right plugin
1143 // first, we need to get the document
1144 nsIDocument* doc = mContent->GetCurrentDoc();
1145 if (!doc)
1146 return;
1148 // now we need to get the shell for the screen
1149 // XXX assuming that the shell at zero will always be the screen one
1150 nsIPresShell *shell = doc->GetPrimaryShell();
1151 if (!shell)
1152 return;
1154 // then the shell can give us the screen frame for this content node
1155 nsIFrame* frame = shell->GetPrimaryFrameFor(mContent);
1156 if (!frame)
1157 return;
1159 nsPresContext* presContext = PresContext();
1160 // make sure this is REALLY an nsIObjectFrame
1161 // we may need to go through the children to get it
1162 nsIObjectFrame* objectFrame = nsnull;
1163 CallQueryInterface(frame,&objectFrame);
1164 if (!objectFrame)
1165 objectFrame = GetNextObjectFrame(presContext,frame);
1166 if (!objectFrame)
1167 return;
1169 // finally we can get our plugin instance
1170 nsCOMPtr<nsIPluginInstance> pi;
1171 if (NS_FAILED(objectFrame->GetPluginInstance(*getter_AddRefs(pi))) || !pi)
1172 return;
1174 // now we need to setup the correct location for printing
1175 nsresult rv;
1176 nsPluginWindow window;
1177 window.window = nsnull;
1179 // prepare embedded mode printing struct
1180 nsPluginPrint npprint;
1181 npprint.mode = nsPluginMode_Embedded;
1183 // we need to find out if we are windowless or not
1184 PRBool windowless = PR_FALSE;
1185 pi->GetValue(nsPluginInstanceVariable_WindowlessBool, (void *)&windowless);
1186 window.type = windowless ? nsPluginWindowType_Drawable : nsPluginWindowType_Window;
1188 window.clipRect.bottom = 0; window.clipRect.top = 0;
1189 window.clipRect.left = 0; window.clipRect.right = 0;
1191 // XXX platform specific printing code
1192 #if defined(XP_UNIX) && !defined(XP_MACOSX)
1194 /* XXX this just flat-out doesn't work in a thebes world --
1195 * RenderEPS is a no-op. So don't bother to do any work here.
1197 #if 0
1198 /* UNIX does things completely differently:
1199 * We call the plugin and it sends generated PostScript data into a
1200 * file handle we provide. If the plugin returns with success we embed
1201 * this PostScript code fragment into the PostScript job we send to the
1202 * printer.
1205 PR_LOG(nsObjectFrameLM, PR_LOG_DEBUG, ("nsObjectFrame::Paint() start for X11 platforms\n"));
1207 FILE *plugintmpfile = tmpfile();
1208 if (!plugintmpfile) {
1209 PR_LOG(nsObjectFrameLM, PR_LOG_DEBUG, ("error: could not open tmp. file, errno=%d\n", errno));
1210 return;
1213 /* Send off print info to plugin */
1214 NPPrintCallbackStruct npPrintInfo;
1215 npPrintInfo.type = NP_PRINT;
1216 npPrintInfo.fp = plugintmpfile;
1217 npprint.print.embedPrint.platformPrint = (void *)&npPrintInfo;
1218 /* aDirtyRect contains the right information for ps print */
1219 window.x = aDirtyRect.x;
1220 window.y = aDirtyRect.y;
1221 window.width = aDirtyRect.width;
1222 window.height = aDirtyRect.height;
1223 npprint.print.embedPrint.window = window;
1224 rv = pi->Print(&npprint);
1225 if (NS_FAILED(rv)) {
1226 PR_LOG(nsObjectFrameLM, PR_LOG_DEBUG, ("error: plugin returned failure %lx\n", (long)rv));
1227 fclose(plugintmpfile);
1228 return;
1231 /* Send data to printer */
1232 rv = aRenderingContext.RenderEPS(aDirtyRect, plugintmpfile);
1234 fclose(plugintmpfile);
1236 PR_LOG(nsObjectFrameLM, PR_LOG_DEBUG, ("plugin printing done, return code is %lx\n", (long)rv));
1237 #endif
1239 #elif defined(XP_OS2)
1240 void *hps = aRenderingContext.GetNativeGraphicData(nsIRenderingContext::NATIVE_OS2_PS);
1241 if (!hps)
1242 return;
1244 npprint.print.embedPrint.platformPrint = hps;
1245 npprint.print.embedPrint.window = window;
1246 // send off print info to plugin
1247 rv = pi->Print(&npprint);
1248 #elif defined(XP_WIN)
1250 /* On Windows, we use the win32 printing surface to print. This, in
1251 * turn, uses the Cairo paginated surface, which in turn uses the
1252 * meta surface to record all operations and then play them back.
1253 * This doesn't work too well for plugins, because if plugins render
1254 * directly into the DC, the meta surface won't have any knowledge
1255 * of them, and so at the end when it actually does the replay step,
1256 * it'll fill the background with white and draw over whatever was
1257 * rendered before.
1259 * So, to avoid this, we use PushGroup, which creates a new windows
1260 * surface, the plugin renders to that, and then we use normal
1261 * cairo methods to composite that in such that it's recorded using the
1262 * meta surface.
1265 /* we'll already be translated into the right spot by gfxWindowsNativeDrawing */
1266 window.x = 0;
1267 window.y = 0;
1268 window.width = presContext->AppUnitsToDevPixels(mRect.width);
1269 window.height = presContext->AppUnitsToDevPixels(mRect.height);
1271 gfxContext *ctx = aRenderingContext.ThebesContext();
1273 ctx->Save();
1275 /* Make sure plugins don't do any damage outside of where they're supposed to */
1276 ctx->NewPath();
1277 ctx->Rectangle(gfxRect(window.x, window.y,
1278 window.width, window.height));
1279 ctx->Clip();
1281 /* If we're windowless, we need to do COLOR_ALPHA, and do alpha recovery.
1282 * XXX - we could have some sort of flag here that would indicate whether
1283 * the plugin knows how to render to an ARGB DIB
1285 if (windowless)
1286 ctx->PushGroup(gfxASurface::CONTENT_COLOR_ALPHA);
1287 else
1288 ctx->PushGroup(gfxASurface::CONTENT_COLOR);
1290 gfxWindowsNativeDrawing nativeDraw(ctx,
1291 gfxRect(window.x, window.y,
1292 window.width, window.height));
1293 do {
1294 HDC dc = nativeDraw.BeginNativeDrawing();
1295 if (!dc)
1296 return;
1298 npprint.print.embedPrint.platformPrint = dc;
1299 npprint.print.embedPrint.window = window;
1300 // send off print info to plugin
1301 rv = pi->Print(&npprint);
1303 nativeDraw.EndNativeDrawing();
1304 } while (nativeDraw.ShouldRenderAgain());
1305 nativeDraw.PaintToContext();
1307 ctx->PopGroupToSource();
1308 ctx->Paint();
1310 ctx->Restore();
1312 #else
1314 // Get the offset of the DC
1315 nsTransform2D* rcTransform;
1316 aRenderingContext.GetCurrentTransform(rcTransform);
1317 nsPoint origin;
1318 rcTransform->GetTranslationCoord(&origin.x, &origin.y);
1320 // set it all up
1321 // XXX is windowless different?
1322 window.x = presContext->AppUnitsToDevPixels(origin.x);
1323 window.y = presContext->AppUnitsToDevPixels(origin.y);
1324 window.width = presContext->AppUnitsToDevPixels(mRect.width);
1325 window.height= presContext->AppUnitsToDevPixels(mRect.height);
1327 // we need the native printer device context to pass to plugin
1328 // NATIVE_WINDOWS_DC is a misnomer, it's whatever the native platform
1329 // thing is.
1330 void* dc;
1331 dc = aRenderingContext.GetNativeGraphicData(nsIRenderingContext::NATIVE_WINDOWS_DC);
1332 if (!dc)
1333 return; // no dc implemented so quit
1335 npprint.print.embedPrint.platformPrint = dc;
1336 npprint.print.embedPrint.window = window;
1337 // send off print info to plugin
1338 rv = pi->Print(&npprint);
1339 #endif
1341 // XXX Nav 4.x always sent a SetWindow call after print. Should we do the same?
1342 nsDidReflowStatus status = NS_FRAME_REFLOW_FINISHED; // should we use a special status?
1343 frame->DidReflow(presContext,
1344 nsnull, status); // DidReflow will take care of it
1347 void
1348 nsObjectFrame::PaintPlugin(nsIRenderingContext& aRenderingContext,
1349 const nsRect& aDirtyRect, const nsPoint& aFramePt)
1351 // Screen painting code
1352 #if defined(XP_MACOSX)
1353 // delegate all painting to the plugin instance.
1354 if (mInstanceOwner) {
1355 // FIXME - Bug 385435: Doesn't aDirtyRect need translating too?
1356 nsIRenderingContext::AutoPushTranslation
1357 translate(&aRenderingContext, aFramePt.x, aFramePt.y);
1359 if (mInstanceOwner->GetDrawingModel() == NPDrawingModelCoreGraphics) {
1360 PRInt32 p2a = PresContext()->AppUnitsPerDevPixel();
1361 gfxRect nativeClipRect(aDirtyRect.x, aDirtyRect.y,
1362 aDirtyRect.width, aDirtyRect.height);
1363 nativeClipRect.ScaleInverse(gfxFloat(p2a));
1364 gfxContext* ctx = aRenderingContext.ThebesContext();
1365 gfxQuartzNativeDrawing nativeDrawing(ctx, nativeClipRect);
1367 CGContextRef cgContext = nativeDrawing.BeginNativeDrawing();
1368 if (!cgContext) {
1369 NS_WARNING("null CGContextRef during PaintPlugin");
1370 return;
1373 // If gfxQuartzNativeDrawing hands out a CGContext other than the last
1374 // one we passed to the plugin, we need to pass the new one to the
1375 // plugin via SetWindow.
1376 // XXXkinetik it's not necessary to call SetWindow for every paint so
1377 // this should eventually be optimized to only do so when necessary
1378 nsPluginPort* pluginPort = mInstanceOwner->GetPluginPort();
1379 nsCOMPtr<nsIPluginInstance> inst;
1380 GetPluginInstance(*getter_AddRefs(inst));
1381 if (!inst) {
1382 NS_WARNING("null plugin instance during PaintPlugin");
1383 return;
1385 nsPluginWindow* window;
1386 mInstanceOwner->GetWindow(window);
1387 if (!window) {
1388 NS_WARNING("null plugin window during PaintPlugin");
1389 return;
1391 pluginPort->cgPort.context = cgContext;
1392 window->window = pluginPort;
1393 inst->SetWindow(window);
1395 mInstanceOwner->Paint(aDirtyRect);
1397 nativeDrawing.EndNativeDrawing();
1398 } else {
1399 mInstanceOwner->Paint(aDirtyRect);
1402 #elif defined(MOZ_X11) || defined(MOZ_DFB)
1403 if (mInstanceOwner)
1405 nsPluginWindow * window;
1406 mInstanceOwner->GetWindow(window);
1408 if (window->type == nsPluginWindowType_Drawable) {
1409 gfxRect frameGfxRect =
1410 PresContext()->AppUnitsToGfxUnits(nsRect(aFramePt, GetSize()));
1411 gfxRect dirtyGfxRect =
1412 PresContext()->AppUnitsToGfxUnits(aDirtyRect);
1413 gfxContext* ctx = aRenderingContext.ThebesContext();
1415 mInstanceOwner->Paint(ctx, frameGfxRect, dirtyGfxRect);
1418 #elif defined (XP_WIN) || defined(XP_OS2)
1419 nsCOMPtr<nsIPluginInstance> inst;
1420 GetPluginInstance(*getter_AddRefs(inst));
1421 if (inst) {
1422 // Look if it's windowless
1423 nsPluginWindow * window;
1424 mInstanceOwner->GetWindow(window);
1426 if (window->type == nsPluginWindowType_Drawable) {
1427 // FIXME - Bug 385435: Doesn't aDirtyRect need translating too?
1428 nsIRenderingContext::AutoPushTranslation
1429 translate(&aRenderingContext, aFramePt.x, aFramePt.y);
1431 // check if we need to call SetWindow with updated parameters
1432 PRBool doupdatewindow = PR_FALSE;
1433 // the offset of the DC
1434 nsPoint origin;
1437 * Layout now has an optimized way of painting. Now we always get
1438 * a new drawing surface, sized to be just what's needed. Windowless
1439 * plugins need a transform applied to their origin so they paint
1440 * in the right place. Since |SetWindow| is no longer being used
1441 * to tell the plugin where it is, we dispatch a NPWindow through
1442 * |HandleEvent| to tell the plugin when its window moved
1444 gfxContext *ctx = aRenderingContext.ThebesContext();
1445 gfxMatrix ctxMatrix = ctx->CurrentMatrix();
1446 if (ctxMatrix.HasNonTranslation()) {
1447 // soo; in the future, we should be able to render
1448 // the object content to an offscreen DC, and then
1449 // composite it in with the right transforms.
1451 // But, we don't bother doing that, because we don't
1452 // have the event handling story figured out yet.
1453 // Instead, let's just bail.
1455 return;
1458 origin.x = NSToIntRound(float(ctxMatrix.GetTranslation().x));
1459 origin.y = NSToIntRound(float(ctxMatrix.GetTranslation().y));
1461 /* Need to force the clip to be set */
1462 ctx->UpdateSurfaceClip();
1464 /* Set the device offsets as appropriate, for whatever our current group offsets might be */
1465 gfxFloat xoff, yoff;
1466 nsRefPtr<gfxASurface> surf = ctx->CurrentSurface(&xoff, &yoff);
1468 if (surf->CairoStatus() != 0) {
1469 NS_WARNING("Plugin is being asked to render to a surface that's in error!");
1470 return;
1473 #ifdef XP_WIN
1474 // check if we need to update hdc
1475 HDC hdc = (HDC)aRenderingContext.GetNativeGraphicData(nsIRenderingContext::NATIVE_WINDOWS_DC);
1477 if (reinterpret_cast<HDC>(window->window) != hdc) {
1478 window->window = reinterpret_cast<nsPluginPort*>(hdc);
1479 doupdatewindow = PR_TRUE;
1482 SaveDC(hdc);
1484 POINT origViewportOrigin;
1485 GetViewportOrgEx(hdc, &origViewportOrigin);
1486 SetViewportOrgEx(hdc, origViewportOrigin.x + (int) xoff, origViewportOrigin.y + (int) yoff, NULL);
1487 #else // do something similar on OS/2
1488 // check if we need to update the PS
1489 HPS hps = (HPS)aRenderingContext.GetNativeGraphicData(nsIRenderingContext::NATIVE_OS2_PS);
1490 if (reinterpret_cast<HPS>(window->window) != hps) {
1491 window->window = reinterpret_cast<nsPluginPort*>(hps);
1492 doupdatewindow = PR_TRUE;
1494 LONG lPSid = GpiSavePS(hps);
1495 RECTL rclViewport;
1496 if (GpiQueryDevice(hps) != NULLHANDLE) { // ensure that we have an associated HDC
1497 if (GpiQueryPageViewport(hps, &rclViewport)) {
1498 rclViewport.xLeft += (LONG)xoff;
1499 rclViewport.xRight += (LONG)xoff;
1500 rclViewport.yBottom += (LONG)yoff;
1501 rclViewport.yTop += (LONG)yoff;
1502 GpiSetPageViewport(hps, &rclViewport);
1505 #endif
1507 if ((window->x != origin.x) || (window->y != origin.y)) {
1508 window->x = origin.x;
1509 window->y = origin.y;
1510 doupdatewindow = PR_TRUE;
1513 // if our location or visible area has changed, we need to tell the plugin
1514 if (doupdatewindow) {
1515 #ifdef XP_WIN // Windowless plugins on windows need a special event to update their location, see bug 135737
1516 // bug 271442: note, the rectangle we send is now purely the bounds of the plugin
1517 // relative to the window it is contained in, which is useful for the plugin to correctly translate mouse coordinates
1519 // this does not mesh with the comments for bug 135737 which imply that the rectangle
1520 // must be clipped in some way to prevent the plugin attempting to paint over areas it shouldn't;
1522 // since the two uses of the rectangle are mutually exclusive in some cases,
1523 // and since I don't see any incorrect painting (at least with Flash and ViewPoint - the originator of 135737),
1524 // it seems that windowless plugins are not relying on information here for clipping their drawing,
1525 // and we can safely use this message to tell the plugin exactly where it is in all cases.
1527 origin = GetWindowOriginInPixels(PR_TRUE);
1528 nsRect winlessRect = nsRect(origin, nsSize(window->width, window->height));
1529 // XXX I don't think we can be certain that the location wrt to
1530 // the window only changes when the location wrt to the drawable
1531 // changes, but the hdc probably changes on every paint so
1532 // doupdatewindow is rarely false, and there is not likely to be
1533 // a problem.
1534 if (mWindowlessRect != winlessRect) {
1535 mWindowlessRect = winlessRect;
1537 WINDOWPOS winpos;
1538 memset(&winpos, 0, sizeof(winpos));
1539 winpos.x = mWindowlessRect.x;
1540 winpos.y = mWindowlessRect.y;
1541 winpos.cx = mWindowlessRect.width;
1542 winpos.cy = mWindowlessRect.height;
1544 // finally, update the plugin by sending it a WM_WINDOWPOSCHANGED event
1545 nsPluginEvent pluginEvent;
1546 pluginEvent.event = WM_WINDOWPOSCHANGED;
1547 pluginEvent.wParam = 0;
1548 pluginEvent.lParam = (uint32)&winpos;
1549 PRBool eventHandled = PR_FALSE;
1551 inst->HandleEvent(&pluginEvent, &eventHandled);
1553 #endif
1555 inst->SetWindow(window);
1558 #ifdef XP_WIN
1559 // FIXME - Bug 385435:
1560 // This expects a dirty rect relative to the plugin's rect
1561 // XXX I wonder if this breaks if we give the frame a border so the
1562 // frame origin and plugin origin are not the same
1563 mInstanceOwner->Paint(aDirtyRect, hdc);
1565 RestoreDC(hdc, -1);
1566 #else // do something similar on OS/2
1567 mInstanceOwner->Paint(aDirtyRect, hps);
1568 if (lPSid >= 1) {
1569 GpiRestorePS(hps, lPSid);
1571 #endif
1572 surf->MarkDirty();
1575 #endif
1578 NS_IMETHODIMP
1579 nsObjectFrame::HandleEvent(nsPresContext* aPresContext,
1580 nsGUIEvent* anEvent,
1581 nsEventStatus* anEventStatus)
1583 NS_ENSURE_ARG_POINTER(anEventStatus);
1584 nsresult rv = NS_OK;
1586 if (!mInstanceOwner)
1587 return NS_ERROR_NULL_POINTER;
1589 mInstanceOwner->ConsiderNewEventloopNestingLevel();
1591 if (anEvent->message == NS_PLUGIN_ACTIVATE) {
1592 nsIContent* content = GetContent();
1593 if (content) {
1594 content->SetFocus(aPresContext);
1595 return rv;
1599 #ifdef XP_WIN
1600 rv = nsObjectFrameSuper::HandleEvent(aPresContext, anEvent, anEventStatus);
1601 return rv;
1602 #endif
1604 switch (anEvent->message) {
1605 case NS_DESTROY:
1606 mInstanceOwner->CancelTimer();
1607 break;
1608 case NS_GOTFOCUS:
1609 case NS_LOSTFOCUS:
1610 *anEventStatus = mInstanceOwner->ProcessEvent(*anEvent);
1611 break;
1613 default:
1614 // instead of using an event listener, we can dispatch events to plugins directly.
1615 rv = nsObjectFrameSuper::HandleEvent(aPresContext, anEvent, anEventStatus);
1618 return rv;
1621 nsresult
1622 nsObjectFrame::GetPluginInstance(nsIPluginInstance*& aPluginInstance)
1624 aPluginInstance = nsnull;
1626 if (!mInstanceOwner)
1627 return NS_OK;
1629 return mInstanceOwner->GetInstance(aPluginInstance);
1632 nsresult
1633 nsObjectFrame::PrepareInstanceOwner()
1635 nsWeakFrame weakFrame(this);
1637 // First, have to stop any possibly running plugins.
1638 StopPluginInternal(PR_FALSE);
1640 if (!weakFrame.IsAlive()) {
1641 return NS_ERROR_NOT_AVAILABLE;
1644 NS_ASSERTION(!mInstanceOwner, "Must not have an instance owner here");
1646 mInstanceOwner = new nsPluginInstanceOwner();
1648 PR_LOG(nsObjectFrameLM, PR_LOG_DEBUG,
1649 ("Created new instance owner %p for frame %p\n", mInstanceOwner.get(),
1650 this));
1652 if (!mInstanceOwner)
1653 return NS_ERROR_OUT_OF_MEMORY;
1655 // Note, |this| may very well be gone after this call.
1656 return mInstanceOwner->Init(PresContext(), this, GetContent());
1659 nsresult
1660 nsObjectFrame::Instantiate(nsIChannel* aChannel, nsIStreamListener** aStreamListener)
1662 if (mPreventInstantiation) {
1663 return NS_OK;
1666 // Note: If PrepareInstanceOwner() returns an error, |this| may very
1667 // well be deleted already.
1668 nsresult rv = PrepareInstanceOwner();
1669 NS_ENSURE_SUCCESS(rv, rv);
1671 nsCOMPtr<nsIPluginHost> pluginHost(do_GetService(kCPluginManagerCID, &rv));
1672 if (NS_FAILED(rv))
1673 return rv;
1674 mInstanceOwner->SetPluginHost(pluginHost);
1676 // This must be done before instantiating the plugin
1677 FixupWindow(mRect.Size());
1679 nsWeakFrame weakFrame(this);
1681 NS_ASSERTION(!mPreventInstantiation, "Say what?");
1682 mPreventInstantiation = PR_TRUE;
1683 rv = pluginHost->InstantiatePluginForChannel(aChannel, mInstanceOwner, aStreamListener);
1685 if (!weakFrame.IsAlive()) {
1686 return NS_ERROR_NOT_AVAILABLE;
1689 NS_ASSERTION(mPreventInstantiation,
1690 "Instantiation should still be prevented!");
1691 mPreventInstantiation = PR_FALSE;
1693 return rv;
1696 nsresult
1697 nsObjectFrame::Instantiate(const char* aMimeType, nsIURI* aURI)
1699 PR_LOG(nsObjectFrameLM, PR_LOG_DEBUG,
1700 ("nsObjectFrame::Instantiate(%s) called on frame %p\n", aMimeType,
1701 this));
1703 if (mPreventInstantiation) {
1704 return NS_OK;
1707 NS_ASSERTION(aMimeType || aURI, "Need a type or a URI!");
1709 // Note: If PrepareInstanceOwner() returns an error, |this| may very
1710 // well be deleted already.
1711 nsresult rv = PrepareInstanceOwner();
1712 NS_ENSURE_SUCCESS(rv, rv);
1714 nsWeakFrame weakFrame(this);
1716 // This must be done before instantiating the plugin
1717 FixupWindow(mRect.Size());
1719 // get the nsIPluginHost service
1720 nsCOMPtr<nsIPluginHost> pluginHost(do_GetService(kCPluginManagerCID, &rv));
1721 if (NS_FAILED(rv))
1722 return rv;
1723 mInstanceOwner->SetPluginHost(pluginHost);
1725 mPreventInstantiation = PR_TRUE;
1727 rv = InstantiatePlugin(pluginHost, aMimeType, aURI);
1729 if (!weakFrame.IsAlive()) {
1730 return NS_ERROR_NOT_AVAILABLE;
1733 // finish up
1734 if (NS_SUCCEEDED(rv)) {
1735 TryNotifyContentObjectWrapper();
1737 if (!weakFrame.IsAlive()) {
1738 return NS_ERROR_NOT_AVAILABLE;
1741 CallSetWindow();
1744 NS_ASSERTION(mPreventInstantiation,
1745 "Instantiation should still be prevented!");
1747 mPreventInstantiation = PR_FALSE;
1749 return rv;
1752 void
1753 nsObjectFrame::TryNotifyContentObjectWrapper()
1755 nsCOMPtr<nsIPluginInstance> inst;
1756 mInstanceOwner->GetInstance(*getter_AddRefs(inst));
1757 if (inst) {
1758 // The plugin may have set up new interfaces; we need to mess with our JS
1759 // wrapper. Note that we DO NOT want to call this if there is no plugin
1760 // instance! That would just reenter Instantiate(), trying to create
1761 // said plugin instance.
1762 NotifyContentObjectWrapper();
1766 class nsStopPluginRunnable : public nsRunnable, public nsITimerCallback
1768 public:
1769 NS_DECL_ISUPPORTS_INHERITED
1771 nsStopPluginRunnable(nsPluginInstanceOwner *aInstanceOwner)
1772 : mInstanceOwner(aInstanceOwner)
1774 NS_ASSERTION(aInstanceOwner, "need an owner");
1777 // nsRunnable
1778 NS_IMETHOD Run();
1780 // nsITimerCallback
1781 NS_IMETHOD Notify(nsITimer *timer);
1783 private:
1784 nsCOMPtr<nsITimer> mTimer;
1785 nsRefPtr<nsPluginInstanceOwner> mInstanceOwner;
1788 NS_IMPL_ISUPPORTS_INHERITED1(nsStopPluginRunnable, nsRunnable, nsITimerCallback)
1790 #ifdef XP_WIN
1791 static const char*
1792 GetMIMEType(nsIPluginInstance *aPluginInstance)
1794 nsCOMPtr<nsIPluginInstancePeer> peer;
1795 aPluginInstance->GetPeer(getter_AddRefs(peer));
1796 if (peer) {
1797 nsMIMEType mime = NULL;
1798 if (NS_SUCCEEDED(peer->GetMIMEType(&mime)) && mime)
1799 return mime;
1801 return "";
1803 #endif
1805 static PRBool
1806 MatchPluginName(nsPluginInstanceOwner *aInstanceOwner, const char *aPluginName)
1808 return strncmp(aInstanceOwner->GetPluginName(),
1809 aPluginName,
1810 strlen(aPluginName)) == 0;
1813 static PRBool
1814 DoDelayedStop(nsPluginInstanceOwner *aInstanceOwner, PRBool aDelayedStop)
1816 // Don't delay stopping QuickTime (bug 425157), Flip4Mac (bug 426524),
1817 // XStandard (bug 430219), CMISS Zinc (bug 429604).
1818 if (aDelayedStop
1819 #ifndef XP_WIN
1820 && !::MatchPluginName(aInstanceOwner, "QuickTime")
1821 && !::MatchPluginName(aInstanceOwner, "Flip4Mac")
1822 && !::MatchPluginName(aInstanceOwner, "XStandard plugin")
1823 && !::MatchPluginName(aInstanceOwner, "CMISS Zinc Plugin")
1824 #endif
1826 nsCOMPtr<nsIRunnable> evt = new nsStopPluginRunnable(aInstanceOwner);
1827 NS_DispatchToCurrentThread(evt);
1828 return PR_TRUE;
1830 return PR_FALSE;
1833 static void
1834 DoStopPlugin(nsPluginInstanceOwner *aInstanceOwner, PRBool aDelayedStop)
1836 nsCOMPtr<nsIPluginInstance> inst;
1837 aInstanceOwner->GetInstance(*getter_AddRefs(inst));
1838 if (inst) {
1839 nsPluginWindow *win;
1840 aInstanceOwner->GetWindow(win);
1841 nsPluginNativeWindow *window = (nsPluginNativeWindow *)win;
1842 nsCOMPtr<nsIPluginInstance> nullinst;
1844 PRBool doCache = PR_TRUE;
1845 PRBool doCallSetWindowAfterDestroy = PR_FALSE;
1847 // first, determine if the plugin wants to be cached
1848 inst->GetValue(nsPluginInstanceVariable_DoCacheBool, (void *)&doCache);
1849 if (!doCache) {
1850 // then determine if the plugin wants Destroy to be called after
1851 // Set Window. This is for bug 50547.
1852 inst->GetValue(nsPluginInstanceVariable_CallSetWindowAfterDestroyBool,
1853 (void *)&doCallSetWindowAfterDestroy);
1854 if (doCallSetWindowAfterDestroy) {
1855 // XXXjst: ns4xPluginInstance::Destroy() is a no-op, clean
1856 // this mess up when there are no other instance types.
1857 inst->Stop();
1858 inst->Destroy();
1860 if (window)
1861 window->CallSetWindow(nullinst);
1862 else
1863 inst->SetWindow(nsnull);
1865 else {
1866 if (window)
1867 window->CallSetWindow(nullinst);
1868 else
1869 inst->SetWindow(nsnull);
1871 if (DoDelayedStop(aInstanceOwner, aDelayedStop))
1872 return;
1874 inst->Stop();
1875 inst->Destroy();
1878 else {
1879 if (window)
1880 window->CallSetWindow(nullinst);
1881 else
1882 inst->SetWindow(nsnull);
1884 if (DoDelayedStop(aInstanceOwner, aDelayedStop))
1885 return;
1887 inst->Stop();
1890 nsCOMPtr<nsIPluginHost> pluginHost = do_GetService(kCPluginManagerCID);
1891 if (pluginHost)
1892 pluginHost->StopPluginInstance(inst);
1894 // the frame is going away along with its widget so tell the
1895 // window to forget its widget too
1896 if (window)
1897 window->SetPluginWidget(nsnull);
1900 aInstanceOwner->Destroy();
1903 NS_IMETHODIMP
1904 nsStopPluginRunnable::Notify(nsITimer *aTimer)
1906 return Run();
1909 NS_IMETHODIMP
1910 nsStopPluginRunnable::Run()
1912 // InitWithCallback calls Release before AddRef so we need to hold a
1913 // strong ref on 'this' since we fall through to this scope if it fails.
1914 nsCOMPtr<nsITimerCallback> kungFuDeathGrip = this;
1915 nsCOMPtr<nsIAppShell> appShell = do_GetService(kAppShellCID);
1916 if (appShell) {
1917 PRUint32 currentLevel = 0;
1918 appShell->GetEventloopNestingLevel(&currentLevel);
1919 if (currentLevel > mInstanceOwner->GetLastEventloopNestingLevel()) {
1920 if (!mTimer)
1921 mTimer = do_CreateInstance("@mozilla.org/timer;1");
1922 if (mTimer) {
1923 // Fire 100ms timer to try to tear down this plugin as quickly as
1924 // possible once the nesting level comes back down.
1925 nsresult rv = mTimer->InitWithCallback(this, 100, nsITimer::TYPE_ONE_SHOT);
1926 if (NS_SUCCEEDED(rv)) {
1927 return rv;
1930 NS_ERROR("Failed to setup a timer to stop the plugin later (at a safe "
1931 "time). Stopping the plugin now, this might crash.");
1935 mTimer = nsnull;
1937 DoStopPlugin(mInstanceOwner, PR_FALSE);
1939 return NS_OK;
1942 void
1943 nsObjectFrame::StopPlugin()
1945 PRBool delayedStop = PR_FALSE;
1946 #ifdef XP_WIN
1947 nsCOMPtr<nsIPluginInstance> inst;
1948 if (mInstanceOwner)
1949 mInstanceOwner->GetInstance(*getter_AddRefs(inst));
1950 if (inst) {
1951 // Delayed stop for Real plugin only; see bug 420886, 426852.
1952 const char* pluginType = ::GetMIMEType(inst);
1953 delayedStop = strcmp(pluginType, "audio/x-pn-realaudio-plugin") == 0;
1955 #endif
1956 StopPluginInternal(delayedStop);
1959 void
1960 nsObjectFrame::StopPluginInternal(PRBool aDelayedStop)
1962 if (!mInstanceOwner) {
1963 return;
1966 // Transfer the reference to the instance owner onto the stack so
1967 // that if we do end up re-entering this code, or if we unwind back
1968 // here witha deleted frame (this), we can still continue to stop
1969 // the plugin. Note that due to that, the ordering of the code in
1970 // this function is extremely important.
1972 nsRefPtr<nsPluginInstanceOwner> owner;
1973 owner.swap(mInstanceOwner);
1975 // Make sure that our windowless rect has been zeroed out, so if we
1976 // get reinstantiated we'll send the right messages to the plug-in.
1977 mWindowlessRect.Empty();
1979 PRBool oldVal = mPreventInstantiation;
1980 mPreventInstantiation = PR_TRUE;
1982 nsWeakFrame weakFrame(this);
1984 #ifdef XP_WIN
1985 if (aDelayedStop) {
1986 // If we're asked to do a delayed stop it means we're stopping the
1987 // plugin because we're destroying the frame. In that case, tell
1988 // the view to disown the widget (i.e. leave it up to us to
1989 // destroy it).
1991 // Disown the view while we still know it's safe to do so.
1992 nsIView *view = GetView();
1993 if (view) {
1994 view->DisownWidget();
1997 #endif
1999 // From this point on, |this| could have been deleted, so don't
2000 // touch it!
2001 owner->PrepareToStop(aDelayedStop);
2003 DoStopPlugin(owner, aDelayedStop);
2005 // If |this| is still alive, reset mPreventInstantiation.
2006 if (weakFrame.IsAlive()) {
2007 NS_ASSERTION(mPreventInstantiation,
2008 "Instantiation should still be prevented!");
2010 mPreventInstantiation = oldVal;
2013 // Break relationship between frame and plugin instance owner
2014 owner->SetOwner(nsnull);
2017 void
2018 nsObjectFrame::NotifyContentObjectWrapper()
2020 nsCOMPtr<nsIDocument> doc = mContent->GetDocument();
2021 if (!doc)
2022 return;
2024 nsIScriptGlobalObject *sgo = doc->GetScriptGlobalObject();
2025 if (!sgo)
2026 return;
2028 nsIScriptContext *scx = sgo->GetContext();
2029 if (!scx)
2030 return;
2032 JSContext *cx = (JSContext *)scx->GetNativeContext();
2034 nsCOMPtr<nsIXPConnectWrappedNative> wrapper;
2035 nsContentUtils::XPConnect()->
2036 GetWrappedNativeOfNativeObject(cx, sgo->GetGlobalJSObject(), mContent,
2037 NS_GET_IID(nsISupports),
2038 getter_AddRefs(wrapper));
2040 if (!wrapper) {
2041 // Nothing to do here if there's no wrapper for mContent. The proto
2042 // chain will be fixed appropriately when the wrapper is created.
2043 return;
2046 JSObject *obj = nsnull;
2047 nsresult rv = wrapper->GetJSObject(&obj);
2048 if (NS_FAILED(rv))
2049 return;
2051 nsHTMLPluginObjElementSH::SetupProtoChain(wrapper, cx, obj);
2054 // static
2055 nsIObjectFrame *
2056 nsObjectFrame::GetNextObjectFrame(nsPresContext* aPresContext, nsIFrame* aRoot)
2058 nsIFrame* child = aRoot->GetFirstChild(nsnull);
2060 while (child) {
2061 nsIObjectFrame* outFrame = nsnull;
2062 CallQueryInterface(child, &outFrame);
2063 if (outFrame) {
2064 nsCOMPtr<nsIPluginInstance> pi;
2065 outFrame->GetPluginInstance(*getter_AddRefs(pi)); // make sure we have a REAL plugin
2066 if (pi)
2067 return outFrame;
2070 outFrame = GetNextObjectFrame(aPresContext, child);
2071 if (outFrame)
2072 return outFrame;
2073 child = child->GetNextSibling();
2076 return nsnull;
2079 nsIFrame*
2080 NS_NewObjectFrame(nsIPresShell* aPresShell, nsStyleContext* aContext)
2082 return new (aPresShell) nsObjectFrame(aContext);
2086 // nsPluginDOMContextMenuListener class implementation
2088 nsPluginDOMContextMenuListener::nsPluginDOMContextMenuListener()
2092 nsPluginDOMContextMenuListener::~nsPluginDOMContextMenuListener()
2096 NS_IMPL_ISUPPORTS3(nsPluginDOMContextMenuListener,
2097 nsIDOMContextMenuListener,
2098 nsIDOMEventListener,
2099 nsIEventListener)
2101 NS_IMETHODIMP
2102 nsPluginDOMContextMenuListener::ContextMenu(nsIDOMEvent* aContextMenuEvent)
2104 aContextMenuEvent->PreventDefault(); // consume event
2106 return NS_OK;
2109 nsresult nsPluginDOMContextMenuListener::Init(nsIContent* aContent)
2111 nsCOMPtr<nsIDOMEventTarget> receiver(do_QueryInterface(aContent));
2112 if (receiver) {
2113 receiver->AddEventListener(NS_LITERAL_STRING("contextmenu"), this, PR_TRUE);
2114 return NS_OK;
2117 return NS_ERROR_NO_INTERFACE;
2120 nsresult nsPluginDOMContextMenuListener::Destroy(nsIContent* aContent)
2122 // Unregister context menu listener
2123 nsCOMPtr<nsIDOMEventTarget> receiver(do_QueryInterface(aContent));
2124 if (receiver) {
2125 receiver->RemoveEventListener(NS_LITERAL_STRING("contextmenu"), this, PR_TRUE);
2128 return NS_OK;
2131 //plugin instance owner
2133 nsPluginInstanceOwner::nsPluginInstanceOwner()
2135 // create nsPluginNativeWindow object, it is derived from nsPluginWindow
2136 // struct and allows to manipulate native window procedure
2137 nsCOMPtr<nsIPluginHost> ph = do_GetService(kCPluginManagerCID);
2138 nsCOMPtr<nsPIPluginHost> pph(do_QueryInterface(ph));
2139 if (pph)
2140 pph->NewPluginNativeWindow(&mPluginWindow);
2141 else
2142 mPluginWindow = nsnull;
2144 mOwner = nsnull;
2145 mTagText = nsnull;
2146 mContentFocused = PR_FALSE;
2147 mWidgetVisible = PR_TRUE;
2148 mNumCachedAttrs = 0;
2149 mNumCachedParams = 0;
2150 mCachedAttrParamNames = nsnull;
2151 mCachedAttrParamValues = nsnull;
2152 mDestroyWidget = PR_FALSE;
2154 PR_LOG(nsObjectFrameLM, PR_LOG_DEBUG,
2155 ("nsPluginInstanceOwner %p created\n", this));
2158 nsPluginInstanceOwner::~nsPluginInstanceOwner()
2160 PRInt32 cnt;
2162 PR_LOG(nsObjectFrameLM, PR_LOG_DEBUG,
2163 ("nsPluginInstanceOwner %p deleted\n", this));
2165 // shut off the timer.
2166 if (mPluginTimer != nsnull) {
2167 CancelTimer();
2170 mOwner = nsnull;
2172 for (cnt = 0; cnt < (mNumCachedAttrs + 1 + mNumCachedParams); cnt++) {
2173 if (mCachedAttrParamNames && mCachedAttrParamNames[cnt]) {
2174 PR_Free(mCachedAttrParamNames[cnt]);
2175 mCachedAttrParamNames[cnt] = nsnull;
2178 if (mCachedAttrParamValues && mCachedAttrParamValues[cnt]) {
2179 PR_Free(mCachedAttrParamValues[cnt]);
2180 mCachedAttrParamValues[cnt] = nsnull;
2184 if (mCachedAttrParamNames) {
2185 PR_Free(mCachedAttrParamNames);
2186 mCachedAttrParamNames = nsnull;
2189 if (mCachedAttrParamValues) {
2190 PR_Free(mCachedAttrParamValues);
2191 mCachedAttrParamValues = nsnull;
2194 if (mTagText) {
2195 NS_Free(mTagText);
2196 mTagText = nsnull;
2199 // clean up plugin native window object
2200 nsCOMPtr<nsIPluginHost> ph = do_GetService(kCPluginManagerCID);
2201 nsCOMPtr<nsPIPluginHost> pph(do_QueryInterface(ph));
2202 if (pph) {
2203 pph->DeletePluginNativeWindow(mPluginWindow);
2204 mPluginWindow = nsnull;
2209 * nsISupports Implementation
2212 NS_IMPL_ADDREF(nsPluginInstanceOwner)
2213 NS_IMPL_RELEASE(nsPluginInstanceOwner)
2215 NS_INTERFACE_MAP_BEGIN(nsPluginInstanceOwner)
2216 NS_INTERFACE_MAP_ENTRY(nsIPluginInstanceOwner)
2217 NS_INTERFACE_MAP_ENTRY(nsIPluginTagInfo)
2218 NS_INTERFACE_MAP_ENTRY(nsIPluginTagInfo2)
2219 #ifdef OJI
2220 NS_INTERFACE_MAP_ENTRY(nsIJVMPluginTagInfo)
2221 #endif
2222 NS_INTERFACE_MAP_ENTRY(nsIEventListener)
2223 NS_INTERFACE_MAP_ENTRY(nsITimerCallback)
2224 NS_INTERFACE_MAP_ENTRY(nsIDOMMouseListener)
2225 NS_INTERFACE_MAP_ENTRY(nsIDOMMouseMotionListener)
2226 NS_INTERFACE_MAP_ENTRY(nsIDOMKeyListener)
2227 NS_INTERFACE_MAP_ENTRY(nsIDOMFocusListener)
2228 NS_INTERFACE_MAP_ENTRY(nsIScrollPositionListener)
2229 NS_INTERFACE_MAP_ENTRY(nsIDOMDragListener)
2230 NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsIDOMEventListener, nsIDOMMouseListener)
2231 NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIPluginInstanceOwner)
2232 NS_INTERFACE_MAP_END
2234 NS_IMETHODIMP nsPluginInstanceOwner::SetInstance(nsIPluginInstance *aInstance)
2236 mInstance = aInstance;
2238 return NS_OK;
2241 NS_IMETHODIMP nsPluginInstanceOwner::GetWindow(nsPluginWindow *&aWindow)
2243 NS_ASSERTION(mPluginWindow, "the plugin window object being returned is null");
2244 aWindow = mPluginWindow;
2245 return NS_OK;
2248 NS_IMETHODIMP nsPluginInstanceOwner::GetMode(nsPluginMode *aMode)
2250 nsCOMPtr<nsIDocument> doc;
2251 nsresult rv = GetDocument(getter_AddRefs(doc));
2252 nsCOMPtr<nsIPluginDocument> pDoc (do_QueryInterface(doc));
2254 if (pDoc) {
2255 *aMode = nsPluginMode_Full;
2256 } else {
2257 *aMode = nsPluginMode_Embedded;
2260 return rv;
2263 NS_IMETHODIMP nsPluginInstanceOwner::GetAttributes(PRUint16& n,
2264 const char*const*& names,
2265 const char*const*& values)
2267 nsresult rv = EnsureCachedAttrParamArrays();
2268 NS_ENSURE_SUCCESS(rv, rv);
2270 n = mNumCachedAttrs;
2271 names = (const char **)mCachedAttrParamNames;
2272 values = (const char **)mCachedAttrParamValues;
2274 return rv;
2277 NS_IMETHODIMP nsPluginInstanceOwner::GetAttribute(const char* name, const char* *result)
2279 NS_ENSURE_ARG_POINTER(name);
2280 NS_ENSURE_ARG_POINTER(result);
2282 nsresult rv = EnsureCachedAttrParamArrays();
2283 NS_ENSURE_SUCCESS(rv, rv);
2285 *result = nsnull;
2287 for (int i = 0; i < mNumCachedAttrs; i++) {
2288 if (0 == PL_strcasecmp(mCachedAttrParamNames[i], name)) {
2289 *result = mCachedAttrParamValues[i];
2290 return NS_OK;
2294 return NS_ERROR_FAILURE;
2297 NS_IMETHODIMP nsPluginInstanceOwner::GetDOMElement(nsIDOMElement* *result)
2299 return CallQueryInterface(mContent, result);
2302 NS_IMETHODIMP nsPluginInstanceOwner::GetInstance(nsIPluginInstance *&aInstance)
2304 NS_IF_ADDREF(aInstance = mInstance);
2306 return NS_OK;
2309 NS_IMETHODIMP nsPluginInstanceOwner::GetURL(const char *aURL, const char *aTarget, void *aPostData, PRUint32 aPostDataLen, void *aHeadersData,
2310 PRUint32 aHeadersDataLen, PRBool isFile)
2312 NS_ENSURE_TRUE(mOwner,NS_ERROR_NULL_POINTER);
2314 if (mContent->IsEditable()) {
2315 return NS_OK;
2318 // the container of the pres context will give us the link handler
2319 nsCOMPtr<nsISupports> container = mOwner->PresContext()->GetContainer();
2320 NS_ENSURE_TRUE(container,NS_ERROR_FAILURE);
2321 nsCOMPtr<nsILinkHandler> lh = do_QueryInterface(container);
2322 NS_ENSURE_TRUE(lh, NS_ERROR_FAILURE);
2324 nsAutoString unitarget;
2325 unitarget.AssignASCII(aTarget); // XXX could this be nonascii?
2327 nsCOMPtr<nsIURI> baseURI = mContent->GetBaseURI();
2329 // Create an absolute URL
2330 nsCOMPtr<nsIURI> uri;
2331 nsresult rv = NS_NewURI(getter_AddRefs(uri), aURL, baseURI);
2333 NS_ENSURE_SUCCESS(rv, NS_ERROR_FAILURE);
2335 nsCOMPtr<nsIInputStream> postDataStream;
2336 nsCOMPtr<nsIInputStream> headersDataStream;
2338 // deal with post data, either in a file or raw data, and any headers
2339 if (aPostData) {
2341 rv = NS_NewPluginPostDataStream(getter_AddRefs(postDataStream), (const char *)aPostData, aPostDataLen, isFile);
2343 NS_ASSERTION(NS_SUCCEEDED(rv),"failed in creating plugin post data stream");
2344 if (NS_FAILED(rv))
2345 return rv;
2347 if (aHeadersData) {
2348 rv = NS_NewPluginPostDataStream(getter_AddRefs(headersDataStream),
2349 (const char *) aHeadersData,
2350 aHeadersDataLen,
2351 PR_FALSE,
2352 PR_TRUE); // last arg says we are headers, no /r/n/r/n fixup!
2354 NS_ASSERTION(NS_SUCCEEDED(rv),"failed in creating plugin header data stream");
2355 if (NS_FAILED(rv))
2356 return rv;
2360 PRInt32 blockPopups =
2361 nsContentUtils::GetIntPref("privacy.popups.disable_from_plugins");
2362 nsAutoPopupStatePusher popupStatePusher((PopupControlState)blockPopups);
2364 rv = lh->OnLinkClick(mContent, uri, unitarget.get(),
2365 postDataStream, headersDataStream);
2367 return rv;
2370 NS_IMETHODIMP nsPluginInstanceOwner::ShowStatus(const char *aStatusMsg)
2372 nsresult rv = NS_ERROR_FAILURE;
2374 rv = this->ShowStatus(NS_ConvertUTF8toUTF16(aStatusMsg).get());
2376 return rv;
2379 NS_IMETHODIMP nsPluginInstanceOwner::ShowStatus(const PRUnichar *aStatusMsg)
2381 nsresult rv = NS_ERROR_FAILURE;
2383 if (!mOwner) {
2384 return rv;
2386 nsCOMPtr<nsISupports> cont = mOwner->PresContext()->GetContainer();
2387 if (!cont) {
2388 return NS_OK;
2391 nsCOMPtr<nsIDocShellTreeItem> docShellItem(do_QueryInterface(cont, &rv));
2392 if (NS_FAILED(rv) || !docShellItem) {
2393 return rv;
2396 nsCOMPtr<nsIDocShellTreeOwner> treeOwner;
2397 rv = docShellItem->GetTreeOwner(getter_AddRefs(treeOwner));
2398 if (NS_FAILED(rv) || !treeOwner) {
2399 return rv;
2402 nsCOMPtr<nsIWebBrowserChrome> browserChrome(do_GetInterface(treeOwner, &rv));
2403 if (NS_FAILED(rv) || !browserChrome) {
2404 return rv;
2406 rv = browserChrome->SetStatus(nsIWebBrowserChrome::STATUS_SCRIPT,
2407 aStatusMsg);
2409 return rv;
2412 NS_IMETHODIMP nsPluginInstanceOwner::GetDocument(nsIDocument* *aDocument)
2414 if (!aDocument)
2415 return NS_ERROR_NULL_POINTER;
2417 // XXX sXBL/XBL2 issue: current doc or owner doc?
2418 // But keep in mind bug 322414 comment 33
2419 NS_IF_ADDREF(*aDocument = mContent->GetOwnerDoc());
2420 return NS_OK;
2423 NS_IMETHODIMP nsPluginInstanceOwner::InvalidateRect(nsPluginRect *invalidRect)
2425 nsresult rv = NS_ERROR_FAILURE;
2427 if (mOwner && invalidRect && mWidgetVisible) {
2428 nsPresContext* presContext = mOwner->PresContext();
2429 nsRect rect(presContext->DevPixelsToAppUnits(invalidRect->left),
2430 presContext->DevPixelsToAppUnits(invalidRect->top),
2431 presContext->DevPixelsToAppUnits(invalidRect->right - invalidRect->left),
2432 presContext->DevPixelsToAppUnits(invalidRect->bottom - invalidRect->top));
2433 mOwner->Invalidate(rect);
2436 return rv;
2439 NS_IMETHODIMP nsPluginInstanceOwner::InvalidateRegion(nsPluginRegion invalidRegion)
2441 return NS_ERROR_NOT_IMPLEMENTED;
2444 NS_IMETHODIMP nsPluginInstanceOwner::ForceRedraw()
2446 NS_ENSURE_TRUE(mOwner,NS_ERROR_NULL_POINTER);
2447 nsIView* view = mOwner->GetView();
2448 if (view) {
2449 return view->GetViewManager()->Composite();
2452 return NS_OK;
2455 NS_IMETHODIMP nsPluginInstanceOwner::GetValue(nsPluginInstancePeerVariable variable, void *value)
2457 nsresult rv = NS_ERROR_FAILURE;
2459 switch(variable) {
2460 case nsPluginInstancePeerVariable_NetscapeWindow:
2462 if (mOwner) {
2463 #if defined(XP_WIN) || defined(XP_OS2)
2464 void** pvalue = (void**)value;
2465 nsIViewManager* vm = mOwner->PresContext()->GetViewManager();
2466 if (vm) {
2467 #if defined(XP_WIN)
2468 // This property is provided to allow a "windowless" plugin to determine the window it is drawing
2469 // in, so it can translate mouse coordinates it receives directly from the operating system
2470 // to coordinates relative to itself.
2472 // The original code (outside this #if) returns the document's window, which is OK if the window the "windowless" plugin
2473 // is drawing into has the same origin as the document's window, but this is not the case for "windowless" plugins inside of scrolling DIVs etc
2475 // To make sure "windowless" plugins always get the right origin for translating mouse coordinates, this code
2476 // determines the window handle of the mozilla window containing the "windowless" plugin.
2478 // Given that this HWND may not be that of the document's window, there is a slight risk
2479 // of confusing a plugin that is using this HWND for illicit purposes, but since the documentation
2480 // does not suggest this HWND IS that of the document window, rather that of the window
2481 // the plugin is drawn in, this seems like a safe fix.
2483 // we only attempt to get the nearest window if this really is a "windowless" plugin so as not
2484 // to change any behaviour for the much more common windowed plugins,
2485 // though why this method would even be being called for a windowed plugin escapes me.
2486 if (mPluginWindow && mPluginWindow->type == nsPluginWindowType_Drawable) {
2487 // it turns out that flash also uses this window for determining focus, and is currently
2488 // unable to show a caret correctly if we return the enclosing window. Therefore for
2489 // now we only return the enclosing window when there is an actual offset which
2490 // would otherwise cause coordinates to be offset incorrectly. (i.e.
2491 // if the enclosing window if offset from the document window)
2493 // fixing both the caret and ability to interact issues for a windowless control in a non document aligned windw
2494 // does not seem to be possible without a change to the flash plugin
2496 nsIWidget* win = mOwner->GetWindow();
2497 if (win) {
2498 nsIView *view = nsIView::GetViewFor(win);
2499 NS_ASSERTION(view, "No view for widget");
2500 nsIView *rootView = nsnull;
2501 vm->GetRootView(rootView);
2502 NS_ASSERTION(rootView, "No root view");
2503 nsPoint offset = view->GetOffsetTo(rootView);
2505 if (offset.x || offset.y) {
2506 // in the case the two windows are offset from eachother, we do go ahead and return the correct enclosing window
2507 // so that mouse co-ordinates are not messed up.
2508 *pvalue = (void*)win->GetNativeData(NS_NATIVE_WINDOW);
2509 if (*pvalue)
2510 return NS_OK;
2514 #endif
2515 // simply return the document window
2516 nsCOMPtr<nsIWidget> widget;
2517 rv = vm->GetWidget(getter_AddRefs(widget));
2518 if (widget) {
2519 *pvalue = (void*)widget->GetNativeData(NS_NATIVE_WINDOW);
2520 } else NS_ASSERTION(widget, "couldn't get doc's widget in getting doc's window handle");
2521 } else NS_ASSERTION(vm, "couldn't get view manager in getting doc's window handle");
2522 #elif defined(MOZ_WIDGET_GTK2)
2523 // X11 window managers want the toplevel window for WM_TRANSIENT_FOR.
2524 nsIWidget* win = mOwner->GetWindow();
2525 if (!win)
2526 return rv;
2527 GdkWindow* gdkWindow =
2528 static_cast<GdkWindow*>(win->GetNativeData(NS_NATIVE_WINDOW));
2529 if (!gdkWindow)
2530 return rv;
2531 gdkWindow = gdk_window_get_toplevel(gdkWindow);
2532 #ifdef MOZ_X11
2533 *static_cast<Window*>(value) = GDK_WINDOW_XID(gdkWindow);
2534 #endif
2535 return NS_OK;
2536 #endif
2537 } else NS_ASSERTION(mOwner, "plugin owner has no owner in getting doc's window handle");
2538 break;
2542 return rv;
2545 NS_IMETHODIMP nsPluginInstanceOwner::GetTagType(nsPluginTagType *result)
2547 NS_ENSURE_ARG_POINTER(result);
2549 *result = nsPluginTagType_Unknown;
2551 nsIAtom *atom = mContent->Tag();
2553 if (atom == nsGkAtoms::applet)
2554 *result = nsPluginTagType_Applet;
2555 else if (atom == nsGkAtoms::embed)
2556 *result = nsPluginTagType_Embed;
2557 else if (atom == nsGkAtoms::object)
2558 *result = nsPluginTagType_Object;
2560 return NS_OK;
2563 NS_IMETHODIMP nsPluginInstanceOwner::GetTagText(const char* *result)
2565 NS_ENSURE_ARG_POINTER(result);
2566 if (nsnull == mTagText) {
2567 nsresult rv;
2568 nsCOMPtr<nsIDOMNode> node(do_QueryInterface(mContent, &rv));
2569 if (NS_FAILED(rv))
2570 return rv;
2572 nsCOMPtr<nsIDocument> document;
2573 rv = GetDocument(getter_AddRefs(document));
2574 if (NS_FAILED(rv))
2575 return rv;
2577 nsCOMPtr<nsIDOMDocument> domDoc = do_QueryInterface(document);
2578 NS_ASSERTION(domDoc, "Need a document");
2580 nsCOMPtr<nsIDocumentEncoder> docEncoder(do_CreateInstance(NS_DOC_ENCODER_CONTRACTID_BASE "text/html", &rv));
2581 if (NS_FAILED(rv))
2582 return rv;
2583 rv = docEncoder->Init(domDoc, NS_LITERAL_STRING("text/html"), nsIDocumentEncoder::OutputEncodeBasicEntities);
2584 if (NS_FAILED(rv))
2585 return rv;
2587 nsCOMPtr<nsIDOMRange> range(do_CreateInstance(kRangeCID,&rv));
2588 if (NS_FAILED(rv))
2589 return rv;
2591 rv = range->SelectNode(node);
2592 if (NS_FAILED(rv))
2593 return rv;
2595 docEncoder->SetRange(range);
2596 nsString elementHTML;
2597 rv = docEncoder->EncodeToString(elementHTML);
2598 if (NS_FAILED(rv))
2599 return rv;
2601 mTagText = ToNewUTF8String(elementHTML);
2602 if (!mTagText)
2603 return NS_ERROR_OUT_OF_MEMORY;
2605 *result = mTagText;
2606 return NS_OK;
2609 NS_IMETHODIMP nsPluginInstanceOwner::GetParameters(PRUint16& n, const char*const*& names, const char*const*& values)
2611 nsresult rv = EnsureCachedAttrParamArrays();
2612 NS_ENSURE_SUCCESS(rv, rv);
2614 n = mNumCachedParams;
2615 if (n) {
2616 names = (const char **)(mCachedAttrParamNames + mNumCachedAttrs + 1);
2617 values = (const char **)(mCachedAttrParamValues + mNumCachedAttrs + 1);
2618 } else
2619 names = values = nsnull;
2621 return rv;
2624 NS_IMETHODIMP nsPluginInstanceOwner::GetParameter(const char* name, const char* *result)
2626 NS_ENSURE_ARG_POINTER(name);
2627 NS_ENSURE_ARG_POINTER(result);
2629 nsresult rv = EnsureCachedAttrParamArrays();
2630 NS_ENSURE_SUCCESS(rv, rv);
2632 *result = nsnull;
2634 for (int i = mNumCachedAttrs + 1; i < (mNumCachedParams + 1 + mNumCachedAttrs); i++) {
2635 if (0 == PL_strcasecmp(mCachedAttrParamNames[i], name)) {
2636 *result = mCachedAttrParamValues[i];
2637 return NS_OK;
2641 return NS_ERROR_FAILURE;
2644 NS_IMETHODIMP nsPluginInstanceOwner::GetDocumentBase(const char* *result)
2646 NS_ENSURE_ARG_POINTER(result);
2647 nsresult rv = NS_OK;
2648 if (mDocumentBase.IsEmpty()) {
2649 if (!mOwner) {
2650 *result = nsnull;
2651 return NS_ERROR_FAILURE;
2654 nsIDocument* doc = mContent->GetOwnerDoc();
2655 NS_ASSERTION(doc, "Must have an owner doc");
2656 rv = doc->GetBaseURI()->GetSpec(mDocumentBase);
2658 if (NS_SUCCEEDED(rv))
2659 *result = ToNewCString(mDocumentBase);
2660 return rv;
2663 static nsDataHashtable<nsDepCharHashKey, const char *> * gCharsetMap;
2664 typedef struct {
2665 char mozName[16];
2666 char javaName[12];
2667 } moz2javaCharset;
2669 /* XXX If you add any strings longer than
2670 * {"x-mac-cyrillic", "MacCyrillic"},
2671 * {"x-mac-ukrainian", "MacUkraine"},
2672 * to the following array then you MUST update the
2673 * sizes of the arrays in the moz2javaCharset struct
2676 static const moz2javaCharset charsets[] =
2678 {"windows-1252", "Cp1252"},
2679 {"IBM850", "Cp850"},
2680 {"IBM852", "Cp852"},
2681 {"IBM855", "Cp855"},
2682 {"IBM857", "Cp857"},
2683 {"IBM828", "Cp862"},
2684 {"IBM864", "Cp864"},
2685 {"IBM866", "Cp866"},
2686 {"windows-1250", "Cp1250"},
2687 {"windows-1251", "Cp1251"},
2688 {"windows-1253", "Cp1253"},
2689 {"windows-1254", "Cp1254"},
2690 {"windows-1255", "Cp1255"},
2691 {"windows-1256", "Cp1256"},
2692 {"windows-1257", "Cp1257"},
2693 {"windows-1258", "Cp1258"},
2694 {"EUC-JP", "EUC_JP"},
2695 {"EUC-KR", "EUC_KR"},
2696 {"x-euc-tw", "EUC_TW"},
2697 {"gb18030", "GB18030"},
2698 {"x-gbk", "GBK"},
2699 {"ISO-2022-JP", "ISO2022JP"},
2700 {"ISO-2022-KR", "ISO2022KR"},
2701 {"ISO-8859-2", "ISO8859_2"},
2702 {"ISO-8859-3", "ISO8859_3"},
2703 {"ISO-8859-4", "ISO8859_4"},
2704 {"ISO-8859-5", "ISO8859_5"},
2705 {"ISO-8859-6", "ISO8859_6"},
2706 {"ISO-8859-7", "ISO8859_7"},
2707 {"ISO-8859-8", "ISO8859_8"},
2708 {"ISO-8859-9", "ISO8859_9"},
2709 {"ISO-8859-13", "ISO8859_13"},
2710 {"x-johab", "Johab"},
2711 {"KOI8-R", "KOI8_R"},
2712 {"TIS-620", "MS874"},
2713 {"windows-936", "MS936"},
2714 {"x-windows-949", "MS949"},
2715 {"x-mac-arabic", "MacArabic"},
2716 {"x-mac-croatian", "MacCroatia"},
2717 {"x-mac-cyrillic", "MacCyrillic"},
2718 {"x-mac-greek", "MacGreek"},
2719 {"x-mac-hebrew", "MacHebrew"},
2720 {"x-mac-icelandic", "MacIceland"},
2721 {"x-mac-roman", "MacRoman"},
2722 {"x-mac-romanian", "MacRomania"},
2723 {"x-mac-ukrainian", "MacUkraine"},
2724 {"Shift_JIS", "SJIS"},
2725 {"TIS-620", "TIS620"}
2728 NS_IMETHODIMP nsPluginInstanceOwner::GetDocumentEncoding(const char* *result)
2730 NS_ENSURE_ARG_POINTER(result);
2731 *result = nsnull;
2733 nsresult rv;
2734 // XXX sXBL/XBL2 issue: current doc or owner doc?
2735 nsCOMPtr<nsIDocument> doc;
2736 rv = GetDocument(getter_AddRefs(doc));
2737 NS_ASSERTION(NS_SUCCEEDED(rv), "failed to get document");
2738 if (NS_FAILED(rv))
2739 return rv;
2741 const nsCString &charset = doc->GetDocumentCharacterSet();
2743 if (charset.IsEmpty())
2744 return NS_OK;
2746 // common charsets and those not requiring conversion first
2747 if (charset.EqualsLiteral("us-ascii")) {
2748 *result = PL_strdup("US_ASCII");
2749 } else if (charset.EqualsLiteral("ISO-8859-1") ||
2750 !nsCRT::strncmp(PromiseFlatCString(charset).get(), "UTF", 3)) {
2751 *result = ToNewCString(charset);
2752 } else {
2753 if (!gCharsetMap) {
2754 const int NUM_CHARSETS = sizeof(charsets) / sizeof(moz2javaCharset);
2755 gCharsetMap = new nsDataHashtable<nsDepCharHashKey, const char*>();
2756 if (!gCharsetMap || !gCharsetMap->Init(NUM_CHARSETS))
2757 return NS_ERROR_OUT_OF_MEMORY;
2759 for (PRUint16 i = 0; i < NUM_CHARSETS; i++) {
2760 gCharsetMap->Put(charsets[i].mozName, charsets[i].javaName);
2763 // if found mapping, return it; otherwise return original charset
2764 const char *mapping;
2765 *result = gCharsetMap->Get(charset.get(), &mapping) ? PL_strdup(mapping) :
2766 ToNewCString(charset);
2769 return (*result) ? NS_OK : NS_ERROR_OUT_OF_MEMORY;
2772 NS_IMETHODIMP nsPluginInstanceOwner::GetAlignment(const char* *result)
2774 return GetAttribute("ALIGN", result);
2777 NS_IMETHODIMP nsPluginInstanceOwner::GetWidth(PRUint32 *result)
2779 NS_ENSURE_ARG_POINTER(result);
2781 NS_ENSURE_TRUE(mPluginWindow, NS_ERROR_NULL_POINTER);
2783 *result = mPluginWindow->width;
2785 return NS_OK;
2788 NS_IMETHODIMP nsPluginInstanceOwner::GetHeight(PRUint32 *result)
2790 NS_ENSURE_ARG_POINTER(result);
2792 NS_ENSURE_TRUE(mPluginWindow, NS_ERROR_NULL_POINTER);
2794 *result = mPluginWindow->height;
2796 return NS_OK;
2800 NS_IMETHODIMP nsPluginInstanceOwner::GetBorderVertSpace(PRUint32 *result)
2802 nsresult rv;
2803 const char *vspace;
2805 rv = GetAttribute("VSPACE", &vspace);
2807 if (NS_OK == rv) {
2808 if (*result != 0)
2809 *result = (PRUint32)atol(vspace);
2810 else
2811 *result = 0;
2813 else
2814 *result = 0;
2816 return rv;
2819 NS_IMETHODIMP nsPluginInstanceOwner::GetBorderHorizSpace(PRUint32 *result)
2821 nsresult rv;
2822 const char *hspace;
2824 rv = GetAttribute("HSPACE", &hspace);
2826 if (NS_OK == rv) {
2827 if (*result != 0)
2828 *result = (PRUint32)atol(hspace);
2829 else
2830 *result = 0;
2832 else
2833 *result = 0;
2835 return rv;
2838 NS_IMETHODIMP nsPluginInstanceOwner::GetUniqueID(PRUint32 *result)
2840 NS_ENSURE_ARG_POINTER(result);
2841 *result = NS_PTR_TO_INT32(mOwner);
2842 return NS_OK;
2845 #ifdef OJI
2846 NS_IMETHODIMP nsPluginInstanceOwner::GetCode(const char* *result)
2848 nsresult rv;
2849 nsPluginTagType tagType;
2850 NS_ENSURE_SUCCESS(rv = GetTagType(&tagType), rv);
2852 rv = NS_ERROR_FAILURE;
2853 if (nsPluginTagType_Object != tagType)
2854 rv = GetAttribute("CODE", result);
2855 if (NS_FAILED(rv))
2856 rv = GetParameter("CODE", result);
2858 return rv;
2861 NS_IMETHODIMP nsPluginInstanceOwner::GetCodeBase(const char* *result)
2863 nsresult rv;
2864 if (NS_FAILED(rv = GetAttribute("CODEBASE", result)))
2865 rv = GetParameter("CODEBASE", result);
2866 return rv;
2869 NS_IMETHODIMP nsPluginInstanceOwner::GetArchive(const char* *result)
2871 nsresult rv;
2872 if (NS_FAILED(rv = GetAttribute("ARCHIVE", result)))
2873 rv = GetParameter("ARCHIVE", result);
2874 return rv;
2877 NS_IMETHODIMP nsPluginInstanceOwner::GetName(const char* *result)
2879 nsresult rv;
2880 nsPluginTagType tagType;
2881 NS_ENSURE_SUCCESS(rv = GetTagType(&tagType), rv);
2883 rv = NS_ERROR_FAILURE;
2884 if (nsPluginTagType_Object != tagType)
2885 rv = GetAttribute("NAME", result);
2886 if (NS_FAILED(rv))
2887 rv = GetParameter("NAME", result);
2889 return rv;
2892 NS_IMETHODIMP nsPluginInstanceOwner::GetMayScript(PRBool *result)
2894 NS_ENSURE_ARG_POINTER(result);
2895 nsPluginTagType tagType;
2896 NS_ENSURE_SUCCESS(GetTagType(&tagType), NS_ERROR_FAILURE);
2898 const char* unused;
2899 if (nsPluginTagType_Object == tagType)
2900 *result = NS_SUCCEEDED(GetParameter("MAYSCRIPT", &unused));
2901 else
2902 *result = NS_SUCCEEDED(GetAttribute("MAYSCRIPT", &unused));
2904 return NS_OK;
2906 #endif /* OJI */
2908 // Cache the attributes and/or parameters of our tag into a single set
2909 // of arrays to be compatible with 4.x. The attributes go first,
2910 // followed by a PARAM/null and then any PARAM tags. Also, hold the
2911 // cached array around for the duration of the life of the instance
2912 // because 4.x did. See bug 111008.
2914 nsresult nsPluginInstanceOwner::EnsureCachedAttrParamArrays()
2916 if (mCachedAttrParamValues)
2917 return NS_OK;
2919 NS_PRECONDITION(((mNumCachedAttrs + mNumCachedParams) == 0) &&
2920 !mCachedAttrParamNames,
2921 "re-cache of attrs/params not implemented! use the DOM "
2922 "node directy instead");
2923 NS_ENSURE_TRUE(mOwner, NS_ERROR_NULL_POINTER);
2925 // first, we need to find out how much we need to allocate for our
2926 // arrays count up attributes
2927 mNumCachedAttrs = 0;
2929 PRUint32 cattrs = mContent->GetAttrCount();
2931 if (cattrs < 0x0000FFFF) {
2932 // unsigned 32 bits to unsigned 16 bits conversion
2933 mNumCachedAttrs = static_cast<PRUint16>(cattrs);
2934 } else {
2935 mNumCachedAttrs = 0xFFFE; // minus one in case we add an extra "src" entry below
2938 // now, we need to find all the PARAM tags that are children of us
2939 // however, be carefull NOT to include any PARAMs that don't have us
2940 // as a direct parent. For nested object (or applet) tags, be sure
2941 // to only round up the param tags that coorespond with THIS
2942 // instance. And also, weed out any bogus tags that may get in the
2943 // way, see bug 39609. Then, with any param tag that meet our
2944 // qualification, temporarly cache them in an nsCOMArray until
2945 // we can figure out what size to make our fixed char* array.
2947 mNumCachedParams = 0;
2948 nsCOMArray<nsIDOMElement> ourParams;
2950 // use the DOM to get us ALL our dependent PARAM tags, even if not
2951 // ours
2952 nsCOMPtr<nsIDOMElement> mydomElement = do_QueryInterface(mContent);
2953 NS_ENSURE_TRUE(mydomElement, NS_ERROR_NO_INTERFACE);
2955 nsCOMPtr<nsIDOMNodeList> allParams;
2957 nsINodeInfo *ni = mContent->NodeInfo();
2959 // Making DOM method calls can cause our frame to go away, which
2960 // might kill us...
2961 nsCOMPtr<nsIPluginInstanceOwner> kungFuDeathGrip(this);
2963 if (ni->NamespaceEquals(kNameSpaceID_XHTML)) {
2964 // For XHTML elements we need to take the namespace URI into
2965 // account when looking for param elements.
2967 NS_NAMED_LITERAL_STRING(xhtml_ns, "http://www.w3.org/1999/xhtml");
2969 mydomElement->GetElementsByTagNameNS(xhtml_ns, NS_LITERAL_STRING("param"),
2970 getter_AddRefs(allParams));
2971 } else {
2972 // If content is not XHTML, it must be HTML, no need to worry
2973 // about namespaces then...
2975 mydomElement->GetElementsByTagName(NS_LITERAL_STRING("param"),
2976 getter_AddRefs(allParams));
2979 if (allParams) {
2980 PRUint32 numAllParams;
2981 allParams->GetLength(&numAllParams);
2982 // loop through every so called dependent PARAM tag to check if it
2983 // "belongs" to us
2985 for (PRUint32 i = 0; i < numAllParams; i++) {
2986 nsCOMPtr<nsIDOMNode> pnode;
2987 allParams->Item(i, getter_AddRefs(pnode));
2989 nsCOMPtr<nsIDOMElement> domelement = do_QueryInterface(pnode);
2990 if (domelement) {
2991 // let's NOT count up param tags that don't have a name attribute
2992 nsAutoString name;
2993 domelement->GetAttribute(NS_LITERAL_STRING("name"), name);
2994 if (!name.IsEmpty()) {
2995 nsCOMPtr<nsIDOMNode> parent;
2996 nsCOMPtr<nsIDOMHTMLObjectElement> domobject;
2997 nsCOMPtr<nsIDOMHTMLAppletElement> domapplet;
2998 pnode->GetParentNode(getter_AddRefs(parent));
2999 // walk up the parents of this PARAM until we find an object
3000 // (or applet) tag
3002 while (!(domobject || domapplet) && parent) {
3003 domobject = do_QueryInterface(parent);
3004 domapplet = do_QueryInterface(parent);
3005 nsCOMPtr<nsIDOMNode> temp;
3006 parent->GetParentNode(getter_AddRefs(temp));
3007 parent = temp;
3010 if (domapplet || domobject) {
3011 if (domapplet)
3012 parent = domapplet;
3013 else
3014 parent = domobject;
3016 // now check to see if this PARAM's parent is us. if so,
3017 // cache it for later
3019 nsCOMPtr<nsIDOMNode> mydomNode = do_QueryInterface(mydomElement);
3020 if (parent == mydomNode) {
3021 ourParams.AppendObject(domelement);
3029 // We're done with DOM method calls now; make sure we still have a frame.
3030 NS_ENSURE_TRUE(mOwner, NS_ERROR_OUT_OF_MEMORY);
3032 PRUint32 cparams = ourParams.Count(); // unsigned 32 bits to unsigned 16 bits conversion
3033 if (cparams < 0x0000FFFF)
3034 mNumCachedParams = static_cast<PRUint16>(cparams);
3035 else
3036 mNumCachedParams = 0xFFFF;
3038 // Some plugins were never written to understand the "data" attribute of the OBJECT tag.
3039 // Real and WMP will not play unless they find a "src" attribute, see bug 152334.
3040 // Nav 4.x would simply replace the "data" with "src". Because some plugins correctly
3041 // look for "data", lets instead copy the "data" attribute and add another entry
3042 // to the bottom of the array if there isn't already a "src" specified.
3043 PRInt16 numRealAttrs = mNumCachedAttrs;
3044 nsAutoString data;
3045 if (mContent->Tag() == nsGkAtoms::object
3046 && !mContent->HasAttr(kNameSpaceID_None, nsGkAtoms::src)
3047 && mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::data, data)) {
3048 mNumCachedAttrs++;
3051 // now lets make the arrays
3052 mCachedAttrParamNames = (char **)PR_Calloc(sizeof(char *) * (mNumCachedAttrs + 1 + mNumCachedParams), 1);
3053 NS_ENSURE_TRUE(mCachedAttrParamNames, NS_ERROR_OUT_OF_MEMORY);
3054 mCachedAttrParamValues = (char **)PR_Calloc(sizeof(char *) * (mNumCachedAttrs + 1 + mNumCachedParams), 1);
3055 NS_ENSURE_TRUE(mCachedAttrParamValues, NS_ERROR_OUT_OF_MEMORY);
3057 // let's fill in our attributes
3058 PRInt16 c = 0;
3060 // Some plugins (eg Flash, see bug 234675.) are actually sensitive to the
3061 // attribute order. So we want to make sure we give the plugin the
3062 // attributes in the order they came in in the source, to be compatible with
3063 // other browsers. Now in HTML, the storage order is the reverse of the
3064 // source order, while in XML and XHTML it's the same as the source order
3065 // (see the AddAttributes functions in the HTML and XML content sinks).
3066 PRInt16 start, end, increment;
3067 if (mContent->IsNodeOfType(nsINode::eHTML) &&
3068 mContent->NodeInfo()->NamespaceEquals(kNameSpaceID_None)) {
3069 // HTML. Walk attributes in reverse order.
3070 start = numRealAttrs - 1;
3071 end = -1;
3072 increment = -1;
3073 } else {
3074 // XHTML or XML. Walk attributes in forward order.
3075 start = 0;
3076 end = numRealAttrs;
3077 increment = 1;
3079 for (PRInt16 index = start; index != end; index += increment) {
3080 const nsAttrName* attrName = mContent->GetAttrNameAt(index);
3081 nsIAtom* atom = attrName->LocalName();
3082 nsAutoString value;
3083 mContent->GetAttr(attrName->NamespaceID(), atom, value);
3084 nsAutoString name;
3085 atom->ToString(name);
3087 FixUpURLS(name, value);
3089 mCachedAttrParamNames [c] = ToNewUTF8String(name);
3090 mCachedAttrParamValues[c] = ToNewUTF8String(value);
3091 c++;
3094 // if the conditions above were met, copy the "data" attribute to a "src" array entry
3095 if (data.Length()) {
3096 mCachedAttrParamNames [mNumCachedAttrs-1] = ToNewUTF8String(NS_LITERAL_STRING("SRC"));
3097 mCachedAttrParamValues[mNumCachedAttrs-1] = ToNewUTF8String(data);
3100 // add our PARAM and null separator
3101 mCachedAttrParamNames [mNumCachedAttrs] = ToNewUTF8String(NS_LITERAL_STRING("PARAM"));
3102 mCachedAttrParamValues[mNumCachedAttrs] = nsnull;
3104 // now fill in the PARAM name/value pairs from the cached DOM nodes
3105 c = 0;
3106 for (PRInt16 idx = 0; idx < mNumCachedParams; idx++) {
3107 nsIDOMElement* param = ourParams.ObjectAt(idx);
3108 if (param) {
3109 nsAutoString name;
3110 nsAutoString value;
3111 param->GetAttribute(NS_LITERAL_STRING("name"), name); // check for empty done above
3112 param->GetAttribute(NS_LITERAL_STRING("value"), value);
3114 FixUpURLS(name, value);
3117 * According to the HTML 4.01 spec, at
3118 * http://www.w3.org/TR/html4/types.html#type-cdata
3119 * ''User agents may ignore leading and trailing
3120 * white space in CDATA attribute values (e.g., "
3121 * myval " may be interpreted as "myval"). Authors
3122 * should not declare attribute values with
3123 * leading or trailing white space.''
3124 * However, do not trim consecutive spaces as in bug 122119
3126 name.Trim(" \n\r\t\b", PR_TRUE, PR_TRUE, PR_FALSE);
3127 value.Trim(" \n\r\t\b", PR_TRUE, PR_TRUE, PR_FALSE);
3128 mCachedAttrParamNames [mNumCachedAttrs + 1 + c] = ToNewUTF8String(name);
3129 mCachedAttrParamValues[mNumCachedAttrs + 1 + c] = ToNewUTF8String(value);
3130 c++; // rules!
3134 return NS_OK;
3138 // Here's where we forward events to plugins.
3140 #ifdef XP_MACOSX
3142 static void InitializeEventRecord(EventRecord* event)
3144 memset(event, 0, sizeof(EventRecord));
3145 ::GetGlobalMouse(&event->where);
3146 event->when = ::TickCount();
3147 event->modifiers = ::GetCurrentEventKeyModifiers();
3150 NPDrawingModel nsPluginInstanceOwner::GetDrawingModel()
3152 #ifndef NP_NO_QUICKDRAW
3153 NPDrawingModel drawingModel = NPDrawingModelQuickDraw;
3154 #else
3155 NPDrawingModel drawingModel = NPDrawingModelCoreGraphics;
3156 #endif
3158 if (!mInstance)
3159 return drawingModel;
3161 mInstance->GetValue(nsPluginInstanceVariable_DrawingModel,
3162 (void *)&drawingModel);
3164 return drawingModel;
3167 void nsPluginInstanceOwner::GUItoMacEvent(const nsGUIEvent& anEvent, EventRecord* origEvent, EventRecord& aMacEvent)
3169 nsPresContext* presContext = mOwner ? mOwner->PresContext() : nsnull;
3170 InitializeEventRecord(&aMacEvent);
3171 switch (anEvent.message) {
3172 case NS_FOCUS_EVENT_START: // this is the same as NS_FOCUS_CONTENT
3173 aMacEvent.what = nsPluginEventType_GetFocusEvent;
3174 if (presContext) {
3175 nsIContent* content = mContent;
3176 if (content)
3177 content->SetFocus(presContext);
3179 break;
3181 case NS_BLUR_CONTENT:
3182 aMacEvent.what = nsPluginEventType_LoseFocusEvent;
3183 if (presContext) {
3184 nsIContent* content = mContent;
3185 if (content)
3186 content->RemoveFocus(presContext);
3188 break;
3190 case NS_MOUSE_MOVE:
3191 case NS_MOUSE_ENTER:
3192 if (origEvent)
3193 aMacEvent = *origEvent;
3194 aMacEvent.what = nsPluginEventType_AdjustCursorEvent;
3195 break;
3199 #endif
3201 nsresult nsPluginInstanceOwner::ScrollPositionWillChange(nsIScrollableView* aScrollable, nscoord aX, nscoord aY)
3203 #ifdef XP_MACOSX
3204 CancelTimer();
3206 if (mInstance) {
3207 nsCOMPtr<nsIPluginWidget> pluginWidget = do_QueryInterface(mWidget);
3208 if (pluginWidget && NS_SUCCEEDED(pluginWidget->StartDrawPlugin())) {
3209 EventRecord scrollEvent;
3210 InitializeEventRecord(&scrollEvent);
3211 scrollEvent.what = nsPluginEventType_ScrollingBeginsEvent;
3213 WindowRef window = FixUpPluginWindow(ePluginPaintDisable);
3214 if (window) {
3215 nsPluginEvent pluginEvent = { &scrollEvent, nsPluginPlatformWindowRef(window) };
3216 PRBool eventHandled = PR_FALSE;
3217 mInstance->HandleEvent(&pluginEvent, &eventHandled);
3219 pluginWidget->EndDrawPlugin();
3222 #endif
3223 return NS_OK;
3226 nsresult nsPluginInstanceOwner::ScrollPositionDidChange(nsIScrollableView* aScrollable, nscoord aX, nscoord aY)
3228 #ifdef XP_MACOSX
3229 if (mInstance) {
3230 nsCOMPtr<nsIPluginWidget> pluginWidget = do_QueryInterface(mWidget);
3231 if (pluginWidget && NS_SUCCEEDED(pluginWidget->StartDrawPlugin())) {
3232 EventRecord scrollEvent;
3233 InitializeEventRecord(&scrollEvent);
3234 scrollEvent.what = nsPluginEventType_ScrollingEndsEvent;
3236 WindowRef window = FixUpPluginWindow(ePluginPaintEnable);
3237 if (window) {
3238 nsPluginEvent pluginEvent = { &scrollEvent, nsPluginPlatformWindowRef(window) };
3239 PRBool eventHandled = PR_FALSE;
3240 mInstance->HandleEvent(&pluginEvent, &eventHandled);
3242 pluginWidget->EndDrawPlugin();
3245 // FIXME - Only invalidate the newly revealed amount.
3246 // XXX necessary?
3247 if (mWidget)
3248 mWidget->Invalidate(PR_FALSE);
3250 #endif
3252 StartTimer(NORMAL_PLUGIN_DELAY);
3253 return NS_OK;
3256 /*=============== nsIFocusListener ======================*/
3257 nsresult nsPluginInstanceOwner::Focus(nsIDOMEvent * aFocusEvent)
3259 mContentFocused = PR_TRUE;
3260 return DispatchFocusToPlugin(aFocusEvent);
3263 nsresult nsPluginInstanceOwner::Blur(nsIDOMEvent * aFocusEvent)
3265 mContentFocused = PR_FALSE;
3266 return DispatchFocusToPlugin(aFocusEvent);
3269 nsresult nsPluginInstanceOwner::DispatchFocusToPlugin(nsIDOMEvent* aFocusEvent)
3271 #ifndef XP_MACOSX
3272 if (!mPluginWindow || nsPluginWindowType_Window == mPluginWindow->type) {
3273 // continue only for cases without child window
3274 return aFocusEvent->PreventDefault(); // consume event
3276 #endif
3278 nsCOMPtr<nsIPrivateDOMEvent> privateEvent(do_QueryInterface(aFocusEvent));
3279 if (privateEvent) {
3280 nsEvent * theEvent;
3281 privateEvent->GetInternalNSEvent(&theEvent);
3282 if (theEvent) {
3283 // we only care about the message in ProcessEvent
3284 nsGUIEvent focusEvent(NS_IS_TRUSTED_EVENT(theEvent), theEvent->message,
3285 nsnull);
3286 nsEventStatus rv = ProcessEvent(focusEvent);
3287 if (nsEventStatus_eConsumeNoDefault == rv) {
3288 aFocusEvent->PreventDefault();
3289 aFocusEvent->StopPropagation();
3292 else NS_ASSERTION(PR_FALSE, "nsPluginInstanceOwner::DispatchFocusToPlugin failed, focusEvent null");
3294 else NS_ASSERTION(PR_FALSE, "nsPluginInstanceOwner::DispatchFocusToPlugin failed, privateEvent null");
3296 return NS_OK;
3299 /*=============== nsIDOMDragListener ======================*/
3300 nsresult nsPluginInstanceOwner::DragEnter(nsIDOMEvent* aMouseEvent)
3302 if (mInstance) {
3303 // Let the plugin handle drag events.
3304 aMouseEvent->PreventDefault();
3305 aMouseEvent->StopPropagation();
3308 return NS_OK;
3311 nsresult nsPluginInstanceOwner::DragOver(nsIDOMEvent* aMouseEvent)
3313 if (mInstance) {
3314 // Let the plugin handle drag events.
3315 aMouseEvent->PreventDefault();
3316 aMouseEvent->StopPropagation();
3319 return NS_OK;
3322 nsresult nsPluginInstanceOwner::DragExit(nsIDOMEvent* aMouseEvent)
3324 if (mInstance) {
3325 // Let the plugin handle drag events.
3326 aMouseEvent->PreventDefault();
3327 aMouseEvent->StopPropagation();
3330 return NS_OK;
3333 nsresult nsPluginInstanceOwner::DragDrop(nsIDOMEvent* aMouseEvent)
3335 if (mInstance) {
3336 // Let the plugin handle drag events.
3337 aMouseEvent->PreventDefault();
3338 aMouseEvent->StopPropagation();
3341 return NS_OK;
3344 nsresult nsPluginInstanceOwner::DragGesture(nsIDOMEvent* aMouseEvent)
3346 if (mInstance) {
3347 // Let the plugin handle drag events.
3348 aMouseEvent->PreventDefault();
3349 aMouseEvent->StopPropagation();
3352 return NS_OK;
3355 nsresult nsPluginInstanceOwner::Drag(nsIDOMEvent* aMouseEvent)
3357 if (mInstance) {
3358 // Let the plugin handle drag events.
3359 aMouseEvent->PreventDefault();
3360 aMouseEvent->StopPropagation();
3363 return NS_OK;
3366 nsresult nsPluginInstanceOwner::DragEnd(nsIDOMEvent* aMouseEvent)
3368 if (mInstance) {
3369 // Let the plugin handle drag events.
3370 aMouseEvent->PreventDefault();
3371 aMouseEvent->StopPropagation();
3374 return NS_OK;
3379 /*=============== nsIKeyListener ======================*/
3380 nsresult nsPluginInstanceOwner::KeyDown(nsIDOMEvent* aKeyEvent)
3382 return DispatchKeyToPlugin(aKeyEvent);
3385 nsresult nsPluginInstanceOwner::KeyUp(nsIDOMEvent* aKeyEvent)
3387 return DispatchKeyToPlugin(aKeyEvent);
3390 nsresult nsPluginInstanceOwner::KeyPress(nsIDOMEvent* aKeyEvent)
3392 #ifdef XP_MACOSX // send KeyPress events only on Mac
3394 // KeyPress events are really synthesized keyDown events.
3395 // Here we check the native message of the event so that
3396 // we won't send the plugin two keyDown events.
3397 nsCOMPtr<nsIPrivateDOMEvent> privateEvent(do_QueryInterface(aKeyEvent));
3398 if (privateEvent) {
3399 nsEvent *theEvent;
3400 privateEvent->GetInternalNSEvent(&theEvent);
3401 const nsGUIEvent *guiEvent = (nsGUIEvent*)theEvent;
3402 const EventRecord *ev = (EventRecord*)(guiEvent->nativeMsg);
3403 if (guiEvent &&
3404 guiEvent->message == NS_KEY_PRESS &&
3405 ev &&
3406 ev->what == keyDown)
3407 return aKeyEvent->PreventDefault(); // consume event
3410 // Nasty hack to avoid recursive event dispatching with Java. Java can
3411 // dispatch key events to a TSM handler, which comes back and calls
3412 // [ChildView insertText:] on the cocoa widget, which sends a key
3413 // event back down.
3414 static PRBool sInKeyDispatch = PR_FALSE;
3416 if (sInKeyDispatch)
3417 return aKeyEvent->PreventDefault(); // consume event
3419 sInKeyDispatch = PR_TRUE;
3420 nsresult rv = DispatchKeyToPlugin(aKeyEvent);
3421 sInKeyDispatch = PR_FALSE;
3422 return rv;
3423 #else
3424 if (mInstance) {
3425 // If this event is going to the plugin, we want to kill it.
3426 // Not actually sending keypress to the plugin, since we didn't before.
3427 aKeyEvent->PreventDefault();
3428 aKeyEvent->StopPropagation();
3430 return NS_OK;
3431 #endif
3434 nsresult nsPluginInstanceOwner::DispatchKeyToPlugin(nsIDOMEvent* aKeyEvent)
3436 #ifndef XP_MACOSX
3437 if (!mPluginWindow || nsPluginWindowType_Window == mPluginWindow->type)
3438 return aKeyEvent->PreventDefault(); // consume event
3439 // continue only for cases without child window
3440 #endif
3442 if (mInstance) {
3443 nsCOMPtr<nsIPrivateDOMEvent> privateEvent(do_QueryInterface(aKeyEvent));
3444 if (privateEvent) {
3445 nsKeyEvent* keyEvent = nsnull;
3446 privateEvent->GetInternalNSEvent((nsEvent**)&keyEvent);
3447 if (keyEvent) {
3448 nsEventStatus rv = ProcessEvent(*keyEvent);
3449 if (nsEventStatus_eConsumeNoDefault == rv) {
3450 aKeyEvent->PreventDefault();
3451 aKeyEvent->StopPropagation();
3454 else NS_ASSERTION(PR_FALSE, "nsPluginInstanceOwner::DispatchKeyToPlugin failed, keyEvent null");
3456 else NS_ASSERTION(PR_FALSE, "nsPluginInstanceOwner::DispatchKeyToPlugin failed, privateEvent null");
3459 return NS_OK;
3462 /*=============== nsIMouseMotionListener ======================*/
3464 nsresult
3465 nsPluginInstanceOwner::MouseMove(nsIDOMEvent* aMouseEvent)
3467 #if !defined(XP_MACOSX)
3468 if (!mPluginWindow || nsPluginWindowType_Window == mPluginWindow->type)
3469 return aMouseEvent->PreventDefault(); // consume event
3470 // continue only for cases without child window
3471 #endif
3473 // don't send mouse events if we are hiddden
3474 if (!mWidgetVisible)
3475 return NS_OK;
3477 nsCOMPtr<nsIPrivateDOMEvent> privateEvent(do_QueryInterface(aMouseEvent));
3478 if (privateEvent) {
3479 nsMouseEvent* mouseEvent = nsnull;
3480 privateEvent->GetInternalNSEvent((nsEvent**)&mouseEvent);
3481 if (mouseEvent) {
3482 nsEventStatus rv = ProcessEvent(*mouseEvent);
3483 if (nsEventStatus_eConsumeNoDefault == rv) {
3484 return aMouseEvent->PreventDefault(); // consume event
3487 else NS_ASSERTION(PR_FALSE, "nsPluginInstanceOwner::MouseMove failed, mouseEvent null");
3489 else NS_ASSERTION(PR_FALSE, "nsPluginInstanceOwner::MouseMove failed, privateEvent null");
3491 return NS_OK;
3494 /*=============== nsIMouseListener ======================*/
3496 nsresult
3497 nsPluginInstanceOwner::MouseDown(nsIDOMEvent* aMouseEvent)
3499 #if !defined(XP_MACOSX)
3500 if (!mPluginWindow || nsPluginWindowType_Window == mPluginWindow->type)
3501 return aMouseEvent->PreventDefault(); // consume event
3502 // continue only for cases without child window
3503 #endif
3505 // if the plugin is windowless, we need to set focus ourselves
3506 // otherwise, we might not get key events
3507 if (mOwner && mPluginWindow &&
3508 mPluginWindow->type == nsPluginWindowType_Drawable) {
3509 mContent->SetFocus(mOwner->PresContext());
3512 nsCOMPtr<nsIPrivateDOMEvent> privateEvent(do_QueryInterface(aMouseEvent));
3513 if (privateEvent) {
3514 nsMouseEvent* mouseEvent = nsnull;
3515 privateEvent->GetInternalNSEvent((nsEvent**)&mouseEvent);
3516 if (mouseEvent) {
3517 nsEventStatus rv = ProcessEvent(*mouseEvent);
3518 if (nsEventStatus_eConsumeNoDefault == rv) {
3519 return aMouseEvent->PreventDefault(); // consume event
3522 else NS_ASSERTION(PR_FALSE, "nsPluginInstanceOwner::MouseDown failed, mouseEvent null");
3524 else NS_ASSERTION(PR_FALSE, "nsPluginInstanceOwner::MouseDown failed, privateEvent null");
3526 return NS_OK;
3529 nsresult
3530 nsPluginInstanceOwner::MouseUp(nsIDOMEvent* aMouseEvent)
3532 return DispatchMouseToPlugin(aMouseEvent);
3535 nsresult
3536 nsPluginInstanceOwner::MouseClick(nsIDOMEvent* aMouseEvent)
3538 return DispatchMouseToPlugin(aMouseEvent);
3541 nsresult
3542 nsPluginInstanceOwner::MouseDblClick(nsIDOMEvent* aMouseEvent)
3544 return DispatchMouseToPlugin(aMouseEvent);
3547 nsresult
3548 nsPluginInstanceOwner::MouseOver(nsIDOMEvent* aMouseEvent)
3550 return DispatchMouseToPlugin(aMouseEvent);
3553 nsresult
3554 nsPluginInstanceOwner::MouseOut(nsIDOMEvent* aMouseEvent)
3556 return DispatchMouseToPlugin(aMouseEvent);
3559 nsresult nsPluginInstanceOwner::DispatchMouseToPlugin(nsIDOMEvent* aMouseEvent)
3561 #if !defined(XP_MACOSX)
3562 if (!mPluginWindow || nsPluginWindowType_Window == mPluginWindow->type)
3563 return aMouseEvent->PreventDefault(); // consume event
3564 // continue only for cases without child window
3565 #endif
3567 // don't send mouse events if we are hiddden
3568 if (!mWidgetVisible)
3569 return NS_OK;
3571 nsCOMPtr<nsIPrivateDOMEvent> privateEvent(do_QueryInterface(aMouseEvent));
3572 if (privateEvent) {
3573 nsMouseEvent* mouseEvent = nsnull;
3574 privateEvent->GetInternalNSEvent((nsEvent**)&mouseEvent);
3575 if (mouseEvent) {
3576 nsEventStatus rv = ProcessEvent(*mouseEvent);
3577 if (nsEventStatus_eConsumeNoDefault == rv) {
3578 aMouseEvent->PreventDefault();
3579 aMouseEvent->StopPropagation();
3582 else NS_ASSERTION(PR_FALSE, "nsPluginInstanceOwner::DispatchMouseToPlugin failed, mouseEvent null");
3584 else NS_ASSERTION(PR_FALSE, "nsPluginInstanceOwner::DispatchMouseToPlugin failed, privateEvent null");
3586 return NS_OK;
3589 nsresult
3590 nsPluginInstanceOwner::HandleEvent(nsIDOMEvent* aEvent)
3592 return NS_OK;
3595 #ifdef MOZ_X11
3596 static unsigned int XInputEventState(const nsInputEvent& anEvent)
3598 unsigned int state = 0;
3599 if(anEvent.isShift) state |= ShiftMask;
3600 if(anEvent.isControl) state |= ControlMask;
3601 if(anEvent.isAlt) state |= Mod1Mask;
3602 if(anEvent.isMeta) state |= Mod4Mask;
3603 return state;
3605 #endif
3607 nsEventStatus nsPluginInstanceOwner::ProcessEvent(const nsGUIEvent& anEvent)
3609 // printf("nsGUIEvent.message: %d\n", anEvent.message);
3610 nsEventStatus rv = nsEventStatus_eIgnore;
3611 if (!mInstance || !mOwner) // if mInstance is null, we shouldn't be here
3612 return rv;
3614 #ifdef XP_MACOSX
3615 // check for null mWidget
3616 if (mWidget) {
3617 nsCOMPtr<nsIPluginWidget> pluginWidget = do_QueryInterface(mWidget);
3618 if (pluginWidget && NS_SUCCEEDED(pluginWidget->StartDrawPlugin())) {
3619 EventRecord macEvent;
3620 EventRecord* event = (EventRecord*)anEvent.nativeMsg;
3621 if ((event == NULL) || (event->what == nullEvent) ||
3622 (anEvent.message == NS_FOCUS_CONTENT) ||
3623 (anEvent.message == NS_BLUR_CONTENT) ||
3624 (anEvent.message == NS_MOUSE_MOVE) ||
3625 (anEvent.message == NS_MOUSE_ENTER)) {
3626 GUItoMacEvent(anEvent, event, macEvent);
3627 event = &macEvent;
3630 if (anEvent.message == NS_FOCUS_CONTENT) {
3631 // Work around an issue in the Flash plugin, which can cache a pointer
3632 // to a doomed TSM document (one that belongs to a NSTSMInputContext)
3633 // and try to activate it after it has been deleted. See bug 183313.
3634 ::DeactivateTSMDocument(::TSMGetActiveDocument());
3637 PRBool eventHandled = PR_FALSE;
3638 WindowRef window = FixUpPluginWindow(ePluginPaintIgnore);
3639 if (window) {
3640 nsPluginEvent pluginEvent = { event, nsPluginPlatformWindowRef(window) };
3641 mInstance->HandleEvent(&pluginEvent, &eventHandled);
3644 if (eventHandled && !(anEvent.eventStructType == NS_MOUSE_EVENT &&
3645 anEvent.message == NS_MOUSE_BUTTON_DOWN &&
3646 static_cast<const nsMouseEvent&>(anEvent).button ==
3647 nsMouseEvent::eLeftButton &&
3648 !mContentFocused))
3649 rv = nsEventStatus_eConsumeNoDefault;
3651 pluginWidget->EndDrawPlugin();
3654 #endif
3656 #ifdef XP_WIN
3657 // this code supports windowless plugins
3658 nsPluginEvent * pPluginEvent = (nsPluginEvent *)anEvent.nativeMsg;
3659 // we can get synthetic events from the nsEventStateManager... these
3660 // have no nativeMsg
3661 nsPluginEvent pluginEvent;
3662 if (!pPluginEvent) {
3663 switch (anEvent.message) {
3664 case NS_FOCUS_CONTENT:
3665 pluginEvent.event = WM_SETFOCUS;
3666 pluginEvent.wParam = 0;
3667 pluginEvent.lParam = 0;
3668 pPluginEvent = &pluginEvent;
3669 break;
3670 case NS_BLUR_CONTENT:
3671 pluginEvent.event = WM_KILLFOCUS;
3672 pluginEvent.wParam = 0;
3673 pluginEvent.lParam = 0;
3674 pPluginEvent = &pluginEvent;
3675 break;
3679 if (pPluginEvent) {
3680 PRBool eventHandled = PR_FALSE;
3681 mInstance->HandleEvent(pPluginEvent, &eventHandled);
3682 if (eventHandled)
3683 rv = nsEventStatus_eConsumeNoDefault;
3685 #endif
3687 #ifdef MOZ_X11
3688 // this code supports windowless plugins
3689 nsIWidget* widget = anEvent.widget;
3690 nsPluginEvent pluginEvent;
3691 pluginEvent.event.type = 0;
3693 switch(anEvent.eventStructType)
3695 case NS_MOUSE_EVENT:
3697 switch (anEvent.message)
3699 case NS_MOUSE_CLICK:
3700 case NS_MOUSE_DOUBLECLICK:
3701 // Button up/down events sent instead.
3702 return rv;
3705 // Get reference point relative to plugin origin.
3706 const nsPresContext* presContext = mOwner->PresContext();
3707 nsPoint appPoint =
3708 nsLayoutUtils::GetEventCoordinatesRelativeTo(&anEvent, mOwner);
3709 nsIntPoint pluginPoint(presContext->AppUnitsToDevPixels(appPoint.x),
3710 presContext->AppUnitsToDevPixels(appPoint.y));
3711 const nsMouseEvent& mouseEvent =
3712 static_cast<const nsMouseEvent&>(anEvent);
3713 // Get reference point relative to screen:
3714 nsRect windowRect(anEvent.refPoint, nsSize(1, 1));
3715 nsRect rootPoint(-1,-1,1,1);
3716 if (widget)
3717 widget->WidgetToScreen(windowRect, rootPoint);
3718 #ifdef MOZ_WIDGET_GTK2
3719 Window root = GDK_ROOT_WINDOW();
3720 #else
3721 Window root = None; // Could XQueryTree, but this is not important.
3722 #endif
3724 switch (anEvent.message)
3726 case NS_MOUSE_ENTER_SYNTH:
3727 case NS_MOUSE_EXIT_SYNTH:
3729 XCrossingEvent& event = pluginEvent.event.xcrossing;
3730 event.type = anEvent.message == NS_MOUSE_ENTER_SYNTH ?
3731 EnterNotify : LeaveNotify;
3732 event.root = root;
3733 event.time = anEvent.time;
3734 event.x = pluginPoint.x;
3735 event.y = pluginPoint.y;
3736 event.x_root = rootPoint.x;
3737 event.y_root = rootPoint.y;
3738 event.state = XInputEventState(mouseEvent);
3739 // information lost
3740 event.subwindow = None;
3741 event.mode = -1;
3742 event.detail = NotifyDetailNone;
3743 event.same_screen = True;
3744 event.focus = mContentFocused;
3746 break;
3747 case NS_MOUSE_MOVE:
3749 XMotionEvent& event = pluginEvent.event.xmotion;
3750 event.type = MotionNotify;
3751 event.root = root;
3752 event.time = anEvent.time;
3753 event.x = pluginPoint.x;
3754 event.y = pluginPoint.y;
3755 event.x_root = rootPoint.x;
3756 event.y_root = rootPoint.y;
3757 event.state = XInputEventState(mouseEvent);
3758 // information lost
3759 event.subwindow = None;
3760 event.is_hint = NotifyNormal;
3761 event.same_screen = True;
3763 break;
3764 case NS_MOUSE_BUTTON_DOWN:
3765 case NS_MOUSE_BUTTON_UP:
3767 XButtonEvent& event = pluginEvent.event.xbutton;
3768 event.type = anEvent.message == NS_MOUSE_BUTTON_DOWN ?
3769 ButtonPress : ButtonRelease;
3770 event.root = root;
3771 event.time = anEvent.time;
3772 event.x = pluginPoint.x;
3773 event.y = pluginPoint.y;
3774 event.x_root = rootPoint.x;
3775 event.y_root = rootPoint.y;
3776 event.state = XInputEventState(mouseEvent);
3777 switch (mouseEvent.button)
3779 case nsMouseEvent::eMiddleButton:
3780 event.button = 2;
3781 break;
3782 case nsMouseEvent::eRightButton:
3783 event.button = 3;
3784 break;
3785 default: // nsMouseEvent::eLeftButton;
3786 event.button = 1;
3787 break;
3789 // information lost:
3790 event.subwindow = None;
3791 event.same_screen = True;
3793 break;
3796 break;
3798 //XXX case NS_MOUSE_SCROLL_EVENT: not received.
3800 case NS_KEY_EVENT:
3801 if (anEvent.nativeMsg)
3803 XKeyEvent &event = pluginEvent.event.xkey;
3804 #ifdef MOZ_WIDGET_GTK2
3805 event.root = GDK_ROOT_WINDOW();
3806 event.time = anEvent.time;
3807 const GdkEventKey* gdkEvent =
3808 static_cast<const GdkEventKey*>(anEvent.nativeMsg);
3809 event.keycode = gdkEvent->hardware_keycode;
3810 event.state = gdkEvent->state;
3811 switch (anEvent.message)
3813 case NS_KEY_DOWN:
3814 event.type = XKeyPress;
3815 break;
3816 case NS_KEY_UP:
3817 event.type = KeyRelease;
3818 break;
3820 #endif
3821 // Information that could be obtained from nativeMsg but we may not
3822 // want to promise to provide:
3823 event.subwindow = None;
3824 event.x = 0;
3825 event.y = 0;
3826 event.x_root = -1;
3827 event.y_root = -1;
3828 event.same_screen = False;
3830 else
3832 // If we need to send synthesized key events, then
3833 // DOMKeyCodeToGdkKeyCode(keyEvent.keyCode) and
3834 // gdk_keymap_get_entries_for_keyval will be useful, but the
3835 // mappings will not be unique.
3836 NS_WARNING("Synthesized key event not sent to plugin");
3838 break;
3840 default:
3841 switch (anEvent.message)
3843 case NS_FOCUS_CONTENT:
3844 case NS_BLUR_CONTENT:
3846 XFocusChangeEvent &event = pluginEvent.event.xfocus;
3847 event.type =
3848 anEvent.message == NS_FOCUS_CONTENT ? FocusIn : FocusOut;
3849 // information lost:
3850 event.mode = -1;
3851 event.detail = NotifyDetailNone;
3853 break;
3857 if (!pluginEvent.event.type) {
3858 PR_LOG(nsObjectFrameLM, PR_LOG_DEBUG,
3859 ("Unhandled event message %d with struct type %d\n",
3860 anEvent.message, anEvent.eventStructType));
3861 return rv;
3864 // Fill in (useless) generic event information.
3865 XAnyEvent& event = pluginEvent.event.xany;
3866 event.display = widget ?
3867 static_cast<Display*>(widget->GetNativeData(NS_NATIVE_DISPLAY)) : nsnull;
3868 event.window = None; // not a real window
3869 // information lost:
3870 event.serial = 0;
3871 event.send_event = False;
3873 PRBool eventHandled = PR_FALSE;
3874 mInstance->HandleEvent(&pluginEvent, &eventHandled);
3875 if (eventHandled)
3876 rv = nsEventStatus_eConsumeNoDefault;
3877 #endif
3879 return rv;
3882 nsresult
3883 nsPluginInstanceOwner::Destroy()
3885 // stop the timer explicitly to reduce reference count.
3886 CancelTimer();
3888 // unregister context menu listener
3889 if (mCXMenuListener) {
3890 mCXMenuListener->Destroy(mContent);
3891 mCXMenuListener = nsnull;
3894 nsCOMPtr<nsIDOMEventTarget> target(do_QueryInterface(mContent));
3895 if (target) {
3897 nsCOMPtr<nsIDOMEventListener> listener;
3898 QueryInterface(NS_GET_IID(nsIDOMEventListener), getter_AddRefs(listener));
3900 // Unregister focus event listener
3901 mContent->RemoveEventListenerByIID(listener, NS_GET_IID(nsIDOMFocusListener));
3903 // Unregister mouse event listener
3904 mContent->RemoveEventListenerByIID(listener, NS_GET_IID(nsIDOMMouseListener));
3906 // now for the mouse motion listener
3907 mContent->RemoveEventListenerByIID(listener, NS_GET_IID(nsIDOMMouseMotionListener));
3909 // Unregister key event listener;
3910 target->RemoveEventListener(NS_LITERAL_STRING("keypress"), listener, PR_TRUE);
3911 target->RemoveEventListener(NS_LITERAL_STRING("keydown"), listener, PR_TRUE);
3912 target->RemoveEventListener(NS_LITERAL_STRING("keyup"), listener, PR_TRUE);
3914 // Unregister drag event listener;
3915 target->RemoveEventListener(NS_LITERAL_STRING("dragdrop"), listener, PR_TRUE);
3916 target->RemoveEventListener(NS_LITERAL_STRING("dragover"), listener, PR_TRUE);
3917 target->RemoveEventListener(NS_LITERAL_STRING("dragexit"), listener, PR_TRUE);
3918 target->RemoveEventListener(NS_LITERAL_STRING("dragenter"), listener, PR_TRUE);
3919 target->RemoveEventListener(NS_LITERAL_STRING("draggesture"), listener, PR_TRUE);
3922 if (mWidget) {
3923 nsCOMPtr<nsIPluginWidget> pluginWidget = do_QueryInterface(mWidget);
3924 if (pluginWidget)
3925 pluginWidget->SetPluginInstanceOwner(nsnull);
3927 if (mDestroyWidget)
3928 mWidget->Destroy();
3931 return NS_OK;
3935 * Prepare to stop
3937 void
3938 nsPluginInstanceOwner::PrepareToStop(PRBool aDelayedStop)
3940 #ifdef XP_WIN
3941 if (aDelayedStop && mWidget) {
3942 // To delay stopping a plugin we need to reparent the plugin
3943 // so that we can safely tear down the
3944 // plugin after its frame (and view) is gone.
3946 // Also hide and disable the widget to avoid it from appearing in
3947 // odd places after reparenting it, but before it gets destroyed.
3948 mWidget->Show(PR_FALSE);
3949 mWidget->Enable(PR_FALSE);
3951 // Reparent the plugins native window. This relies on the widget
3952 // and plugin et al not holding any other references to its
3953 // parent.
3954 mWidget->SetParent(nsnull);
3956 mDestroyWidget = PR_TRUE;
3958 #endif
3960 // Unregister scroll position listener
3961 nsIFrame* parentWithView = mOwner->GetAncestorWithView();
3962 nsIView* curView = parentWithView ? parentWithView->GetView() : nsnull;
3963 while (curView) {
3964 nsIScrollableView* scrollingView = curView->ToScrollableView();
3965 if (scrollingView)
3966 scrollingView->RemoveScrollPositionListener((nsIScrollPositionListener *)this);
3968 curView = curView->GetParent();
3972 // Paints are handled differently, so we just simulate an update event.
3974 #ifdef XP_MACOSX
3975 void nsPluginInstanceOwner::Paint(const nsRect& aDirtyRect)
3977 if (!mInstance || !mOwner)
3978 return;
3980 #ifdef DO_DIRTY_INTERSECT // aDirtyRect isn't always correct, see bug 56128
3981 nsPoint rel(aDirtyRect.x, aDirtyRect.y);
3982 nsPoint abs(0,0);
3983 nsCOMPtr<nsIWidget> containerWidget;
3985 // Convert dirty rect relative coordinates to absolute and also get the containerWidget
3986 ConvertRelativeToWindowAbsolute(mOwner, rel, abs, *getter_AddRefs(containerWidget));
3988 nsRect absDirtyRect = nsRect(abs.x, abs.y, aDirtyRect.width, aDirtyRect.height);
3990 // Convert to absolute pixel values for the dirty rect
3991 nsIntRect absDirtyRectInPixels;
3992 ConvertAppUnitsToPixels(*mOwner->GetPresContext(), absDirtyRect,
3993 absDirtyRectInPixels);
3994 #endif
3996 nsCOMPtr<nsIPluginWidget> pluginWidget = do_QueryInterface(mWidget);
3997 if (pluginWidget && NS_SUCCEEDED(pluginWidget->StartDrawPlugin())) {
3998 WindowRef window = FixUpPluginWindow(ePluginPaintEnable);
3999 if (window) {
4000 EventRecord updateEvent;
4001 InitializeEventRecord(&updateEvent);
4002 updateEvent.what = updateEvt;
4003 updateEvent.message = UInt32(window);
4005 nsPluginEvent pluginEvent = { &updateEvent, nsPluginPlatformWindowRef(window) };
4006 PRBool eventHandled = PR_FALSE;
4007 mInstance->HandleEvent(&pluginEvent, &eventHandled);
4009 pluginWidget->EndDrawPlugin();
4012 #endif
4014 #ifdef XP_WIN
4015 void nsPluginInstanceOwner::Paint(const nsRect& aDirtyRect, HDC ndc)
4017 if (!mInstance || !mOwner)
4018 return;
4020 nsPluginWindow * window;
4021 GetWindow(window);
4022 nsRect relDirtyRect = nsRect(aDirtyRect.x, aDirtyRect.y, aDirtyRect.width, aDirtyRect.height);
4023 nsIntRect relDirtyRectInPixels;
4024 ConvertAppUnitsToPixels(*mOwner->PresContext(), relDirtyRect,
4025 relDirtyRectInPixels);
4027 // we got dirty rectangle in relative window coordinates, but we
4028 // need it in absolute units and in the (left, top, right, bottom) form
4029 RECT drc;
4030 drc.left = relDirtyRectInPixels.x + window->x;
4031 drc.top = relDirtyRectInPixels.y + window->y;
4032 drc.right = drc.left + relDirtyRectInPixels.width;
4033 drc.bottom = drc.top + relDirtyRectInPixels.height;
4035 nsPluginEvent pluginEvent;
4036 pluginEvent.event = WM_PAINT;
4037 pluginEvent.wParam = (uint32)ndc;
4038 pluginEvent.lParam = (uint32)&drc;
4039 PRBool eventHandled = PR_FALSE;
4040 mInstance->HandleEvent(&pluginEvent, &eventHandled);
4042 #endif
4044 #ifdef XP_OS2
4045 void nsPluginInstanceOwner::Paint(const nsRect& aDirtyRect, HPS aHPS)
4047 if (!mInstance || !mOwner)
4048 return;
4050 nsPluginWindow * window;
4051 GetWindow(window);
4052 nsRect relDirtyRect = nsRect(aDirtyRect.x, aDirtyRect.y, aDirtyRect.width, aDirtyRect.height);
4053 nsIntRect relDirtyRectInPixels;
4054 ConvertAppUnitsToPixels(*mOwner->PresContext(), relDirtyRect,
4055 relDirtyRectInPixels);
4057 // we got dirty rectangle in relative window coordinates, but we
4058 // need it in absolute units and in the (left, top, right, bottom) form
4059 RECTL rectl;
4060 rectl.xLeft = relDirtyRectInPixels.x + window->x;
4061 rectl.yBottom = relDirtyRectInPixels.y + window->y;
4062 rectl.xRight = rectl.xLeft + relDirtyRectInPixels.width;
4063 rectl.yTop = rectl.yBottom + relDirtyRectInPixels.height;
4065 nsPluginEvent pluginEvent;
4066 pluginEvent.event = WM_PAINT;
4067 pluginEvent.wParam = (uint32)aHPS;
4068 pluginEvent.lParam = (uint32)&rectl;
4069 PRBool eventHandled = PR_FALSE;
4070 mInstance->HandleEvent(&pluginEvent, &eventHandled);
4072 #endif
4074 #if defined(MOZ_X11) || defined(MOZ_DFB)
4075 void nsPluginInstanceOwner::Paint(gfxContext* aContext,
4076 const gfxRect& aFrameRect,
4077 const gfxRect& aDirtyRect)
4079 if (!mInstance || !mOwner)
4080 return;
4082 // Align to device pixels where sensible
4083 // to provide crisper and faster drawing.
4084 gfxRect pluginRect = aFrameRect;
4085 if (aContext->UserToDevicePixelSnapped(pluginRect)) {
4086 pluginRect = aContext->DeviceToUser(pluginRect);
4089 // Round out the dirty rect to plugin pixels to ensure the plugin draws
4090 // enough pixels for interpolation to device pixels.
4091 gfxRect dirtyRect = aDirtyRect + -pluginRect.pos;
4092 dirtyRect.RoundOut();
4094 // Plugins can only draw an integer number of pixels.
4096 // With translation-only transformation matrices, pluginRect is already
4097 // pixel-aligned.
4099 // With more complex transformations, modifying the scales in the
4100 // transformation matrix could retain subpixel accuracy and let the plugin
4101 // draw a suitable number of pixels for interpolation to device pixels in
4102 // Renderer::Draw, but such cases are not common enough to warrant the
4103 // effort now.
4104 nsIntSize pluginSize(NS_lround(pluginRect.size.width),
4105 NS_lround(pluginRect.size.height));
4107 // Determine what the plugin needs to draw.
4108 nsIntRect pluginDirtyRect(PRInt32(dirtyRect.pos.x),
4109 PRInt32(dirtyRect.pos.y),
4110 PRInt32(dirtyRect.size.width),
4111 PRInt32(dirtyRect.size.height));
4112 if (!pluginDirtyRect.
4113 IntersectRect(nsIntRect(0, 0, pluginSize.width, pluginSize.height),
4114 pluginDirtyRect))
4115 return;
4117 nsPluginWindow* window;
4118 GetWindow(window);
4120 Renderer renderer(window, mInstance, pluginSize, pluginDirtyRect);
4121 PRUint32 rendererFlags =
4122 Renderer::DRAW_SUPPORTS_OFFSET |
4123 Renderer::DRAW_SUPPORTS_CLIP_RECT |
4124 Renderer::DRAW_SUPPORTS_NONDEFAULT_VISUAL |
4125 Renderer::DRAW_SUPPORTS_ALTERNATE_SCREEN;
4127 PRBool transparent = PR_TRUE;
4128 mInstance->GetValue(nsPluginInstanceVariable_TransparentBool,
4129 (void *)&transparent);
4130 if (!transparent)
4131 rendererFlags |= Renderer::DRAW_IS_OPAQUE;
4133 // Renderer::Draw() draws a rectangle with top-left at the aContext origin.
4134 gfxContextAutoSaveRestore autoSR(aContext);
4135 aContext->Translate(pluginRect.pos);
4137 renderer.Draw(aContext, window->width, window->height,
4138 rendererFlags, nsnull);
4141 #ifdef MOZ_X11
4142 static int
4143 DepthOfVisual(const Screen* screen, const Visual* visual)
4145 for (int d = 0; d < screen->ndepths; d++) {
4146 Depth *d_info = &screen->depths[d];
4147 for (int v = 0; v < d_info->nvisuals; v++) {
4148 if (&d_info->visuals[v] == visual)
4149 return d_info->depth;
4153 NS_ERROR("Visual not on Screen.");
4154 return 0;
4156 #endif
4158 #if defined(MOZ_WIDGET_GTK2)
4159 nsresult
4160 nsPluginInstanceOwner::Renderer::NativeDraw(GdkDrawable * drawable,
4161 short offsetX, short offsetY,
4162 GdkRectangle * clipRects,
4163 PRUint32 numClipRects)
4166 #ifdef MOZ_X11
4167 Visual * visual = GDK_VISUAL_XVISUAL(gdk_drawable_get_visual(drawable));
4168 Colormap colormap = GDK_COLORMAP_XCOLORMAP(gdk_drawable_get_colormap(drawable));
4169 Screen * screen = GDK_SCREEN_XSCREEN (gdk_drawable_get_screen(drawable));
4170 #endif
4171 #elif defined(MOZ_WIDGET_QT)
4172 nsresult
4173 nsPluginInstanceOwner::Renderer::NativeDraw(QWidget * drawable,
4174 short offsetX, short offsetY,
4175 QRect * clipRects,
4176 PRUint32 numClipRects)
4178 #ifdef MOZ_X11
4179 QX11Info xinfo = drawable->x11Info();
4180 Visual * visual = (Visual*) xinfo.visual();
4181 Colormap colormap = xinfo.colormap();
4182 Screen * screen = (Screen*) xinfo.screen();
4183 #endif
4184 #endif
4185 // See if the plugin must be notified of new window parameters.
4186 PRBool doupdatewindow = PR_FALSE;
4188 if (mWindow->x != offsetX || mWindow->y != offsetY) {
4189 mWindow->x = offsetX;
4190 mWindow->y = offsetY;
4191 doupdatewindow = PR_TRUE;
4194 if (nsIntSize(mWindow->width, mWindow->height) != mPluginSize) {
4195 mWindow->width = mPluginSize.width;
4196 mWindow->height = mPluginSize.height;
4197 doupdatewindow = PR_TRUE;
4200 // The clip rect is relative to drawable top-left.
4201 NS_ASSERTION(numClipRects <= 1, "We don't support multiple clip rectangles!");
4202 nsIntRect clipRect;
4203 if (numClipRects) {
4204 #if defined(MOZ_WIDGET_GTK2)
4205 clipRect.x = clipRects[0].x;
4206 clipRect.y = clipRects[0].y;
4207 clipRect.width = clipRects[0].width;
4208 clipRect.height = clipRects[0].height;
4209 #elif defined(MOZ_WIDGET_QT)
4210 clipRect.x = clipRects[0].x();
4211 clipRect.y = clipRects[0].y();
4212 clipRect.width = clipRects[0].width();
4213 clipRect.height = clipRects[0].height();
4214 #endif
4216 else {
4217 // nsPluginRect members are unsigned, but
4218 // we should have been given a clip if an offset is -ve.
4219 NS_ASSERTION(offsetX >= 0 && offsetY >= 0,
4220 "Clip rectangle offsets are negative!");
4221 clipRect.x = offsetX;
4222 clipRect.y = offsetY;
4223 clipRect.width = mWindow->width;
4224 clipRect.height = mWindow->height;
4227 nsPluginRect newClipRect;
4228 newClipRect.left = clipRect.x;
4229 newClipRect.top = clipRect.y;
4230 newClipRect.right = clipRect.XMost();
4231 newClipRect.bottom = clipRect.YMost();
4232 if (mWindow->clipRect.left != newClipRect.left ||
4233 mWindow->clipRect.top != newClipRect.top ||
4234 mWindow->clipRect.right != newClipRect.right ||
4235 mWindow->clipRect.bottom != newClipRect.bottom) {
4236 mWindow->clipRect = newClipRect;
4237 doupdatewindow = PR_TRUE;
4240 NPSetWindowCallbackStruct* ws_info =
4241 static_cast<NPSetWindowCallbackStruct*>(mWindow->ws_info);
4242 #ifdef MOZ_X11
4243 if (ws_info->visual != visual || ws_info->colormap != colormap) {
4244 ws_info->visual = visual;
4245 ws_info->colormap = colormap;
4246 ws_info->depth = DepthOfVisual(screen, visual);
4247 doupdatewindow = PR_TRUE;
4249 #endif
4251 if (doupdatewindow)
4252 mInstance->SetWindow(mWindow);
4254 #ifdef MOZ_X11
4255 // Translate the dirty rect to drawable coordinates.
4256 nsIntRect dirtyRect = mDirtyRect + nsIntPoint(offsetX, offsetY);
4257 // Intersect the dirty rect with the clip rect to ensure that it lies within
4258 // the drawable.
4259 if (!dirtyRect.IntersectRect(dirtyRect, clipRect))
4260 return NS_OK;
4262 nsPluginEvent pluginEvent;
4263 XGraphicsExposeEvent& exposeEvent = pluginEvent.event.xgraphicsexpose;
4264 // set the drawing info
4265 exposeEvent.type = GraphicsExpose;
4266 exposeEvent.display = DisplayOfScreen(screen);
4267 exposeEvent.drawable =
4268 #if defined(MOZ_WIDGET_GTK2)
4269 GDK_DRAWABLE_XID(drawable);
4270 #elif defined(MOZ_WIDGET_QT)
4271 drawable->x11PictureHandle();
4272 #endif
4273 exposeEvent.x = mDirtyRect.x + offsetX;
4274 exposeEvent.y = mDirtyRect.y + offsetY;
4275 exposeEvent.width = mDirtyRect.width;
4276 exposeEvent.height = mDirtyRect.height;
4277 exposeEvent.count = 0;
4278 // information not set:
4279 exposeEvent.serial = 0;
4280 exposeEvent.send_event = False;
4281 exposeEvent.major_code = 0;
4282 exposeEvent.minor_code = 0;
4284 PRBool eventHandled = PR_FALSE;
4285 mInstance->HandleEvent(&pluginEvent, &eventHandled);
4286 #endif
4288 return NS_OK;
4290 #endif
4292 // Here's how we give idle time to plugins.
4294 NS_IMETHODIMP nsPluginInstanceOwner::Notify(nsITimer* /* timer */)
4296 #ifdef XP_MACOSX
4297 // validate the plugin clipping information by syncing the plugin window info to
4298 // reflect the current widget location. This makes sure that everything is updated
4299 // correctly in the event of scrolling in the window.
4300 if (mInstance) {
4301 nsCOMPtr<nsIPluginWidget> pluginWidget = do_QueryInterface(mWidget);
4302 if (pluginWidget && NS_SUCCEEDED(pluginWidget->StartDrawPlugin())) {
4303 WindowRef window = FixUpPluginWindow(ePluginPaintIgnore);
4304 if (window) {
4305 EventRecord idleEvent;
4306 InitializeEventRecord(&idleEvent);
4307 idleEvent.what = nullEvent;
4309 // give a bogus 'where' field of our null event when hidden, so Flash
4310 // won't respond to mouse moves in other tabs, see bug 120875
4311 if (!mWidgetVisible)
4312 idleEvent.where.h = idleEvent.where.v = 20000;
4314 nsPluginEvent pluginEvent = { &idleEvent, nsPluginPlatformWindowRef(window) };
4316 PRBool eventHandled = PR_FALSE;
4317 mInstance->HandleEvent(&pluginEvent, &eventHandled);
4320 pluginWidget->EndDrawPlugin();
4323 #endif
4324 return NS_OK;
4327 void nsPluginInstanceOwner::StartTimer(unsigned int aDelay)
4329 #ifdef XP_MACOSX
4330 nsresult rv;
4332 // start a periodic timer to provide null events to the plugin instance.
4333 if (!mPluginTimer) {
4334 mPluginTimer = do_CreateInstance("@mozilla.org/timer;1", &rv);
4335 if (NS_SUCCEEDED(rv))
4336 mPluginTimer->InitWithCallback(this, aDelay, nsITimer::TYPE_REPEATING_SLACK);
4338 #endif
4341 void nsPluginInstanceOwner::CancelTimer()
4343 if (mPluginTimer) {
4344 mPluginTimer->Cancel();
4345 mPluginTimer = nsnull;
4349 nsresult nsPluginInstanceOwner::Init(nsPresContext* aPresContext,
4350 nsObjectFrame* aFrame,
4351 nsIContent* aContent)
4353 mLastEventloopNestingLevel = 0;
4354 nsCOMPtr<nsIAppShell> appShell = do_GetService(kAppShellCID);
4355 if (appShell) {
4356 appShell->GetEventloopNestingLevel(&mLastEventloopNestingLevel);
4359 PR_LOG(nsObjectFrameLM, PR_LOG_DEBUG,
4360 ("nsPluginInstanceOwner::Init() called on %p for frame %p\n", this,
4361 aFrame));
4363 mOwner = aFrame;
4364 mContent = aContent;
4366 nsWeakFrame weakFrame(aFrame);
4368 // Some plugins require a specific sequence of shutdown and startup when
4369 // a page is reloaded. Shutdown happens usually when the last instance
4370 // is destroyed. Here we make sure the plugin instance in the old
4371 // document is destroyed before we try to create the new one.
4372 aPresContext->EnsureVisible(PR_TRUE);
4374 if (!weakFrame.IsAlive()) {
4375 PR_LOG(nsObjectFrameLM, PR_LOG_DEBUG,
4376 ("nsPluginInstanceOwner::Init's EnsureVisible() call destroyed "
4377 "instance owner %p\n", this));
4379 return NS_ERROR_NOT_AVAILABLE;
4382 // register context menu listener
4383 mCXMenuListener = new nsPluginDOMContextMenuListener();
4384 if (mCXMenuListener) {
4385 mCXMenuListener->Init(aContent);
4388 nsCOMPtr<nsIDOMEventTarget> target(do_QueryInterface(mContent));
4389 if (target) {
4391 nsCOMPtr<nsIDOMEventListener> listener;
4392 QueryInterface(NS_GET_IID(nsIDOMEventListener), getter_AddRefs(listener));
4394 // Register focus listener
4395 mContent->AddEventListenerByIID(listener, NS_GET_IID(nsIDOMFocusListener));
4397 // Register mouse listener
4398 mContent->AddEventListenerByIID(listener, NS_GET_IID(nsIDOMMouseListener));
4400 // now do the mouse motion listener
4401 mContent->AddEventListenerByIID(listener, NS_GET_IID(nsIDOMMouseMotionListener));
4403 // Register key listener
4404 target->AddEventListener(NS_LITERAL_STRING("keypress"), listener, PR_TRUE);
4405 target->AddEventListener(NS_LITERAL_STRING("keydown"), listener, PR_TRUE);
4406 target->AddEventListener(NS_LITERAL_STRING("keyup"), listener, PR_TRUE);
4408 // Register drag listener
4409 target->AddEventListener(NS_LITERAL_STRING("dragdrop"), listener, PR_TRUE);
4410 target->AddEventListener(NS_LITERAL_STRING("dragover"), listener, PR_TRUE);
4411 target->AddEventListener(NS_LITERAL_STRING("dragexit"), listener, PR_TRUE);
4412 target->AddEventListener(NS_LITERAL_STRING("dragenter"), listener, PR_TRUE);
4413 target->AddEventListener(NS_LITERAL_STRING("draggesture"), listener, PR_TRUE);
4416 // Register scroll position listener
4417 // We need to register a scroll pos listener on every scrollable
4418 // view up to the top
4419 nsIFrame* parentWithView = mOwner->GetAncestorWithView();
4420 nsIView* curView = parentWithView ? parentWithView->GetView() : nsnull;
4421 while (curView) {
4422 nsIScrollableView* scrollingView = curView->ToScrollableView();
4423 if (scrollingView)
4424 scrollingView->AddScrollPositionListener((nsIScrollPositionListener *)this);
4426 curView = curView->GetParent();
4429 return NS_OK;
4432 nsPluginPort* nsPluginInstanceOwner::GetPluginPort()
4434 //!!! Port must be released for windowless plugins on Windows, because it is HDC !!!
4436 nsPluginPort* result = NULL;
4437 if (mWidget) {
4438 #ifdef XP_WIN
4439 if (mPluginWindow && mPluginWindow->type == nsPluginWindowType_Drawable)
4440 result = (nsPluginPort*) mWidget->GetNativeData(NS_NATIVE_GRAPHIC);
4441 else
4442 #endif
4443 #ifdef XP_MACOSX
4444 if (GetDrawingModel() == NPDrawingModelCoreGraphics)
4445 result = (nsPluginPort*) mWidget->GetNativeData(NS_NATIVE_PLUGIN_PORT_CG);
4446 else
4447 #endif
4448 result = (nsPluginPort*) mWidget->GetNativeData(NS_NATIVE_PLUGIN_PORT);
4450 return result;
4453 void nsPluginInstanceOwner::ReleasePluginPort(nsPluginPort * pluginPort)
4455 #ifdef XP_WIN
4456 if (mWidget && mPluginWindow &&
4457 mPluginWindow->type == nsPluginWindowType_Drawable) {
4458 mWidget->FreeNativeData((HDC)pluginPort, NS_NATIVE_GRAPHIC);
4460 #endif
4463 NS_IMETHODIMP nsPluginInstanceOwner::CreateWidget(void)
4465 NS_ENSURE_TRUE(mPluginWindow, NS_ERROR_NULL_POINTER);
4467 nsIView *view;
4468 nsresult rv = NS_ERROR_FAILURE;
4470 if (mOwner) {
4471 // Create view if necessary
4473 view = mOwner->GetView();
4475 if (!view || !mWidget) {
4476 PRBool windowless = PR_FALSE;
4478 mInstance->GetValue(nsPluginInstanceVariable_WindowlessBool,
4479 (void *)&windowless);
4481 // always create widgets in Twips, not pixels
4482 nsPresContext* context = mOwner->PresContext();
4483 rv = mOwner->CreateWidget(context->DevPixelsToAppUnits(mPluginWindow->width),
4484 context->DevPixelsToAppUnits(mPluginWindow->height),
4485 windowless);
4486 if (NS_OK == rv) {
4487 view = mOwner->GetView();
4489 if (view) {
4490 mWidget = view->GetWidget();
4493 if (PR_TRUE == windowless) {
4494 mPluginWindow->type = nsPluginWindowType_Drawable;
4496 // this needs to be a HDC according to the spec, but I do
4497 // not see the right way to release it so let's postpone
4498 // passing HDC till paint event when it is really
4499 // needed. Change spec?
4500 mPluginWindow->window = nsnull;
4501 #ifdef MOZ_X11
4502 // Fill in the display field.
4503 nsIWidget* win = mOwner->GetWindow();
4504 NPSetWindowCallbackStruct* ws_info =
4505 static_cast<NPSetWindowCallbackStruct*>(mPluginWindow->ws_info);
4506 if (win) {
4507 ws_info->display =
4508 static_cast<Display*>(win->GetNativeData(NS_NATIVE_DISPLAY));
4510 #ifdef MOZ_WIDGET_GTK2
4511 else {
4512 ws_info->display = GDK_DISPLAY();
4514 #endif
4515 #endif
4516 } else if (mWidget) {
4517 mWidget->Resize(mPluginWindow->width, mPluginWindow->height,
4518 PR_FALSE);
4520 // mPluginWindow->type is used in |GetPluginPort| so it must
4521 // be initialized first
4522 mPluginWindow->type = nsPluginWindowType_Window;
4523 mPluginWindow->window = GetPluginPort();
4525 // start the idle timer.
4526 StartTimer(NORMAL_PLUGIN_DELAY);
4528 // tell the plugin window about the widget
4529 mPluginWindow->SetPluginWidget(mWidget);
4531 // tell the widget about the current plugin instance owner.
4532 nsCOMPtr<nsIPluginWidget> pluginWidget = do_QueryInterface(mWidget);
4533 if (pluginWidget)
4534 pluginWidget->SetPluginInstanceOwner(this);
4540 return rv;
4543 void nsPluginInstanceOwner::SetPluginHost(nsIPluginHost* aHost)
4545 mPluginHost = aHost;
4548 #if defined(XP_WIN) || (defined(DO_DIRTY_INTERSECT) && defined(XP_MACOSX)) || defined(XP_OS2)
4549 // convert frame coordinates from twips to pixels
4550 static void ConvertAppUnitsToPixels(const nsPresContext& aPresContext, const nsRect& aTwipsRect, nsIntRect& aPixelRect)
4552 aPixelRect.x = aPresContext.AppUnitsToDevPixels(aTwipsRect.x);
4553 aPixelRect.y = aPresContext.AppUnitsToDevPixels(aTwipsRect.y);
4554 aPixelRect.width = aPresContext.AppUnitsToDevPixels(aTwipsRect.width);
4555 aPixelRect.height = aPresContext.AppUnitsToDevPixels(aTwipsRect.height);
4557 #endif
4559 // Mac specific code to fix up the port location and clipping region
4560 #ifdef XP_MACOSX
4562 #ifdef DO_DIRTY_INTERSECT
4563 // Convert from a frame relative coordinate to a coordinate relative to its
4564 // containing window
4565 static void ConvertRelativeToWindowAbsolute(nsIFrame* aFrame,
4566 nsPoint& aRel,
4567 nsPoint& aAbs,
4568 nsIWidget*& aContainerWidget)
4570 // See if this frame has a view
4571 nsIView *view = aFrame->GetView();
4572 if (!view) {
4573 aAbs.x = 0;
4574 aAbs.y = 0;
4575 // Calculate frames offset from its nearest view
4576 aFrame->GetOffsetFromView(aAbs, &view);
4577 } else {
4578 // Store frames offset from its view.
4579 aAbs = aFrame->GetPosition();
4582 NS_ASSERTION(view, "the object frame does not have a view");
4583 if (view) {
4584 // Calculate the view's offset from its nearest widget
4585 nsPoint viewOffset;
4586 aContainerWidget = view->GetNearestWidget(&viewOffset);
4587 NS_IF_ADDREF(aContainerWidget);
4588 aAbs += viewOffset;
4591 // Add relative coordinate to the absolute coordinate that has been calculated
4592 aAbs += aRel;
4594 #endif // DO_DIRTY_INTERSECT
4596 WindowRef nsPluginInstanceOwner::FixUpPluginWindow(PRInt32 inPaintState)
4598 if (!mWidget || !mPluginWindow || !mInstance || !mOwner)
4599 return nsnull;
4601 nsPluginPort* pluginPort = GetPluginPort();
4603 if (!pluginPort)
4604 return nsnull;
4606 NPDrawingModel drawingModel = GetDrawingModel();
4608 // first, check our view for CSS visibility style
4609 PRBool isVisible =
4610 mOwner->GetView()->GetVisibility() == nsViewVisibility_kShow;
4612 nsCOMPtr<nsIPluginWidget> pluginWidget = do_QueryInterface(mWidget);
4614 nsPoint pluginOrigin;
4615 nsRect widgetClip;
4616 PRBool widgetVisible;
4617 pluginWidget->GetPluginClipRect(widgetClip, pluginOrigin, /* out */ widgetVisible);
4619 // printf("GetPluginClipRect returning visible %d\n", widgetVisible);
4621 isVisible &= widgetVisible;
4622 if (!isVisible)
4623 widgetClip.Empty();
4625 #ifndef NP_NO_QUICKDRAW
4626 // set the port coordinates
4627 if (drawingModel == NPDrawingModelQuickDraw) {
4628 mPluginWindow->x = -pluginPort->qdPort.portx;
4629 mPluginWindow->y = -pluginPort->qdPort.porty;
4631 else if (drawingModel == NPDrawingModelCoreGraphics)
4632 #endif
4634 // This would be a lot easier if we could use obj-c here,
4635 // but we can't. Since we have only nsIWidget and we can't
4636 // use its native widget (an obj-c object) we have to go
4637 // from the widget's screen coordinates to its window coords
4638 // instead of straight to window coords.
4639 nsRect geckoBounds;
4640 mWidget->GetBounds(geckoBounds);
4641 // we need a rect that is the entire *internal* rect, so the
4642 // x and y coords are 0, width is the same.
4643 geckoBounds.x = 0;
4644 geckoBounds.y = 0;
4645 nsRect geckoScreenCoords;
4646 mWidget->WidgetToScreen(geckoBounds, geckoScreenCoords);
4648 Rect windowRect;
4649 WindowRef window = (WindowRef)pluginPort->cgPort.window;
4650 ::GetWindowBounds(window, kWindowStructureRgn, &windowRect);
4652 mPluginWindow->x = geckoScreenCoords.x - windowRect.left;
4653 mPluginWindow->y = geckoScreenCoords.y - windowRect.top;
4656 nsPluginRect oldClipRect = mPluginWindow->clipRect;
4658 // fix up the clipping region
4659 mPluginWindow->clipRect.top = widgetClip.y;
4660 mPluginWindow->clipRect.left = widgetClip.x;
4662 mWidgetVisible = isVisible;
4664 if (!mWidgetVisible || inPaintState == ePluginPaintDisable) {
4665 mPluginWindow->clipRect.bottom = mPluginWindow->clipRect.top;
4666 mPluginWindow->clipRect.right = mPluginWindow->clipRect.left;
4667 // pluginPort = nsnull; // don't uncomment this
4669 else if (inPaintState == ePluginPaintEnable)
4671 mPluginWindow->clipRect.bottom = mPluginWindow->clipRect.top + widgetClip.height;
4672 mPluginWindow->clipRect.right = mPluginWindow->clipRect.left + widgetClip.width;
4675 // if the clip rect changed, call SetWindow()
4676 // (RealPlayer needs this to draw correctly)
4677 if (mPluginWindow->clipRect.left != oldClipRect.left ||
4678 mPluginWindow->clipRect.top != oldClipRect.top ||
4679 mPluginWindow->clipRect.right != oldClipRect.right ||
4680 mPluginWindow->clipRect.bottom != oldClipRect.bottom)
4682 mInstance->SetWindow(mPluginWindow);
4683 // if the clipRect is of size 0, make the null timer fire less often
4684 CancelTimer();
4685 if (mPluginWindow->clipRect.left == mPluginWindow->clipRect.right ||
4686 mPluginWindow->clipRect.top == mPluginWindow->clipRect.bottom) {
4687 StartTimer(HIDDEN_PLUGIN_DELAY);
4689 else {
4690 StartTimer(NORMAL_PLUGIN_DELAY);
4694 #ifndef NP_NO_QUICKDRAW
4695 if (drawingModel == NPDrawingModelQuickDraw)
4696 return ::GetWindowFromPort(pluginPort->qdPort.port);
4697 #endif
4699 if (drawingModel == NPDrawingModelCoreGraphics)
4700 return pluginPort->cgPort.window;
4702 return nsnull;
4705 #endif // XP_MACOSX
4707 // Little helper function to resolve relative URL in
4708 // |value| for certain inputs of |name|
4709 void nsPluginInstanceOwner::FixUpURLS(const nsString &name, nsAString &value)
4711 if (name.LowerCaseEqualsLiteral("pluginurl") ||
4712 name.LowerCaseEqualsLiteral("pluginspage")) {
4714 nsCOMPtr<nsIURI> baseURI = mContent->GetBaseURI();
4715 nsAutoString newURL;
4716 NS_MakeAbsoluteURI(newURL, value, baseURI);
4717 if (!newURL.IsEmpty())
4718 value = newURL;