Back to index

lightning-sunbird  0.9+nobinonly
nsObjectFrame.cpp
Go to the documentation of this file.
00001 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
00002 // vim:set ts=2 sts=2 sw=2 et cin:
00003 /* ***** BEGIN LICENSE BLOCK *****
00004  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
00005  *
00006  * The contents of this file are subject to the Mozilla Public License Version
00007  * 1.1 (the "License"); you may not use this file except in compliance with
00008  * the License. You may obtain a copy of the License at
00009  * http://www.mozilla.org/MPL/
00010  *
00011  * Software distributed under the License is distributed on an "AS IS" basis,
00012  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
00013  * for the specific language governing rights and limitations under the
00014  * License.
00015  *
00016  * The Original Code is Mozilla Communicator client code.
00017  *
00018  * The Initial Developer of the Original Code is
00019  * Netscape Communications Corporation.
00020  * Portions created by the Initial Developer are Copyright (C) 1998
00021  * the Initial Developer. All Rights Reserved.
00022  *
00023  * Contributor(s):
00024  *   Pierre Phaneuf <pp@ludusdesign.com>
00025  *   Jacek Piskozub <piskozub@iopan.gda.pl>
00026  *   Leon Sha <leon.sha@sun.com>
00027  *   Roland Mainz <roland.mainz@informatik.med.uni-giessen.de>
00028  *   Robert O'Callahan <roc+moz@cs.cmu.edu>
00029  *
00030  * Alternatively, the contents of this file may be used under the terms of
00031  * either of the GNU General Public License Version 2 or later (the "GPL"),
00032  * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
00033  * in which case the provisions of the GPL or the LGPL are applicable instead
00034  * of those above. If you wish to allow use of your version of this file only
00035  * under the terms of either the GPL or the LGPL, and not to allow others to
00036  * use your version of this file under the terms of the MPL, indicate your
00037  * decision by deleting the provisions above and replace them with the notice
00038  * and other provisions required by the GPL or the LGPL. If you do not delete
00039  * the provisions above, a recipient may use your version of this file under
00040  * the terms of any one of the MPL, the GPL or the LGPL.
00041  *
00042  * ***** END LICENSE BLOCK ***** */
00043 #include "nscore.h"
00044 #include "nsCOMPtr.h"
00045 #include "nsAutoPtr.h"
00046 #include "nsHTMLParts.h"
00047 #include "nsHTMLContainerFrame.h"
00048 #include "nsPresContext.h"
00049 #include "nsIPresShell.h"
00050 #include "nsStyleSet.h"
00051 #include "nsWidgetsCID.h"
00052 #include "nsIView.h"
00053 #include "nsIViewManager.h"
00054 #include "nsIDOMKeyListener.h"
00055 #include "nsIPluginHost.h"
00056 #include "nsplugin.h"
00057 #include "nsString.h"
00058 #include "nsReadableUtils.h"
00059 #include "prmem.h"
00060 #include "nsHTMLAtoms.h"
00061 #include "nsIDocument.h"
00062 #include "nsIHTMLDocument.h"
00063 #include "nsINodeInfo.h"
00064 #include "nsIPluginElement.h"
00065 #include "nsIURL.h"
00066 #include "nsNetUtil.h"
00067 #include "nsIPluginInstanceOwner.h"
00068 #include "nsISupportsArray.h"
00069 #include "plstr.h"
00070 #include "nsILinkHandler.h"
00071 #ifdef OJI
00072 #include "nsIJVMPluginTagInfo.h"
00073 #endif
00074 #include "nsINameSpaceManager.h"
00075 #include "nsIEventListener.h"
00076 #include "nsIScrollableView.h"
00077 #include "nsIScrollPositionListener.h"
00078 #include "nsIStringStream.h" // for NS_NewCharInputStream
00079 #include "nsITimer.h"
00080 #include "nsLayoutAtoms.h"
00081 #include "nsIDocShellTreeItem.h"
00082 #include "nsIDocShellTreeOwner.h"
00083 #include "nsIWebNavigation.h"
00084 #include "nsIWebNavigationInfo.h"
00085 #include "nsDocShellCID.h"
00086 #include "nsIWebBrowserChrome.h"
00087 #include "nsIDOMElement.h"
00088 #include "nsIDOMNodeList.h"
00089 #include "nsIDOMHTMLObjectElement.h"
00090 #include "nsIDOMHTMLEmbedElement.h"
00091 #include "nsIDOMHTMLAppletElement.h"
00092 #include "nsIDOMElementCSSInlineStyle.h"
00093 #include "nsIDOMCSSStyleDeclaration.h"
00094 #include "nsIDOMCSS2Properties.h"
00095 #include "nsContentPolicyUtils.h"
00096 #include "nsIDOMWindow.h"
00097 #include "nsIDOMDocumentEvent.h"
00098 #include "nsIDOMMouseListener.h"
00099 #include "nsIDOMMouseMotionListener.h"
00100 #include "nsIDOMFocusListener.h"
00101 #include "nsIDOMContextMenuListener.h"
00102 #include "nsIDOMDragListener.h"
00103 #include "nsIDOMEventReceiver.h"
00104 #include "nsIDOMNSEvent.h"
00105 #include "nsITextContent.h"
00106 #include "nsIPrivateDOMEvent.h"
00107 #include "nsIDocumentEncoder.h"
00108 #include "nsXPIDLString.h"
00109 #include "nsIDOMRange.h"
00110 #include "nsIPluginWidget.h"
00111 #include "nsGUIEvent.h"
00112 #include "nsIRenderingContext.h"
00113 #include "npapi.h"
00114 #include "nsGfxCIID.h"
00115 #include "nsUnicharUtils.h"
00116 #include "nsTransform2D.h"
00117 #include "nsIImageLoadingContent.h"
00118 #include "nsPIDOMWindow.h"
00119 #include "nsContentUtils.h"
00120 #include "nsIStringBundle.h"
00121 
00122 // headers for plugin scriptability
00123 #include "nsIScriptGlobalObject.h"
00124 #include "nsIScriptContext.h"
00125 #include "nsIXPConnect.h"
00126 #include "nsIXPCScriptable.h"
00127 #include "nsIClassInfo.h"
00128 #include "jsapi.h"
00129 
00130 // XXX For temporary paint code
00131 #include "nsStyleContext.h"
00132 
00133 // For mime types
00134 #include "nsMimeTypes.h"
00135 #include "nsIMIMEService.h"
00136 #include "nsCExternalHandlerService.h"
00137 #include "imgILoader.h"
00138 
00139 #include "nsObjectFrame.h"
00140 #include "nsIObjectFrame.h"
00141 #include "nsPluginNativeWindow.h"
00142 #include "nsPIPluginHost.h"
00143 #include "nsIPluginDocument.h"
00144 
00145 // accessibility support
00146 #ifdef ACCESSIBILITY
00147 #include "nsIAccessibilityService.h"
00148 #endif
00149 
00150 #ifdef MOZ_LOGGING
00151 #define FORCE_PR_LOG 1 /* Allow logging in the release build */
00152 #endif /* MOZ_LOGGING */
00153 #include "prlog.h"
00154 
00155 #include <errno.h>
00156 
00157 #include "nsContentCID.h"
00158 static NS_DEFINE_CID(kRangeCID, NS_RANGE_CID);
00159 
00160 /* X headers suck */
00161 #ifdef KeyPress
00162 #undef KeyPress
00163 #endif
00164 
00165 #ifdef XP_WIN
00166 #include <wtypes.h>
00167 #include <winuser.h>
00168 #endif
00169 
00170 #ifdef CreateEvent // Thank you MS.
00171 #undef CreateEvent
00172 #endif
00173 
00174 #ifdef PR_LOGGING 
00175 static PRLogModuleInfo *nsObjectFrameLM = PR_NewLogModule("nsObjectFrame");
00176 #endif /* PR_LOGGING */
00177 
00178 // True if the default plugin is disabled. Initialize to non-boolean
00179 // value so that we know if we've checked the pref or not.
00180 static PRBool sDefaultPluginDisabled = 0xffffffff;
00181 
00182 // special class for handeling DOM context menu events because for
00183 // some reason it starves other mouse events if implemented on the
00184 // same class
00185 class nsPluginDOMContextMenuListener : public nsIDOMContextMenuListener,
00186                                        public nsIEventListener
00187 {
00188 public:
00189   nsPluginDOMContextMenuListener();
00190   virtual ~nsPluginDOMContextMenuListener();
00191 
00192   NS_DECL_ISUPPORTS
00193 
00194   NS_IMETHOD ContextMenu(nsIDOMEvent* aContextMenuEvent);
00195   
00196   nsresult Init(nsObjectFrame *aFrame);
00197   nsresult Destroy(nsObjectFrame *aFrame);
00198   
00199   NS_IMETHOD HandleEvent(nsIDOMEvent* aEvent)
00200   {
00201     return NS_OK;
00202   }
00203   nsEventStatus ProcessEvent(const nsGUIEvent& anEvent)
00204   {
00205     return nsEventStatus_eConsumeNoDefault;
00206   }
00207 };
00208 
00209 
00210 class nsPluginInstanceOwner : public nsIPluginInstanceOwner,
00211                               public nsIPluginTagInfo2,
00212 #ifdef OJI
00213                               public nsIJVMPluginTagInfo,
00214 #endif
00215                               public nsIEventListener,
00216                               public nsITimerCallback,
00217                               public nsIDOMMouseListener,
00218                               public nsIDOMMouseMotionListener,
00219                               public nsIDOMKeyListener,
00220                               public nsIDOMFocusListener,
00221                               public nsIScrollPositionListener,
00222                               public nsIDOMDragListener
00223 
00224 {
00225 public:
00226   nsPluginInstanceOwner();
00227   virtual ~nsPluginInstanceOwner();
00228 
00229   NS_DECL_ISUPPORTS
00230 
00231   //nsIPluginInstanceOwner interface
00232 
00233   NS_IMETHOD SetInstance(nsIPluginInstance *aInstance);
00234 
00235   NS_IMETHOD GetInstance(nsIPluginInstance *&aInstance);
00236 
00237   NS_IMETHOD GetWindow(nsPluginWindow *&aWindow);
00238 
00239   NS_IMETHOD GetMode(nsPluginMode *aMode);
00240 
00241   NS_IMETHOD CreateWidget(void);
00242 
00243   NS_IMETHOD GetURL(const char *aURL, const char *aTarget, void *aPostData, 
00244                     PRUint32 aPostDataLen, void *aHeadersData, 
00245                     PRUint32 aHeadersDataLen, PRBool isFile = PR_FALSE);
00246 
00247   NS_IMETHOD ShowStatus(const char *aStatusMsg);
00248 
00249   NS_IMETHOD ShowStatus(const PRUnichar *aStatusMsg);
00250   
00251   NS_IMETHOD GetDocument(nsIDocument* *aDocument);
00252 
00253   NS_IMETHOD InvalidateRect(nsPluginRect *invalidRect);
00254 
00255   NS_IMETHOD InvalidateRegion(nsPluginRegion invalidRegion);
00256 
00257   NS_IMETHOD ForceRedraw();
00258 
00259   NS_IMETHOD GetValue(nsPluginInstancePeerVariable variable, void *value);
00260 
00261   NS_IMETHOD PluginNotAvailable(const char *aMimeType);
00262 
00263   //nsIPluginTagInfo interface
00264 
00265   NS_IMETHOD GetAttributes(PRUint16& n, const char*const*& names,
00266                            const char*const*& values);
00267 
00268   NS_IMETHOD GetAttribute(const char* name, const char* *result);
00269 
00270   //nsIPluginTagInfo2 interface
00271 
00272   NS_IMETHOD GetTagType(nsPluginTagType *result);
00273 
00274   NS_IMETHOD GetTagText(const char* *result);
00275 
00276   NS_IMETHOD GetParameters(PRUint16& n, const char*const*& names, const char*const*& values);
00277 
00278   NS_IMETHOD GetParameter(const char* name, const char* *result);
00279   
00280   NS_IMETHOD GetDocumentBase(const char* *result);
00281   
00282   NS_IMETHOD GetDocumentEncoding(const char* *result);
00283   
00284   NS_IMETHOD GetAlignment(const char* *result);
00285   
00286   NS_IMETHOD GetWidth(PRUint32 *result);
00287   
00288   NS_IMETHOD GetHeight(PRUint32 *result);
00289 
00290   NS_IMETHOD GetBorderVertSpace(PRUint32 *result);
00291   
00292   NS_IMETHOD GetBorderHorizSpace(PRUint32 *result);
00293 
00294   NS_IMETHOD GetUniqueID(PRUint32 *result);
00295 
00296   NS_IMETHOD GetDOMElement(nsIDOMElement* *result);
00297 
00298 #ifdef OJI
00299   //nsIJVMPluginTagInfo interface
00300 
00301   NS_IMETHOD GetCode(const char* *result);
00302 
00303   NS_IMETHOD GetCodeBase(const char* *result);
00304 
00305   NS_IMETHOD GetArchive(const char* *result);
00306 
00307   NS_IMETHOD GetName(const char* *result);
00308 
00309   NS_IMETHOD GetMayScript(PRBool *result);
00310 
00311 #endif /* OJI */
00312 
00316   NS_IMETHOD MouseDown(nsIDOMEvent* aMouseEvent);
00317   NS_IMETHOD MouseUp(nsIDOMEvent* aMouseEvent);
00318   NS_IMETHOD MouseClick(nsIDOMEvent* aMouseEvent);
00319   NS_IMETHOD MouseDblClick(nsIDOMEvent* aMouseEvent);
00320   NS_IMETHOD MouseOver(nsIDOMEvent* aMouseEvent);
00321   NS_IMETHOD MouseOut(nsIDOMEvent* aMouseEvent);
00322   NS_IMETHOD HandleEvent(nsIDOMEvent* aEvent);     
00323   /* END interfaces from nsIDOMMouseListener*/
00324 
00325   // nsIDOMMouseListener intefaces
00326   NS_IMETHOD MouseMove(nsIDOMEvent* aMouseEvent);
00327   NS_IMETHOD DragMove(nsIDOMEvent* aMouseEvent) { return NS_OK; }
00328 
00329   // nsIDOMKeyListener interfaces
00330   NS_IMETHOD KeyDown(nsIDOMEvent* aKeyEvent);
00331   NS_IMETHOD KeyUp(nsIDOMEvent* aKeyEvent);
00332   NS_IMETHOD KeyPress(nsIDOMEvent* aKeyEvent);
00333   // end nsIDOMKeyListener interfaces
00334 
00335   // nsIDOMFocuListener interfaces
00336   NS_IMETHOD Focus(nsIDOMEvent * aFocusEvent);
00337   NS_IMETHOD Blur(nsIDOMEvent * aFocusEvent);
00338   
00339   // nsIDOMDragListener interfaces
00340   NS_IMETHOD DragEnter(nsIDOMEvent* aMouseEvent);
00341   NS_IMETHOD DragOver(nsIDOMEvent* aMouseEvent);
00342   NS_IMETHOD DragExit(nsIDOMEvent* aMouseEvent);
00343   NS_IMETHOD DragDrop(nsIDOMEvent* aMouseEvent);
00344   NS_IMETHOD DragGesture(nsIDOMEvent* aMouseEvent);
00345   
00346 
00347   nsresult Destroy();  
00348 
00349   //nsIEventListener interface
00350   nsEventStatus ProcessEvent(const nsGUIEvent & anEvent);
00351   
00352   void Paint(const nsRect& aDirtyRect, PRUint32 ndc = 0);
00353 
00354   // nsITimerCallback interface
00355   NS_DECL_NSITIMERCALLBACK
00356   
00357   void CancelTimer();
00358   void StartTimer();
00359 
00360   // nsIScrollPositionListener interface
00361   NS_IMETHOD ScrollPositionWillChange(nsIScrollableView* aScrollable, nscoord aX, nscoord aY);
00362   NS_IMETHOD ScrollPositionDidChange(nsIScrollableView* aScrollable, nscoord aX, nscoord aY);
00363 
00364   //locals
00365 
00366   NS_IMETHOD Init(nsPresContext *aPresContext, nsObjectFrame *aFrame);
00367 
00368   nsPluginPort* GetPluginPort();
00369   void ReleasePluginPort(nsPluginPort * pluginPort);
00370 
00371   void SetPluginHost(nsIPluginHost* aHost);
00372 
00373 #if defined(XP_MAC) || defined(XP_MACOSX)
00374   nsPluginPort* FixUpPluginWindow(PRInt32 inPaintState);
00375   void GUItoMacEvent(const nsGUIEvent& anEvent, EventRecord* origEvent, EventRecord& aMacEvent);
00376   void Composite();
00377 #endif
00378 
00379 private:
00380   nsPluginNativeWindow       *mPluginWindow;
00381   nsCOMPtr<nsIPluginInstance> mInstance;
00382   nsObjectFrame              *mOwner;
00383   nsCString                   mDocumentBase;
00384   char                       *mTagText;
00385   nsCOMPtr<nsIWidget>         mWidget;
00386   nsPresContext              *mContext;
00387   nsCOMPtr<nsITimer>          mPluginTimer;
00388   nsCOMPtr<nsIPluginHost>     mPluginHost;
00389   PRPackedBool                mContentFocused;
00390   PRPackedBool                mWidgetVisible;    // used on Mac to store our widget's visible state
00391   PRUint16          mNumCachedAttrs;
00392   PRUint16          mNumCachedParams;
00393   char              **mCachedAttrParamNames;
00394   char              **mCachedAttrParamValues;
00395   
00396   nsPluginDOMContextMenuListener * mCXMenuListener;  // pointer to wrapper for nsIDOMContextMenuListener
00397   
00398   nsresult DispatchKeyToPlugin(nsIDOMEvent* aKeyEvent);
00399   nsresult DispatchMouseToPlugin(nsIDOMEvent* aMouseEvent);
00400   nsresult DispatchFocusToPlugin(nsIDOMEvent* aFocusEvent);
00401 
00402   nsresult EnsureCachedAttrParamArrays();
00403 
00404   PRPackedBool mInDispatchFocus; // Used in DispatchFocusToPlugin()
00405 };
00406 
00407 #if defined(XP_WIN) || (defined(DO_DIRTY_INTERSECT) && (defined(XP_MAC) || defined(XP_MACOSX)))
00408 static void ConvertTwipsToPixels(nsPresContext& aPresContext, nsRect& aTwipsRect, nsRect& aPixelRect);
00409 #endif
00410 
00411   // Mac specific code to fix up port position and clip during paint
00412 #if defined(XP_MAC) || defined(XP_MACOSX)
00413 
00414 #ifdef DO_DIRTY_INTERSECT
00415   // convert relative coordinates to absolute
00416   static void ConvertRelativeToWindowAbsolute(nsIFrame* aFrame, nsPoint& aRel, nsPoint& aAbs, nsIWidget *&aContainerWidget);
00417 #endif
00418 
00419   enum { ePluginPaintIgnore, ePluginPaintEnable, ePluginPaintDisable };
00420 
00421 #endif // XP_MAC
00422 
00423 nsObjectFrame::~nsObjectFrame()
00424 {
00425 }
00426 
00427 NS_IMETHODIMP
00428 nsObjectFrame::QueryInterface(const nsIID& aIID, void** aInstancePtr)
00429 {
00430   NS_ENSURE_ARG_POINTER(aInstancePtr);
00431   *aInstancePtr = nsnull;
00432 
00433 #ifdef DEBUG
00434   if (aIID.Equals(NS_GET_IID(nsIFrameDebug))) {
00435     *aInstancePtr = NS_STATIC_CAST(nsIFrameDebug*,this);
00436     return NS_OK;
00437   }
00438 #endif
00439 
00440   if (aIID.Equals(NS_GET_IID(nsIObjectFrame))) {
00441     *aInstancePtr = NS_STATIC_CAST(nsIObjectFrame*,this);
00442     return NS_OK;
00443   } else if (aIID.Equals(NS_GET_IID(nsIFrame))) {
00444     *aInstancePtr = NS_STATIC_CAST(nsIFrame*,this);
00445     return NS_OK;
00446   } else if (aIID.Equals(NS_GET_IID(nsISupports))) {
00447     *aInstancePtr = NS_STATIC_CAST(nsIObjectFrame*,this);
00448     return NS_OK;
00449   }
00450   return NS_NOINTERFACE;
00451 }
00452 
00453 NS_IMETHODIMP_(nsrefcnt) nsObjectFrame::AddRef(void)
00454 {
00455   NS_WARNING("not supported for frames");
00456   return 1;
00457 }
00458 
00459 NS_IMETHODIMP_(nsrefcnt) nsObjectFrame::Release(void)
00460 {
00461   NS_WARNING("not supported for frames");
00462   return 1;
00463 }
00464 
00465 #ifdef ACCESSIBILITY
00466 NS_IMETHODIMP nsObjectFrame::GetAccessible(nsIAccessible** aAccessible)
00467 {
00468   nsCOMPtr<nsIAccessibilityService> accService = do_GetService("@mozilla.org/accessibilityService;1");
00469 
00470   if (accService) {
00471     return accService->CreateHTMLObjectFrameAccessible(this, aAccessible);
00472   }
00473 
00474   return NS_ERROR_FAILURE;
00475 }
00476 
00477 #ifdef XP_WIN
00478 NS_IMETHODIMP nsObjectFrame::GetPluginPort(HWND *aPort)
00479 {
00480   *aPort = (HWND) mInstanceOwner->GetPluginPort();
00481   return NS_OK;
00482 }
00483 #endif
00484 #endif
00485 
00486 
00487 static NS_DEFINE_CID(kWidgetCID, NS_CHILD_CID);
00488 static NS_DEFINE_CID(kCAppShellCID, NS_APPSHELL_CID);
00489 static NS_DEFINE_CID(kCPluginManagerCID, NS_PLUGINMANAGER_CID);
00490 
00491 PRIntn
00492 nsObjectFrame::GetSkipSides() const
00493 {
00494   return 0;
00495 }
00496 
00497 // #define DO_DIRTY_INTERSECT 1   // enable dirty rect intersection during paint
00498 static PRBool
00499 IsSupportedImage(const nsCString& aMimeType)
00500 {
00501   nsCOMPtr<imgILoader> loader(do_GetService("@mozilla.org/image/loader;1"));
00502 
00503   PRBool supported;
00504   nsresult rv = loader->SupportImageWithMimeType(aMimeType.get(), &supported);
00505 
00506   return NS_SUCCEEDED(rv) && supported;
00507 }
00508 
00509 static PRBool
00510 IsSupportedDocument(nsIContent* aOurContent,
00511                     const nsCString& aMimeType)
00512 {
00513   nsresult rv;
00514 
00515   // only allow browser to handle content of <embed> for svg (bug 240408)
00516   if (aOurContent->Tag() == nsHTMLAtoms::embed)
00517 #ifdef MOZ_SVG
00518     if (!aMimeType.LowerCaseEqualsLiteral("image/svg+xml"))
00519 #endif
00520       return PR_FALSE;
00521 
00522 
00523   nsCOMPtr<nsIWebNavigationInfo> info(
00524     do_GetService(NS_WEBNAVIGATION_INFO_CONTRACTID, &rv));
00525   PRUint32 supported;
00526   if (info) {
00527     nsCOMPtr<nsIWebNavigation> webNav =
00528       do_GetInterface(aOurContent->GetCurrentDoc()->GetScriptGlobalObject());
00529     rv = info->IsTypeSupported(aMimeType, webNav, &supported);
00530   }
00531 
00532   return NS_SUCCEEDED(rv) &&
00533     supported != nsIWebNavigationInfo::UNSUPPORTED &&
00534     supported != nsIWebNavigationInfo::PLUGIN;
00535 }
00536 
00537 nsresult
00538 nsObjectFrame::GetMIMEType(nsACString& aType)
00539 {
00540   nsAutoString type;
00541   nsresult rv = mContent->GetAttr(kNameSpaceID_None, nsHTMLAtoms::type, type);
00542   if (rv != NS_CONTENT_ATTR_HAS_VALUE || type.IsEmpty()) {
00543     // if we don't have a TYPE= try getting the mime-type via the DATA= url
00544     nsAutoString data;
00545     // If this is an OBJECT tag, we should look for a DATA attribute.
00546     // If not, it's an EMBED tag, and so we should look for a SRC attribute.
00547     if (mContent->Tag() == nsHTMLAtoms::object)
00548       rv = mContent->GetAttr(kNameSpaceID_None, nsHTMLAtoms::data, data);
00549     else
00550       rv = mContent->GetAttr(kNameSpaceID_None, nsHTMLAtoms::src, data);
00551 
00552     if (rv != NS_CONTENT_ATTR_HAS_VALUE || data.IsEmpty()) {
00553       return NS_ERROR_NOT_AVAILABLE;
00554     }
00555     
00556     nsCOMPtr<nsIURI> uri;
00557     nsCOMPtr<nsIURI> baseURI = mContent->GetBaseURI();
00558     rv = NS_NewURI(getter_AddRefs(uri), data, mContent->GetOwnerDoc()->GetDocumentCharacterSet().get(), baseURI);
00559     if (NS_FAILED(rv))
00560       return rv;
00561 
00562     nsCOMPtr<nsIMIMEService> mimeService = do_GetService(NS_MIMESERVICE_CONTRACTID, &rv);
00563     if (NS_FAILED(rv))
00564       return rv;
00565 
00566     nsXPIDLCString contentType;
00567     rv = mimeService->GetTypeFromURI(uri, contentType);
00568     if (NS_FAILED(rv) || contentType.IsEmpty())
00569       return NS_ERROR_NOT_AVAILABLE;
00570     
00571     aType = contentType;
00572   } else {
00573     CopyUTF16toUTF8(type, aType);
00574   }
00575 
00576   return NS_OK;
00577 }
00578 
00579 NS_IMETHODIMP
00580 nsObjectFrame::SetInitialChildList(nsPresContext*  aPresContext,
00581                                    nsIAtom*        aListName,
00582                                    nsIFrame*       aChildList)
00583 {
00584   // we don't want to call this if it is already set (image)
00585   nsresult rv = NS_OK;
00586   if (mFrames.IsEmpty())
00587     rv = nsObjectFrameSuper::SetInitialChildList(aPresContext, aListName, aChildList);
00588   return rv;
00589 }
00590 
00591 static void
00592 FirePluginNotFoundEvent(nsIContent *aTarget)
00593 {
00594   nsCOMPtr<nsIDOMDocumentEvent> eventDoc =
00595     do_QueryInterface(aTarget->GetDocument());
00596   nsCOMPtr<nsIDOMEventTarget> target(do_QueryInterface(aTarget));
00597 
00598   if (eventDoc) {
00599     nsCOMPtr<nsIDOMEvent> event;
00600     nsresult rv = eventDoc->CreateEvent(NS_LITERAL_STRING("Events"),
00601                                         getter_AddRefs(event));
00602     if (NS_SUCCEEDED(rv)) {
00603       rv = event->InitEvent(NS_LITERAL_STRING("PluginNotFound"), PR_TRUE,
00604                             PR_TRUE);
00605       if (NS_SUCCEEDED(rv)) {
00606         nsCOMPtr<nsIPrivateDOMEvent> privateEvent(do_QueryInterface(event));
00607         privateEvent->SetTrusted(PR_TRUE);
00608 
00609         PRBool defaultActionEnabled;
00610         target->DispatchEvent(event, &defaultActionEnabled);
00611       }
00612     }
00613   }
00614 }
00615 
00616 NS_IMETHODIMP 
00617 nsObjectFrame::Init(nsPresContext*   aPresContext,
00618                     nsIContent*      aContent,
00619                     nsIFrame*        aParent,
00620                     nsStyleContext*  aContext,
00621                     nsIFrame*        aPrevInFlow)
00622 {
00623 #ifdef DEBUG
00624   mInstantiating = PR_FALSE;
00625 #endif
00626   mIsBrokenPlugin = PR_FALSE;
00627 
00628   if (sDefaultPluginDisabled == (PRBool)0xffffffff) {
00629     sDefaultPluginDisabled =
00630       nsContentUtils::GetBoolPref("plugin.default_plugin_disabled");
00631   }
00632 
00633   nsresult rv = nsObjectFrameSuper::Init(aPresContext, aContent, aParent,
00634                                          aContext, aPrevInFlow);
00635 
00636   if (NS_FAILED(rv))
00637     return rv;
00638 
00639   // Find our content type
00640   nsCAutoString type;
00641   rv = GetMIMEType(type);
00642   // If that fails, just return and render nothing.
00643   if (NS_FAILED(rv))
00644     return NS_OK;
00645 
00646   // Ideally this should move to Reflow when the stream starts to come
00647   if (IsSupportedImage(type)) {
00648     // kick off the image load in the content node
00649     // XXX once this moves to somewhere where we have the data stream,
00650     // we should have a way to load images with a channel....
00651     nsCOMPtr<nsIImageLoadingContent> imageLoader = do_QueryInterface(aContent);
00652     if (!imageLoader) {
00653       NS_ERROR("Not an image loading content?");
00654       return NS_ERROR_UNEXPECTED;
00655     }
00656 
00657     nsAutoString data;
00658 
00659     // If this is an OBJECT tag, we should look for a DATA attribute.
00660     // If not, it's an EMBED tag, and so we should look for a SRC attribute.
00661     if (aContent->Tag() == nsHTMLAtoms::object)
00662       rv = aContent->GetAttr(kNameSpaceID_None, nsHTMLAtoms::data, data);
00663     else
00664       rv = aContent->GetAttr(kNameSpaceID_None, nsHTMLAtoms::src, data);
00665 
00666     imageLoader->ImageURIChanged(data);
00667 
00668     nsIFrame * aNewFrame = nsnull;
00669     rv = NS_NewImageFrame(aPresContext->PresShell(), &aNewFrame);
00670     if (NS_FAILED(rv))
00671       return rv;
00672 
00673     // XXX we're using the same style context for ourselves and the
00674     // image frame.  If this ever changes, please fix HandleChild() to deal.
00675     rv = aNewFrame->Init(aPresContext, aContent, this, aContext, aPrevInFlow);
00676     if (NS_SUCCEEDED(rv)) {
00677       nsHTMLContainerFrame::CreateViewForFrame(aNewFrame, nsnull, PR_FALSE);
00678       mFrames.AppendFrame(this, aNewFrame);
00679     }
00680     else
00681       aNewFrame->Destroy(aPresContext);
00682 
00683     return rv; // bail at this point
00684   }
00685 
00686   // for now, we should try to do the same for "document" types and
00687   // create an iframe-like sub-frame
00688   if (IsSupportedDocument(aContent, type)) {
00689     nsIFrame * aNewFrame = nsnull;
00690     rv = NS_NewSubDocumentFrame(aPresContext->PresShell(), &aNewFrame);
00691     if (NS_FAILED(rv))
00692       return rv;
00693     
00694     // XXX we're using the same style context for ourselves and the
00695     // iframe.  If this ever changes, please fix HandleChild() to deal.
00696     rv = aNewFrame->Init(aPresContext, aContent, this, aContext, aPrevInFlow);
00697     if (NS_SUCCEEDED(rv)) {
00698       nsHTMLContainerFrame::CreateViewForFrame(aNewFrame, nsnull, PR_FALSE);
00699       mFrames.AppendFrame(this, aNewFrame);
00700     } else {
00701       aNewFrame->Destroy(aPresContext);
00702     }
00703   }
00704 
00705   return rv;
00706 }
00707 
00708 NS_IMETHODIMP
00709 nsObjectFrame::Destroy(nsPresContext* aPresContext)
00710 {
00711   NS_ASSERTION(!mInstantiating, "about to crash due to bug 136927");
00712 
00713   // we need to finish with the plugin before native window is destroyed
00714   // doing this in the destructor is too late.
00715   if (mInstanceOwner != nsnull) {
00716     nsCOMPtr<nsIPluginInstance> inst;
00717     mInstanceOwner->GetInstance(*getter_AddRefs(inst));
00718     if (inst) {
00719       nsPluginWindow *win;
00720       mInstanceOwner->GetWindow(win);
00721       nsPluginNativeWindow *window = (nsPluginNativeWindow *)win;
00722       nsCOMPtr<nsIPluginInstance> nullinst;
00723 
00724       PRBool doCache = PR_TRUE;
00725       PRBool doCallSetWindowAfterDestroy = PR_FALSE;
00726 
00727       // first, determine if the plugin wants to be cached
00728       inst->GetValue(nsPluginInstanceVariable_DoCacheBool, 
00729                      (void *) &doCache);
00730       if (!doCache) {
00731         // then determine if the plugin wants Destroy to be called after
00732         // Set Window.  This is for bug 50547.
00733         inst->GetValue(nsPluginInstanceVariable_CallSetWindowAfterDestroyBool, 
00734                        (void *) &doCallSetWindowAfterDestroy);
00735         if (doCallSetWindowAfterDestroy) {
00736           inst->Stop();
00737           inst->Destroy();
00738           
00739           if (window) 
00740             window->CallSetWindow(nullinst);
00741           else 
00742             inst->SetWindow(nsnull);
00743         }
00744         else {
00745           if (window) 
00746             window->CallSetWindow(nullinst);
00747           else 
00748             inst->SetWindow(nsnull);
00749 
00750           inst->Stop();
00751           inst->Destroy();
00752         }
00753       }
00754       else {
00755         if (window) 
00756           window->CallSetWindow(nullinst);
00757         else 
00758           inst->SetWindow(nsnull);
00759 
00760         inst->Stop();
00761       }
00762 
00763       nsCOMPtr<nsIPluginHost> pluginHost = do_GetService(kCPluginManagerCID);
00764       if (pluginHost)
00765         pluginHost->StopPluginInstance(inst);
00766 
00767       // the frame is going away along with its widget
00768       // so tell the window to forget its widget too
00769       if (window)
00770         window->SetPluginWidget(nsnull);
00771     }
00772 
00773     mInstanceOwner->Destroy();
00774     NS_RELEASE(mInstanceOwner);
00775   }
00776   
00777   return nsObjectFrameSuper::Destroy(aPresContext);
00778 }
00779 
00780 nsIAtom*
00781 nsObjectFrame::GetType() const
00782 {
00783   return nsLayoutAtoms::objectFrame; 
00784 }
00785 
00786 #ifdef DEBUG
00787 NS_IMETHODIMP
00788 nsObjectFrame::GetFrameName(nsAString& aResult) const
00789 {
00790   return MakeFrameName(NS_LITERAL_STRING("ObjectFrame"), aResult);
00791 }
00792 #endif
00793 
00794 nsresult
00795 nsObjectFrame::CreateWidgetForView(nsIView* aView)
00796 {
00797   // Bug 179822: Create widget and allow non-unicode SubClass
00798   nsWidgetInitData initData;
00799   initData.mUnicode = PR_FALSE;
00800   return aView->CreateWidget(kWidgetCID, &initData);
00801 }
00802 
00803 PRBool
00804 nsObjectFrame::IsLeaf() const
00805 {
00806   // We're actually a leaf.  We inherit from nsContainerFrame for
00807   // convenience for now, but we construct our own kids and the frame
00808   // constructor shouldn't be messing with them.
00809   // XXXbz ideally, we wouldn't have this child frame thing at all.
00810   return PR_TRUE;
00811 }
00812 
00813 nsresult
00814 nsObjectFrame::CreateWidget(nscoord aWidth,
00815                             nscoord aHeight,
00816                             PRBool  aViewOnly)
00817 {
00818   nsIView* view = GetView();
00819   NS_ASSERTION(view, "Object frames must have views");  
00820   if (!view) {
00821     return NS_OK;       //XXX why OK? MMP
00822   }
00823 
00824   nsIViewManager* viewMan = view->GetViewManager();
00825   // make the view as hidden since we don't know the (x,y) until Paint
00826   // XXX is the above comment correct?
00827   viewMan->SetViewVisibility(view, nsViewVisibility_kHide);
00828 
00829   // Turn off double buffering on the Mac. This depends on bug 49743 and partially
00830   // fixes 32327, 19931 amd 51787
00831 #if defined(XP_MAC) || defined(XP_MACOSX)
00832   PRBool doubleBuffer =
00833     nsContentUtils::GetBoolPref("plugin.enable_double_buffer");
00834   
00835   viewMan->AllowDoubleBuffering(doubleBuffer);
00836 #endif
00837   
00838   //this is ugly. it was ripped off from didreflow(). MMP
00839   // Position and size view relative to its parent, not relative to our
00840   // parent frame (our parent frame may not have a view).
00841   
00842   nsIView* parentWithView;
00843   nsPoint origin;
00844   nsRect r(0, 0, mRect.width, mRect.height);
00845 
00846   GetOffsetFromView(origin, &parentWithView);
00847   viewMan->ResizeView(view, r);
00848   viewMan->MoveViewTo(view, origin.x, origin.y);
00849 
00850   if (!aViewOnly && !view->HasWidget()) {
00851     nsresult rv = CreateWidgetForView(view);
00852     if (NS_FAILED(rv)) {
00853       return NS_OK;       //XXX why OK? MMP
00854     }
00855   }
00856 
00857   {
00858     // Here we set the background color for this widget because some plugins will use 
00859     // the child window background color when painting. If it's not set, it may default to gray
00860     // Sometimes, a frame doesn't have a background color or is transparent. In this
00861     // case, walk up the frame tree until we do find a frame with a background color
00862     for (nsIFrame* frame = this; frame; frame = frame->GetParent()) {
00863       const nsStyleBackground* background = frame->GetStyleBackground();
00864       if (!background->IsTransparent()) {  // make sure we got an actual color
00865         nsIWidget* win = view->GetWidget();
00866         if (win)
00867           win->SetBackgroundColor(background->mBackgroundColor);
00868         break;
00869       }
00870     }
00871 
00872   }
00873 
00874   viewMan->SetViewVisibility(view, nsViewVisibility_kShow);
00875 
00876   return NS_OK;
00877 }
00878 
00879 #define EMBED_DEF_WIDTH 240
00880 #define EMBED_DEF_HEIGHT 200
00881 
00882 void
00883 nsObjectFrame::GetDesiredSize(nsPresContext* aPresContext,
00884                               const nsHTMLReflowState& aReflowState,
00885                               nsHTMLReflowMetrics& aMetrics)
00886 {
00887   // By default, we have no area
00888   aMetrics.width = 0;
00889   aMetrics.height = 0;
00890   aMetrics.ascent = 0;
00891   aMetrics.descent = 0;
00892 
00893   if (IsHidden(PR_FALSE)) {
00894     if (aMetrics.mComputeMEW) {
00895       aMetrics.mMaxElementWidth = 0;
00896     }      
00897     return;
00898   }
00899   
00900   aMetrics.width = aReflowState.mComputedWidth;
00901   aMetrics.height = aReflowState.mComputedHeight;
00902 
00903   // for EMBED and APPLET, default to 240x200 for compatibility
00904   nsIAtom *atom = mContent->Tag();
00905   if (atom == nsHTMLAtoms::applet || atom == nsHTMLAtoms::embed) {
00906     float p2t = aPresContext->ScaledPixelsToTwips();
00907     if (aMetrics.width == NS_UNCONSTRAINEDSIZE) {
00908       aMetrics.width = PR_MIN(PR_MAX(NSIntPixelsToTwips(EMBED_DEF_WIDTH, p2t),
00909                                      aReflowState.mComputedMinWidth),
00910                               aReflowState.mComputedMaxWidth);
00911     }
00912     if (aMetrics.height == NS_UNCONSTRAINEDSIZE) {
00913       aMetrics.height = PR_MIN(PR_MAX(NSIntPixelsToTwips(EMBED_DEF_HEIGHT, p2t),
00914                                       aReflowState.mComputedMinHeight),
00915                                aReflowState.mComputedMaxHeight);
00916     }
00917 
00918 #if defined (MOZ_WIDGET_GTK) || defined (MOZ_WIDGET_GTK2) || defined (MOZ_WIDGET_XLIB)  
00919     // We need to make sure that the size of the object frame does not
00920     // exceed the maximum size of X coordinates.  See bug #225357 for
00921     // more information.  In theory Gtk2 can handle large coordinates,
00922     // but underlying plugins can't.
00923     aMetrics.height = PR_MIN(NSIntPixelsToTwips(PR_INT16_MAX, p2t), aMetrics.height);
00924     aMetrics.width = PR_MIN(NSIntPixelsToTwips(PR_INT16_MAX, p2t), aMetrics.width);
00925 #endif
00926   }
00927 
00928   // At this point, the width has an unconstrained value only if we have
00929   // nothing to go on (no width set, no information from the plugin, nothing).
00930   // Make up a number.
00931   if (aMetrics.width == NS_UNCONSTRAINEDSIZE) {
00932     aMetrics.width =
00933       (aReflowState.mComputedMinWidth != NS_UNCONSTRAINEDSIZE) ?
00934         aReflowState.mComputedMinWidth : 0;
00935   }
00936 
00937   // At this point, the height has an unconstrained value only in two cases:
00938   // a) We are in standards mode with percent heights and parent is auto-height
00939   // b) We have no height information at all.
00940   // In either case, we have to make up a number.
00941   if (aMetrics.height == NS_UNCONSTRAINEDSIZE) {
00942     aMetrics.height =
00943       (aReflowState.mComputedMinHeight != NS_UNCONSTRAINEDSIZE) ?
00944         aReflowState.mComputedMinHeight : 0;
00945   }
00946 
00947   // XXXbz don't add in the border and padding, because we screw up our
00948   // plugin's size and positioning if we do...  Eventually we _do_ want to
00949   // paint borders, though!  At that point, we will need to adjust the desired
00950   // size either here or in Reflow....  Further, we will need to fix Paint() to
00951   // call the superclass in all cases.
00952   
00953   // ascent
00954   aMetrics.ascent = aMetrics.height;
00955 
00956   if (aMetrics.mComputeMEW) {
00957     aMetrics.SetMEWToActualWidth(aReflowState.mStylePosition->mWidth.GetUnit());
00958   }
00959 }
00960 
00961 nsresult 
00962 nsObjectFrame::MakeAbsoluteURL(nsIURI* *aFullURI, 
00963                               nsString aSrc,
00964                               nsIURI* aBaseURI)
00965 {
00966   nsresult rv;
00967   nsCOMPtr<nsIDocument> document;
00968   rv = mInstanceOwner->GetDocument(getter_AddRefs(document));
00969 
00970   // get document charset
00971   nsCAutoString originCharset;
00972   if (document)
00973     originCharset = document->GetDocumentCharacterSet();
00974 
00975   return NS_NewURI(aFullURI, aSrc, originCharset.get(), aBaseURI);
00976 }
00977 
00978 static void
00979 SizeAnchor(nsIContent *aAnchor, PRInt32 aWidth, PRInt32 aHeight)
00980 {
00981   nsCOMPtr<nsIDOMElementCSSInlineStyle> element(do_QueryInterface(aAnchor));
00982 
00983   if (!element)
00984     return;
00985 
00986   nsCOMPtr<nsIDOMCSSStyleDeclaration> style;
00987   element->GetStyle(getter_AddRefs(style));
00988 
00989   nsCOMPtr<nsIDOMCSS2Properties> css2props(do_QueryInterface(style));
00990 
00991   if (!css2props) {
00992     return;
00993   }
00994 
00995   nsAutoString tmp;
00996   tmp.AppendInt(aWidth);
00997   AppendASCIItoUTF16("px", tmp);
00998   css2props->SetWidth(tmp);
00999 
01000   tmp.Truncate();
01001   tmp.AppendInt(aHeight);
01002   AppendASCIItoUTF16("px", tmp);
01003   css2props->SetHeight(tmp);
01004 }
01005 
01006 NS_IMETHODIMP
01007 nsObjectFrame::Reflow(nsPresContext*           aPresContext,
01008                       nsHTMLReflowMetrics&     aMetrics,
01009                       const nsHTMLReflowState& aReflowState,
01010                       nsReflowStatus&          aStatus)
01011 {
01012   DO_GLOBAL_REFLOW_COUNT("nsObjectFrame", aReflowState.reason);
01013   DISPLAY_REFLOW(aPresContext, this, aReflowState, aMetrics, aStatus);
01014   nsresult rv = NS_OK;
01015 
01016   // If we have a child, we toss the reflow over to it.
01017   nsIFrame * child = mFrames.FirstChild();
01018 
01019   if (IsBroken()) {
01020     // This is a broken plugin, if we don't already have a child
01021     // frame, create the child frames manually. If any of this frame
01022     // construction code ever changes to use the frame constructor, or
01023     // any other change, this probably needs some changes too.
01024     if (!child) {
01025       CreateDefaultFrames(aPresContext, aMetrics, aReflowState);
01026 
01027       child = mFrames.FirstChild();
01028     }
01029 
01030     if (child) {
01031       GetDesiredSize(aPresContext, aReflowState, aMetrics);
01032 
01033       // Build a reflow state so we can see what the child's border and
01034       // padding are going to be
01035       nsHTMLReflowState state(aPresContext, aReflowState, child,
01036                               nsSize(aReflowState.availableWidth,
01037                                      aReflowState.availableHeight));
01038 
01039       float t2p = aPresContext->TwipsToPixels();
01040       PRInt32 width = NSTwipsToIntPixels(aMetrics.width - state.mComputedBorderPadding.LeftRight(), t2p);
01041       PRInt32 height = NSTwipsToIntPixels(aMetrics.height - state.mComputedBorderPadding.TopBottom(), t2p);
01042 
01043       // Set the child's content width and height
01044       SizeAnchor(child->GetContent(), width, height);
01045 
01046       // SizeAnchor() is seriously evil as it ends up setting an
01047       // attribute (through the style changes that it does) while
01048       // we're in reflow. This is also seriously evil, as it pulls
01049       // that reflow command out of the reflow queue, as leaving it
01050       // there can get us into infinite loops while reflowing object
01051       // frames for missing plugins.
01052       nsReflowType reflowType(eReflowType_StyleChanged);
01053       aPresContext->PresShell()->CancelReflowCommand(child, &reflowType);
01054     }
01055   }
01056 
01057   if (child) {
01058     // Reflow the child; our size just depends on that of the child,
01059     // pure and simple
01060     return HandleChild(aPresContext, aMetrics, aReflowState, aStatus, child);
01061   }
01062 
01063   // Get our desired size
01064   GetDesiredSize(aPresContext, aReflowState, aMetrics);
01065 
01066   // delay plugin instantiation until all children have
01067   // arrived. Otherwise there may be PARAMs or other stuff that the
01068   // plugin needs to see that haven't arrived yet.
01069   if (!GetContent()->IsDoneAddingChildren()) {
01070     aStatus = NS_FRAME_COMPLETE;
01071     return rv;
01072   }
01073 
01074   // if we are printing or print previewing, bail for now
01075   if (aPresContext->Medium() == nsLayoutAtoms::print) {
01076     aStatus = NS_FRAME_COMPLETE;
01077     return rv;
01078   }
01079 
01080   // if mInstance is null, we need to determine what kind of object we are and instantiate ourselves
01081   if (!mInstanceOwner) {
01082     // XXX - do we need to create this for widgets as well?
01083     mInstanceOwner = new nsPluginInstanceOwner();
01084     if (!mInstanceOwner)
01085       return NS_ERROR_OUT_OF_MEMORY;
01086 
01087     NS_ADDREF(mInstanceOwner);
01088     mInstanceOwner->Init(aPresContext, this);
01089 
01090     // get the nsIPluginHost service
01091     nsCOMPtr<nsIPluginHost> pluginHost(do_GetService(kCPluginManagerCID));
01092 
01093     nsCOMPtr<nsISupports> container;
01094     nsCOMPtr<nsIURI> fullURL;
01095 
01096     nsAutoString classid;
01097 
01098     nsCOMPtr<nsIURI> baseURI = mContent->GetBaseURI();
01099     nsAutoString codeBase;
01100     if ((NS_CONTENT_ATTR_HAS_VALUE ==
01101          mContent->GetAttr(kNameSpaceID_None, nsHTMLAtoms::codebase, codeBase)) &&
01102         !codeBase.IsEmpty()) {
01103       nsCOMPtr<nsIURI> codeBaseURL;
01104       rv = MakeAbsoluteURL(getter_AddRefs(codeBaseURL), codeBase, baseURI);
01105       if (NS_SUCCEEDED(rv)) {
01106         baseURI = codeBaseURL;
01107       }
01108     }
01109 
01110     // if we have a clsid, we're either an internal widget, an ActiveX control, or an applet
01111     if (mContent->Tag() == nsHTMLAtoms::object &&
01112         NS_CONTENT_ATTR_HAS_VALUE == mContent->GetAttr(kNameSpaceID_None, nsHTMLAtoms::classid, classid)) {
01113       PRBool bJavaObject;
01114 
01115       bJavaObject = StringBeginsWith(classid, NS_LITERAL_STRING("java:"));
01116 
01117       // if we find "java:" in the class id, we have a java applet
01118       if (bJavaObject) {
01119         if (!baseURI) {
01120           rv = NS_ERROR_FAILURE;
01121         }
01122         else {
01123           fullURL = baseURI;
01124 
01125           if (pluginHost) {
01126             mInstanceOwner->SetPluginHost(pluginHost);
01127             rv = InstantiatePlugin(aPresContext, aMetrics, aReflowState,
01128                                    pluginHost, "application/x-java-vm",
01129                                    fullURL);
01130           }
01131         }
01132       }
01133       else { // otherwise, we're either an ActiveX control or an internal widget
01134         // These are some builtin types that we know about for now.
01135         // (Eventually this will move somewhere else.)
01136         if (classid.EqualsLiteral("browser")) {
01137           rv = InstantiateWidget(aPresContext, aMetrics,
01138                                  aReflowState, kCAppShellCID);
01139         }
01140         else {
01141           // if we haven't matched to an internal type, check to see if
01142           // we have an ActiveX handler
01143           // if not, create the default plugin
01144           if (!baseURI) {
01145             rv = NS_ERROR_FAILURE;
01146           }
01147           else {
01148             fullURL = baseURI;
01149 
01150             if (pluginHost) {
01151               mInstanceOwner->SetPluginHost(pluginHost);
01152               if (NS_SUCCEEDED(pluginHost->IsPluginEnabledForType("application/x-oleobject"))) {
01153                 rv = InstantiatePlugin(aPresContext, aMetrics, aReflowState,
01154                                        pluginHost, "application/x-oleobject",
01155                                        fullURL);
01156               } else if (NS_SUCCEEDED(pluginHost->IsPluginEnabledForType("application/oleobject"))) {
01157                 rv = InstantiatePlugin(aPresContext, aMetrics, aReflowState,
01158                                        pluginHost, "application/oleobject",
01159                                        fullURL);
01160               } else {
01161                 rv = NS_ERROR_FAILURE;
01162               }
01163             }
01164           }
01165         }
01166       }
01167 
01168       // finish up
01169       if (NS_SUCCEEDED(rv)) {
01170         aStatus = NS_FRAME_COMPLETE;
01171         return NS_OK;
01172       }
01173     }
01174     else { // no clsid - the object is either an applet or a plugin
01175       nsAutoString    src;
01176       if (!baseURI) {
01177         rv = NS_ERROR_FAILURE;
01178       }
01179       else {
01180         if (pluginHost) {
01181           mInstanceOwner->SetPluginHost(pluginHost);
01182 
01183           nsIAtom *tag = mContent->Tag();
01184           if (tag == nsHTMLAtoms::applet) {
01185             if (NS_CONTENT_ATTR_HAS_VALUE == mContent->GetAttr(kNameSpaceID_None, nsHTMLAtoms::code, src)) {
01186               // Create an absolute URL
01187               rv = MakeAbsoluteURL(getter_AddRefs(fullURL), src, baseURI);
01188             }
01189             else
01190               fullURL = baseURI;
01191 
01192             rv = InstantiatePlugin(aPresContext, aMetrics, aReflowState,
01193                                   pluginHost, "application/x-java-vm", fullURL);
01194           } else { // traditional plugin
01195             nsXPIDLCString mimeTypeStr;
01196             nsAutoString type;
01197             mContent->GetAttr(kNameSpaceID_None, nsHTMLAtoms::type, type);
01198 
01199             if (type.Length()) {
01200               mimeTypeStr.Adopt(ToNewCString(type));
01201             }
01202             // Stream in the object source if there is one...
01203             // If this is an OBJECT tag, we should look for a DATA attribute.
01204             // If not, it's an EMBED tag, and so we should look for a SRC attribute.
01205             if (tag == nsHTMLAtoms::object)
01206               rv = mContent->GetAttr(kNameSpaceID_None, nsHTMLAtoms::data, src);
01207             else
01208               rv = mContent->GetAttr(kNameSpaceID_None, nsHTMLAtoms::src, src);
01209             
01210             if (NS_CONTENT_ATTR_HAS_VALUE == rv) {
01211               // Create an absolute URL
01212               rv = MakeAbsoluteURL(getter_AddRefs(fullURL), src, baseURI);
01213               if (NS_FAILED(rv)) {
01214                 // Failed to create URI, maybe because we didn't
01215                 // reconize the protocol handler ==> treat like
01216                 // no 'src'/'data' was specified in the embed/object tag
01217                 fullURL = baseURI;
01218               }
01219             }
01220             else {
01221               // we didn't find a src or data param, so just set the url
01222               // to the base
01223 
01224               fullURL = baseURI;
01225             }
01226 
01227             // now try to instantiate a plugin instance based on a mime type
01228             const char* mimeType = mimeTypeStr.get();
01229             if (mimeType || !src.IsEmpty()) {
01230               if (!mimeType) {
01231                 // we don't have a mime type, try to figure it out
01232                 // from extension
01233                 PRInt32 offset = src.RFindChar(PRUnichar('.'));
01234                 if (offset != kNotFound)
01235                   pluginHost->IsPluginEnabledForExtension(NS_ConvertUTF16toUTF8(Substring(src, offset + 1, src.Length())).get(), mimeType);
01236               }
01237               // if we fail to get a mime type from extension we can
01238               // still try to instantiate plugin as it can be possible
01239               // to determine it later
01240               rv = InstantiatePlugin(aPresContext, aMetrics, aReflowState,
01241                                      pluginHost, mimeType, fullURL);
01242             }
01243             else // if we have neither we should not bother
01244               rv = NS_ERROR_FAILURE;
01245           }
01246         }
01247       }
01248     }
01249   }
01250   else { // if (!mInstanceOwner)
01251     rv = ReinstantiatePlugin(aPresContext, aMetrics, aReflowState);
01252   }
01253 
01254   // finish up
01255   if (NS_FAILED(rv)) {
01256     // if we got an error, we are probably going to be replaced
01257 
01258     // for a replaced object frame, clear our vertical alignment style info, see bug 36997
01259     nsStyleTextReset* text = NS_STATIC_CAST(nsStyleTextReset*,
01260       mStyleContext->GetUniqueStyleData(eStyleStruct_TextReset));
01261     text->mVerticalAlign.SetNormalValue();
01262 
01263     //check for alternative content with CantRenderReplacedElement()
01264     rv = aPresContext->PresShell()->CantRenderReplacedElement(this);
01265   } else {
01266     NotifyContentObjectWrapper();
01267   }
01268 
01269   aStatus = NS_FRAME_COMPLETE;
01270 
01271   NS_FRAME_SET_TRUNCATION(aStatus, aReflowState, aMetrics);
01272   return rv;
01273 }
01274 
01275 nsresult
01276 nsObjectFrame::InstantiateWidget(nsPresContext*           aPresContext,
01277                                  nsHTMLReflowMetrics&     aMetrics,
01278                                  const nsHTMLReflowState& aReflowState,
01279                                  nsCID aWidgetCID)
01280 {
01281   nsresult rv;
01282 
01283   GetDesiredSize(aPresContext, aReflowState, aMetrics);
01284   nsIView *parentWithView;
01285   nsPoint origin;
01286   GetOffsetFromView(origin, &parentWithView);
01287   // Just make the frigging widget
01288 
01289   float           t2p;
01290   t2p = aPresContext->TwipsToPixels();
01291   PRInt32 x = NSTwipsToIntPixels(origin.x, t2p);
01292   PRInt32 y = NSTwipsToIntPixels(origin.y, t2p);
01293   PRInt32 width = NSTwipsToIntPixels(aMetrics.width, t2p);
01294   PRInt32 height = NSTwipsToIntPixels(aMetrics.height, t2p);
01295   nsRect r = nsRect(x, y, width, height);
01296 
01297   mWidget = do_CreateInstance(aWidgetCID, &rv);
01298   if (NS_FAILED(rv)) {
01299     return rv;
01300   }
01301 
01302   mWidget->Create(parentWithView->GetNearestWidget(nsnull), r, nsnull, nsnull);
01303   mWidget->Show(PR_TRUE);
01304   return rv;
01305 }
01306 
01307 nsresult
01308 nsObjectFrame::InstantiatePlugin(nsPresContext* aPresContext,
01309                                  nsHTMLReflowMetrics& aMetrics,
01310                                  const nsHTMLReflowState& aReflowState,
01311                                  nsIPluginHost* aPluginHost, 
01312                                  const char* aMimeType,
01313                                  nsIURI* aURI)
01314 {
01315   nsIView *parentWithView;
01316   nsPoint origin;
01317   nsPluginWindow  *window;
01318   float           t2p;
01319   
01320   t2p = aPresContext->TwipsToPixels();
01321 
01322   mFullURL = aURI;
01323 
01324   // we need to recalculate this now that we have access to the nsPluginInstanceOwner
01325   // and its size info (as set in the tag)
01326   GetDesiredSize(aPresContext, aReflowState, aMetrics);
01327 
01328   mInstanceOwner->GetWindow(window);
01329 
01330   NS_ENSURE_TRUE(window, NS_ERROR_NULL_POINTER);
01331 
01332   GetOffsetFromView(origin, &parentWithView);
01333   window->x = NSTwipsToIntPixels(origin.x, t2p);
01334   window->y = NSTwipsToIntPixels(origin.y, t2p);
01335   window->width = NSTwipsToIntPixels(aMetrics.width, t2p);
01336   window->height = NSTwipsToIntPixels(aMetrics.height, t2p);
01337 
01338   // on the Mac we need to set the clipRect to { 0, 0, 0, 0 } for now. This will keep
01339   // us from drawing on screen until the widget is properly positioned, which will not
01340   // happen until we have finished the reflow process.
01341   window->clipRect.top = 0;
01342   window->clipRect.left = 0;
01343 #if !(defined(XP_MAC) || defined(XP_MACOSX))
01344   window->clipRect.bottom = NSTwipsToIntPixels(aMetrics.height, t2p);
01345   window->clipRect.right = NSTwipsToIntPixels(aMetrics.width, t2p);
01346 #else
01347   window->clipRect.bottom = 0;
01348   window->clipRect.right = 0;
01349 #endif
01350 
01351 #ifdef DEBUG
01352   mInstantiating = PR_TRUE;
01353 #endif
01354 
01355   nsCOMPtr<nsIDocument> doc;
01356   nsresult rv = mInstanceOwner->GetDocument(getter_AddRefs(doc));
01357   nsCOMPtr<nsIPluginDocument> pDoc (do_QueryInterface(doc));
01358 
01359   if (pDoc) {  /* full-page mode */
01360     nsCOMPtr<nsIStreamListener> stream;
01361     rv = aPluginHost->InstantiateFullPagePlugin(aMimeType, aURI,
01362           /* resulting stream listener */       *getter_AddRefs(stream),
01363                                                 mInstanceOwner);
01364     if (NS_SUCCEEDED(rv))
01365       pDoc->SetStreamListener(stream);
01366   } else {   /* embedded mode */
01367     rv = aPluginHost->InstantiateEmbeddedPlugin(aMimeType, aURI,
01368                                                 mInstanceOwner);
01369   }
01370 #ifdef DEBUG
01371   mInstantiating = PR_FALSE;
01372 #endif
01373 
01374   return rv;
01375 }
01376 
01377 // This is called when the page containing plugin is resized, and plugin has its dimensions
01378 // specified in percentage, so it needs to follow the page on the fly.
01379 nsresult
01380 nsObjectFrame::ReinstantiatePlugin(nsPresContext* aPresContext, nsHTMLReflowMetrics& aMetrics, const nsHTMLReflowState& aReflowState)
01381 {
01382   nsIView *parentWithView;
01383   nsPoint origin;
01384   nsPluginWindow  *window;
01385   float           t2p;
01386   t2p = aPresContext->TwipsToPixels();
01387 
01388   // we need to recalculate this now that we have access to the nsPluginInstanceOwner
01389   // and its size info (as set in the tag)
01390   GetDesiredSize(aPresContext, aReflowState, aMetrics);
01391 
01392   mInstanceOwner->GetWindow(window);
01393   
01394   NS_ENSURE_TRUE(window, NS_ERROR_NULL_POINTER);
01395 
01396   GetOffsetFromView(origin, &parentWithView);
01397 
01398   window->x = NSTwipsToIntPixels(origin.x, t2p);
01399   window->y = NSTwipsToIntPixels(origin.y, t2p);
01400   window->width = NSTwipsToIntPixels(aMetrics.width, t2p);
01401   window->height = NSTwipsToIntPixels(aMetrics.height, t2p);
01402 
01403   // ignore this for now on the Mac because the widget is not properly positioned
01404   // yet and won't be until we have finished the reflow process.
01405 #if defined(XP_MAC) || defined(XP_MACOSX)
01406   window->clipRect.top = 0;
01407   window->clipRect.left = 0;
01408   window->clipRect.bottom = NSTwipsToIntPixels(aMetrics.height, t2p);
01409   window->clipRect.right = NSTwipsToIntPixels(aMetrics.width, t2p);
01410 #endif
01411 
01412   return NS_OK;
01413 }
01414 
01415 nsresult
01416 nsObjectFrame::HandleChild(nsPresContext*           aPresContext,
01417                            nsHTMLReflowMetrics&     aMetrics,
01418                            const nsHTMLReflowState& aReflowState,
01419                            nsReflowStatus&          aStatus,
01420                            nsIFrame* child)
01421 {
01422   // Note that in the image and document cases the child shares our
01423   // style context, so we simply want to reflow the child with pretty
01424   // much our own reflow state, in the case of a broken plugin, the
01425   // child has its own style context, so we create a new reflow
01426   // state....
01427   // XXXbz maybe we should always have a different style context?
01428   // XXXroc no, that seems to break things. But as is, this causes
01429   // an assertion failure in nsContainerFrame because the reflow
01430   // state isn't built for the right frame.
01431 
01432   nsReflowStatus status;
01433 
01434   if (IsBroken()) {
01435     nsHTMLReflowState state(aPresContext, aReflowState, child,
01436                             nsSize(aReflowState.availableWidth,
01437                                    aReflowState.availableHeight));
01438 
01439     ReflowChild(child, aPresContext, aMetrics, state, 0, 0, 0, status);
01440     FinishReflowChild(child, aPresContext, &state, aMetrics, 0, 0, 0);
01441   } else {
01442     ReflowChild(child, aPresContext, aMetrics, aReflowState, 0, 0, 0, status);
01443     FinishReflowChild(child, aPresContext, &aReflowState, aMetrics, 0, 0, 0);
01444   }
01445 
01446   aStatus = NS_FRAME_COMPLETE;
01447   return NS_OK;
01448 }
01449 
01450 PRBool
01451 nsObjectFrame::IsFocusable(PRInt32 *aTabIndex, PRBool aWithMouse)
01452 {
01453   if (aTabIndex)
01454     *aTabIndex = -1;
01455   if (IsBroken()) {
01456     // Inner anchor for "click to install plugin" is focusable,
01457     // but not the object frame itself
01458     return PR_FALSE;
01459   }
01460   return nsObjectFrameSuper::IsFocusable(aTabIndex, aWithMouse);
01461 }
01462 
01463 PRBool
01464 nsObjectFrame::IsHidden(PRBool aCheckVisibilityStyle) const
01465 {
01466   if (aCheckVisibilityStyle) {
01467     if (!GetStyleVisibility()->IsVisibleOrCollapsed())
01468       return PR_TRUE;    
01469   }
01470 
01471   // only <embed> tags support the HIDDEN attribute
01472   if (mContent->Tag() == nsHTMLAtoms::embed) {
01473     nsAutoString hidden;
01474     nsresult result = mContent->GetAttr(kNameSpaceID_None, nsHTMLAtoms::hidden, hidden);
01475 
01476     // Yes, these are really the kooky ways that you could tell 4.x
01477     // not to hide the <embed> once you'd put the 'hidden' attribute
01478     // on the tag...
01479 
01480     // these |NS_ConvertASCIItoUCS2|s can't be |NS_LITERAL_STRING|s
01481     // until |EqualsIgnoreCase| get's fixed
01482 
01483     // HIDDEN w/ no attributes gets translated as we are hidden for
01484     // compatibility w/ 4.x and IE so we don't create a non-painting
01485     // widget in layout. See bug 188959.
01486     if (NS_CONTENT_ATTR_NOT_THERE != result &&
01487        (hidden.IsEmpty() ||
01488         !hidden.LowerCaseEqualsLiteral("false") &&
01489         !hidden.LowerCaseEqualsLiteral("no") &&
01490         !hidden.LowerCaseEqualsLiteral("off"))) {
01491       return PR_TRUE;
01492     }
01493   }
01494 
01495   return PR_FALSE;
01496 }
01497 
01498 nsPoint nsObjectFrame::GetWindowOriginInPixels(PRBool aWindowless)
01499 {
01500   nsIView * parentWithView;
01501   nsPoint origin(0,0);
01502 
01503   GetOffsetFromView(origin, &parentWithView);
01504 
01505   // if it's windowless, let's make sure we have our origin set right
01506   // it may need to be corrected, like after scrolling
01507   if (aWindowless && parentWithView) {
01508     nsIViewManager* parentVM = parentWithView->GetViewManager();
01509 
01510     // Walk up all the views and add up their positions until we
01511     // reach the first view with a window (non-null widget). This will give us our
01512     // position relative to the containing window which is what we want to give the plugin
01513     nsIView* theView = parentWithView;
01514     while (theView && !theView->GetWidget()) {
01515       if (theView->GetViewManager() != parentVM)
01516         break;
01517 
01518       origin += theView->GetPosition();
01519       theView = theView->GetParent();
01520     }  
01521   }
01522 
01523   float t2p;
01524   t2p = GetPresContext()->TwipsToPixels();
01525   origin.x = NSTwipsToIntPixels(origin.x, t2p);
01526   origin.y = NSTwipsToIntPixels(origin.y, t2p);
01527 
01528   return origin;
01529 }
01530 
01531 void
01532 nsObjectFrame::CreateDefaultFrames(nsPresContext *aPresContext,
01533                                    nsHTMLReflowMetrics& aMetrics,
01534                                    const nsHTMLReflowState& aReflowState)
01535 {
01536   NS_ASSERTION(IsBroken(),
01537                "CreateDefaultFrames() called on non-broken plugin!");
01538 
01539   nsIFrame * child = mFrames.FirstChild();
01540   if (child) {
01541     NS_ERROR("Um, this should only be called once!");
01542 
01543     // We have a child already, don't do anything
01544     return;
01545   }
01546 
01547   // first, we need to get the document
01548   nsIDocument *doc = mContent->GetDocument();
01549 
01550   nsIPresShell *shell = aPresContext->GetPresShell();
01551   nsStyleSet *styleSet = shell->StyleSet();
01552 
01553   nsCOMPtr<nsIHTMLDocument> htmldoc(do_QueryInterface(doc));
01554   PRInt32 id;
01555   if (htmldoc && !doc->IsCaseSensitive())
01556     id = kNameSpaceID_None;
01557   else
01558     id = kNameSpaceID_XHTML;
01559 
01560   nsCOMPtr<nsIContent> anchor;
01561   nsresult rv = doc->CreateElem(nsHTMLAtoms::a, nsnull, id, htmldoc != nsnull,
01562                                 getter_AddRefs(anchor));
01563 
01564   nsCOMPtr<nsIContent> img;
01565   rv |= doc->CreateElem(nsHTMLAtoms::img, nsnull, id, htmldoc != nsnull,
01566                         getter_AddRefs(img));
01567 
01568   nsCOMPtr<nsITextContent> text;
01569   rv |= NS_NewTextNode(getter_AddRefs(text), doc->NodeInfoManager());
01570 
01571   if (NS_FAILED(rv))
01572     return;
01573 
01574   // Mark the nodes anonymous
01575   anchor->SetNativeAnonymous(PR_TRUE);
01576   img->SetNativeAnonymous(PR_TRUE);
01577   text->SetNativeAnonymous(PR_TRUE);
01578 
01579   // Set up the anonymous tree.  Note that the binding parent for the anchor is
01580   // used to cut off style rules from the page so they won't apply to it.
01581   rv = anchor->BindToTree(doc, mContent, anchor, PR_TRUE);
01582   if (NS_FAILED(rv)) {
01583     anchor->UnbindFromTree();
01584     return;
01585   }
01586 
01587   anchor->AppendChildTo(img, PR_FALSE);
01588   anchor->AppendChildTo(text, PR_FALSE);
01589 
01590   nsAutoString style;
01591   CopyASCIItoUTF16("text-align: -moz-center;"
01592                    "overflow: -moz-hidden-unscrollable;"
01593                    "display: block;"
01594                    "border: 1px outset;"
01595                    "padding: 5px;"
01596                    "font-size: 12px;"
01597                    "font-family: sans-serif;"
01598                    "background: white;"
01599                    "-moz-user-select: none;"
01600                    "text-decoration: none;"
01601                    "color: black;", style);
01602 
01603   // Style things and load the image
01604   anchor->SetAttr(kNameSpaceID_None, nsHTMLAtoms::style, style, PR_TRUE);
01605   anchor->SetAttr(kNameSpaceID_None, nsHTMLAtoms::href, NS_LITERAL_STRING("#"), PR_TRUE);
01606 
01607   NS_NAMED_LITERAL_STRING(src,
01608                           "chrome://mozapps/skin/xpinstall/xpinstallItemGeneric.png");
01609   img->SetAttr(kNameSpaceID_None, nsHTMLAtoms::src, src, PR_FALSE);
01610   NS_NAMED_LITERAL_STRING(imgStyle,
01611                           "display: block; border: 0px; width: 32px; height: 32px;");
01612   img->SetAttr(kNameSpaceID_None, nsHTMLAtoms::style, imgStyle, PR_FALSE);
01613 
01614   // Kick off the image load.
01615   nsCOMPtr<nsIImageLoadingContent> imageLoader = do_QueryInterface(img);
01616   imageLoader->ImageURIChanged(src);
01617 
01618   // get the localized text
01619   nsXPIDLString missingPluginLabel;
01620 
01621   nsCOMPtr<nsIStringBundleService> stringBundleService =
01622     do_GetService(NS_STRINGBUNDLE_CONTRACTID);
01623 
01624   if (stringBundleService) {
01625     nsCOMPtr<nsIStringBundle> stringBundle;
01626     stringBundleService->CreateBundle(
01627       "chrome://mozapps/locale/plugins/plugins.properties", 
01628       getter_AddRefs(stringBundle));
01629 
01630     if (stringBundle)
01631       rv = stringBundle->GetStringFromName(NS_LITERAL_STRING("missingPlugin.label").get(), 
01632                                            getter_Copies(missingPluginLabel));
01633   }
01634 
01635   if (!stringBundleService || NS_FAILED(rv))
01636     missingPluginLabel = NS_LITERAL_STRING("Click here to download plugin.");
01637 
01638   text->SetText(missingPluginLabel, PR_FALSE);
01639 
01640   // Resolve style for the anchor, img, and text nodes.
01641   nsRefPtr<nsStyleContext> anchorStyleContext =
01642     styleSet->ResolveStyleFor(anchor, mStyleContext);
01643   nsRefPtr<nsStyleContext> imgStyleContext =
01644     styleSet->ResolveStyleFor(img, anchorStyleContext);
01645   nsRefPtr<nsStyleContext> textStyleContext =
01646     shell->StyleSet()->ResolveStyleForNonElement(anchorStyleContext);
01647 
01648   if (!anchorStyleContext || !imgStyleContext || !textStyleContext)
01649     return;
01650 
01651   nsIFrame *anchorFrame = nsnull;
01652   nsIFrame *imgFrame = nsnull;
01653   nsIFrame *textFrame = nsnull;
01654 
01655   do {
01656     rv = NS_NewBlockFrame(shell, &anchorFrame);
01657     if (NS_FAILED(rv))
01658       break;
01659 
01660     rv = anchorFrame->Init(aPresContext, anchor, this, anchorStyleContext, PR_FALSE);
01661     if (NS_FAILED(rv))
01662       break;
01663 
01664     // Give it a space manager, so it won't crash of ancestors don't have one
01665     anchorFrame->AddStateBits(NS_BLOCK_SPACE_MGR | NS_BLOCK_MARGIN_ROOT);
01666     
01667     nsHTMLContainerFrame::CreateViewForFrame(anchorFrame, this, PR_FALSE);
01668 
01669     rv = NS_NewImageFrame(shell, &imgFrame);
01670     if (NS_FAILED(rv))
01671       return;
01672 
01673     rv = imgFrame->Init(aPresContext, img, anchorFrame, imgStyleContext, PR_FALSE);
01674     if (NS_FAILED(rv))
01675       break;
01676 
01677     nsHTMLContainerFrame::CreateViewForFrame(imgFrame, anchorFrame, PR_FALSE);
01678     anchorFrame->AppendFrames(nsnull, imgFrame);
01679 
01680     rv = NS_NewTextFrame(shell, &textFrame);
01681     if (NS_FAILED(rv))
01682       break;
01683 
01684     rv = textFrame->Init(aPresContext, text, anchorFrame, textStyleContext,
01685                          PR_FALSE);
01686     if (NS_FAILED(rv))
01687       break;
01688 
01689     textFrame->SetInitialChildList(aPresContext, nsnull, nsnull);
01690 
01691     anchorFrame->AppendFrames(nsnull, textFrame);
01692   } while (0);
01693 
01694   if (NS_FAILED(rv)) {
01695     if (anchorFrame)
01696       anchorFrame->Destroy(aPresContext);
01697 
01698     if (imgFrame)
01699       imgFrame->Destroy(aPresContext);
01700 
01701     if (textFrame)
01702       textFrame->Destroy(aPresContext);
01703   } else {
01704     // Creation of all our anonymous content succeeded.
01705     mFrames.AppendFrame(this, anchorFrame);
01706   }
01707 
01708   nsCOMPtr<nsISupportsArray> array;
01709   NS_NewISupportsArray(getter_AddRefs(array));
01710 
01711   if (array) {
01712     array->AppendElement(anchor);
01713     array->AppendElement(img);
01714     array->AppendElement(text);
01715 
01716     shell->SetAnonymousContentFor(mContent, array);
01717   }
01718 }
01719 
01720 NS_IMETHODIMP
01721 nsObjectFrame::DidReflow(nsPresContext*            aPresContext,
01722                          const nsHTMLReflowState*  aReflowState,
01723                          nsDidReflowStatus         aStatus)
01724 {
01725   nsresult rv = nsObjectFrameSuper::DidReflow(aPresContext, aReflowState, aStatus);
01726 
01727   // The view is created hidden; once we have reflowed it and it has been
01728   // positioned then we show it.
01729   if (aStatus != NS_FRAME_REFLOW_FINISHED) 
01730     return rv;
01731 
01732   PRBool bHidden = IsHidden();
01733 
01734   if (HasView()) {
01735     nsIView* view = GetView();
01736     nsIViewManager* vm = view->GetViewManager();
01737     if (vm)
01738       vm->SetViewVisibility(view, bHidden ? nsViewVisibility_kHide : nsViewVisibility_kShow);
01739   }
01740 
01741   nsPluginWindow *win = nsnull;
01742  
01743   nsCOMPtr<nsIPluginInstance> pi; 
01744   if (!mInstanceOwner ||
01745       NS_FAILED(rv = mInstanceOwner->GetInstance(*getter_AddRefs(pi))) ||
01746       !pi ||
01747       NS_FAILED(rv = mInstanceOwner->GetWindow(win)) || 
01748       !win)
01749     return rv;
01750 
01751   nsPluginNativeWindow *window = (nsPluginNativeWindow *)win;
01752 
01753 #if defined(XP_MAC) || defined(XP_MACOSX) 
01754   mInstanceOwner->FixUpPluginWindow(ePluginPaintDisable);
01755 #endif // XP_MAC || XP_MACOSX
01756 
01757   if (bHidden)
01758     return rv;
01759 
01760   PRBool windowless = (window->type == nsPluginWindowType_Drawable);
01761   if (windowless)
01762     return rv;
01763 
01764   nsPoint origin = GetWindowOriginInPixels(windowless);
01765 
01766   window->x = origin.x;
01767   window->y = origin.y;
01768 
01769   // refresh the plugin port as well
01770   window->window = mInstanceOwner->GetPluginPort();
01771 
01772   // this will call pi->SetWindow and take care of window subclassing
01773   // if needed, see bug 132759
01774   window->CallSetWindow(pi);
01775 
01776   mInstanceOwner->ReleasePluginPort((nsPluginPort *)window->window);
01777 
01778   if (mWidget) {
01779     PRInt32 x = origin.x;
01780     PRInt32 y = origin.y;
01781     mWidget->Move(x, y);
01782   }
01783 
01784   return rv;
01785 }
01786 
01787 NS_IMETHODIMP
01788 nsObjectFrame::Paint(nsPresContext*       aPresContext,
01789                      nsIRenderingContext& aRenderingContext,
01790                      const nsRect&        aDirtyRect,
01791                      nsFramePaintLayer    aWhichLayer,
01792                      PRUint32             aFlags)
01793 {
01794   if (!GetStyleVisibility()->IsVisibleOrCollapsed())
01795     return NS_OK;
01796   
01797   nsIFrame * child = mFrames.FirstChild();
01798   if (child) {    // if we have children, we are probably not really a plugin
01799     nsObjectFrameSuper::Paint(aPresContext, aRenderingContext, aDirtyRect, aWhichLayer);
01800     return NS_OK;
01801   }
01802 
01803   // If we are painting in Print Preview do nothing....
01804   if (aPresContext->Type() == nsPresContext::eContext_PrintPreview) {
01805     return NS_OK;
01806   }
01807 
01808   // determine if we are printing
01809   if (aPresContext->Type() == nsPresContext::eContext_Print) {
01810     // UNIX Plugins can't PP at this time, so draw an empty box
01811     // we only want to print on the content layer pass
01812     if (eFramePaintLayer_Content != aWhichLayer)
01813       return NS_OK;
01814 
01815     // if we are printing, we need to get the correct nsIPluginInstance
01816     // for THIS content node in order to call ->Print() on the right plugin
01817 
01818     // first, we need to get the document
01819     nsCOMPtr<nsIDocument> doc = mContent->GetDocument();
01820     NS_ENSURE_TRUE(doc, NS_ERROR_NULL_POINTER);
01821 
01822     // now we need to get the shell for the screen
01823     // XXX assuming that the shell at zero will always be the screen one
01824     nsIPresShell *shell = doc->GetShellAt(0);
01825     NS_ENSURE_TRUE(shell, NS_ERROR_NULL_POINTER);
01826 
01827     // then the shell can give us the screen frame for this content node
01828     nsIFrame* frame = nsnull;
01829     shell->GetPrimaryFrameFor(mContent, &frame);
01830     NS_ENSURE_TRUE(frame, NS_ERROR_NULL_POINTER);
01831 
01832     // make sure this is REALLY an nsIObjectFrame
01833     // we may need to go through the children to get it
01834     nsIObjectFrame* objectFrame = nsnull;
01835     CallQueryInterface(frame,&objectFrame);
01836     if (!objectFrame)
01837       objectFrame = GetNextObjectFrame(aPresContext,frame);
01838     NS_ENSURE_TRUE(objectFrame,NS_ERROR_FAILURE);
01839 
01840     // finally we can get our plugin instance
01841     nsCOMPtr<nsIPluginInstance> pi;
01842     if (NS_FAILED(objectFrame->GetPluginInstance(*getter_AddRefs(pi))) || !pi)
01843       return NS_ERROR_FAILURE;
01844 
01845     // now we need to setup the correct location for printing
01846     nsresult rv;
01847     nsPluginWindow    window;
01848     nsPoint           origin;
01849     float             t2p;
01850     window.window =   nsnull;
01851 
01852     // prepare embedded mode printing struct
01853     nsPluginPrint npprint;
01854     npprint.mode = nsPluginMode_Embedded;
01855 
01856     // we need to find out if we are windowless or not
01857     PRBool windowless = PR_FALSE;
01858     pi->GetValue(nsPluginInstanceVariable_WindowlessBool, (void *)&windowless);
01859     window.type  =  windowless ? nsPluginWindowType_Drawable : nsPluginWindowType_Window;
01860 
01861     // Get the offset of the DC
01862     nsTransform2D* rcTransform;
01863     aRenderingContext.GetCurrentTransform(rcTransform);
01864     rcTransform->GetTranslationCoord(&origin.x, &origin.y);
01865     
01866     // Get the conversion factor between pixels and twips
01867     t2p = aPresContext->TwipsToPixels();
01868 
01869     // set it all up
01870     // XXX is windowless different?
01871     window.x = origin.x;
01872     window.y = origin.y;
01873     window.width = NSToCoordRound(mRect.width * t2p);
01874     window.height= NSToCoordRound(mRect.height * t2p);
01875     window.clipRect.bottom = 0; window.clipRect.top = 0;
01876     window.clipRect.left = 0; window.clipRect.right = 0;
01877     
01878 // XXX platform specific printing code
01879 #if defined(XP_MAC) && !TARGET_CARBON
01880     // Mac does things a little differently.
01881     GrafPtr curPort;
01882     ::GetPort(&curPort);  // get the current port
01883 
01884     nsPluginPort port;
01885     port.port = (CGrafPort*)curPort;
01886     port.portx = window.x;
01887     port.porty = window.y;
01888 
01889     RgnHandle curClip = ::NewRgn();
01890     NS_ENSURE_TRUE(curClip, NS_ERROR_NULL_POINTER);
01891     ::GetClip(curClip); // save old clip
01892     
01893     ::SetOrigin(-window.x,-window.y); // port must be set correctly prior to telling plugin to print
01894     Rect r = {0,0,window.height,window.width};
01895     ::ClipRect(&r);  // also set the clip
01896     
01897     window.window = &port;
01898     npprint.print.embedPrint.platformPrint = (void*)window.window;
01899     npprint.print.embedPrint.window = window;
01900     // send off print info to plugin
01901     rv = pi->Print(&npprint);
01902 #elif defined(XP_UNIX) && !defined(XP_MACOSX)
01903     /* UNIX does things completely differently:
01904      * We call the plugin and it sends generated PostScript data into a
01905      * file handle we provide. If the plugin returns with success we embed
01906      * this PostScript code fragment into the PostScript job we send to the
01907      * printer.
01908      */
01909 
01910     PR_LOG(nsObjectFrameLM, PR_LOG_DEBUG, ("nsObjectFrame::Paint() start for X11 platforms\n"));
01911            
01912     FILE *plugintmpfile = tmpfile();
01913     if (!plugintmpfile) {
01914       PR_LOG(nsObjectFrameLM, PR_LOG_DEBUG, ("error: could not open tmp. file, errno=%d\n", errno));
01915       return NS_ERROR_FAILURE;
01916     }
01917  
01918     /* Send off print info to plugin */
01919     NPPrintCallbackStruct npPrintInfo;
01920     npPrintInfo.type = NP_PRINT;
01921     npPrintInfo.fp   = plugintmpfile;
01922     npprint.print.embedPrint.platformPrint = (void *)&npPrintInfo;
01923     /* aDirtyRect contains the right information for ps print */
01924     window.x =   aDirtyRect.x;
01925     window.y =   aDirtyRect.y;
01926     window.width =   aDirtyRect.width;
01927     window.height =   aDirtyRect.height;
01928     npprint.print.embedPrint.window        = window;
01929     rv = pi->Print(&npprint);
01930     if (NS_FAILED(rv)) {
01931       PR_LOG(nsObjectFrameLM, PR_LOG_DEBUG, ("error: plugin returned failure %lx\n", (long)rv));
01932       fclose(plugintmpfile);
01933       return rv;
01934     }
01935 
01936     /* Send data to printer */
01937     rv = aRenderingContext.RenderEPS(aDirtyRect, plugintmpfile);
01938 
01939     fclose(plugintmpfile);
01940 
01941     PR_LOG(nsObjectFrameLM, PR_LOG_DEBUG, ("plugin printing done, return code is %lx\n", (long)rv));
01942 
01943 #else  // Windows and non-UNIX, non-Mac(Classic) cases
01944 
01945     // we need the native printer device context to pass to plugin
01946     // On Windows, this will be the HDC
01947     void *pDC = 0;
01948     aRenderingContext.RetrieveCurrentNativeGraphicData(&pDC);
01949 
01950     if (!pDC)
01951       return NS_OK;  // no dc implemented so quit
01952 
01953     npprint.print.embedPrint.platformPrint = (void*)pDC;
01954     npprint.print.embedPrint.window = window;
01955     // send off print info to plugin
01956     rv = pi->Print(&npprint);
01957 
01958 #endif
01959 
01960 #if defined(XP_MAC) && !TARGET_CARBON
01961     // Clean-up on Mac
01962     ::SetOrigin(0,0);
01963     ::SetClip(curClip);  // restore previous clip
01964     ::DisposeRgn(curClip);
01965 #endif
01966 
01967     // XXX Nav 4.x always sent a SetWindow call after print. Should we do the same?
01968     nsDidReflowStatus status = NS_FRAME_REFLOW_FINISHED; // should we use a special status?
01969     frame->DidReflow(shell->GetPresContext(),
01970                      nsnull, status);  // DidReflow will take care of it
01971 
01972     return rv;  // done with printing
01973   }
01974 
01975 // Screen painting code
01976 #if defined(XP_MAC) || defined(XP_MACOSX)
01977   // delegate all painting to the plugin instance.
01978   if ((NS_FRAME_PAINT_LAYER_FOREGROUND == aWhichLayer) && mInstanceOwner)
01979       mInstanceOwner->Paint(aDirtyRect);
01980 #elif defined (XP_WIN) || defined(XP_OS2)
01981   if (NS_FRAME_PAINT_LAYER_FOREGROUND == aWhichLayer) {
01982     nsCOMPtr<nsIPluginInstance> inst;
01983     GetPluginInstance(*getter_AddRefs(inst));
01984     if (inst) {
01985       // Look if it's windowless
01986       nsPluginWindow * window;
01987       mInstanceOwner->GetWindow(window);
01988 
01989       if (window->type == nsPluginWindowType_Drawable) {
01990         // check if we need to call SetWindow with updated parameters
01991         PRBool doupdatewindow = PR_FALSE;
01992 
01993         // check if we need to update hdc
01994         void *data;
01995         aRenderingContext.RetrieveCurrentNativeGraphicData((void**)&data);
01996         PRUint32 hdc = (PRUint32) data;
01997         if (NS_REINTERPRET_CAST(PRUint32, window->window) != hdc) {
01998           window->window = NS_REINTERPRET_CAST(nsPluginPort*, hdc);
01999           doupdatewindow = PR_TRUE;
02000         }
02001 
02002         /*
02003          * Layout now has an optimized way of painting. Now we always get
02004          * a new drawing surface, sized to be just what's needed. Windowsless
02005          * plugins need a transform applied to their origin so they paint
02006          * in the right place. Since |SetWindow| is no longer being used
02007          * to tell the plugin where it is, we dispatch a NPWindow through
02008          * |HandleEvent| to tell the plugin when its window moved
02009          */
02010 
02011         // Get the offset of the DC
02012         nsTransform2D* rcTransform;
02013         aRenderingContext.GetCurrentTransform(rcTransform);
02014         nsPoint origin;
02015         rcTransform->GetTranslationCoord(&origin.x, &origin.y);
02016 
02017         if ((window->x != origin.x) || (window->y != origin.y)) {
02018           window->x = origin.x;
02019           window->y = origin.y;
02020           doupdatewindow = PR_TRUE;
02021         }
02022 
02023         // if our location or visible area has changed, we need to tell the plugin
02024         if (doupdatewindow) {
02025 #ifdef XP_WIN    // Windowless plugins on windows need a special event to update their location, see bug 135737
02026            // bug 271442: note, the rectangle we send is now purely the bounds of the plugin
02027            // relative to the window it is contained in, which is useful for the plugin to correctly translate mouse coordinates
02028            //
02029            // this does not mesh with the comments for bug 135737 which imply that the rectangle
02030            // must be clipped in some way to prevent the plugin attempting to paint over areas it shouldn't;
02031            //
02032            // since the two uses of the rectangle are mutually exclusive in some cases,
02033            // and since I don't see any incorrect painting (at least with Flash and ViewPoint - the originator of 135737),
02034            // it seems that windowless plugins are not relying on information here for clipping their drawing,
02035            // and we can safely use this message to tell the plugin exactly where it is in all cases.
02036 
02037            origin = GetWindowOriginInPixels(PR_TRUE);
02038            nsRect winlessRect = nsRect(origin, nsSize(window->width, window->height));
02039            if (mWindowlessRect != winlessRect) {
02040              mWindowlessRect = winlessRect;
02041 
02042              WINDOWPOS winpos;
02043              memset(&winpos, 0, sizeof(winpos));
02044              winpos.x = mWindowlessRect.x;
02045              winpos.y = mWindowlessRect.y;
02046              winpos.cx = mWindowlessRect.width;
02047              winpos.cy = mWindowlessRect.height;
02048 
02049              // finally, update the plugin by sending it a WM_WINDOWPOSCHANGED event
02050              nsPluginEvent pluginEvent;
02051              pluginEvent.event = WM_WINDOWPOSCHANGED;
02052              pluginEvent.wParam = 0;
02053              pluginEvent.lParam = (uint32)&winpos;
02054              PRBool eventHandled = PR_FALSE;
02055 
02056              inst->HandleEvent(&pluginEvent, &eventHandled);
02057           }
02058 #endif
02059 
02060           inst->SetWindow(window);        
02061         }
02062 
02063         mInstanceOwner->Paint(aDirtyRect, hdc);
02064       }
02065     }
02066   }
02067 #endif /* !XP_MAC */
02068   DO_GLOBAL_REFLOW_COUNT_DSP("nsObjectFrame", &aRenderingContext);
02069   return NS_OK;
02070 }
02071 
02072 NS_IMETHODIMP
02073 nsObjectFrame::HandleEvent(nsPresContext* aPresContext,
02074                            nsGUIEvent*     anEvent,
02075                            nsEventStatus*  anEventStatus)
02076 {
02077   NS_ENSURE_ARG_POINTER(anEventStatus);
02078   nsresult rv = NS_OK;
02079 
02080   //FIX FOR CRASHING WHEN NO INSTANCE OWVER
02081   if (!mInstanceOwner)
02082     return NS_ERROR_NULL_POINTER;
02083 
02084   if (anEvent->message == NS_PLUGIN_ACTIVATE) {
02085     nsIContent* content = GetContent();
02086     if (content) {
02087       content->SetFocus(aPresContext);
02088       return rv;
02089     }
02090   }
02091 
02092 #ifdef XP_WIN
02093   rv = nsObjectFrameSuper::HandleEvent(aPresContext, anEvent, anEventStatus);
02094   return rv;
02095 #endif
02096 
02097        switch (anEvent->message) {
02098        case NS_DESTROY:
02099               mInstanceOwner->CancelTimer();
02100               break;
02101        case NS_GOTFOCUS:
02102        case NS_LOSTFOCUS:
02103               *anEventStatus = mInstanceOwner->ProcessEvent(*anEvent);
02104               break;
02105               
02106        default:
02107               // instead of using an event listener, we can dispatch events to plugins directly.
02108               rv = nsObjectFrameSuper::HandleEvent(aPresContext, anEvent, anEventStatus);
02109        }
02110        
02111        return rv;
02112 }
02113 
02114 nsresult nsObjectFrame::GetPluginInstance(nsIPluginInstance*& aPluginInstance)
02115 {
02116   aPluginInstance = nsnull;
02117 
02118   if (!mInstanceOwner)
02119     return NS_OK;
02120   
02121   return mInstanceOwner->GetInstance(aPluginInstance);
02122 }
02123 
02124 void
02125 nsObjectFrame::NotifyContentObjectWrapper()
02126 {
02127   nsCOMPtr<nsIDocument> doc = mContent->GetDocument();
02128   if (!doc)
02129     return;
02130 
02131   nsIScriptGlobalObject *sgo = doc->GetScriptGlobalObject();
02132   if (!sgo)
02133     return;
02134 
02135   nsIScriptContext *scx = sgo->GetContext();
02136   if (!scx)
02137     return;
02138 
02139   JSContext *cx = (JSContext *)scx->GetNativeContext();
02140 
02141   nsCOMPtr<nsIXPConnectWrappedNative> wrapper;
02142   nsContentUtils::XPConnect()->
02143     GetWrappedNativeOfNativeObject(cx, sgo->GetGlobalJSObject(), mContent,
02144                                    NS_GET_IID(nsISupports),
02145                                    getter_AddRefs(wrapper));
02146 
02147   if (!wrapper) {
02148     // Nothing to do here if there's no wrapper for mContent
02149     return;
02150   }
02151 
02152   nsCOMPtr<nsIClassInfo> ci(do_QueryInterface(mContent));
02153   if (!ci)
02154     return;
02155 
02156   nsCOMPtr<nsISupports> s;
02157   ci->GetHelperForLanguage(nsIProgrammingLanguage::JAVASCRIPT,
02158                            getter_AddRefs(s));
02159 
02160   nsCOMPtr<nsIXPCScriptable> helper(do_QueryInterface(s));
02161 
02162   if (!helper) {
02163     // There's nothing we can do if there's no helper
02164     return;
02165   }
02166 
02167   JSObject *obj = nsnull;
02168   nsresult rv = wrapper->GetJSObject(&obj);
02169   if (NS_FAILED(rv))
02170     return;
02171 
02172   // Abuse the scriptable helper to trigger prototype setup for the
02173   // wrapper for mContent so that this plugin becomes part of the DOM
02174   // object.
02175   helper->PostCreate(wrapper, cx, obj);
02176 }
02177 
02178 // static
02179 nsIObjectFrame *
02180 nsObjectFrame::GetNextObjectFrame(nsPresContext* aPresContext, nsIFrame* aRoot)
02181 {
02182   nsIFrame* child = aRoot->GetFirstChild(nsnull);
02183 
02184   while (child) {
02185     nsIObjectFrame* outFrame = nsnull;
02186     CallQueryInterface(child, &outFrame);
02187     if (outFrame) {
02188       nsCOMPtr<nsIPluginInstance> pi;
02189       outFrame->GetPluginInstance(*getter_AddRefs(pi));  // make sure we have a REAL plugin
02190       if (pi)
02191         return outFrame;
02192     }
02193 
02194     outFrame = GetNextObjectFrame(aPresContext, child);
02195     if (outFrame)
02196       return outFrame;
02197     child = child->GetNextSibling();
02198   }
02199 
02200   return nsnull;
02201 }
02202 
02203 nsresult
02204 NS_NewObjectFrame(nsIPresShell* aPresShell, nsIFrame** aNewFrame)
02205 {
02206   NS_PRECONDITION(aNewFrame, "null OUT ptr");
02207   if (nsnull == aNewFrame) {
02208     return NS_ERROR_NULL_POINTER;
02209   }
02210   nsObjectFrame* it = new (aPresShell) nsObjectFrame;
02211   if (nsnull == it) {
02212     return NS_ERROR_OUT_OF_MEMORY;
02213   }
02214   *aNewFrame = it;
02215   return NS_OK;
02216 }
02217 
02218 
02219 // nsPluginDOMContextMenuListener class implementation
02220 
02221 nsPluginDOMContextMenuListener::nsPluginDOMContextMenuListener()
02222 {
02223 }
02224 
02225 nsPluginDOMContextMenuListener::~nsPluginDOMContextMenuListener()
02226 {
02227 }
02228 
02229 NS_IMPL_ISUPPORTS2(nsPluginDOMContextMenuListener, nsIDOMContextMenuListener, nsIEventListener)
02230 
02231 NS_IMETHODIMP
02232 nsPluginDOMContextMenuListener::ContextMenu(nsIDOMEvent* aContextMenuEvent)
02233 {
02234   aContextMenuEvent->PreventDefault(); // consume event
02235 
02236   return NS_OK;
02237 }
02238 
02239 nsresult nsPluginDOMContextMenuListener::Init(nsObjectFrame *aFrame)
02240 {
02241   nsIContent* content = aFrame->GetContent();
02242 
02243   // Register context menu listener
02244   if (content) {
02245     nsCOMPtr<nsIDOMEventTarget> receiver(do_QueryInterface(content));
02246     if (receiver) {
02247       nsCOMPtr<nsIDOMContextMenuListener> cxMenuListener;
02248       QueryInterface(NS_GET_IID(nsIDOMContextMenuListener), getter_AddRefs(cxMenuListener));
02249       if (cxMenuListener) {
02250         receiver->AddEventListener(NS_LITERAL_STRING("contextmenu"), cxMenuListener, PR_TRUE);
02251         return NS_OK;
02252       }
02253     }
02254   }
02255 
02256   return NS_ERROR_NO_INTERFACE;
02257 }
02258 
02259 nsresult nsPluginDOMContextMenuListener::Destroy(nsObjectFrame *aFrame)
02260 {
02261   nsIContent* content = aFrame->GetContent();
02262 
02263   // Unregister context menu listener
02264   if (content) {
02265     nsCOMPtr<nsIDOMEventTarget> receiver(do_QueryInterface(content));
02266     if (receiver) {
02267       nsCOMPtr<nsIDOMContextMenuListener> cxMenuListener;
02268       QueryInterface(NS_GET_IID(nsIDOMContextMenuListener), getter_AddRefs(cxMenuListener));
02269       if (cxMenuListener) { 
02270         receiver->RemoveEventListener(NS_LITERAL_STRING("contextmenu"), cxMenuListener, PR_TRUE);
02271       }
02272       else NS_ASSERTION(PR_FALSE, "Unable to remove event listener for plugin");
02273     }
02274     else NS_ASSERTION(PR_FALSE, "plugin was not an event listener");
02275   }
02276   else NS_ASSERTION(PR_FALSE, "plugin had no content");
02277 
02278   return NS_OK;
02279 }
02280 
02281 //plugin instance owner
02282 
02283 nsPluginInstanceOwner::nsPluginInstanceOwner()
02284 {
02285   // create nsPluginNativeWindow object, it is derived from nsPluginWindow
02286   // struct and allows to manipulate native window procedure
02287   nsCOMPtr<nsIPluginHost> ph = do_GetService(kCPluginManagerCID);
02288   nsCOMPtr<nsPIPluginHost> pph(do_QueryInterface(ph));
02289   if (pph)
02290     pph->NewPluginNativeWindow(&mPluginWindow);
02291   else
02292     mPluginWindow = nsnull;
02293 
02294   mOwner = nsnull;
02295   mContext = nsnull;
02296   mTagText = nsnull;
02297   mContentFocused = PR_FALSE;
02298   mWidgetVisible = PR_TRUE;
02299   mNumCachedAttrs = 0;
02300   mNumCachedParams = 0;
02301   mCachedAttrParamNames = nsnull;
02302   mCachedAttrParamValues = nsnull;
02303   mInDispatchFocus = PR_FALSE;
02304 }
02305 
02306 nsPluginInstanceOwner::~nsPluginInstanceOwner()
02307 {
02308   PRInt32 cnt;
02309 
02310   // shut off the timer.
02311   if (mPluginTimer != nsnull) {
02312     CancelTimer();
02313   }
02314 
02315   mOwner = nsnull;
02316 
02317   for (cnt = 0; cnt < (mNumCachedAttrs + 1 + mNumCachedParams); cnt++) {
02318     if (mCachedAttrParamNames && mCachedAttrParamNames[cnt]) {
02319       PR_Free(mCachedAttrParamNames[cnt]);
02320       mCachedAttrParamNames[cnt] = nsnull;
02321     }
02322 
02323     if (mCachedAttrParamValues && mCachedAttrParamValues[cnt]) {
02324       PR_Free(mCachedAttrParamValues[cnt]);
02325       mCachedAttrParamValues[cnt] = nsnull;
02326     }
02327   }
02328 
02329   if (mCachedAttrParamNames) {
02330     PR_Free(mCachedAttrParamNames);
02331     mCachedAttrParamNames = nsnull;
02332   }
02333 
02334   if (mCachedAttrParamValues) {
02335     PR_Free(mCachedAttrParamValues);
02336     mCachedAttrParamValues = nsnull;
02337   }
02338 
02339   if (mTagText) {
02340     NS_Free(mTagText);
02341     mTagText = nsnull;
02342   }
02343 
02344   mContext = nsnull;
02345 
02346 #if defined(XP_UNIX) && !defined(XP_MACOSX)
02347   // the mem for this struct is allocated
02348   // by PR_MALLOC in ns4xPluginInstance.cpp:ns4xPluginInstance::SetWindow()
02349   if (mPluginWindow && mPluginWindow->ws_info) {
02350     PR_Free(mPluginWindow->ws_info);
02351     mPluginWindow->ws_info = nsnull;
02352   }
02353 #endif
02354 
02355   // clean up plugin native window object
02356   nsCOMPtr<nsIPluginHost> ph = do_GetService(kCPluginManagerCID);
02357   nsCOMPtr<nsPIPluginHost> pph(do_QueryInterface(ph));
02358   if (pph) {
02359     pph->DeletePluginNativeWindow(mPluginWindow);
02360     mPluginWindow = nsnull;
02361   }
02362 }
02363 
02364 /*
02365  * nsISupports Implementation
02366  */
02367 
02368 NS_IMPL_ADDREF(nsPluginInstanceOwner)
02369 NS_IMPL_RELEASE(nsPluginInstanceOwner)
02370 
02371 NS_INTERFACE_MAP_BEGIN(nsPluginInstanceOwner)
02372   NS_INTERFACE_MAP_ENTRY(nsIPluginInstanceOwner)
02373   NS_INTERFACE_MAP_ENTRY(nsIPluginTagInfo)
02374   NS_INTERFACE_MAP_ENTRY(nsIPluginTagInfo2)
02375 #ifdef OJI
02376   NS_INTERFACE_MAP_ENTRY(nsIJVMPluginTagInfo)
02377 #endif
02378   NS_INTERFACE_MAP_ENTRY(nsIEventListener)
02379   NS_INTERFACE_MAP_ENTRY(nsITimerCallback)
02380   NS_INTERFACE_MAP_ENTRY(nsIDOMMouseListener)
02381   NS_INTERFACE_MAP_ENTRY(nsIDOMMouseMotionListener)
02382   NS_INTERFACE_MAP_ENTRY(nsIDOMKeyListener)
02383   NS_INTERFACE_MAP_ENTRY(nsIDOMFocusListener)
02384   NS_INTERFACE_MAP_ENTRY(nsIScrollPositionListener)
02385   NS_INTERFACE_MAP_ENTRY(nsIDOMDragListener)
02386   NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsIDOMEventListener, nsIDOMMouseListener)
02387   NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIPluginInstanceOwner)
02388 NS_INTERFACE_MAP_END
02389 
02390 NS_IMETHODIMP nsPluginInstanceOwner::SetInstance(nsIPluginInstance *aInstance)
02391 {
02392   mInstance = aInstance;
02393 
02394   return NS_OK;
02395 }
02396 
02397 NS_IMETHODIMP nsPluginInstanceOwner::GetWindow(nsPluginWindow *&aWindow)
02398 {
02399   NS_ASSERTION(mPluginWindow, "the plugin window object being returned is null");
02400   aWindow = mPluginWindow;
02401   return NS_OK;
02402 }
02403 
02404 NS_IMETHODIMP nsPluginInstanceOwner::GetMode(nsPluginMode *aMode)
02405 {
02406   nsCOMPtr<nsIDocument> doc;
02407   nsresult rv = GetDocument(getter_AddRefs(doc));
02408   nsCOMPtr<nsIPluginDocument> pDoc (do_QueryInterface(doc));
02409 
02410   if (pDoc) {
02411     *aMode = nsPluginMode_Full;
02412   } else {
02413     *aMode = nsPluginMode_Embedded;
02414   }
02415 
02416   return rv;
02417 }
02418 
02419 NS_IMETHODIMP nsPluginInstanceOwner::GetAttributes(PRUint16& n,
02420                                                      const char*const*& names,
02421                                                      const char*const*& values)
02422 {
02423   nsresult rv = EnsureCachedAttrParamArrays();
02424   NS_ENSURE_SUCCESS(rv, rv);
02425 
02426   n = mNumCachedAttrs;
02427   names  = (const char **)mCachedAttrParamNames;
02428   values = (const char **)mCachedAttrParamValues;
02429 
02430   return rv;
02431 }
02432 
02433 NS_IMETHODIMP nsPluginInstanceOwner::GetAttribute(const char* name, const char* *result)
02434 {
02435   NS_ENSURE_ARG_POINTER(name);
02436   NS_ENSURE_ARG_POINTER(result);
02437   
02438   nsresult rv = EnsureCachedAttrParamArrays();
02439   NS_ENSURE_SUCCESS(rv, rv);
02440 
02441   *result = nsnull;
02442 
02443   for (int i = 0; i < mNumCachedAttrs; i++) {
02444     if (0 == PL_strcasecmp(mCachedAttrParamNames[i], name)) {
02445       *result = mCachedAttrParamValues[i];
02446       return NS_OK;
02447     }
02448   }
02449 
02450   return NS_ERROR_FAILURE;
02451 }
02452 
02453 NS_IMETHODIMP nsPluginInstanceOwner::GetDOMElement(nsIDOMElement* *result)
02454 {
02455   NS_ENSURE_ARG_POINTER(result);
02456   nsresult rv = NS_ERROR_FAILURE;
02457 
02458   *result = nsnull;
02459 
02460   if (nsnull != mOwner) {
02461     nsIContent* cont = mOwner->GetContent();
02462     if (cont) {
02463       rv = cont->QueryInterface(NS_GET_IID(nsIDOMElement), (void **)result);
02464     }
02465   }
02466 
02467   return rv;
02468 }
02469 
02470 NS_IMETHODIMP nsPluginInstanceOwner::GetInstance(nsIPluginInstance *&aInstance)
02471 {
02472   NS_IF_ADDREF(aInstance = mInstance);
02473 
02474   return NS_OK;
02475 }
02476 
02477 NS_IMETHODIMP nsPluginInstanceOwner::GetURL(const char *aURL, const char *aTarget, void *aPostData, PRUint32 aPostDataLen, void *aHeadersData, 
02478                                             PRUint32 aHeadersDataLen, PRBool isFile)
02479 {
02480   NS_ENSURE_TRUE(mOwner,NS_ERROR_NULL_POINTER);
02481   NS_ENSURE_TRUE(mContext,NS_ERROR_NULL_POINTER);
02482 
02483   // the container of the pres context will give us the link handler
02484   nsCOMPtr<nsISupports> container = mContext->GetContainer();
02485   NS_ENSURE_TRUE(container,NS_ERROR_FAILURE);
02486   nsCOMPtr<nsILinkHandler> lh = do_QueryInterface(container);
02487   NS_ENSURE_TRUE(lh, NS_ERROR_FAILURE);
02488 
02489   nsAutoString  unitarget; unitarget.AssignASCII(aTarget); // XXX could this be nonascii?
02490 
02491   nsCOMPtr<nsIURI> baseURL;
02492   nsCOMPtr<nsIDocument> doc;
02493   nsresult rv = GetDocument(getter_AddRefs(doc));
02494   if (NS_SUCCEEDED(rv) && doc) {
02495     // XXX should this really be the document base URL?  Or the
02496     // content's base URL?
02497     baseURL = doc->GetBaseURI();  // gets the document's url
02498   } else {
02499     baseURL = mOwner->GetFullURL(); // gets the plugin's content url
02500   }
02501 
02502   // Create an absolute URL
02503   nsCOMPtr<nsIURI> uri;
02504   rv = NS_NewURI(getter_AddRefs(uri), aURL, baseURL);
02505 
02506   NS_ENSURE_SUCCESS(rv, NS_ERROR_FAILURE);
02507   nsIContent* content = mOwner->GetContent();
02508   NS_ENSURE_TRUE(content, NS_ERROR_FAILURE);
02509 
02510   nsCOMPtr<nsIInputStream> postDataStream;
02511   nsCOMPtr<nsIInputStream> headersDataStream;
02512 
02513   // deal with post data, either in a file or raw data, and any headers
02514   if (aPostData) {
02515 
02516     rv = NS_NewPluginPostDataStream(getter_AddRefs(postDataStream), (const char *)aPostData, aPostDataLen, isFile);
02517 
02518     NS_ASSERTION(NS_SUCCEEDED(rv),"failed in creating plugin post data stream");
02519     if (NS_FAILED(rv))
02520       return rv;
02521 
02522     if (aHeadersData) {
02523       rv = NS_NewPluginPostDataStream(getter_AddRefs(headersDataStream), 
02524                                       (const char *) aHeadersData, 
02525                                       aHeadersDataLen,
02526                                       PR_FALSE,
02527                                       PR_TRUE);  // last arg says we are headers, no /r/n/r/n fixup!
02528 
02529       NS_ASSERTION(NS_SUCCEEDED(rv),"failed in creating plugin header data stream");
02530       if (NS_FAILED(rv))
02531         return rv;
02532     }
02533   }
02534 
02535   PRInt32 blockPopups =
02536     nsContentUtils::GetIntPref("privacy.popups.disable_from_plugins");
02537   nsAutoPopupStatePusher popupStatePusher((PopupControlState)blockPopups);
02538 
02539   rv = lh->OnLinkClick(content, eLinkVerb_Replace, 
02540                        uri, unitarget.get(), 
02541                        postDataStream, headersDataStream);
02542 
02543   return rv;
02544 }
02545 
02546 NS_IMETHODIMP nsPluginInstanceOwner::ShowStatus(const char *aStatusMsg)
02547 {
02548   nsresult  rv = NS_ERROR_FAILURE;
02549   
02550   rv = this->ShowStatus(NS_ConvertUTF8toUCS2(aStatusMsg).get());
02551   
02552   return rv;
02553 }
02554 
02555 NS_IMETHODIMP nsPluginInstanceOwner::ShowStatus(const PRUnichar *aStatusMsg)
02556 {
02557   nsresult  rv = NS_ERROR_FAILURE;
02558 
02559   if (!mContext) {
02560     return rv;
02561   }
02562   nsCOMPtr<nsISupports> cont = mContext->GetContainer();
02563   if (!cont) {
02564     return NS_OK;
02565   }
02566 
02567   nsCOMPtr<nsIDocShellTreeItem> docShellItem(do_QueryInterface(cont, &rv));
02568   if (NS_FAILED(rv) || !docShellItem) {
02569     return rv;
02570   }
02571 
02572   nsCOMPtr<nsIDocShellTreeOwner> treeOwner;
02573   rv = docShellItem->GetTreeOwner(getter_AddRefs(treeOwner));
02574   if (NS_FAILED(rv) || !treeOwner) {
02575     return rv;
02576   }
02577 
02578   nsCOMPtr<nsIWebBrowserChrome> browserChrome(do_GetInterface(treeOwner, &rv));
02579   if (NS_FAILED(rv) || !browserChrome) {
02580     return rv;
02581   }
02582   rv = browserChrome->SetStatus(nsIWebBrowserChrome::STATUS_SCRIPT, 
02583                                 aStatusMsg);
02584 
02585   return rv;
02586 }
02587 
02588 NS_IMETHODIMP nsPluginInstanceOwner::GetDocument(nsIDocument* *aDocument)
02589 {
02590   if (!aDocument)
02591     return NS_ERROR_NULL_POINTER;
02592 
02593   *aDocument = nsnull;
02594   if (nsnull != mContext) {
02595     nsIPresShell *shell = mContext->GetPresShell();
02596     if (shell)
02597       NS_IF_ADDREF(*aDocument = shell->GetDocument());
02598   }
02599   return NS_OK;
02600 }
02601 
02602 NS_IMETHODIMP nsPluginInstanceOwner::InvalidateRect(nsPluginRect *invalidRect)
02603 {
02604   nsresult rv = NS_ERROR_FAILURE;
02605 
02606   if (invalidRect) {
02607     //no reference count on view
02608     nsIView* view = mOwner->GetView();
02609 
02610     if (view) {
02611       float ptot;
02612       ptot = mContext->PixelsToTwips();
02613 
02614       nsRect rect((int)(ptot * invalidRect->left),
02615             (int)(ptot * invalidRect->top),
02616             (int)(ptot * (invalidRect->right - invalidRect->left)),
02617             (int)(ptot * (invalidRect->bottom - invalidRect->top)));
02618 
02619       //set flags to not do a synchronous update, force update does the redraw
02620       view->GetViewManager()->UpdateView(view, rect, NS_VMREFRESH_NO_SYNC);
02621     }
02622   }
02623 
02624   return rv;
02625 }
02626 
02627 NS_IMETHODIMP nsPluginInstanceOwner::InvalidateRegion(nsPluginRegion invalidRegion)
02628 {
02629   return NS_ERROR_NOT_IMPLEMENTED;
02630 }
02631 
02632 NS_IMETHODIMP nsPluginInstanceOwner::ForceRedraw()
02633 {
02634   nsIView* view = mOwner->GetView();
02635   if (view) {
02636     return view->GetViewManager()->Composite();
02637   }
02638 
02639   return NS_OK;
02640 }
02641 
02642 NS_IMETHODIMP nsPluginInstanceOwner::GetValue(nsPluginInstancePeerVariable variable, void *value)
02643 {
02644   nsresult rv = NS_ERROR_FAILURE;
02645 
02646   switch(variable) {
02647     case nsPluginInstancePeerVariable_NetscapeWindow:
02648     {      
02649       // get the document's widget from the view manager
02650       // get the view manager from the pres shell, not from the view!
02651       // we may not have a view if we are hidden
02652       if (mContext) {
02653         void** pvalue = (void**)value;
02654         nsIViewManager* vm = mContext->GetViewManager();
02655         if (vm) {
02656 #if defined(XP_WIN)
02657           // This property is provided to allow a "windowless" plugin to determine the window it is drawing
02658           // in, so it can translate mouse coordinates it receives directly from the operating system
02659           // to coordinates relative to itself.
02660           
02661           // The original code (outside this #if) returns the document's window, which is OK if the window the "windowless" plugin
02662           // 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
02663    
02664           // To make sure "windowless" plugins always get the right origin for translating mouse coordinates, this code
02665           // determines the window handle of the mozilla window containing the "windowless" plugin.
02666    
02667           // Given that this HWND may not be that of the document's window, there is a slight risk
02668           // of confusing a plugin that is using this HWND for illicit purposes, but since the documentation
02669           // does not suggest this HWND IS that of the document window, rather that of the window
02670           // the plugin is drawn in, this seems like a safe fix.
02671            
02672           // we only attempt to get the nearest window if this really is a "windowless" plugin so as not
02673           // to change any behaviour for the much more common windowed plugins,
02674           // though why this method would even be being called for a windowed plugin escapes me.
02675           if (mPluginWindow && mPluginWindow->type == nsPluginWindowType_Drawable) {
02676             if (mOwner) {
02677               // it turns out that flash also uses this window for determining focus, and is currently
02678               // unable to show a caret correctly if we return the enclosing window. Therefore for
02679               // now we only return the enclosing window when there is an actual offset which
02680               // would otherwise cause coordinates to be offset incorrectly. (i.e.
02681               // if the enclosing window if offset from the document window)
02682               //
02683               // fixing both the caret and ability to interact issues for a windowless control in a non document aligned windw
02684               // does not seem to be possible without a change to the flash plugin
02685     
02686               nsIWidget* win = mOwner->GetWindow();
02687               if (win) {
02688                 nsIView *view = nsIView::GetViewFor(win);
02689                 NS_ASSERTION(view, "No view for widget");
02690                 nsIView *rootView = nsnull;
02691                 vm->GetRootView(rootView);
02692                 NS_ASSERTION(rootView, "No root view");
02693                 nsPoint offset = view->GetOffsetTo(rootView);
02694       
02695                 if (offset.x || offset.y) {
02696                   // in the case the two windows are offset from eachother, we do go ahead and return the correct enclosing window
02697                   // so that mouse co-ordinates are not messed up.
02698                   *pvalue = (void*)win->GetNativeData(NS_NATIVE_WINDOW);
02699                   if (*pvalue) {
02700                     return NS_OK;
02701                   }
02702                 }
02703               }
02704             }
02705           }
02706 #endif
02707           // simply return the document window
02708           nsCOMPtr<nsIWidget> widget;
02709           rv = vm->GetWidget(getter_AddRefs(widget));            
02710           if (widget) {
02711             *pvalue = (void*)widget->GetNativeData(NS_NATIVE_WINDOW);
02712           } else NS_ASSERTION(widget, "couldn't get doc's widget in getting doc's window handle");
02713         } else NS_ASSERTION(vm, "couldn't get view manager in getting doc's window handle");
02714       } else NS_ASSERTION(mContext, "plugin owner has no pres context in getting doc's window handle");
02715 
02716       break;
02717     }
02718   }
02719 
02720   return rv;
02721 }
02722 
02723 NS_IMETHODIMP
02724 nsPluginInstanceOwner::PluginNotAvailable(const char *aMimeType)
02725 {
02726   if (mOwner) {
02727     mOwner->PluginNotAvailable(aMimeType);
02728   }
02729 
02730   return NS_OK;
02731 }
02732 
02733 NS_IMETHODIMP nsPluginInstanceOwner::GetTagType(nsPluginTagType *result)
02734 {
02735   NS_ENSURE_ARG_POINTER(result);
02736   nsresult rv = NS_ERROR_FAILURE;
02737 
02738   *result = nsPluginTagType_Unknown;
02739 
02740   if (mOwner) {
02741     nsIContent* cont = mOwner->GetContent();
02742     if (cont) {
02743       nsIAtom *atom = cont->Tag();
02744 
02745       if (atom == nsHTMLAtoms::applet)
02746         *result = nsPluginTagType_Applet;
02747       else if (atom == nsHTMLAtoms::embed)
02748         *result = nsPluginTagType_Embed;
02749       else if (atom == nsHTMLAtoms::object)
02750         *result = nsPluginTagType_Object;
02751 
02752       rv = NS_OK;
02753     }
02754   }
02755 
02756   return rv;
02757 }
02758 
02759 NS_IMETHODIMP nsPluginInstanceOwner::GetTagText(const char* *result)
02760 {
02761     NS_ENSURE_ARG_POINTER(result);
02762     if (nsnull == mTagText) {
02763         nsresult rv;
02764         nsIContent* content = mOwner->GetContent();
02765 
02766         nsCOMPtr<nsIDOMNode> node(do_QueryInterface(content, &rv));
02767         if (NS_FAILED(rv))
02768             return rv;
02769         nsCOMPtr<nsIDocument> document;
02770         rv = GetDocument(getter_AddRefs(document));
02771         if (NS_FAILED(rv))
02772             return rv;
02773         nsCOMPtr<nsIDocumentEncoder> docEncoder(do_CreateInstance(NS_DOC_ENCODER_CONTRACTID_BASE "text/html", &rv));
02774         if (NS_FAILED(rv))
02775             return rv;
02776         rv = docEncoder->Init(document, NS_LITERAL_STRING("text/html"), nsIDocumentEncoder::OutputEncodeBasicEntities);
02777         if (NS_FAILED(rv))
02778             return rv;
02779 
02780         nsCOMPtr<nsIDOMRange> range(do_CreateInstance(kRangeCID,&rv));
02781         if (NS_FAILED(rv))
02782             return rv;
02783 
02784         rv = range->SelectNode(node);
02785         if (NS_FAILED(rv))
02786             return rv;
02787 
02788         docEncoder->SetRange(range);
02789         nsString elementHTML;
02790         rv = docEncoder->EncodeToString(elementHTML);
02791         if (NS_FAILED(rv))
02792             return rv;
02793 
02794         mTagText = ToNewUTF8String(elementHTML);
02795         if (!mTagText)
02796             return NS_ERROR_OUT_OF_MEMORY;
02797     }
02798     *result = mTagText;
02799     return NS_OK;
02800 }
02801 
02802 NS_IMETHODIMP nsPluginInstanceOwner::GetParameters(PRUint16& n, const char*const*& names, const char*const*& values)
02803 {
02804   nsresult rv = EnsureCachedAttrParamArrays();
02805   NS_ENSURE_SUCCESS(rv, rv);
02806 
02807   n = mNumCachedParams;
02808   if (n) {
02809     names  = (const char **)(mCachedAttrParamNames + mNumCachedAttrs + 1);
02810     values = (const char **)(mCachedAttrParamValues + mNumCachedAttrs + 1);
02811   } else
02812     names = values = nsnull;
02813 
02814   return rv;
02815 }
02816 
02817 NS_IMETHODIMP nsPluginInstanceOwner::GetParameter(const char* name, const char* *result)
02818 {
02819   NS_ENSURE_ARG_POINTER(name);
02820   NS_ENSURE_ARG_POINTER(result);
02821   
02822   nsresult rv = EnsureCachedAttrParamArrays();
02823   NS_ENSURE_SUCCESS(rv, rv);
02824 
02825   *result = nsnull;
02826 
02827   for (int i = mNumCachedAttrs + 1; i < (mNumCachedParams + 1 + mNumCachedAttrs); i++) {
02828     if (0 == PL_strcasecmp(mCachedAttrParamNames[i], name)) {
02829       *result = mCachedAttrParamValues[i];
02830       return NS_OK;
02831     }
02832   }
02833 
02834   return NS_ERROR_FAILURE;
02835 }
02836   
02837 NS_IMETHODIMP nsPluginInstanceOwner::GetDocumentBase(const char* *result)
02838 {
02839   NS_ENSURE_ARG_POINTER(result);
02840   nsresult rv = NS_OK;
02841   if (mDocumentBase.IsEmpty()) {
02842     if (nsnull == mContext) {
02843       *result = nsnull;
02844       return NS_ERROR_FAILURE;
02845     }
02846     
02847     rv = mContext->PresShell()->GetDocument()->GetBaseURI()->GetSpec(mDocumentBase);
02848   }
02849   if (NS_SUCCEEDED(rv))
02850     *result = ToNewCString(mDocumentBase);
02851   return rv;
02852 }
02853 
02854 static nsHashtable *gCharsetMap = nsnull;
02855 typedef struct {
02856     char mozName[16];
02857     char javaName[12];
02858 } moz2javaCharset;
02859 
02860 /* XXX If you add any strings longer than
02861  *  {"x-mac-cyrillic",  "MacCyrillic"},
02862  *  {"x-mac-ukrainian", "MacUkraine"},
02863  * to the following array then you MUST update the
02864  * sizes of the arrays in the moz2javaCharset struct
02865  */
02866 
02867 static const moz2javaCharset charsets[] = 
02868 {
02869     {"windows-1252",    "Cp1252"},
02870     {"IBM850",          "Cp850"},
02871     {"IBM852",          "Cp852"},
02872     {"IBM855",          "Cp855"},
02873     {"IBM857",          "Cp857"},
02874     {"IBM828",          "Cp862"},
02875     {"IBM864",          "Cp864"},
02876     {"IBM866",          "Cp866"},
02877     {"windows-1250",    "Cp1250"},
02878     {"windows-1251",    "Cp1251"},
02879     {"windows-1253",    "Cp1253"},
02880     {"windows-1254",    "Cp1254"},
02881     {"windows-1255",    "Cp1255"},
02882     {"windows-1256",    "Cp1256"},
02883     {"windows-1257",    "Cp1257"},
02884     {"windows-1258",    "Cp1258"},
02885     {"EUC-JP",          "EUC_JP"},
02886     {"EUC-KR",          "EUC_KR"},
02887     {"x-euc-tw",        "EUC_TW"},
02888     {"gb18030",         "GB18030"},
02889     {"x-gbk",           "GBK"},
02890     {"ISO-2022-JP",     "ISO2022JP"},
02891     {"ISO-2022-KR",     "ISO2022KR"},
02892     {"ISO-8859-2",      "ISO8859_2"},
02893     {"ISO-8859-3",      "ISO8859_3"},
02894     {"ISO-8859-4",      "ISO8859_4"},
02895     {"ISO-8859-5",      "ISO8859_5"},
02896     {"ISO-8859-6",      "ISO8859_6"},
02897     {"ISO-8859-7",      "ISO8859_7"},
02898     {"ISO-8859-8",      "ISO8859_8"},
02899     {"ISO-8859-9",      "ISO8859_9"},
02900     {"ISO-8859-13",     "ISO8859_13"},
02901     {"x-johab",         "Johab"},
02902     {"KOI8-R",          "KOI8_R"},
02903     {"TIS-620",         "MS874"},
02904     {"windows-936",     "MS936"},
02905     {"x-windows-949",   "MS949"},
02906     {"x-mac-arabic",    "MacArabic"},
02907     {"x-mac-croatian",  "MacCroatia"},
02908     {"x-mac-cyrillic",  "MacCyrillic"},
02909     {"x-mac-greek",     "MacGreek"},
02910     {"x-mac-hebrew",    "MacHebrew"},
02911     {"x-mac-icelandic", "MacIceland"},
02912     {"x-mac-roman",     "MacRoman"},
02913     {"x-mac-romanian",  "MacRomania"},
02914     {"x-mac-ukrainian", "MacUkraine"},
02915     {"Shift_JIS",       "SJIS"},
02916     {"TIS-620",         "TIS620"}
02917 };
02918   
02919 NS_IMETHODIMP nsPluginInstanceOwner::GetDocumentEncoding(const char* *result)
02920 {
02921   NS_ENSURE_ARG_POINTER(result);
02922   *result = nsnull;
02923 
02924   nsresult rv;
02925   nsCOMPtr<nsIDocument> doc;
02926   rv = GetDocument(getter_AddRefs(doc));
02927   NS_ASSERTION(NS_SUCCEEDED(rv), "failed to get document");
02928   if (NS_FAILED(rv))
02929     return rv;
02930 
02931   const nsACString &charset = doc->GetDocumentCharacterSet();
02932 
02933   if (charset.IsEmpty())
02934     return NS_OK;
02935 
02936   // common charsets and those not requiring conversion first
02937   if (charset.EqualsLiteral("us-ascii")) {
02938     *result = PL_strdup("US_ASCII");
02939   } else if (charset.EqualsLiteral("ISO-8859-1") ||
02940       !nsCRT::strncmp(PromiseFlatCString(charset).get(), "UTF", 3)) {
02941     *result = ToNewCString(charset);
02942   } else {
02943     if (!gCharsetMap) {
02944       gCharsetMap = new nsHashtable(sizeof(charsets)/sizeof(moz2javaCharset));
02945       if (!gCharsetMap)
02946         return NS_ERROR_OUT_OF_MEMORY;
02947 
02948       for (PRUint16 i = 0; i < sizeof(charsets)/sizeof(moz2javaCharset); i++) {
02949         nsCStringKey key(charsets[i].mozName);
02950         gCharsetMap->Put(&key, (void *)(charsets[i].javaName));
02951       }
02952     }
02953     nsCStringKey mozKey(charset);
02954     // if found mapping, return it; otherwise return original charset
02955     char *mapping = (char *)gCharsetMap->Get(&mozKey);
02956     *result = mapping ? PL_strdup(mapping) : ToNewCString(charset);
02957   }
02958 
02959   return (*result) ? NS_OK : NS_ERROR_OUT_OF_MEMORY;
02960 }
02961 
02962 NS_IMETHODIMP nsPluginInstanceOwner::GetAlignment(const char* *result)
02963 {
02964   return GetAttribute("ALIGN", result);
02965 }
02966   
02967 NS_IMETHODIMP nsPluginInstanceOwner::GetWidth(PRUint32 *result)
02968 {
02969   NS_ENSURE_ARG_POINTER(result);
02970 
02971   NS_ENSURE_TRUE(mPluginWindow, NS_ERROR_NULL_POINTER);
02972 
02973   *result = mPluginWindow->width;
02974 
02975   return NS_OK;
02976 }
02977   
02978 NS_IMETHODIMP nsPluginInstanceOwner::GetHeight(PRUint32 *result)
02979 {
02980   NS_ENSURE_ARG_POINTER(result);
02981 
02982   NS_ENSURE_TRUE(mPluginWindow, NS_ERROR_NULL_POINTER);
02983 
02984   *result = mPluginWindow->height;
02985 
02986   return NS_OK;
02987 }
02988 
02989   
02990 NS_IMETHODIMP nsPluginInstanceOwner::GetBorderVertSpace(PRUint32 *result)
02991 {
02992   nsresult    rv;
02993   const char  *vspace;
02994 
02995   rv = GetAttribute("VSPACE", &vspace);
02996 
02997   if (NS_OK == rv) {
02998     if (*result != 0)
02999       *result = (PRUint32)atol(vspace);
03000     else
03001       *result = 0;
03002   }
03003   else
03004     *result = 0;
03005 
03006   return rv;
03007 }
03008   
03009 NS_IMETHODIMP nsPluginInstanceOwner::GetBorderHorizSpace(PRUint32 *result)
03010 {
03011   nsresult    rv;
03012   const char  *hspace;
03013 
03014   rv = GetAttribute("HSPACE", &hspace);
03015 
03016   if (NS_OK == rv) {
03017     if (*result != 0)
03018       *result = (PRUint32)atol(hspace);
03019     else
03020       *result = 0;
03021   }
03022   else
03023     *result = 0;
03024 
03025   return rv;
03026 }
03027 
03028 NS_IMETHODIMP nsPluginInstanceOwner::GetUniqueID(PRUint32 *result)
03029 {
03030   NS_ENSURE_ARG_POINTER(result);
03031   *result = NS_PTR_TO_INT32(mContext);
03032   return NS_OK;
03033 }
03034 
03035 #ifdef OJI
03036 NS_IMETHODIMP nsPluginInstanceOwner::GetCode(const char* *result)
03037 {
03038   nsresult rv;
03039   nsPluginTagType tagType;  
03040   NS_ENSURE_SUCCESS(rv = GetTagType(&tagType), rv);
03041 
03042   rv = NS_ERROR_FAILURE;
03043   if (nsPluginTagType_Object != tagType)
03044     rv = GetAttribute("CODE", result);
03045   if (NS_FAILED(rv))
03046     rv = GetParameter("CODE", result);
03047 
03048   return rv;
03049 }
03050 
03051 NS_IMETHODIMP nsPluginInstanceOwner::GetCodeBase(const char* *result)
03052 {
03053   nsresult rv;
03054   if (NS_FAILED(rv = GetAttribute("CODEBASE", result)))
03055     rv = GetParameter("CODEBASE", result);
03056   return rv;
03057 }
03058 
03059 NS_IMETHODIMP nsPluginInstanceOwner::GetArchive(const char* *result)
03060 {
03061   nsresult rv;
03062   if (NS_FAILED(rv = GetAttribute("ARCHIVE", result)))
03063     rv = GetParameter("ARCHIVE", result);
03064   return rv;
03065 }
03066 
03067 NS_IMETHODIMP nsPluginInstanceOwner::GetName(const char* *result)
03068 {
03069   nsresult rv;
03070   nsPluginTagType tagType;  
03071   NS_ENSURE_SUCCESS(rv = GetTagType(&tagType), rv);
03072 
03073   rv = NS_ERROR_FAILURE;
03074   if (nsPluginTagType_Object != tagType)
03075     rv = GetAttribute("NAME", result);
03076   if (NS_FAILED(rv))
03077     rv = GetParameter("NAME", result);
03078 
03079   return rv;
03080 }
03081 
03082 NS_IMETHODIMP nsPluginInstanceOwner::GetMayScript(PRBool *result)
03083 {
03084   NS_ENSURE_ARG_POINTER(result);
03085   nsPluginTagType tagType;  
03086   NS_ENSURE_SUCCESS(GetTagType(&tagType), NS_ERROR_FAILURE);
03087 
03088   const char* unused;
03089   if (nsPluginTagType_Object == tagType)
03090     *result = NS_SUCCEEDED(GetParameter("MAYSCRIPT", &unused)); 
03091   else
03092     *result = NS_SUCCEEDED(GetAttribute("MAYSCRIPT", &unused));
03093 
03094   return NS_OK;
03095 }
03096 #endif /* OJI */
03097 
03098 // Little helper function to resolve relative URL in
03099 // |value| for certain inputs of |name|
03100 void nsObjectFrame::FixUpURLS(const nsString &name, nsAString &value)
03101 {
03102   if (name.LowerCaseEqualsLiteral("pluginurl") ||
03103       name.LowerCaseEqualsLiteral("pluginspage")) {        
03104     
03105     nsCOMPtr<nsIURI> baseURI = mContent->GetBaseURI();
03106     nsAutoString newURL;
03107     NS_MakeAbsoluteURI(newURL, value, baseURI);
03108     if (!newURL.IsEmpty())
03109       value = newURL;
03110   }
03111 }
03112 
03113 void
03114 nsObjectFrame::PluginNotAvailable(const char *aMimeType)
03115 {
03116   if (!aMimeType) {
03117     NS_ERROR("bogus type... behavior will be broken");
03118     return;
03119   }
03120   
03121   nsDependentCString type(aMimeType);
03122 
03123   // Tell mContent about the mime type
03124 
03125   nsCOMPtr<nsIPluginElement> pluginElement(do_QueryInterface(mContent));
03126 
03127   if (pluginElement) {
03128     pluginElement->SetActualType(type);
03129   }
03130 
03131   if (!sDefaultPluginDisabled) {
03132     // The default plugin is enabled, don't fire events etc.
03133     return;
03134   }
03135 
03136   // For non-image and non-document mime types, fire the plugin not
03137   // found event and mark this plugin as broken.
03138   if (!IsSupportedImage(type) &&
03139       !IsSupportedDocument(mContent, type)) {
03140     mIsBrokenPlugin = PR_TRUE;
03141 
03142     nsIDocument *doc = mContent->GetDocument();
03143     if (!doc) {
03144       return;
03145     }
03146 
03147     mState |= NS_FRAME_HAS_DIRTY_CHILDREN;
03148 
03149     GetParent()->ReflowDirtyChild(doc->GetShellAt(0), this);
03150 
03151     // Make sure to fire the event AFTER we've finished touching out members.
03152 
03153     // Hold a strong ref to our content across this event dispatch.
03154     nsCOMPtr<nsIContent> kungFuDeathGrip(mContent);
03155     
03156     FirePluginNotFoundEvent(mContent);
03157   }
03158 }
03159 
03160 
03161 // Cache the attributes and/or parameters of our tag into a single set
03162 // of arrays to be compatible with 4.x. The attributes go first,
03163 // followed by a PARAM/null and then any PARAM tags. Also, hold the
03164 // cached array around for the duration of the life of the instance
03165 // because 4.x did. See bug 111008.
03166 
03167 nsresult nsPluginInstanceOwner::EnsureCachedAttrParamArrays()
03168 {
03169   if (mCachedAttrParamValues)
03170     return NS_OK;
03171 
03172   NS_PRECONDITION(((mNumCachedAttrs + mNumCachedParams) == 0) &&
03173                   !mCachedAttrParamNames,
03174                   "re-cache of attrs/params not implemented! use the DOM "
03175                   "node directy instead");
03176   NS_ENSURE_TRUE(mOwner, NS_ERROR_NULL_POINTER);
03177 
03178   // first, we need to find out how much we need to allocate for our
03179   // arrays count up attributes
03180   mNumCachedAttrs = 0;
03181 
03182   nsIContent* content = mOwner->GetContent();
03183   nsresult rv = NS_OK;
03184   NS_ENSURE_TRUE(content, rv);
03185 
03186   PRUint32 cattrs = content->GetAttrCount();
03187 
03188   if (cattrs < 0x0000FFFF) {
03189     // unsigned 32 bits to unsigned 16 bits conversion
03190     mNumCachedAttrs = NS_STATIC_CAST(PRUint16, cattrs);
03191   } else {
03192     mNumCachedAttrs = 0xFFFE;  // minus one in case we add an extra "src" entry below
03193   }
03194 
03195   // now, we need to find all the PARAM tags that are children of us
03196   // however, be carefull NOT to include any PARAMs that don't have us
03197   // as a direct parent. For nested object (or applet) tags, be sure
03198   // to only round up the param tags that coorespond with THIS
03199   // instance. And also, weed out any bogus tags that may get in the
03200   // way, see bug 39609. Then, with any param tag that meet our
03201   // qualification, temporarly cache them in an nsISupportsArray until
03202   // we can figure out what size to make our fixed char* array.
03203 
03204   mNumCachedParams = 0;
03205   nsCOMPtr<nsISupportsArray> ourParams;
03206   rv = NS_NewISupportsArray(getter_AddRefs(ourParams));
03207   NS_ENSURE_SUCCESS(rv, rv);
03208  
03209   // use the DOM to get us ALL our dependant PARAM tags, even if not
03210   // ours
03211   nsCOMPtr<nsIDOMElement> mydomElement = do_QueryInterface(content);
03212   NS_ENSURE_TRUE(mydomElement, NS_ERROR_NO_INTERFACE);
03213 
03214   nsCOMPtr<nsIDOMNodeList> allParams; 
03215 
03216   nsINodeInfo *ni = content->GetNodeInfo();
03217 
03218   if (ni->NamespaceEquals(kNameSpaceID_XHTML)) {
03219     // For XHTML elements we need to take the namespace URI into
03220     // account when looking for param elements.
03221 
03222     NS_NAMED_LITERAL_STRING(xhtml_ns, "http://www.w3.org/1999/xhtml");
03223 
03224     mydomElement->GetElementsByTagNameNS(xhtml_ns, NS_LITERAL_STRING("param"),
03225                                          getter_AddRefs(allParams));
03226   } else {
03227     // If content is not XHTML, it must be HTML, no need to worry
03228     // about namespaces then...
03229 
03230     mydomElement->GetElementsByTagName(NS_LITERAL_STRING("param"),
03231                                        getter_AddRefs(allParams));
03232   }    
03233 
03234   if (allParams) {
03235     PRUint32 numAllParams; 
03236     allParams->GetLength(&numAllParams);
03237     // loop through every so called dependant PARAM tag to check if it
03238     // "belongs" to us
03239 
03240     for (PRUint32 i = 0; i < numAllParams; i++) {
03241       nsCOMPtr<nsIDOMNode> pnode;
03242       allParams->Item(i, getter_AddRefs(pnode));
03243 
03244       nsCOMPtr<nsIDOMElement> domelement = do_QueryInterface(pnode);
03245       if (domelement) {
03246         // let's NOT count up param tags that don't have a name attribute
03247         nsAutoString name;
03248         domelement->GetAttribute(NS_LITERAL_STRING("name"), name);
03249         if (!name.IsEmpty()) {
03250           nsCOMPtr<nsIDOMNode> parent;
03251           nsCOMPtr<nsIDOMHTMLObjectElement> domobject;
03252           nsCOMPtr<nsIDOMHTMLAppletElement> domapplet;
03253           pnode->GetParentNode(getter_AddRefs(parent));
03254           // walk up the parents of this PARAM until we find an object
03255           // (or applet) tag
03256 
03257           while (!(domobject || domapplet) && parent) {
03258             domobject = do_QueryInterface(parent);
03259             domapplet = do_QueryInterface(parent);
03260             nsCOMPtr<nsIDOMNode> temp;
03261             parent->GetParentNode(getter_AddRefs(temp));
03262             parent = temp;
03263           }
03264 
03265           if (domapplet || domobject) {
03266             if (domapplet)
03267               parent = do_QueryInterface(domapplet);
03268             else
03269               parent = do_QueryInterface(domobject);
03270 
03271             // now check to see if this PARAM's parent is us. if so,
03272             // cache it for later
03273 
03274             nsCOMPtr<nsIDOMNode> mydomNode = do_QueryInterface(mydomElement);
03275             if (parent == mydomNode) {
03276               ourParams->AppendElement(pnode);
03277             }
03278           }
03279         }
03280       }
03281     }
03282   }
03283 
03284   PRUint32 cparams;
03285   ourParams->Count(&cparams); // unsigned 32 bits to unsigned 16 bits conversion
03286   if (cparams < 0x0000FFFF)
03287     mNumCachedParams = NS_STATIC_CAST(PRUint16, cparams);
03288   else 
03289     mNumCachedParams = 0xFFFF;
03290 
03291   // Some plugins were never written to understand the "data" attribute of the OBJECT tag.
03292   // Real and WMP will not play unless they find a "src" attribute, see bug 152334.
03293   // Nav 4.x would simply replace the "data" with "src". Because some plugins correctly
03294   // look for "data", lets instead copy the "data" attribute and add another entry
03295   // to the bottom of the array if there isn't already a "src" specified.
03296   PRInt16 numRealAttrs = mNumCachedAttrs;
03297   nsAutoString data;
03298   nsIAtom *tag = content->Tag();
03299   if (nsHTMLAtoms::object == tag
03300     && !content->HasAttr(kNameSpaceID_None, nsHTMLAtoms::src)
03301     && NS_CONTENT_ATTR_NOT_THERE != content->GetAttr(kNameSpaceID_None, nsHTMLAtoms::data, data)) {
03302       mNumCachedAttrs++;
03303   }
03304 
03305   // now lets make the arrays
03306   mCachedAttrParamNames  = (char **)PR_Calloc(sizeof(char *) * (mNumCachedAttrs + 1 + mNumCachedParams), 1);
03307   NS_ENSURE_TRUE(mCachedAttrParamNames,  NS_ERROR_OUT_OF_MEMORY);
03308   mCachedAttrParamValues = (char **)PR_Calloc(sizeof(char *) * (mNumCachedAttrs + 1 + mNumCachedParams), 1);
03309   NS_ENSURE_TRUE(mCachedAttrParamValues, NS_ERROR_OUT_OF_MEMORY);
03310 
03311   // let's fill in our attributes
03312   PRInt16 c = 0;
03313 
03314   // Some plugins (eg Flash, see bug 234675.) are actually sensitive to the
03315   // attribute order.  So we want to make sure we give the plugin the
03316   // attributes in the order they came in in the source, to be compatible with
03317   // other browsers.  Now in HTML, the storage order is the reverse of the
03318   // source order, while in XML and XHTML it's the same as the source order
03319   // (see the AddAttributes functions in the HTML and XML content sinks).
03320   PRInt16 start, end, increment;
03321   if (content->IsContentOfType(nsIContent::eHTML) &&
03322       content->GetNodeInfo()->NamespaceEquals(kNameSpaceID_None)) {
03323     // HTML.  Walk attributes in reverse order.
03324     start = numRealAttrs - 1;
03325     end = -1;
03326     increment = -1;
03327   } else {
03328     // XHTML or XML.  Walk attributes in forward order.
03329     start = 0;
03330     end = numRealAttrs;
03331     increment = 1;
03332   }
03333   for (PRInt16 index = start; index != end; index += increment) {
03334     PRInt32 nameSpaceID;
03335     nsCOMPtr<nsIAtom> atom;
03336     nsCOMPtr<nsIAtom> prefix;
03337     content->GetAttrNameAt(index, &nameSpaceID,
03338                            getter_AddRefs(atom),
03339                            getter_AddRefs(prefix));
03340     nsAutoString value;
03341     if (NS_CONTENT_ATTR_NOT_THERE != content->GetAttr(nameSpaceID, atom, value)) {
03342       nsAutoString name;
03343       atom->ToString(name);
03344       
03345       mOwner->FixUpURLS(name, value);
03346 
03347       mCachedAttrParamNames [c] = ToNewUTF8String(name);
03348       mCachedAttrParamValues[c] = ToNewUTF8String(value);
03349       c++;
03350     }
03351   }
03352 
03353   // if the conditions above were met, copy the "data" attribute to a "src" array entry
03354   if (data.Length()) {
03355     mCachedAttrParamNames [mNumCachedAttrs-1] = ToNewUTF8String(NS_LITERAL_STRING("SRC"));
03356     mCachedAttrParamValues[mNumCachedAttrs-1] = ToNewUTF8String(data);
03357   }
03358 
03359   // add our PARAM and null separator
03360   mCachedAttrParamNames [mNumCachedAttrs] = ToNewUTF8String(NS_LITERAL_STRING("PARAM"));
03361   mCachedAttrParamValues[mNumCachedAttrs] = nsnull;
03362 
03363   // now fill in the PARAM name/value pairs from the cached DOM nodes
03364   c = 0;
03365   for (PRInt16 idx = 0; idx < mNumCachedParams; idx++) {
03366     nsCOMPtr<nsIDOMElement> param = do_QueryElementAt(ourParams, idx);
03367     if (param) {
03368      nsAutoString name;
03369      nsAutoString value;
03370      param->GetAttribute(NS_LITERAL_STRING("name"), name); // check for empty done above
03371      param->GetAttribute(NS_LITERAL_STRING("value"), value);
03372 
03373      mOwner->FixUpURLS(name, value);
03374 
03375      /*
03376       * According to the HTML 4.01 spec, at
03377       * http://www.w3.org/TR/html4/types.html#type-cdata
03378       * ''User agents may ignore leading and trailing
03379       * white space in CDATA attribute values (e.g., "
03380       * myval " may be interpreted as "myval"). Authors
03381       * should not declare attribute values with
03382       * leading or trailing white space.''
03383       * However, do not trim consecutive spaces as in bug 122119
03384       */            
03385      name.Trim(" \n\r\t\b", PR_TRUE, PR_TRUE, PR_FALSE);
03386      value.Trim(" \n\r\t\b", PR_TRUE, PR_TRUE, PR_FALSE);
03387      mCachedAttrParamNames [mNumCachedAttrs + 1 + c] = ToNewUTF8String(name);
03388      mCachedAttrParamValues[mNumCachedAttrs + 1 + c] = ToNewUTF8String(value);
03389      c++;                                                      // rules!
03390     }
03391   }
03392 
03393   return NS_OK;
03394 }
03395 
03396 
03397 // Here's where we forward events to plugins.
03398 
03399 #if defined(XP_MAC) || defined(XP_MACOSX)
03400 
03401 #if TARGET_CARBON
03402 static void InitializeEventRecord(EventRecord* event)
03403 {
03404     memset(event, 0, sizeof(EventRecord));
03405     ::GetGlobalMouse(&event->where);
03406     event->when = ::TickCount();
03407     event->modifiers = ::GetCurrentKeyModifiers();
03408 }
03409 #else
03410 inline void InitializeEventRecord(EventRecord* event) { ::OSEventAvail(0, event); }
03411 #endif
03412 
03413 void nsPluginInstanceOwner::GUItoMacEvent(const nsGUIEvent& anEvent, EventRecord* origEvent, EventRecord& aMacEvent)
03414 {
03415   nsPresContext* presContext = mOwner ? mOwner->GetPresContext() : nsnull;
03416   InitializeEventRecord(&aMacEvent);
03417   switch (anEvent.message) {
03418     case NS_FOCUS_EVENT_START:   // this is the same as NS_FOCUS_CONTENT
03419         aMacEvent.what = nsPluginEventType_GetFocusEvent;
03420         if (presContext) {
03421             nsIContent* content = mOwner->GetContent();
03422             if (content)
03423                 content->SetFocus(presContext);
03424         }
03425         break;
03426 
03427     case NS_BLUR_CONTENT:
03428         aMacEvent.what = nsPluginEventType_LoseFocusEvent;
03429         if (presContext) {
03430             nsIContent* content = mOwner->GetContent();
03431             if (content)
03432                 content->RemoveFocus(presContext);
03433         }
03434         break;
03435 
03436     case NS_MOUSE_MOVE:
03437     case NS_MOUSE_ENTER:
03438         if (origEvent)
03439           aMacEvent = *origEvent;
03440         aMacEvent.what = nsPluginEventType_AdjustCursorEvent;
03441         break;
03442   }
03443 }
03444 
03445 #endif
03446 
03447 nsresult nsPluginInstanceOwner::ScrollPositionWillChange(nsIScrollableView* aScrollable, nscoord aX, nscoord aY)
03448 {
03449 #if defined(XP_MAC) || defined(XP_MACOSX)
03450     CancelTimer();
03451 
03452     if (mInstance) {
03453         nsCOMPtr<nsIPluginWidget> pluginWidget = do_QueryInterface(mWidget);
03454         if (pluginWidget && NS_SUCCEEDED(pluginWidget->StartDrawPlugin())) {
03455             EventRecord scrollEvent;
03456             InitializeEventRecord(&scrollEvent);
03457             scrollEvent.what = nsPluginEventType_ScrollingBeginsEvent;
03458     
03459             nsPluginPort* pluginPort = FixUpPluginWindow(ePluginPaintDisable);
03460             if (pluginPort) {
03461               nsPluginEvent pluginEvent = { &scrollEvent, nsPluginPlatformWindowRef(GetWindowFromPort(pluginPort->port)) };
03462             
03463               PRBool eventHandled = PR_FALSE;
03464               mInstance->HandleEvent(&pluginEvent, &eventHandled);
03465             }
03466             pluginWidget->EndDrawPlugin();
03467         }
03468     }
03469 #endif
03470     return NS_OK;
03471 }
03472 
03473 nsresult nsPluginInstanceOwner::ScrollPositionDidChange(nsIScrollableView* aScrollable, nscoord aX, nscoord aY)
03474 {
03475 #if defined(XP_MACOSX)
03476     if (mInstance) {
03477       nsCOMPtr<nsIPluginWidget> pluginWidget = do_QueryInterface(mWidget);
03478       if (pluginWidget && NS_SUCCEEDED(pluginWidget->StartDrawPlugin())) {
03479         EventRecord scrollEvent;
03480         InitializeEventRecord(&scrollEvent);
03481         scrollEvent.what = nsPluginEventType_ScrollingEndsEvent;
03482   
03483         nsPluginPort* pluginPort = FixUpPluginWindow(ePluginPaintEnable);
03484         if (pluginPort) {
03485           nsPluginEvent pluginEvent =
03486             { &scrollEvent,
03487               nsPluginPlatformWindowRef(GetWindowFromPort(pluginPort->port))
03488             };
03489 
03490           PRBool eventHandled = PR_FALSE;
03491           mInstance->HandleEvent(&pluginEvent, &eventHandled);
03492         }
03493         pluginWidget->EndDrawPlugin();
03494       }
03495 
03496       // FIXME - Only invalidate the newly revealed amount.
03497       // XXX necessary?
03498       if (mWidget)
03499         mWidget->Invalidate(PR_TRUE);
03500     }
03501 #endif
03502 
03503     StartTimer();
03504     return NS_OK;
03505 }
03506 
03507 /*=============== nsIFocusListener ======================*/
03508 nsresult nsPluginInstanceOwner::Focus(nsIDOMEvent * aFocusEvent)
03509 {
03510   mContentFocused = PR_TRUE;
03511   return DispatchFocusToPlugin(aFocusEvent);
03512 }
03513 
03514 nsresult nsPluginInstanceOwner::Blur(nsIDOMEvent * aFocusEvent)
03515 {
03516   mContentFocused = PR_FALSE;
03517   return DispatchFocusToPlugin(aFocusEvent);
03518 }
03519 
03520 nsresult nsPluginInstanceOwner::DispatchFocusToPlugin(nsIDOMEvent* aFocusEvent)
03521 {
03522 #if !(defined(XP_MAC) || defined(XP_MACOSX))
03523   if (!mPluginWindow || nsPluginWindowType_Window == mPluginWindow->type) {
03524     // continue only for cases without child window
03525     return aFocusEvent->PreventDefault(); // consume event
03526   }
03527 #endif
03528 
03529   if (mInDispatchFocus) {
03530     NS_WARNING("nsPluginInstanceOwner::DispatchFocusToPlugin() called recursively on same plugin instance owner");
03531     return aFocusEvent->PreventDefault();
03532   }
03533   mInDispatchFocus = PR_TRUE;
03534 
03535   nsCOMPtr<nsIPrivateDOMEvent> privateEvent(do_QueryInterface(aFocusEvent));
03536   if (privateEvent) {
03537     nsEvent * theEvent;
03538     privateEvent->GetInternalNSEvent(&theEvent);
03539     if (theEvent) {
03540       // we only care about the message in ProcessEvent
03541       nsGUIEvent focusEvent(NS_IS_TRUSTED_EVENT(theEvent), theEvent->message,
03542                             nsnull);
03543       nsEventStatus rv = ProcessEvent(focusEvent);
03544       if (nsEventStatus_eConsumeNoDefault == rv) {
03545         aFocusEvent->PreventDefault();
03546         aFocusEvent->StopPropagation();
03547       }
03548     }
03549     else NS_ASSERTION(PR_FALSE, "nsPluginInstanceOwner::DispatchFocusToPlugin failed, focusEvent null");   
03550   }
03551   else NS_ASSERTION(PR_FALSE, "nsPluginInstanceOwner::DispatchFocusToPlugin failed, privateEvent null");   
03552   
03553   mInDispatchFocus = PR_FALSE;
03554   return NS_OK;
03555 }    
03556 
03557 /*=============== nsIDOMDragListener ======================*/
03558 nsresult nsPluginInstanceOwner::DragEnter(nsIDOMEvent* aMouseEvent)
03559 {
03560   if (mInstance) {
03561     // Let the plugin handle drag events.
03562     aMouseEvent->PreventDefault();
03563     aMouseEvent->StopPropagation();
03564   }
03565 
03566   return NS_OK;
03567 }
03568 
03569 nsresult nsPluginInstanceOwner::DragOver(nsIDOMEvent* aMouseEvent)
03570 {
03571   if (mInstance) {
03572     // Let the plugin handle drag events.
03573     aMouseEvent->PreventDefault();
03574     aMouseEvent->StopPropagation();
03575   }
03576 
03577   return NS_OK;
03578 }
03579 
03580 nsresult nsPluginInstanceOwner::DragExit(nsIDOMEvent* aMouseEvent)
03581 {
03582   if (mInstance) {
03583     // Let the plugin handle drag events.
03584     aMouseEvent->PreventDefault();
03585     aMouseEvent->StopPropagation();
03586   }
03587 
03588   return NS_OK;
03589 }
03590 
03591 nsresult nsPluginInstanceOwner::DragDrop(nsIDOMEvent* aMouseEvent)
03592 {
03593   if (mInstance) {
03594     // Let the plugin handle drag events.
03595     aMouseEvent->PreventDefault();
03596     aMouseEvent->StopPropagation();
03597   }
03598 
03599   return NS_OK;
03600 }
03601 
03602 nsresult nsPluginInstanceOwner::DragGesture(nsIDOMEvent* aMouseEvent)
03603 {
03604   if (mInstance) {
03605     // Let the plugin handle drag events.
03606     aMouseEvent->PreventDefault();
03607     aMouseEvent->StopPropagation();
03608   }
03609 
03610   return NS_OK;
03611 }
03612 
03613 
03614 
03615 /*=============== nsIKeyListener ======================*/
03616 nsresult nsPluginInstanceOwner::KeyDown(nsIDOMEvent* aKeyEvent)
03617 {
03618   return DispatchKeyToPlugin(aKeyEvent);
03619 }
03620 
03621 nsresult nsPluginInstanceOwner::KeyUp(nsIDOMEvent* aKeyEvent)
03622 {
03623   return DispatchKeyToPlugin(aKeyEvent);
03624 }
03625 
03626 nsresult nsPluginInstanceOwner::KeyPress(nsIDOMEvent* aKeyEvent)
03627 {
03628 #if defined(XP_MAC) || defined(XP_MACOSX) // send KeyPress events only on Mac
03629 
03630   // KeyPress events are really synthesized keyDown events.
03631   // Here we check the native message of the event so that
03632   // we won't send the plugin two keyDown events.
03633   nsCOMPtr<nsIPrivateDOMEvent> privateEvent(do_QueryInterface(aKeyEvent));
03634   if (privateEvent) {
03635     nsEvent *theEvent;
03636     privateEvent->GetInternalNSEvent(&theEvent);
03637     const nsGUIEvent *guiEvent = (nsGUIEvent*)theEvent;
03638     const EventRecord *ev = (EventRecord*)(guiEvent->nativeMsg); 
03639     if (guiEvent &&
03640         guiEvent->message == NS_KEY_PRESS &&
03641         ev &&
03642         ev->what == keyDown)
03643       return aKeyEvent->PreventDefault(); // consume event
03644   }
03645 
03646   // Nasty hack to avoid recursive event dispatching with Java. Java can
03647   // dispatch key events to a TSM handler, which comes back and calls 
03648   // [ChildView insertText:] on the cocoa widget, which sends a key
03649   // event back down.
03650   static PRBool sInKeyDispatch = PR_FALSE;
03651   
03652   if (sInKeyDispatch)
03653     return aKeyEvent->PreventDefault(); // consume event
03654 
03655   sInKeyDispatch = PR_TRUE;
03656   nsresult rv =  DispatchKeyToPlugin(aKeyEvent);
03657   sInKeyDispatch = PR_FALSE;
03658   return rv;
03659 #else
03660   if (mInstance) {
03661     // If this event is going to the plugin, we want to kill it.
03662     // Not actually sending keypress to the plugin, since we didn't before.
03663     aKeyEvent->PreventDefault();
03664     aKeyEvent->StopPropagation();
03665   }
03666   return NS_OK;
03667 #endif
03668 }
03669 
03670 nsresult nsPluginInstanceOwner::DispatchKeyToPlugin(nsIDOMEvent* aKeyEvent)
03671 {
03672 #if !(defined(XP_MAC) || defined(XP_MACOSX))
03673   if (!mPluginWindow || nsPluginWindowType_Window == mPluginWindow->type)
03674     return aKeyEvent->PreventDefault(); // consume event
03675   // continue only for cases without child window
03676 #endif
03677 
03678   if (mInstance) {
03679     nsCOMPtr<nsIPrivateDOMEvent> privateEvent(do_QueryInterface(aKeyEvent));
03680     if (privateEvent) {
03681       nsKeyEvent* keyEvent = nsnull;
03682       privateEvent->GetInternalNSEvent((nsEvent**)&keyEvent);
03683       if (keyEvent) {
03684         nsEventStatus rv = ProcessEvent(*keyEvent);
03685         if (nsEventStatus_eConsumeNoDefault == rv) {
03686           aKeyEvent->PreventDefault();
03687           aKeyEvent->StopPropagation();
03688         }
03689       }
03690       else NS_ASSERTION(PR_FALSE, "nsPluginInstanceOwner::DispatchKeyToPlugin failed, keyEvent null");   
03691     }
03692     else NS_ASSERTION(PR_FALSE, "nsPluginInstanceOwner::DispatchKeyToPlugin failed, privateEvent null");   
03693   }
03694 
03695   return NS_OK;
03696 }    
03697 
03698 /*=============== nsIMouseMotionListener ======================*/
03699 
03700 nsresult
03701 nsPluginInstanceOwner::MouseMove(nsIDOMEvent* aMouseEvent)
03702 {
03703 #if !(defined(XP_MAC) || defined(XP_MACOSX))
03704   if (!mPluginWindow || nsPluginWindowType_Window == mPluginWindow->type)
03705     return aMouseEvent->PreventDefault(); // consume event
03706   // continue only for cases without child window
03707 #endif
03708 
03709   // don't send mouse events if we are hiddden
03710   if (!mWidgetVisible)
03711     return NS_OK;
03712 
03713   nsCOMPtr<nsIPrivateDOMEvent> privateEvent(do_QueryInterface(aMouseEvent));
03714   if (privateEvent) {
03715     nsMouseEvent* mouseEvent = nsnull;
03716     privateEvent->GetInternalNSEvent((nsEvent**)&mouseEvent);
03717     if (mouseEvent) {
03718       nsEventStatus rv = ProcessEvent(*mouseEvent);
03719       if (nsEventStatus_eConsumeNoDefault == rv) {
03720         return aMouseEvent->PreventDefault(); // consume event
03721       }
03722     }
03723     else NS_ASSERTION(PR_FALSE, "nsPluginInstanceOwner::MouseMove failed, mouseEvent null");   
03724   }
03725   else NS_ASSERTION(PR_FALSE, "nsPluginInstanceOwner::MouseMove failed, privateEvent null");   
03726   
03727   return NS_OK;
03728 }
03729 
03730 /*=============== nsIMouseListener ======================*/
03731 
03732 nsresult
03733 nsPluginInstanceOwner::MouseDown(nsIDOMEvent* aMouseEvent)
03734 {
03735 #if !(defined(XP_MAC) || defined(XP_MACOSX))
03736   if (!mPluginWindow || nsPluginWindowType_Window == mPluginWindow->type)
03737     return aMouseEvent->PreventDefault(); // consume event
03738   // continue only for cases without child window
03739 #endif
03740 
03741   // if the plugin is windowless, we need to set focus ourselves
03742   // otherwise, we might not get key events
03743   if (mPluginWindow && mPluginWindow->type == nsPluginWindowType_Drawable) {
03744     nsIContent* content = mOwner->GetContent();
03745     if (content)
03746       content->SetFocus(mContext);
03747   }
03748 
03749   nsCOMPtr<nsIPrivateDOMEvent> privateEvent(do_QueryInterface(aMouseEvent));
03750   if (privateEvent) {
03751     nsMouseEvent* mouseEvent = nsnull;
03752     privateEvent->GetInternalNSEvent((nsEvent**)&mouseEvent);
03753     if (mouseEvent) {
03754       nsEventStatus rv = ProcessEvent(*mouseEvent);
03755       if (nsEventStatus_eConsumeNoDefault == rv) {
03756         return aMouseEvent->PreventDefault(); // consume event
03757       }
03758     }
03759     else NS_ASSERTION(PR_FALSE, "nsPluginInstanceOwner::MouseDown failed, mouseEvent null");   
03760   }
03761   else NS_ASSERTION(PR_FALSE, "nsPluginInstanceOwner::MouseDown failed, privateEvent null");   
03762   
03763   return NS_OK;
03764 }
03765 
03766 nsresult
03767 nsPluginInstanceOwner::MouseUp(nsIDOMEvent* aMouseEvent)
03768 {
03769   return DispatchMouseToPlugin(aMouseEvent);
03770 }
03771 
03772 nsresult
03773 nsPluginInstanceOwner::MouseClick(nsIDOMEvent* aMouseEvent)
03774 {
03775   if (mOwner->IsBroken()) {
03776     FirePluginNotFoundEvent(mOwner->GetContent());
03777 
03778     aMouseEvent->PreventDefault();
03779 
03780     return NS_OK;
03781   }
03782 
03783   return DispatchMouseToPlugin(aMouseEvent);
03784 }
03785 
03786 nsresult
03787 nsPluginInstanceOwner::MouseDblClick(nsIDOMEvent* aMouseEvent)
03788 {
03789   return DispatchMouseToPlugin(aMouseEvent);
03790 }
03791 
03792 nsresult
03793 nsPluginInstanceOwner::MouseOver(nsIDOMEvent* aMouseEvent)
03794 {
03795   return DispatchMouseToPlugin(aMouseEvent);
03796 }
03797 
03798 nsresult
03799 nsPluginInstanceOwner::MouseOut(nsIDOMEvent* aMouseEvent)
03800 {
03801   return DispatchMouseToPlugin(aMouseEvent);
03802 }
03803 
03804 nsresult nsPluginInstanceOwner::DispatchMouseToPlugin(nsIDOMEvent* aMouseEvent)
03805 {
03806 #if !(defined(XP_MAC) || defined(XP_MACOSX))
03807   if (!mPluginWindow || nsPluginWindowType_Window == mPluginWindow->type)
03808     return aMouseEvent->PreventDefault(); // consume event
03809   // continue only for cases without child window
03810 #endif
03811 
03812   // don't send mouse events if we are hiddden
03813   if (!mWidgetVisible)
03814     return NS_OK;
03815 
03816   nsCOMPtr<nsIPrivateDOMEvent> privateEvent(do_QueryInterface(aMouseEvent));
03817   if (privateEvent) {
03818     nsMouseEvent* mouseEvent = nsnull;
03819     privateEvent->GetInternalNSEvent((nsEvent**)&mouseEvent);
03820     if (mouseEvent) {
03821       nsEventStatus rv = ProcessEvent(*mouseEvent);
03822       if (nsEventStatus_eConsumeNoDefault == rv) {
03823         aMouseEvent->PreventDefault();
03824         aMouseEvent->StopPropagation();
03825       }
03826     }
03827     else NS_ASSERTION(PR_FALSE, "nsPluginInstanceOwner::DispatchMouseToPlugin failed, mouseEvent null");   
03828   }
03829   else NS_ASSERTION(PR_FALSE, "nsPluginInstanceOwner::DispatchMouseToPlugin failed, privateEvent null");   
03830   
03831   return NS_OK;
03832 }
03833 
03834 nsresult
03835 nsPluginInstanceOwner::HandleEvent(nsIDOMEvent* aEvent)
03836 {
03837   return NS_OK;
03838 }
03839 
03840 
03841 nsEventStatus nsPluginInstanceOwner::ProcessEvent(const nsGUIEvent& anEvent)
03842 {
03843   // printf("nsGUIEvent.message: %d\n", anEvent.message);
03844   nsEventStatus rv = nsEventStatus_eIgnore;
03845   if (!mInstance)   // if mInstance is null, we shouldn't be here
03846     return rv;
03847 
03848 #if defined(XP_MAC) || defined(XP_MACOSX)
03849   // check for null mWidget
03850   if (mWidget) {
03851     nsCOMPtr<nsIPluginWidget> pluginWidget = do_QueryInterface(mWidget);
03852     if (pluginWidget && NS_SUCCEEDED(pluginWidget->StartDrawPlugin())) {
03853       EventRecord macEvent;
03854       EventRecord* event = (EventRecord*)anEvent.nativeMsg;
03855       if ((event == NULL) || (event->what == nullEvent)  || 
03856           (anEvent.message == NS_FOCUS_EVENT_START)      || 
03857           (anEvent.message == NS_BLUR_CONTENT)           || 
03858           (anEvent.message == NS_MOUSE_MOVE)             ||
03859           (anEvent.message == NS_MOUSE_ENTER)) {
03860         GUItoMacEvent(anEvent, event, macEvent);
03861         event = &macEvent;
03862       }
03863 
03864 #ifdef MOZ_WIDGET_COCOA
03865       if (anEvent.message == NS_FOCUS_CONTENT)
03866       {
03867         // Work around an issue in the Flash plugin, which can cache a pointer
03868         // to a doomed TSM document (one that belongs to a NSTSMInputContext)
03869         // and try to activate it after it has been deleted. See bug 183313.
03870         ::DeactivateTSMDocument(::TSMGetActiveDocument());
03871       }
03872 #endif
03873       
03874       nsPluginPort* pluginPort = FixUpPluginWindow(ePluginPaintIgnore);
03875       PRBool eventHandled = PR_FALSE;
03876       if (pluginPort) {
03877         nsPluginEvent pluginEvent =
03878           {
03879             event,
03880             nsPluginPlatformWindowRef(GetWindowFromPort(pluginPort->port))
03881           };
03882 
03883         mInstance->HandleEvent(&pluginEvent, &eventHandled);
03884       }
03885 
03886       if (eventHandled && !(anEvent.message == NS_MOUSE_LEFT_BUTTON_DOWN &&
03887                             !mContentFocused))
03888         rv = nsEventStatus_eConsumeNoDefault;
03889 
03890       pluginWidget->EndDrawPlugin();
03891     }
03892   }
03893 #endif
03894 
03895 #ifdef XP_WIN
03896   // this code supports windowless plugins
03897   nsPluginEvent * pPluginEvent = (nsPluginEvent *)anEvent.nativeMsg;
03898   // we can get synthetic events from the nsEventStateManager... these
03899   // have no nativeMsg
03900 
03901   if (pPluginEvent) {
03902     PRBool eventHandled = PR_FALSE;
03903     mInstance->HandleEvent(pPluginEvent, &eventHandled);
03904     if (eventHandled)
03905       rv = nsEventStatus_eConsumeNoDefault;
03906   }
03907 #endif
03908 
03909   return rv;
03910 }
03911 
03912 nsresult
03913 nsPluginInstanceOwner::Destroy()
03914 {
03915   nsIContent* content = mOwner->GetContent();
03916 
03917   // stop the timer explicitly to reduce reference count.
03918   CancelTimer();
03919 
03920   // unregister context menu listener
03921   if (mCXMenuListener) {
03922     mCXMenuListener->Destroy(mOwner);    
03923     NS_RELEASE(mCXMenuListener);
03924   }
03925 
03926   nsCOMPtr<nsIDOMEventReceiver> receiver(do_QueryInterface(content));
03927   if (receiver) {
03928 
03929     nsCOMPtr<nsIDOMEventListener> listener;
03930     QueryInterface(NS_GET_IID(nsIDOMEventListener), getter_AddRefs(listener));
03931 
03932     // Unregister focus event listener
03933     receiver->RemoveEventListenerByIID(listener, NS_GET_IID(nsIDOMFocusListener));
03934 
03935     // Unregister mouse event listener
03936     receiver->RemoveEventListenerByIID(listener, NS_GET_IID(nsIDOMMouseListener));
03937 
03938     // now for the mouse motion listener
03939     receiver->RemoveEventListenerByIID(listener, NS_GET_IID(nsIDOMMouseMotionListener));
03940 
03941     // Unregister key event listener;
03942     receiver->RemoveEventListener(NS_LITERAL_STRING("keypress"), listener, PR_TRUE);
03943     receiver->RemoveEventListener(NS_LITERAL_STRING("keydown"), listener, PR_TRUE);
03944     receiver->RemoveEventListener(NS_LITERAL_STRING("keyup"), listener, PR_TRUE);
03945 
03946     // Unregister drag event listener;
03947     receiver->RemoveEventListener(NS_LITERAL_STRING("dragdrop"), listener, PR_TRUE);
03948     receiver->RemoveEventListener(NS_LITERAL_STRING("dragover"), listener, PR_TRUE);
03949     receiver->RemoveEventListener(NS_LITERAL_STRING("dragexit"), listener, PR_TRUE);
03950     receiver->RemoveEventListener(NS_LITERAL_STRING("dragenter"), listener, PR_TRUE);
03951     receiver->RemoveEventListener(NS_LITERAL_STRING("draggesture"), listener, PR_TRUE);
03952   }
03953 
03954   // Unregister scroll position listener
03955   nsIFrame* parentWithView = mOwner->GetAncestorWithView();
03956   nsIView* curView = parentWithView ? parentWithView->GetView() : nsnull;
03957   while (curView) {
03958     nsIScrollableView* scrollingView = curView->ToScrollableView();
03959     if (scrollingView)
03960       scrollingView->RemoveScrollPositionListener((nsIScrollPositionListener *)this);
03961     
03962     curView = curView->GetParent();
03963   }
03964 
03965   mOwner = nsnull; // break relationship between frame and plugin instance owner
03966 
03967   return NS_OK;
03968 }
03969 
03970 // Paints are handled differently, so we just simulate an update event.
03971 
03972 void nsPluginInstanceOwner::Paint(const nsRect& aDirtyRect, PRUint32 ndc)
03973 {
03974   if (!mInstance)
03975     return;
03976  
03977 #if defined(XP_MACOSX)
03978 #ifdef DO_DIRTY_INTERSECT   // aDirtyRect isn't always correct, see bug 56128
03979   nsPoint rel(aDirtyRect.x, aDirtyRect.y);
03980   nsPoint abs(0,0);
03981   nsCOMPtr<nsIWidget> containerWidget;
03982 
03983   // Convert dirty rect relative coordinates to absolute and also get the containerWidget
03984   ConvertRelativeToWindowAbsolute(mOwner, rel, abs, *getter_AddRefs(containerWidget));
03985 
03986   nsRect absDirtyRect = nsRect(abs.x, abs.y, aDirtyRect.width, aDirtyRect.height);
03987 
03988   // Convert to absolute pixel values for the dirty rect
03989   nsRect absDirtyRectInPixels;
03990   ConvertTwipsToPixels(*mContext, absDirtyRect, absDirtyRectInPixels);
03991 #endif
03992 
03993   nsCOMPtr<nsIPluginWidget> pluginWidget = do_QueryInterface(mWidget);
03994   if (pluginWidget && NS_SUCCEEDED(pluginWidget->StartDrawPlugin())) {
03995     nsPluginPort* pluginPort = FixUpPluginWindow(ePluginPaintEnable);
03996     if (pluginPort) {
03997       WindowRef  nativeWindowRef = ::GetWindowFromPort(pluginPort->port);
03998       
03999       EventRecord updateEvent;
04000       InitializeEventRecord(&updateEvent);
04001       updateEvent.what = updateEvt;
04002       updateEvent.message = UInt32(nativeWindowRef);
04003     
04004       nsPluginEvent pluginEvent = { &updateEvent, nsPluginPlatformWindowRef(nativeWindowRef) };
04005       PRBool eventHandled = PR_FALSE;
04006       mInstance->HandleEvent(&pluginEvent, &eventHandled);
04007     }
04008     pluginWidget->EndDrawPlugin();
04009   }
04010 #endif
04011 
04012 #ifdef XP_WIN
04013   nsPluginWindow * window;
04014   GetWindow(window);
04015   nsRect relDirtyRect = nsRect(aDirtyRect.x, aDirtyRect.y, aDirtyRect.width, aDirtyRect.height);
04016   nsRect relDirtyRectInPixels;
04017   ConvertTwipsToPixels(*mContext, relDirtyRect, relDirtyRectInPixels);
04018 
04019   // we got dirty rectangle in relative window coordinates, but we
04020   // need it in absolute units and in the (left, top, right, bottom) form
04021   RECT drc;
04022   drc.left   = relDirtyRectInPixels.x + window->x;
04023   drc.top    = relDirtyRectInPixels.y + window->y;
04024   drc.right  = drc.left + relDirtyRectInPixels.width;
04025   drc.bottom = drc.top + relDirtyRectInPixels.height;
04026 
04027   nsPluginEvent pluginEvent;
04028   pluginEvent.event = 0x000F; 
04029   pluginEvent.wParam = (uint32)ndc;
04030   pluginEvent.lParam = (uint32)&drc;
04031   PRBool eventHandled = PR_FALSE;
04032   mInstance->HandleEvent(&pluginEvent, &eventHandled);
04033 #endif
04034 }
04035 
04036 // Here's how we give idle time to plugins.
04037 
04038 NS_IMETHODIMP nsPluginInstanceOwner::Notify(nsITimer* /* timer */)
04039 {
04040 #if defined(XP_MAC) || defined(XP_MACOSX)
04041     // validate the plugin clipping information by syncing the plugin window info to
04042     // reflect the current widget location. This makes sure that everything is updated
04043     // correctly in the event of scrolling in the window.
04044     if (mInstance) {
04045         nsCOMPtr<nsIPluginWidget> pluginWidget = do_QueryInterface(mWidget);
04046         if (pluginWidget && NS_SUCCEEDED(pluginWidget->StartDrawPlugin())) {
04047             nsPluginPort* pluginPort = FixUpPluginWindow(ePluginPaintIgnore);
04048             if (pluginPort) {
04049                 EventRecord idleEvent;
04050                 InitializeEventRecord(&idleEvent);
04051                 idleEvent.what = nullEvent;
04052                     
04053                 // give a bogus 'where' field of our null event when hidden, so Flash
04054                 // won't respond to mouse moves in other tabs, see bug 120875
04055                 if (!mWidgetVisible)
04056                     idleEvent.where.h = idleEvent.where.v = 20000;
04057     
04058                 nsPluginEvent pluginEvent = { &idleEvent, nsPluginPlatformWindowRef(GetWindowFromPort(pluginPort->port)) };
04059     
04060                 PRBool eventHandled = PR_FALSE;
04061                 mInstance->HandleEvent(&pluginEvent, &eventHandled);
04062             }
04063             
04064             pluginWidget->EndDrawPlugin();
04065        }
04066     }
04067 #endif
04068     return NS_OK;
04069 }
04070 
04071 void nsPluginInstanceOwner::StartTimer()
04072 {
04073 #if defined(XP_MAC) || defined(XP_MACOSX)
04074     nsresult rv;
04075 
04076     // start a periodic timer to provide null events to the plugin instance.
04077     if (!mPluginTimer) {
04078       mPluginTimer = do_CreateInstance("@mozilla.org/timer;1", &rv);
04079       if (NS_SUCCEEDED(rv))
04080         rv = mPluginTimer->InitWithCallback(this, 1020 / 60, nsITimer::TYPE_REPEATING_SLACK);
04081     }
04082 #endif
04083 }
04084 
04085 void nsPluginInstanceOwner::CancelTimer()
04086 {
04087     if (mPluginTimer) {
04088         mPluginTimer->Cancel();
04089         mPluginTimer = nsnull;
04090     }
04091 }
04092 
04093 NS_IMETHODIMP nsPluginInstanceOwner::Init(nsPresContext* aPresContext, nsObjectFrame *aFrame)
04094 {
04095   //do not addref to avoid circular refs. MMP
04096   mContext = aPresContext;
04097   mOwner = aFrame;
04098   
04099   nsIContent* content = mOwner->GetContent();
04100   
04101   // Some plugins require a specific sequence of shutdown and startup when
04102   // a page is reloaded. Shutdown happens usually when the last instance
04103   // is destroyed. Here we make sure the plugin instance in the old
04104   // document is destroyed before we try to create the new one.
04105   aPresContext->EnsureVisible(PR_TRUE);
04106 
04107   // register context menu listener
04108   mCXMenuListener = new nsPluginDOMContextMenuListener();
04109   if (mCXMenuListener) {    
04110     NS_ADDREF(mCXMenuListener);    
04111     mCXMenuListener->Init(aFrame);
04112   }
04113 
04114   nsCOMPtr<nsIDOMEventReceiver> receiver(do_QueryInterface(content));
04115   if (receiver) {
04116 
04117     nsCOMPtr<nsIDOMEventListener> listener;
04118     QueryInterface(NS_GET_IID(nsIDOMEventListener), getter_AddRefs(listener));
04119 
04120     // Register focus listener
04121     receiver->AddEventListenerByIID(listener, NS_GET_IID(nsIDOMFocusListener));
04122 
04123     // Register mouse listener
04124     receiver->AddEventListenerByIID(listener, NS_GET_IID(nsIDOMMouseListener));
04125 
04126     // now do the mouse motion listener
04127     receiver->AddEventListenerByIID(listener, NS_GET_IID(nsIDOMMouseMotionListener));
04128 
04129     // Register key listener
04130     receiver->AddEventListener(NS_LITERAL_STRING("keypress"), listener, PR_TRUE);
04131     receiver->AddEventListener(NS_LITERAL_STRING("keydown"), listener, PR_TRUE);
04132     receiver->AddEventListener(NS_LITERAL_STRING("keyup"), listener, PR_TRUE);
04133 
04134     // Register drag listener
04135     receiver->AddEventListener(NS_LITERAL_STRING("dragdrop"), listener, PR_TRUE);
04136     receiver->AddEventListener(NS_LITERAL_STRING("dragover"), listener, PR_TRUE);
04137     receiver->AddEventListener(NS_LITERAL_STRING("dragexit"), listener, PR_TRUE);
04138     receiver->AddEventListener(NS_LITERAL_STRING("dragenter"), listener, PR_TRUE);
04139     receiver->AddEventListener(NS_LITERAL_STRING("draggesture"), listener, PR_TRUE);
04140   }
04141   
04142   // Register scroll position listener
04143   // We need to register a scroll pos listener on every scrollable
04144   // view up to the top
04145   nsIFrame* parentWithView = mOwner->GetAncestorWithView();
04146   nsIView* curView = parentWithView ? parentWithView->GetView() : nsnull;
04147   while (curView) {
04148     nsIScrollableView* scrollingView = curView->ToScrollableView();
04149     if (scrollingView)
04150       scrollingView->AddScrollPositionListener((nsIScrollPositionListener *)this);
04151     
04152     curView = curView->GetParent();
04153   }
04154 
04155   return NS_OK; 
04156 }
04157 
04158 nsPluginPort* nsPluginInstanceOwner::GetPluginPort()
04159 {
04161 
04162   nsPluginPort* result = NULL;
04163   if (mWidget) {
04164 #ifdef XP_WIN
04165     if (mPluginWindow && mPluginWindow->type == nsPluginWindowType_Drawable)
04166       result = (nsPluginPort*) mWidget->GetNativeData(NS_NATIVE_GRAPHIC);
04167     else
04168 #endif
04169       result = (nsPluginPort*) mWidget->GetNativeData(NS_NATIVE_PLUGIN_PORT);
04170     }
04171     return result;
04172 }
04173 
04174 void nsPluginInstanceOwner::ReleasePluginPort(nsPluginPort * pluginPort)
04175 {
04176 #ifdef XP_WIN
04177   if (mWidget && mPluginWindow &&
04178       mPluginWindow->type == nsPluginWindowType_Drawable) {
04179     mWidget->FreeNativeData((HDC)pluginPort, NS_NATIVE_GRAPHIC);
04180   }
04181 #endif
04182 }
04183 
04184 NS_IMETHODIMP nsPluginInstanceOwner::CreateWidget(void)
04185 {
04186   NS_ENSURE_TRUE(mPluginWindow, NS_ERROR_NULL_POINTER);
04187 
04188   nsIView   *view;
04189   nsresult  rv = NS_ERROR_FAILURE;
04190 
04191   if (mOwner) {
04192     // Create view if necessary
04193 
04194     view = mOwner->GetView();
04195 
04196     if (!view || !mWidget) {
04197       PRBool windowless = PR_FALSE;
04198 
04199       mInstance->GetValue(nsPluginInstanceVariable_WindowlessBool,
04200                           (void *)&windowless);
04201 
04202       // always create widgets in Twips, not pixels
04203       float p2t = mContext->ScaledPixelsToTwips();
04204       rv = mOwner->CreateWidget(NSIntPixelsToTwips(mPluginWindow->width, p2t),
04205                                 NSIntPixelsToTwips(mPluginWindow->height, p2t),
04206                                 windowless);
04207       if (NS_OK == rv) {
04208         view = mOwner->GetView();
04209 
04210         if (view) {
04211           mWidget = view->GetWidget();
04212           PRBool fTransparent = PR_FALSE;
04213           mInstance->GetValue(nsPluginInstanceVariable_TransparentBool,
04214                               (void *)&fTransparent);
04215           
04216           view->GetViewManager()->SetViewContentTransparency(view,
04217                                                              fTransparent);
04218         }
04219 
04220         if (PR_TRUE == windowless) {
04221           mPluginWindow->type = nsPluginWindowType_Drawable;
04222 
04223           // this needs to be a HDC according to the spec, but I do
04224           // not see the right way to release it so let's postpone
04225           // passing HDC till paint event when it is really
04226           // needed. Change spec?
04227           mPluginWindow->window = nsnull;
04228         } else if (mWidget) {
04229           mWidget->Resize(mPluginWindow->width, mPluginWindow->height,
04230                           PR_FALSE);
04231 
04232           // mPluginWindow->type is used in |GetPluginPort| so it must
04233           // be initilized first
04234           mPluginWindow->type = nsPluginWindowType_Window;
04235           mPluginWindow->window = GetPluginPort();
04236 
04237           // start the idle timer.
04238           StartTimer();
04239 
04240           // tell the plugin window about the widget
04241           mPluginWindow->SetPluginWidget(mWidget);
04242         }
04243       }
04244     }
04245   }
04246 
04247   return rv;
04248 }
04249 
04250 void nsPluginInstanceOwner::SetPluginHost(nsIPluginHost* aHost)
04251 {
04252   mPluginHost = aHost;
04253 }
04254 
04255 #if defined(XP_WIN) || (defined(DO_DIRTY_INTERSECT) && (defined(XP_MAC) || defined(XP_MACOSX)))
04256 // convert frame coordinates from twips to pixels
04257 static void ConvertTwipsToPixels(nsPresContext& aPresContext, nsRect& aTwipsRect, nsRect& aPixelRect)
04258 {
04259   float t2p;
04260   t2p = aPresContext.TwipsToPixels();
04261   aPixelRect.x = NSTwipsToIntPixels(aTwipsRect.x, t2p);
04262   aPixelRect.y = NSTwipsToIntPixels(aTwipsRect.y, t2p);
04263   aPixelRect.width = NSTwipsToIntPixels(aTwipsRect.width, t2p);
04264   aPixelRect.height = NSTwipsToIntPixels(aTwipsRect.height, t2p);
04265 }
04266 #endif
04267 
04268   // Mac specific code to fix up the port location and clipping region
04269 #if defined(XP_MAC) || defined(XP_MACOSX)
04270 
04271 #ifdef DO_DIRTY_INTERSECT
04272 // Convert from a frame relative coordinate to a coordinate relative to its
04273 // containing window
04274 static void ConvertRelativeToWindowAbsolute(nsIFrame*   aFrame,
04275                                             nsPoint&    aRel, 
04276                                             nsPoint&    aAbs,
04277                                             nsIWidget*& aContainerWidget)
04278 {
04279   // See if this frame has a view
04280   nsIView *view = aFrame->GetView();
04281   if (!view) {
04282     aAbs.x = 0;
04283     aAbs.y = 0;
04284     // Calculate frames offset from its nearest view
04285     aFrame->GetOffsetFromView(aAbs, &view);
04286   } else {
04287     // Store frames offset from its view.
04288     aAbs = aFrame->GetPosition();
04289   }
04290 
04291   NS_ASSERTION(view, "the object frame does not have a view");
04292   if (view) {
04293     // Calculate the view's offset from its nearest widget
04294     nsPoint viewOffset;
04295     aContainerWidget = view->GetNearestWidget(&viewOffset);
04296     NS_IF_ADDREF(aContainerWidget);
04297     aAbs += viewOffset;
04298   }
04299 
04300   // Add relative coordinate to the absolute coordinate that has been calculated
04301   aAbs += aRel;
04302 }
04303 #endif // DO_DIRTY_INTERSECT
04304 
04305 nsPluginPort* nsPluginInstanceOwner::FixUpPluginWindow(PRInt32 inPaintState)
04306 {
04307   if (!mWidget || !mPluginWindow)
04308     return nsnull;
04309 
04310   nsPluginPort* pluginPort = GetPluginPort(); 
04311 
04312   if (!pluginPort)
04313     return nsnull;
04314 
04315   // first, check our view for CSS visibility style
04316   PRBool isVisible =
04317     mOwner->GetView()->GetVisibility() == nsViewVisibility_kShow;
04318 
04319   nsCOMPtr<nsIPluginWidget> pluginWidget = do_QueryInterface(mWidget);
04320   
04321   nsPoint pluginOrigin;
04322   nsRect widgetClip;
04323   PRBool widgetVisible;
04324   pluginWidget->GetPluginClipRect(widgetClip, pluginOrigin, /* out */ widgetVisible);
04325   
04326   // printf("GetPluginClipRect returning visible %d\n", widgetVisible);
04327 
04328   isVisible &= widgetVisible;
04329   if (!isVisible)
04330     widgetClip.Empty();
04331   
04332   // set the port coordinates
04333   mPluginWindow->x = -pluginPort->portx;
04334   mPluginWindow->y = -pluginPort->porty;
04335 
04336   nsPluginRect oldClipRect = mPluginWindow->clipRect;
04337   
04338   // fix up the clipping region
04339   mPluginWindow->clipRect.top    = widgetClip.y;
04340   mPluginWindow->clipRect.left   = widgetClip.x;
04341 
04342   mWidgetVisible = isVisible;
04343 
04344   if (!mWidgetVisible || inPaintState == ePluginPaintDisable) {
04345     mPluginWindow->clipRect.bottom = mPluginWindow->clipRect.top;
04346     mPluginWindow->clipRect.right  = mPluginWindow->clipRect.left;
04347     // pluginPort = nsnull; // don't uncomment this
04348   }
04349   else if (inPaintState == ePluginPaintEnable)
04350   {
04351     mPluginWindow->clipRect.bottom = mPluginWindow->clipRect.top + widgetClip.height;
04352     mPluginWindow->clipRect.right  = mPluginWindow->clipRect.left + widgetClip.width; 
04353   }
04354 
04355   // if the clip rect changed, call SetWindow()
04356   // (RealPlayer needs this to draw correctly)
04357   if (mPluginWindow->clipRect.left    != oldClipRect.left   ||
04358       mPluginWindow->clipRect.top     != oldClipRect.top    ||
04359       mPluginWindow->clipRect.right   != oldClipRect.right  ||
04360       mPluginWindow->clipRect.bottom  != oldClipRect.bottom)
04361   {  
04362     mInstance->SetWindow(mPluginWindow);
04363   }
04364 
04365   return pluginPort;
04366 }
04367 
04368 void nsPluginInstanceOwner::Composite()
04369 {
04370   //no reference count on view
04371   nsIView* view = mOwner->GetView();
04372   if (view) {
04373     view->GetViewManager()->UpdateView(view, NS_VMREFRESH_IMMEDIATE);
04374   }
04375 }
04376 
04377 #endif // XP_MAC || XP_MACOSX
04378