NS_IMETHODIMP nsDOMWindowList::NamedItem(const nsAString& aName, nsIDOMWindow** aReturn) { nsCOMPtr<nsIDocShellTreeItem> item; *aReturn = nsnull; nsCOMPtr<nsIWebNavigation> shellAsNav(do_QueryInterface(mDocShellNode)); if (shellAsNav) { nsCOMPtr<nsIDOMDocument> domdoc; shellAsNav->GetDocument(getter_AddRefs(domdoc)); nsCOMPtr<nsIDocument> doc(do_QueryInterface(domdoc)); if (doc) { doc->FlushPendingNotifications(Flush_ContentAndNotify); } } // The above flush might cause mDocShellNode to be cleared, so we // need to check that it's still non-null here. if (mDocShellNode) { mDocShellNode->FindChildWithName(PromiseFlatString(aName).get(), false, false, nsnull, nsnull, getter_AddRefs(item)); nsCOMPtr<nsIScriptGlobalObject> globalObject(do_GetInterface(item)); if (globalObject) { CallQueryInterface(globalObject.get(), aReturn); } } return NS_OK; }
/* readonly attribute nsIDOMElement documentFrameElement; */ NS_IMETHODIMP nsXTFElementWrapper::GetDocumentFrameElement(nsIDOMElement * *aDocumentFrameElement) { *aDocumentFrameElement = nsnull; nsIDocument *doc = GetCurrentDoc(); if (!doc) { NS_WARNING("no document"); return NS_OK; } nsCOMPtr<nsISupports> container = doc->GetContainer(); if (!container) { NS_ERROR("no docshell"); return NS_ERROR_FAILURE; } nsCOMPtr<nsPIDOMWindow> pidomwin = do_GetInterface(container); if (!pidomwin) { NS_ERROR("no nsPIDOMWindow interface on docshell"); return NS_ERROR_FAILURE; } *aDocumentFrameElement = pidomwin->GetFrameElementInternal(); NS_IF_ADDREF(*aDocumentFrameElement); return NS_OK; }
NS_IMETHODIMP nsDOMWindowList::Item(PRUint32 aIndex, nsIDOMWindow** aReturn) { nsCOMPtr<nsIDocShellTreeItem> item; *aReturn = nsnull; nsCOMPtr<nsIWebNavigation> shellAsNav = do_QueryInterface(mDocShellNode); if (shellAsNav) { nsCOMPtr<nsIDOMDocument> domdoc; shellAsNav->GetDocument(getter_AddRefs(domdoc)); nsCOMPtr<nsIDocument> doc = do_QueryInterface(domdoc); if (doc) { doc->FlushPendingNotifications(Flush_ContentAndNotify); } } // The above flush might cause mDocShellNode to be cleared, so we // need to check that it's still non-null here. if (mDocShellNode) { mDocShellNode->GetChildAt(aIndex, getter_AddRefs(item)); nsCOMPtr<nsIScriptGlobalObject> globalObject(do_GetInterface(item)); NS_ASSERTION(!item || (item && globalObject), "Couldn't get to the globalObject"); if (globalObject) { CallQueryInterface(globalObject, aReturn); } } return NS_OK; }
nsIntPoint nsCoreUtils::GetScreenCoordsForWindow(nsINode *aNode) { nsIntPoint coords(0, 0); nsCOMPtr<nsIDocShellTreeItem> treeItem(GetDocShellTreeItemFor(aNode)); if (!treeItem) return coords; nsCOMPtr<nsIDocShellTreeItem> rootTreeItem; treeItem->GetRootTreeItem(getter_AddRefs(rootTreeItem)); nsCOMPtr<nsIDOMDocument> domDoc = do_GetInterface(rootTreeItem); if (!domDoc) return coords; nsCOMPtr<nsIDOMWindow> window; domDoc->GetDefaultView(getter_AddRefs(window)); nsCOMPtr<nsIDOMWindowInternal> windowInter(do_QueryInterface(window)); if (!windowInter) return coords; windowInter->GetScreenX(&coords.x); windowInter->GetScreenY(&coords.y); return coords; }
/* * Register a new top level window (created elsewhere) */ NS_IMETHODIMP nsAppShellService::RegisterTopLevelWindow(nsIXULWindow* aWindow) { // tell the window mediator about the new window nsCOMPtr<nsIWindowMediator> mediator ( do_GetService(NS_WINDOWMEDIATOR_CONTRACTID) ); NS_ASSERTION(mediator, "Couldn't get window mediator."); if (mediator) mediator->RegisterWindow(aWindow); // tell the window watcher about the new window nsCOMPtr<nsPIWindowWatcher> wwatcher ( do_GetService(NS_WINDOWWATCHER_CONTRACTID) ); NS_ASSERTION(wwatcher, "No windowwatcher?"); if (wwatcher) { nsCOMPtr<nsIDocShell> docShell; aWindow->GetDocShell(getter_AddRefs(docShell)); NS_ASSERTION(docShell, "Window has no docshell"); if (docShell) { nsCOMPtr<nsIDOMWindow> domWindow(do_GetInterface(docShell)); NS_ASSERTION(domWindow, "Couldn't get DOM window."); if (domWindow) wwatcher->AddWindow(domWindow, 0); } } // an ongoing attempt to quit is stopped by a newly opened window nsCOMPtr<nsIObserverService> obssvc = do_GetService("@mozilla.org/observer-service;1"); NS_ASSERTION(obssvc, "Couldn't get observer service."); if (obssvc) obssvc->NotifyObservers(aWindow, "xul-window-registered", nsnull); return NS_OK; }
int EmbedWindow::SaveAs(char *fname, char *dirname) { nsresult rv; nsCOMPtr<nsIWebBrowserPersist> persist(do_GetInterface(mWebBrowser, &rv)); if (NS_FAILED(rv)) return rv; nsCOMPtr<nsILocalFile> file; NS_NewNativeLocalFile(nsDependentCString(fname), PR_TRUE, getter_AddRefs(file)); /* the nsIWebBrowserPersist wants a parent directory where to download images and other items related to the document */ /* we have to provide a directory, otherwise the current SaveDocument is marked as not finished and the next one is aborted */ nsCOMPtr<nsILocalFile> parentDirAsLocal; rv = NS_NewNativeLocalFile(nsDependentCString( dirname ), PR_TRUE, getter_AddRefs(parentDirAsLocal)); if (NS_FAILED(rv)) return rv; PRUint32 flags; persist->GetPersistFlags( &flags ); if( !(flags & nsIWebBrowserPersist::PERSIST_FLAGS_REPLACE_EXISTING_FILES ) ) persist->SetPersistFlags( nsIWebBrowserPersist::PERSIST_FLAGS_REPLACE_EXISTING_FILES ); persist->SaveDocument(nsnull, file, parentDirAsLocal, nsnull, 0, 0); return 0; }
nsresult nsDocShellEditorData::DetachFromWindow() { NS_ASSERTION(mEditingSession, "Can't detach when we don't have a session to detach!"); nsCOMPtr<nsIDOMWindow> domWindow = do_GetInterface(mDocShell); nsresult rv = mEditingSession->DetachFromWindow(domWindow); NS_ENSURE_SUCCESS(rv, rv); mIsDetached = true; mDetachedMakeEditable = mMakeEditable; mMakeEditable = false; nsCOMPtr<nsIDOMDocument> domDoc; domWindow->GetDocument(getter_AddRefs(domDoc)); nsCOMPtr<nsIHTMLDocument> htmlDoc = do_QueryInterface(domDoc); if (htmlDoc) mDetachedEditingState = htmlDoc->GetEditingState(); mDocShell = nullptr; return NS_OK; }
nsresult nsPluginStreamListenerPeer::GetInterfaceGlobal(const nsIID& aIID, void** result) { if (!mPluginInstance) { return NS_ERROR_FAILURE; } nsCOMPtr<nsIPluginInstanceOwner> owner; mPluginInstance->GetOwner(getter_AddRefs(owner)); if (owner) { nsCOMPtr<nsIDocument> doc; nsresult rv = owner->GetDocument(getter_AddRefs(doc)); if (NS_SUCCEEDED(rv) && doc) { nsPIDOMWindow *window = doc->GetWindow(); if (window) { nsCOMPtr<nsIWebNavigation> webNav = do_GetInterface(window); nsCOMPtr<nsIInterfaceRequestor> ir = do_QueryInterface(webNav); return ir->GetInterface(aIID, result); } } } return NS_ERROR_FAILURE; }
/* void viewCert (in nsIX509Cert cert); */ NS_IMETHODIMP nsNSSDialogs::ViewCert(nsIInterfaceRequestor *ctx, nsIX509Cert *cert) { nsresult rv; nsCOMPtr<nsIPKIParamBlock> block = do_CreateInstance(NS_PKIPARAMBLOCK_CONTRACTID); if (!block) return NS_ERROR_FAILURE; rv = block->SetISupportAtIndex(1, cert); if (NS_FAILED(rv)) return rv; // Get the parent window for the dialog nsCOMPtr<nsIDOMWindow> parent = do_GetInterface(ctx); rv = nsNSSDialogHelper::openDialog(parent, "chrome://pippki/content/certViewer.xul", block, false); return rv; }
NS_IMETHODIMP nsTypeAheadFind::SetDocShell(nsIDocShell* aDocShell) { mDocShell = do_GetWeakReference(aDocShell); mWebBrowserFind = do_GetInterface(aDocShell); NS_ENSURE_TRUE(mWebBrowserFind, NS_ERROR_FAILURE); nsCOMPtr<nsIPresShell> presShell; aDocShell->GetPresShell(getter_AddRefs(presShell)); mPresShell = do_GetWeakReference(presShell); mStartFindRange = nsnull; mStartPointRange = do_CreateInstance(kRangeCID); mSearchRange = do_CreateInstance(kRangeCID); mFoundLink = nsnull; mFoundEditable = nsnull; mCurrentWindow = nsnull; mSelectionController = nsnull; return NS_OK; }
nsresult nsEditingSession::ReattachToWindow(nsIDOMWindow* aWindow) { NS_ENSURE_TRUE(mDoneSetup, NS_OK); NS_ASSERTION(mStateMaintainer, "mStateMaintainer should exist."); // Imitate nsEditorDocShell::MakeEditable() to reattach the // old editor ot the window. nsresult rv; nsIDocShell *docShell = GetDocShellFromWindow(aWindow); NS_ENSURE_TRUE(docShell, NS_ERROR_FAILURE); mDocShell = do_GetWeakReference(docShell); // Disable plugins. if (!mInteractive) { rv = DisableJSAndPlugins(aWindow); NS_ENSURE_SUCCESS(rv, rv); } // Tells embedder that startup is in progress. mEditorStatus = eEditorCreationInProgress; // Adds back web progress listener. rv = PrepareForEditing(aWindow); NS_ENSURE_SUCCESS(rv, rv); // Setup the command controllers again. rv = SetupEditorCommandController("@mozilla.org/editor/editingcontroller;1", aWindow, static_cast<nsIEditingSession*>(this), &mBaseCommandControllerId); NS_ENSURE_SUCCESS(rv, rv); rv = SetupEditorCommandController("@mozilla.org/editor/editordocstatecontroller;1", aWindow, static_cast<nsIEditingSession*>(this), &mDocStateControllerId); NS_ENSURE_SUCCESS(rv, rv); if (mStateMaintainer) mStateMaintainer->Init(aWindow); // Get editor nsCOMPtr<nsIEditor> editor; rv = GetEditorForWindow(aWindow, getter_AddRefs(editor)); NS_ENSURE_TRUE(editor, NS_ERROR_FAILURE); if (!mInteractive) { // Disable animation of images in this document: nsCOMPtr<nsIDOMWindowUtils> utils(do_GetInterface(aWindow)); NS_ENSURE_TRUE(utils, NS_ERROR_FAILURE); rv = utils->GetImageAnimationMode(&mImageAnimationMode); NS_ENSURE_SUCCESS(rv, rv); utils->SetImageAnimationMode(imgIContainer::kDontAnimMode); } // The third controller takes an nsIEditor as the context rv = SetupEditorCommandController("@mozilla.org/editor/htmleditorcontroller;1", aWindow, editor, &mHTMLCommandControllerId); NS_ENSURE_SUCCESS(rv, rv); // Set context on all controllers to be the editor rv = SetEditorOnControllers(aWindow, editor); NS_ENSURE_SUCCESS(rv, rv); #ifdef DEBUG { bool isEditable; rv = WindowIsEditable(aWindow, &isEditable); NS_ENSURE_SUCCESS(rv, rv); NS_ASSERTION(isEditable, "Window is not editable after reattaching editor."); } #endif // DEBUG return NS_OK; }
// This is called when the channel is redirected. NS_IMETHODIMP FetchDriver::AsyncOnChannelRedirect(nsIChannel* aOldChannel, nsIChannel* aNewChannel, uint32_t aFlags, nsIAsyncVerifyRedirectCallback *aCallback) { NS_PRECONDITION(aNewChannel, "Redirect without a channel?"); nsresult rv; // HTTP Fetch step 5, "redirect status", step 1 if (NS_WARN_IF(mRequest->GetRedirectMode() == RequestRedirect::Error)) { aOldChannel->Cancel(NS_BINDING_FAILED); return NS_BINDING_FAILED; } // HTTP Fetch step 5, "redirect status", steps 2 through 6 are automatically // handled by necko before calling AsyncOnChannelRedirect() with the new // nsIChannel. // HTTP Fetch step 5, "redirect status", steps 7 and 8 enforcing a redirect // count are done by Necko. The pref used is "network.http.redirection-limit" // which is set to 20 by default. // HTTP Fetch Step 9, "redirect status". We only unset this for spec // compatibility. Any actions we take on mRequest here do not affect what the //channel does. mRequest->UnsetSameOriginDataURL(); // HTTP Fetch step 5, "redirect status", step 10 requires us to halt the // redirect, but successfully return an opaqueredirect Response to the // initiating Fetch. if (mRequest->GetRedirectMode() == RequestRedirect::Manual) { // Ideally we would simply not cancel the old channel and allow it to // be processed as normal. Unfortunately this is quite fragile and // other redirect handlers can easily break it for certain use cases. // // For example, nsCORSListenerProxy cancels vetoed redirect channels. // The HTTP cache will also error on vetoed redirects when the // redirect has been previously cached. // // Therefore simulate the completion of the channel to produce the // opaqueredirect Response and then cancel the original channel. This // will result in OnStartRequest() getting called twice, but the second // time will be with an error response (from the Cancel) which will // be ignored. mRequest->SetResponseTainting(InternalRequest::RESPONSETAINT_OPAQUEREDIRECT); unused << OnStartRequest(aOldChannel, nullptr); unused << OnStopRequest(aOldChannel, nullptr, NS_OK); aOldChannel->Cancel(NS_BINDING_FAILED); return NS_BINDING_FAILED; } // The following steps are from HTTP Fetch step 5, "redirect status", step 11 // which requires the RequestRedirect to be "follow". MOZ_ASSERT(mRequest->GetRedirectMode() == RequestRedirect::Follow); // HTTP Fetch step 5, "redirect status", steps 11.1 and 11.2 block redirecting // to a URL with credentials in CORS mode. This is implemented in // nsCORSListenerProxy. mRedirectCallback = aCallback; mOldRedirectChannel = aOldChannel; mNewRedirectChannel = aNewChannel; nsCOMPtr<nsIChannelEventSink> outer = do_GetInterface(mNotificationCallbacks); if (outer) { // The callee is supposed to call OnRedirectVerifyCallback() on success, // and nobody has to call it on failure, so we can just return after this // block. rv = outer->AsyncOnChannelRedirect(aOldChannel, aNewChannel, aFlags, this); if (NS_FAILED(rv)) { aOldChannel->Cancel(rv); mRedirectCallback = nullptr; mOldRedirectChannel = nullptr; mNewRedirectChannel = nullptr; } return rv; } (void) OnRedirectVerifyCallback(NS_OK); return NS_OK; }
/* boolean findNext (); */ NS_IMETHODIMP nsWebBrowserFind::FindNext(bool *outDidFind) { NS_ENSURE_ARG_POINTER(outDidFind); *outDidFind = false; NS_ENSURE_TRUE(CanFindNext(), NS_ERROR_NOT_INITIALIZED); nsresult rv = NS_OK; nsCOMPtr<nsIDOMWindow> searchFrame = do_QueryReferent(mCurrentSearchFrame); NS_ENSURE_TRUE(searchFrame, NS_ERROR_NOT_INITIALIZED); nsCOMPtr<nsIDOMWindow> rootFrame = do_QueryReferent(mRootSearchFrame); NS_ENSURE_TRUE(rootFrame, NS_ERROR_NOT_INITIALIZED); // first, if there's a "cmd_findagain" observer around, check to see if it // wants to perform the find again command . If it performs the find again // it will return true, in which case we exit ::FindNext() early. // Otherwise, nsWebBrowserFind needs to perform the find again command itself // this is used by nsTypeAheadFind, which controls find again when it was // the last executed find in the current window. nsCOMPtr<nsIObserverService> observerSvc = mozilla::services::GetObserverService(); if (observerSvc) { nsCOMPtr<nsISupportsInterfacePointer> windowSupportsData = do_CreateInstance(NS_SUPPORTS_INTERFACE_POINTER_CONTRACTID, &rv); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr<nsISupports> searchWindowSupports = do_QueryInterface(rootFrame); windowSupportsData->SetData(searchWindowSupports); NS_NAMED_LITERAL_STRING(dnStr, "down"); NS_NAMED_LITERAL_STRING(upStr, "up"); observerSvc->NotifyObservers(windowSupportsData, "nsWebBrowserFind_FindAgain", mFindBackwards? upStr.get(): dnStr.get()); windowSupportsData->GetData(getter_AddRefs(searchWindowSupports)); // findnext performed if search window data cleared out *outDidFind = searchWindowSupports == nullptr; if (*outDidFind) return NS_OK; } // next, look in the current frame. If found, return. // Beware! This may flush notifications via synchronous // ScrollSelectionIntoView. rv = SearchInFrame(searchFrame, false, outDidFind); if (NS_FAILED(rv)) return rv; if (*outDidFind) return OnFind(searchFrame); // we are done // if we are not searching other frames, return if (!mSearchSubFrames && !mSearchParentFrames) return NS_OK; nsIDocShell *rootDocShell = GetDocShellFromWindow(rootFrame); if (!rootDocShell) return NS_ERROR_FAILURE; int32_t enumDirection; if (mFindBackwards) enumDirection = nsIDocShell::ENUMERATE_BACKWARDS; else enumDirection = nsIDocShell::ENUMERATE_FORWARDS; nsCOMPtr<nsISimpleEnumerator> docShellEnumerator; rv = rootDocShell->GetDocShellEnumerator(nsIDocShellTreeItem::typeAll, enumDirection, getter_AddRefs(docShellEnumerator)); if (NS_FAILED(rv)) return rv; // remember where we started nsCOMPtr<nsIDocShellTreeItem> startingItem = do_QueryInterface(GetDocShellFromWindow(searchFrame), &rv); if (NS_FAILED(rv)) return rv; nsCOMPtr<nsIDocShellTreeItem> curItem; // XXX We should avoid searching in frameset documents here. // We also need to honour mSearchSubFrames and mSearchParentFrames. bool hasMore, doFind = false; while (NS_SUCCEEDED(docShellEnumerator->HasMoreElements(&hasMore)) && hasMore) { nsCOMPtr<nsISupports> curSupports; rv = docShellEnumerator->GetNext(getter_AddRefs(curSupports)); if (NS_FAILED(rv)) break; curItem = do_QueryInterface(curSupports, &rv); if (NS_FAILED(rv)) break; if (doFind) { searchFrame = do_GetInterface(curItem, &rv); if (NS_FAILED(rv)) break; OnStartSearchFrame(searchFrame); // Beware! This may flush notifications via synchronous // ScrollSelectionIntoView. rv = SearchInFrame(searchFrame, false, outDidFind); if (NS_FAILED(rv)) return rv; if (*outDidFind) return OnFind(searchFrame); // we are done OnEndSearchFrame(searchFrame); } if (curItem.get() == startingItem.get()) doFind = true; // start looking in frames after this one }; if (!mWrapFind) { // remember where we left off SetCurrentSearchFrame(searchFrame); return NS_OK; } // From here on, we're wrapping, first through the other frames, // then finally from the beginning of the starting frame back to // the starting point. // because nsISimpleEnumerator is totally lame and isn't resettable, I // have to make a new one docShellEnumerator = nullptr; rv = rootDocShell->GetDocShellEnumerator(nsIDocShellTreeItem::typeAll, enumDirection, getter_AddRefs(docShellEnumerator)); if (NS_FAILED(rv)) return rv; while (NS_SUCCEEDED(docShellEnumerator->HasMoreElements(&hasMore)) && hasMore) { nsCOMPtr<nsISupports> curSupports; rv = docShellEnumerator->GetNext(getter_AddRefs(curSupports)); if (NS_FAILED(rv)) break; curItem = do_QueryInterface(curSupports, &rv); if (NS_FAILED(rv)) break; searchFrame = do_GetInterface(curItem, &rv); if (NS_FAILED(rv)) break; if (curItem.get() == startingItem.get()) { // Beware! This may flush notifications via synchronous // ScrollSelectionIntoView. rv = SearchInFrame(searchFrame, true, outDidFind); if (NS_FAILED(rv)) return rv; if (*outDidFind) return OnFind(searchFrame); // we are done break; } OnStartSearchFrame(searchFrame); // Beware! This may flush notifications via synchronous // ScrollSelectionIntoView. rv = SearchInFrame(searchFrame, false, outDidFind); if (NS_FAILED(rv)) return rv; if (*outDidFind) return OnFind(searchFrame); // we are done OnEndSearchFrame(searchFrame); } // remember where we left off SetCurrentSearchFrame(searchFrame); NS_ASSERTION(NS_SUCCEEDED(rv), "Something failed"); return rv; }
HRESULT nsEventSink::InternalInvoke(DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS *pDispParams, VARIANT *pVarResult, EXCEPINFO *pExcepInfo, UINT *puArgErr) { FUNCDESC *pFuncDesc = NULL; HRESULT hr = S_OK; CComBSTR bstrName; // Must search and compare each member to the dispid... if (m_spEventSinkTypeInfo) { HRESULT hr = S_OK; TYPEATTR* pAttr; hr = m_spEventSinkTypeInfo->GetTypeAttr(&pAttr); if (pAttr) { int i; for (i = 0; i < pAttr->cFuncs;i++) { hr = m_spEventSinkTypeInfo->GetFuncDesc(i, &pFuncDesc); if (FAILED(hr)) return hr; if (pFuncDesc->memid == dispIdMember) { UINT cNames = 0; m_spEventSinkTypeInfo->GetNames(dispIdMember, &bstrName, 1, &cNames); break; } m_spEventSinkTypeInfo->ReleaseFuncDesc(pFuncDesc); pFuncDesc = NULL; } m_spEventSinkTypeInfo->ReleaseTypeAttr(pAttr); } } if (!pFuncDesc) { // Return return S_OK; } #ifdef DEBUG { // Dump out some info to look at ATLTRACE(_T("Invoke(%d)\n"), (int) dispIdMember); ATLTRACE(_T(" ")); /* Return code */ switch (pFuncDesc->elemdescFunc.tdesc.vt) { case VT_HRESULT: ATLTRACE(_T("HRESULT")); break; case VT_VOID: ATLTRACE(_T("void")); break; default: ATLTRACE(_T("void /* vt = %d */"), pFuncDesc->elemdescFunc.tdesc.vt); break; } /* Function name */ ATLTRACE(_T(" %S("), SUCCEEDED(hr) ? bstrName.m_str : L"?unknown?"); /* Parameters */ for (int i = 0; i < pFuncDesc->cParams; i++) { USHORT paramFlags = pFuncDesc->lprgelemdescParam[i].paramdesc.wParamFlags; ATLTRACE("["); BOOL addComma = FALSE; if (paramFlags & PARAMFLAG_FIN) { ATLTRACE(_T("in")); addComma = TRUE; } if (paramFlags & PARAMFLAG_FOUT) { ATLTRACE(addComma ? _T(",out") : _T("out")); addComma = TRUE; } if (paramFlags & PARAMFLAG_FRETVAL) { ATLTRACE(addComma ? _T(",retval") : _T("retval")); addComma = TRUE; } ATLTRACE("] "); VARTYPE vt = pFuncDesc->lprgelemdescParam[i].tdesc.vt; switch (vt) { case VT_HRESULT: ATLTRACE(_T("HRESULT")); break; case VT_VARIANT: ATLTRACE(_T("VARIANT")); break; case VT_I2: ATLTRACE(_T("short")); break; case VT_I4: ATLTRACE(_T("long")); break; case VT_R8: ATLTRACE(_T("double")); break; case VT_BOOL: ATLTRACE(_T("VARIANT_BOOL")); break; case VT_BSTR: ATLTRACE(_T("BSTR")); break; case VT_DISPATCH: ATLTRACE(_T("IDispatch *")); break; case VT_UNKNOWN: ATLTRACE(_T("IUnknown *")); break; case VT_USERDEFINED: ATLTRACE(_T("/* Userdefined */")); break; case VT_PTR: ATLTRACE(_T("void *")); break; case VT_VOID: ATLTRACE(_T("void")); break; // More could be added... default: ATLTRACE(_T("/* vt = %d */"), vt); break; } if (i + 1 < pFuncDesc->cParams) { ATLTRACE(_T(", ")); } } ATLTRACE(_T(");\n")); } #endif m_spEventSinkTypeInfo->ReleaseFuncDesc(pFuncDesc); pFuncDesc = NULL; nsCOMPtr<nsIDOMElement> element; NPN_GetValue(mPlugin->pPluginInstance, NPNVDOMElement, static_cast<nsIDOMElement **>(getter_AddRefs(element))); if (!element) { NS_ERROR("can't get the object element"); return S_OK; } nsAutoString id; if (NS_FAILED(element->GetAttribute(NS_LITERAL_STRING("id"), id)) || id.IsEmpty()) { // Object has no name so it can't fire events return S_OK; } nsDependentString eventName(bstrName.m_str); // Fire the script event handler... nsCOMPtr<nsIDOMWindow> window; NPN_GetValue(mPlugin->pPluginInstance, NPNVDOMWindow, static_cast<nsIDOMWindow **>(getter_AddRefs(window))); nsCOMPtr<nsIScriptEventManager> eventManager(do_GetInterface(window)); if (!eventManager) return S_OK; nsCOMPtr<nsISupports> handler; eventManager->FindEventHandler(id, eventName, pDispParams->cArgs, getter_AddRefs(handler)); if (!handler) { return S_OK; } // Create a list of arguments to pass along // // This array is created on the stack if the number of arguments // less than kMaxArgsOnStack. Otherwise, the array is heap // allocated. // const int kMaxArgsOnStack = 10; PRUint32 argc = pDispParams->cArgs; jsval *args = nsnull; jsval stackArgs[kMaxArgsOnStack]; // Heap allocate the jsval array if it is too big to fit on // the stack (ie. more than kMaxArgsOnStack arguments) if (argc > kMaxArgsOnStack) { args = new jsval[argc]; if (!args) return S_OK; } else if (argc) { // Use the jsval array on the stack... args = stackArgs; } if (argc) { nsCOMPtr<nsIDispatchSupport> disp(do_GetService("@mozilla.org/nsdispatchsupport;1")); for (UINT i = 0; i < argc; i++) { // Arguments are listed backwards, intentionally, in rgvarg disp->COMVariant2JSVal(&pDispParams->rgvarg[argc - 1 - i], &args[i]); } } // Fire the Event. eventManager->InvokeEventHandler(handler, element, args, argc); // Free the jsvals if they were heap allocated... if (args != stackArgs) { delete [] args; } // TODO Turn js objects for out params back into VARIANTS // TODO Turn js return code into VARIANT // TODO handle js exception and fill in exception info (do we care?) if (pExcepInfo) { pExcepInfo->wCode = 0; } return S_OK; }
// Override a web page NS_IMETHODIMP nsParentalControlsServiceWin::RequestURIOverrides(nsIArray *aTargets, nsIInterfaceRequestor *aWindowContext, bool *_retval) { *_retval = false; if (!mEnabled) return NS_ERROR_NOT_AVAILABLE; NS_ENSURE_ARG_POINTER(aTargets); uint32_t arrayLength = 0; aTargets->GetLength(&arrayLength); if (!arrayLength) return NS_ERROR_INVALID_ARG; if (arrayLength == 1) { nsCOMPtr<nsIURI> uri = do_QueryElementAt(aTargets, 0); if (!uri) return NS_ERROR_INVALID_ARG; return RequestURIOverride(uri, aWindowContext, _retval); } HWND hWnd = nullptr; // If we have a native window, use its handle instead nsCOMPtr<nsIWidget> widget(do_GetInterface(aWindowContext)); if (widget) hWnd = (HWND)widget->GetNativeData(NS_NATIVE_WINDOW); if (hWnd == nullptr) hWnd = GetDesktopWindow(); // The first entry should be the root uri nsAutoCString rootSpec; nsCOMPtr<nsIURI> rootURI = do_QueryElementAt(aTargets, 0); if (!rootURI) return NS_ERROR_INVALID_ARG; rootURI->GetSpec(rootSpec); if (rootSpec.IsEmpty()) return NS_ERROR_INVALID_ARG; // Allocate an array of sub uri int32_t count = arrayLength - 1; nsAutoArrayPtr<LPCWSTR> arrUrls(new LPCWSTR[count]); if (!arrUrls) return NS_ERROR_OUT_OF_MEMORY; uint32_t uriIdx = 0, idx; for (idx = 1; idx < arrayLength; idx++) { nsCOMPtr<nsIURI> uri = do_QueryElementAt(aTargets, idx); if (!uri) continue; nsAutoCString subURI; if (NS_FAILED(uri->GetSpec(subURI))) continue; arrUrls[uriIdx] = (LPCWSTR)UTF8ToNewUnicode(subURI); // allocation if (!arrUrls[uriIdx]) continue; uriIdx++; } if (!uriIdx) return NS_ERROR_INVALID_ARG; BOOL ret; nsRefPtr<IWPCWebSettings> wpcws; if (SUCCEEDED(mPC->GetWebSettings(NULL, getter_AddRefs(wpcws)))) { wpcws->RequestURLOverride(hWnd, NS_ConvertUTF8toUTF16(rootSpec).get(), uriIdx, (LPCWSTR*)arrUrls.get(), &ret); *_retval = ret; } // Free up the allocated strings in our array for (idx = 0; idx < uriIdx; idx++) NS_Free((void*)arrUrls[idx]); return NS_OK; }
LoadInfo::LoadInfo(nsIPrincipal* aLoadingPrincipal, nsIPrincipal* aTriggeringPrincipal, nsINode* aLoadingContext, nsSecurityFlags aSecurityFlags, nsContentPolicyType aContentPolicyType) : mLoadingPrincipal(aLoadingContext ? aLoadingContext->NodePrincipal() : aLoadingPrincipal) , mTriggeringPrincipal(aTriggeringPrincipal ? aTriggeringPrincipal : mLoadingPrincipal.get()) , mLoadingContext(do_GetWeakReference(aLoadingContext)) , mSecurityFlags(aSecurityFlags) , mInternalContentPolicyType(aContentPolicyType) , mTainting(LoadTainting::Basic) , mUpgradeInsecureRequests(false) , mInnerWindowID(0) , mOuterWindowID(0) , mParentOuterWindowID(0) , mEnforceSecurity(false) , mInitialSecurityCheckDone(false) , mIsThirdPartyContext(true) , mForcePreflight(false) , mIsPreflight(false) { MOZ_ASSERT(mLoadingPrincipal); MOZ_ASSERT(mTriggeringPrincipal); // if consumers pass both, aLoadingContext and aLoadingPrincipal // then the loadingPrincipal must be the same as the node's principal MOZ_ASSERT(!aLoadingContext || !aLoadingPrincipal || aLoadingContext->NodePrincipal() == aLoadingPrincipal); // if the load is sandboxed, we can not also inherit the principal if (mSecurityFlags & nsILoadInfo::SEC_SANDBOXED) { mSecurityFlags ^= nsILoadInfo::SEC_FORCE_INHERIT_PRINCIPAL; } if (aLoadingContext) { nsCOMPtr<nsPIDOMWindow> outerWindow; // When the element being loaded is a frame, we choose the frame's window // for the window ID and the frame element's window as the parent // window. This is the behavior that Chrome exposes to add-ons. nsCOMPtr<nsIFrameLoaderOwner> frameLoaderOwner = do_QueryInterface(aLoadingContext); if (frameLoaderOwner) { nsCOMPtr<nsIFrameLoader> fl = frameLoaderOwner->GetFrameLoader(); nsCOMPtr<nsIDocShell> docShell; if (fl && NS_SUCCEEDED(fl->GetDocShell(getter_AddRefs(docShell))) && docShell) { outerWindow = do_GetInterface(docShell); } } else { outerWindow = aLoadingContext->OwnerDoc()->GetWindow(); } if (outerWindow) { nsCOMPtr<nsPIDOMWindow> inner = outerWindow->GetCurrentInnerWindow(); mInnerWindowID = inner ? inner->WindowID() : 0; mOuterWindowID = outerWindow->WindowID(); nsCOMPtr<nsPIDOMWindow> parent = outerWindow->GetScriptableParent(); mParentOuterWindowID = parent->WindowID(); ComputeIsThirdPartyContext(outerWindow); } // if the document forces all requests to be upgraded from http to https, then // we should do that for all requests. If it only forces preloads to be upgraded // then we should enforce upgrade insecure requests only for preloads. mUpgradeInsecureRequests = aLoadingContext->OwnerDoc()->GetUpgradeInsecureRequests(false) || (nsContentUtils::IsPreloadType(mInternalContentPolicyType) && aLoadingContext->OwnerDoc()->GetUpgradeInsecureRequests(true)); } const PrincipalOriginAttributes attrs = BasePrincipal::Cast(mLoadingPrincipal)->OriginAttributesRef(); mOriginAttributes.InheritFromDocToNecko(attrs); }
JNIEXPORT void JNICALL Java_org_mozilla_webclient_impl_wrapper_1native_CurrentPageImpl_nativeGetSource (JNIEnv *env, jobject obj, jint nativeBCPtr, jobject selection) { NativeBrowserControl* nativeBrowserControl = (NativeBrowserControl *) nativeBCPtr; nsresult rv = NS_OK; // get the nsIWebPageDescriptor for the existing window nsCOMPtr<nsIWebBrowser> oldWebBrowser = nsnull; rv = nativeBrowserControl->mWindow->GetWebBrowser(getter_AddRefs(oldWebBrowser)); if (NS_FAILED(rv)) { ::util_ThrowExceptionToJava(env, "Exception: Can't get existing webBrowser for view source window"); return; } nsCOMPtr<nsIDocShell> oldDocShell = do_GetInterface(oldWebBrowser); if (!oldDocShell) { ::util_ThrowExceptionToJava(env, "Exception: Can't get existing docShell for view source window"); return; } nsCOMPtr<nsIWebPageDescriptor> oldPageDesc = do_GetInterface(oldDocShell); if (!oldPageDesc) { ::util_ThrowExceptionToJava(env, "Exception: Can't get existing pageDescriptor for view source window"); return; } nsCOMPtr<nsISupports> pageCookie = nsnull; rv = oldPageDesc->GetCurrentDescriptor(getter_AddRefs(pageCookie)); if (NS_FAILED(rv)) { ::util_ThrowExceptionToJava(env, "Exception: GetCurrentDescriptor failed"); return; } EmbedWindow *sourceWindow = new EmbedWindow(); sourceWindow->InitNoChrome(nativeBrowserControl); rv = sourceWindow->CreateWindow_(0,0); if (NS_FAILED(rv)) { ::util_ThrowExceptionToJava(env, "Exception: Can't create window for view source window"); return; } nsCOMPtr<nsIWebBrowser> newWebBrowser = nsnull; rv = sourceWindow->GetWebBrowser(getter_AddRefs(newWebBrowser)); if (NS_FAILED(rv)) { ::util_ThrowExceptionToJava(env, "Exception: Can't get existing webBrowser for new view source window"); return; } // create and install the LoadCompleteProgressListener on the new // window LoadCompleteProgressListener *loadCompleteListener = new LoadCompleteProgressListener(); loadCompleteListener->Init(nativeBrowserControl); nsCOMPtr<nsISupports> loadCompleteGuard = static_cast<nsIWebProgressListener *>(loadCompleteListener); nsCOMPtr<nsISupportsWeakReference> supportsWeak; supportsWeak = do_QueryInterface(loadCompleteGuard); nsCOMPtr<nsIWeakReference> weakRef; supportsWeak->GetWeakReference(getter_AddRefs(weakRef)); rv = newWebBrowser->AddWebBrowserListener(weakRef, nsIWebProgressListener::GetIID()); if (NS_FAILED(rv)) { ::util_ThrowExceptionToJava(env, "Exception: install progress listener for view source window"); return; } nsCOMPtr<nsIDocShell> newDocShell = do_GetInterface(newWebBrowser); if (!newDocShell) { ::util_ThrowExceptionToJava(env, "Exception: Can't get existing docShell for new view source window"); return; } // get the page descriptor from the new window nsCOMPtr<nsIWebPageDescriptor> newPageDesc = do_GetInterface(newDocShell); if (!newPageDesc) { ::util_ThrowExceptionToJava(env, "Exception: Can't get pageDescriptor for view source window"); return; } rv = newPageDesc->LoadPage(pageCookie, nsIWebPageDescriptor::DISPLAY_AS_SOURCE); if (NS_FAILED(rv)) { ::util_ThrowExceptionToJava(env, "Exception: Can't load page for view source window"); return; } // allow the page load to complete PRBool loadComplete = PR_FALSE; while (!loadComplete) { nativeBrowserControl->GetWrapperFactory()->ProcessEventLoop(); rv = loadCompleteListener->IsLoadComplete(&loadComplete); if (NS_FAILED(rv)) { ::util_ThrowExceptionToJava(env, "Exception: Error getting status of load in view source window"); return; } } rv = sourceWindow->SelectAll(); if (NS_FAILED(rv)) { ::util_ThrowExceptionToJava(env, "Exception: Can't select all for view source window"); return; } rv = sourceWindow->GetSelection(env, selection); if (NS_FAILED(rv)) { ::util_ThrowExceptionToJava(env, "Exception: Can't get seletion for view source window"); return; } newPageDesc = nsnull; newDocShell = nsnull; sourceWindow->ReleaseChildren(); delete sourceWindow; weakRef = nsnull; supportsWeak = nsnull; loadCompleteGuard = nsnull; // not necessary to delete sourceWindow, the guard takes care of it. return; }
/*--------------------------------------------------------------------------- SetupEditorOnWindow nsIEditor setupEditorOnWindow (in nsIDOMWindow aWindow); ----------------------------------------------------------------------------*/ NS_IMETHODIMP nsEditingSession::SetupEditorOnWindow(nsIDOMWindow *aWindow) { mDoneSetup = true; nsresult rv; //MIME CHECKING //must get the content type // Note: the doc gets this from the network channel during StartPageLoad, // so we don't have to get it from there ourselves nsCOMPtr<nsIDOMDocument> doc; nsCAutoString mimeCType; //then lets check the mime type if (NS_SUCCEEDED(aWindow->GetDocument(getter_AddRefs(doc))) && doc) { nsAutoString mimeType; if (NS_SUCCEEDED(doc->GetContentType(mimeType))) AppendUTF16toUTF8(mimeType, mimeCType); if (IsSupportedTextType(mimeCType.get())) { mEditorType.AssignLiteral("text"); mimeCType = "text/plain"; } else if (!mimeCType.EqualsLiteral("text/html") && !mimeCType.EqualsLiteral("application/xhtml+xml")) { // Neither an acceptable text or html type. mEditorStatus = eEditorErrorCantEditMimeType; // Turn editor into HTML -- we will load blank page later mEditorType.AssignLiteral("html"); mimeCType.AssignLiteral("text/html"); } // Flush out frame construction to make sure that the subframe's // presshell is set up if it needs to be. nsCOMPtr<nsIDocument> document = do_QueryInterface(doc); if (document) { document->FlushPendingNotifications(Flush_Frames); if (mMakeWholeDocumentEditable) { document->SetEditableFlag(true); nsCOMPtr<nsIHTMLDocument> htmlDocument = do_QueryInterface(document); if (htmlDocument) { // Enable usage of the execCommand API htmlDocument->SetEditingState(nsIHTMLDocument::eDesignMode); } } } } bool needHTMLController = false; const char *classString = "@mozilla.org/editor/htmleditor;1"; if (mEditorType.EqualsLiteral("textmail")) { mEditorFlags = nsIPlaintextEditor::eEditorPlaintextMask | nsIPlaintextEditor::eEditorEnableWrapHackMask | nsIPlaintextEditor::eEditorMailMask; } else if (mEditorType.EqualsLiteral("text")) { mEditorFlags = nsIPlaintextEditor::eEditorPlaintextMask | nsIPlaintextEditor::eEditorEnableWrapHackMask; } else if (mEditorType.EqualsLiteral("htmlmail")) { if (mimeCType.EqualsLiteral("text/html")) { needHTMLController = true; mEditorFlags = nsIPlaintextEditor::eEditorMailMask; } else //set the flags back to textplain. mEditorFlags = nsIPlaintextEditor::eEditorPlaintextMask | nsIPlaintextEditor::eEditorEnableWrapHackMask; } else // Defaulted to html { needHTMLController = true; } if (mInteractive) { mEditorFlags |= nsIPlaintextEditor::eEditorAllowInteraction; } // make the UI state maintainer mStateMaintainer = new nsComposerCommandsUpdater(); // now init the state maintainer // This allows notification of error state // even if we don't create an editor rv = mStateMaintainer->Init(aWindow); NS_ENSURE_SUCCESS(rv, rv); if (mEditorStatus != eEditorCreationInProgress) { mStateMaintainer->NotifyDocumentCreated(); return NS_ERROR_FAILURE; } // Create editor and do other things // only if we haven't found some error above, nsIDocShell *docShell = GetDocShellFromWindow(aWindow); NS_ENSURE_TRUE(docShell, NS_ERROR_FAILURE); if (!mInteractive) { // Disable animation of images in this document: nsCOMPtr<nsIDOMWindowUtils> utils(do_GetInterface(aWindow)); NS_ENSURE_TRUE(utils, NS_ERROR_FAILURE); rv = utils->GetImageAnimationMode(&mImageAnimationMode); NS_ENSURE_SUCCESS(rv, rv); utils->SetImageAnimationMode(imgIContainer::kDontAnimMode); } // create and set editor nsCOMPtr<nsIEditorDocShell> editorDocShell = do_QueryInterface(docShell, &rv); NS_ENSURE_SUCCESS(rv, rv); // Try to reuse an existing editor nsCOMPtr<nsIEditor> editor = do_QueryReferent(mExistingEditor); if (editor) { editor->PreDestroy(false); } else { editor = do_CreateInstance(classString, &rv); NS_ENSURE_SUCCESS(rv, rv); mExistingEditor = do_GetWeakReference(editor); } // set the editor on the docShell. The docShell now owns it. rv = editorDocShell->SetEditor(editor); NS_ENSURE_SUCCESS(rv, rv); // setup the HTML editor command controller if (needHTMLController) { // The third controller takes an nsIEditor as the context rv = SetupEditorCommandController("@mozilla.org/editor/htmleditorcontroller;1", aWindow, editor, &mHTMLCommandControllerId); NS_ENSURE_SUCCESS(rv, rv); } // Set mimetype on editor rv = editor->SetContentsMIMEType(mimeCType.get()); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr<nsIContentViewer> contentViewer; rv = docShell->GetContentViewer(getter_AddRefs(contentViewer)); NS_ENSURE_SUCCESS(rv, rv); NS_ENSURE_TRUE(contentViewer, NS_ERROR_FAILURE); nsCOMPtr<nsIDOMDocument> domDoc; rv = contentViewer->GetDOMDocument(getter_AddRefs(domDoc)); NS_ENSURE_SUCCESS(rv, rv); NS_ENSURE_TRUE(domDoc, NS_ERROR_FAILURE); // Set up as a doc state listener // Important! We must have this to broadcast the "obs_documentCreated" message rv = editor->AddDocumentStateListener(mStateMaintainer); NS_ENSURE_SUCCESS(rv, rv); rv = editor->Init(domDoc, nullptr /* root content */, nullptr, mEditorFlags); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr<nsISelection> selection; editor->GetSelection(getter_AddRefs(selection)); nsCOMPtr<nsISelectionPrivate> selPriv = do_QueryInterface(selection); NS_ENSURE_TRUE(selPriv, NS_ERROR_FAILURE); rv = selPriv->AddSelectionListener(mStateMaintainer); NS_ENSURE_SUCCESS(rv, rv); // and as a transaction listener nsCOMPtr<nsITransactionManager> txnMgr; editor->GetTransactionManager(getter_AddRefs(txnMgr)); if (txnMgr) txnMgr->AddListener(mStateMaintainer); // Set context on all controllers to be the editor rv = SetEditorOnControllers(aWindow, editor); NS_ENSURE_SUCCESS(rv, rv); // Everything went fine! mEditorStatus = eEditorOK; // This will trigger documentCreation notification return editor->PostCreate(); }
LoadInfo::LoadInfo(nsIPrincipal* aLoadingPrincipal, nsIPrincipal* aTriggeringPrincipal, nsINode* aLoadingContext, nsSecurityFlags aSecurityFlags, nsContentPolicyType aContentPolicyType) : mLoadingPrincipal(aLoadingContext ? aLoadingContext->NodePrincipal() : aLoadingPrincipal) , mTriggeringPrincipal(aTriggeringPrincipal ? aTriggeringPrincipal : mLoadingPrincipal.get()) , mLoadingContext(do_GetWeakReference(aLoadingContext)) , mSecurityFlags(aSecurityFlags) , mInternalContentPolicyType(aContentPolicyType) , mTainting(LoadTainting::Basic) , mUpgradeInsecureRequests(false) , mInnerWindowID(0) , mOuterWindowID(0) , mParentOuterWindowID(0) , mEnforceSecurity(false) , mInitialSecurityCheckDone(false) , mIsThirdPartyContext(false) , mForcePreflight(false) , mIsPreflight(false) { MOZ_ASSERT(mLoadingPrincipal); MOZ_ASSERT(mTriggeringPrincipal); // TODO(bug 1259873): Above, we initialize mIsThirdPartyContext to false meaning // that consumers of LoadInfo that don't pass a context or pass a context from // which we can't find a window will default to assuming that they're 1st // party. It would be nice if we could default "safe" and assume that we are // 3rd party until proven otherwise. // if consumers pass both, aLoadingContext and aLoadingPrincipal // then the loadingPrincipal must be the same as the node's principal MOZ_ASSERT(!aLoadingContext || !aLoadingPrincipal || aLoadingContext->NodePrincipal() == aLoadingPrincipal); // if the load is sandboxed, we can not also inherit the principal if (mSecurityFlags & nsILoadInfo::SEC_SANDBOXED) { mSecurityFlags ^= nsILoadInfo::SEC_FORCE_INHERIT_PRINCIPAL; } if (aLoadingContext) { nsCOMPtr<nsPIDOMWindow> contextOuter = aLoadingContext->OwnerDoc()->GetWindow(); if (contextOuter) { ComputeIsThirdPartyContext(contextOuter); } nsCOMPtr<nsPIDOMWindow> outerWindow; // When the element being loaded is a frame, we choose the frame's window // for the window ID and the frame element's window as the parent // window. This is the behavior that Chrome exposes to add-ons. // NB: If the frameLoaderOwner doesn't have a frame loader, then the load // must be coming from an object (such as a plugin) that's loaded into it // instead of a document being loaded. In that case, treat this object like // any other non-document-loading element. nsCOMPtr<nsIFrameLoaderOwner> frameLoaderOwner = do_QueryInterface(aLoadingContext); nsCOMPtr<nsIFrameLoader> fl = frameLoaderOwner ? frameLoaderOwner->GetFrameLoader() : nullptr; if (fl) { nsCOMPtr<nsIDocShell> docShell; if (NS_SUCCEEDED(fl->GetDocShell(getter_AddRefs(docShell))) && docShell) { outerWindow = do_GetInterface(docShell); } } else { outerWindow = contextOuter.forget(); } if (outerWindow) { nsCOMPtr<nsPIDOMWindow> inner = outerWindow->GetCurrentInnerWindow(); mInnerWindowID = inner ? inner->WindowID() : 0; mOuterWindowID = outerWindow->WindowID(); nsCOMPtr<nsPIDOMWindow> parent = outerWindow->GetScriptableParent(); mParentOuterWindowID = parent->WindowID(); } // if the document forces all requests to be upgraded from http to https, then // we should do that for all requests. If it only forces preloads to be upgraded // then we should enforce upgrade insecure requests only for preloads. mUpgradeInsecureRequests = aLoadingContext->OwnerDoc()->GetUpgradeInsecureRequests(false) || (nsContentUtils::IsPreloadType(mInternalContentPolicyType) && aLoadingContext->OwnerDoc()->GetUpgradeInsecureRequests(true)); } const PrincipalOriginAttributes attrs = BasePrincipal::Cast(mLoadingPrincipal)->OriginAttributesRef(); mOriginAttributes.InheritFromDocToNecko(attrs); }
// nsIWebProgressListener implementation NS_IMETHODIMP nsMsgPrintEngine::OnStateChange(nsIWebProgress* aWebProgress, nsIRequest *aRequest, PRUint32 progressStateFlags, nsresult aStatus) { nsresult rv = NS_OK; // top-level document load data if (progressStateFlags & nsIWebProgressListener::STATE_IS_DOCUMENT) { if (progressStateFlags & nsIWebProgressListener::STATE_START) { // Tell the user we are loading... nsString msg; GetString(NS_LITERAL_STRING("LoadingMessageToPrint").get(), msg); SetStatusMessage(msg); } if (progressStateFlags & nsIWebProgressListener::STATE_STOP) { nsCOMPtr<nsIDocumentLoader> docLoader(do_QueryInterface(aWebProgress)); if (docLoader) { // Check to see if the document DOMWin that is finished loading is the same // one as the mail msg that we started to load. // We only want to print when the entire msg and all of its attachments // have finished loading. // The mail msg doc is the last one to receive the STATE_STOP notification nsCOMPtr<nsISupports> container; docLoader->GetContainer(getter_AddRefs(container)); nsCOMPtr<nsIDOMWindow> domWindow(do_GetInterface(container)); if (domWindow.get() != mMsgDOMWin.get()) { return NS_OK; } } nsCOMPtr<nsIWebProgressListener> wpl(do_QueryInterface(mPrintPromptService)); if (wpl) { wpl->OnStateChange(nsnull, nsnull, nsIWebProgressListener::STATE_STOP|nsIWebProgressListener::STATE_IS_DOCUMENT, nsnull); mPrintProgressListener = nsnull; mPrintProgress = nsnull; mPrintProgressParams = nsnull; } bool isPrintingCancelled = false; if (mPrintSettings) { mPrintSettings->GetIsCancelled(&isPrintingCancelled); } if (!isPrintingCancelled) { // if aWebProgress is a documentloader than the notification from // loading the documents. If it is NULL (or not a DocLoader) then it // it coming from Printing if (docLoader) { // Now, fire off the print operation! rv = NS_ERROR_FAILURE; // Tell the user the message is loaded... nsString msg; GetString(NS_LITERAL_STRING("MessageLoaded").get(), msg); SetStatusMessage(msg); NS_ASSERTION(mDocShell,"can't print, there is no docshell"); if ( (!mDocShell) || (!aRequest) ) { return StartNextPrintOperation(); } nsCOMPtr<nsIChannel> aChannel = do_QueryInterface(aRequest); if (!aChannel) return NS_ERROR_FAILURE; // Make sure this isn't just "about:blank" finishing.... nsCOMPtr<nsIURI> originalURI = nsnull; if (NS_SUCCEEDED(aChannel->GetOriginalURI(getter_AddRefs(originalURI))) && originalURI) { nsCAutoString spec; if (NS_SUCCEEDED(originalURI->GetSpec(spec))) { if (spec.Equals("about:blank")) { return StartNextPrintOperation(); } } } // If something bad happens here (menaing we can fire the PLEvent, highly unlikely) // we will still ask the msg to print, but if the user "cancels" out of the // print dialog the hidden print window will not be "closed" if (!FirePrintEvent()) { PrintMsgWindow(); } } else { FireStartNextEvent(); rv = NS_OK; } } else { mWindow->Close(); } } } return rv; }
// Check if X-Frame-Options permits this document to be loaded as a subdocument. bool nsDSURIContentListener::CheckFrameOptions(nsIRequest* request) { nsCAutoString xfoHeaderValue; nsCOMPtr<nsIHttpChannel> httpChannel = do_QueryInterface(request); if (!httpChannel) { return true; } httpChannel->GetResponseHeader(NS_LITERAL_CSTRING("X-Frame-Options"), xfoHeaderValue); // return early if header does not have one of the two values with meaning if (!xfoHeaderValue.LowerCaseEqualsLiteral("deny") && !xfoHeaderValue.LowerCaseEqualsLiteral("sameorigin")) return true; if (mDocShell) { // We need to check the location of this window and the location of the top // window, if we're not the top. X-F-O: SAMEORIGIN requires that the // document must be same-origin with top window. X-F-O: DENY requires that // the document must never be framed. nsCOMPtr<nsIDOMWindow> thisWindow = do_GetInterface(static_cast<nsIDocShell*>(mDocShell)); // If we don't have DOMWindow there is no risk of clickjacking if (!thisWindow) return true; nsCOMPtr<nsIDOMWindow> topWindow; thisWindow->GetTop(getter_AddRefs(topWindow)); // if the document is in the top window, it's not in a frame. if (thisWindow == topWindow) return true; // Find the top docshell in our parent chain that doesn't have the system // principal and use it for the principal comparison. Finding the top // content-type docshell doesn't work because some chrome documents are // loaded in content docshells (see bug 593387). nsCOMPtr<nsIDocShellTreeItem> thisDocShellItem(do_QueryInterface( static_cast<nsIDocShell*> (mDocShell))); nsCOMPtr<nsIDocShellTreeItem> parentDocShellItem, curDocShellItem = thisDocShellItem; nsCOMPtr<nsIDocument> topDoc; nsresult rv; nsCOMPtr<nsIScriptSecurityManager> ssm = do_GetService(NS_SCRIPTSECURITYMANAGER_CONTRACTID, &rv); if (!ssm) return false; // Traverse up the parent chain to the top docshell that doesn't have // a system principal while (NS_SUCCEEDED(curDocShellItem->GetParent(getter_AddRefs(parentDocShellItem))) && parentDocShellItem) { bool system = false; topDoc = do_GetInterface(parentDocShellItem); if (topDoc) { if (NS_SUCCEEDED(ssm->IsSystemPrincipal(topDoc->NodePrincipal(), &system)) && system) { break; } } else { return false; } curDocShellItem = parentDocShellItem; } // If this document has the top non-SystemPrincipal docshell it is not being // framed or it is being framed by a chrome document, which we allow. if (curDocShellItem == thisDocShellItem) return true; // If the X-Frame-Options value is SAMEORIGIN, then the top frame in the // parent chain must be from the same origin as this document. if (xfoHeaderValue.LowerCaseEqualsLiteral("sameorigin")) { nsCOMPtr<nsIURI> uri; httpChannel->GetURI(getter_AddRefs(uri)); topDoc = do_GetInterface(curDocShellItem); nsCOMPtr<nsIURI> topUri; topDoc->NodePrincipal()->GetURI(getter_AddRefs(topUri)); rv = ssm->CheckSameOriginURI(uri, topUri, PR_TRUE); if (NS_SUCCEEDED(rv)) return true; } else { // If the value of the header is DENY, then the document // should never be permitted to load as a subdocument. NS_ASSERTION(xfoHeaderValue.LowerCaseEqualsLiteral("deny"), "How did we get here with some random header value?"); } // cancel the load and display about:blank httpChannel->Cancel(NS_BINDING_ABORTED); nsCOMPtr<nsIWebNavigation> webNav(do_QueryObject(mDocShell)); if (webNav) { webNav->LoadURI(NS_LITERAL_STRING("about:blank").get(), 0, nsnull, nsnull, nsnull); } return false; } return true; }
void MediaEngineTabVideoSource::Draw() { nsIntSize size(mBufW, mBufH); nsresult rv; float scale = 1.0; nsCOMPtr<nsPIDOMWindow> win = do_QueryInterface(mWindow); if (!win) { return; } // take a screenshot, as wide as possible, proportional to the destination size nsCOMPtr<nsIDOMWindowUtils> utils = do_GetInterface(win); if (!utils) { return; } nsCOMPtr<nsIDOMClientRect> rect; rv = utils->GetRootBounds(getter_AddRefs(rect)); NS_ENSURE_SUCCESS_VOID(rv); if (!rect) { return; } float left, top, width, height; rect->GetLeft(&left); rect->GetTop(&top); rect->GetWidth(&width); rect->GetHeight(&height); if (width == 0 || height == 0) { return; } int32_t srcX = left; int32_t srcY = top; int32_t srcW; int32_t srcH; float aspectRatio = ((float) size.width) / size.height; if (width / aspectRatio < height) { srcW = width; srcH = width / aspectRatio; } else { srcW = height * aspectRatio; srcH = height; } nsRefPtr<nsPresContext> presContext; nsIDocShell* docshell = win->GetDocShell(); if (docshell) { docshell->GetPresContext(getter_AddRefs(presContext)); } if (!presContext) { return; } nscolor bgColor = NS_RGB(255, 255, 255); nsCOMPtr<nsIPresShell> presShell = presContext->PresShell(); uint32_t renderDocFlags = (nsIPresShell::RENDER_IGNORE_VIEWPORT_SCROLLING | nsIPresShell::RENDER_DOCUMENT_RELATIVE); nsRect r(nsPresContext::CSSPixelsToAppUnits(srcX / scale), nsPresContext::CSSPixelsToAppUnits(srcY / scale), nsPresContext::CSSPixelsToAppUnits(srcW / scale), nsPresContext::CSSPixelsToAppUnits(srcH / scale)); gfxImageFormat format = gfxImageFormatRGB24; uint32_t stride = gfxASurface::FormatStrideForWidth(format, size.width); nsRefPtr<layers::ImageContainer> container = layers::LayerManager::CreateImageContainer(); nsRefPtr<gfxASurface> surf; surf = new gfxImageSurface(static_cast<unsigned char*>(mData), size, stride, format); if (surf->CairoStatus() != 0) { return; } nsRefPtr<gfxContext> context = new gfxContext(surf); gfxPoint pt(0, 0); context->Translate(pt); context->Scale(scale * size.width / srcW, scale * size.height / srcH); rv = presShell->RenderDocument(r, renderDocFlags, bgColor, context); NS_ENSURE_SUCCESS_VOID(rv); layers::CairoImage::Data cairoData; cairoData.mSurface = surf; cairoData.mSize = size; nsRefPtr<layers::CairoImage> image = new layers::CairoImage(); image->SetData(cairoData); MonitorAutoLock mon(mMonitor); mImage = image; }
nsresult XRemoteService::OpenURL(nsCString &aArgument, nsIDOMWindow *aParent, PRBool aOpenBrowser) { // the eventual toplevel target of the load nsCOMPtr<nsIDOMWindowInternal> finalWindow = do_QueryInterface(aParent); // see if there's a new-window or new-tab argument on the end nsCString lastArgument; PRBool newWindow = PR_FALSE, newTab = PR_FALSE; PRUint32 index = 0; FindLastInList(aArgument, lastArgument, &index); newTab = lastArgument.LowerCaseEqualsLiteral("new-tab"); if (newTab || lastArgument.LowerCaseEqualsLiteral("new-window")) { aArgument.Truncate(index); // only open new windows if it's OK to do so if (!newTab && aOpenBrowser) newWindow = PR_TRUE; // recheck for a possible noraise argument since it might have // been before the new-window argument FindLastInList(aArgument, lastArgument, &index); if (lastArgument.LowerCaseEqualsLiteral("noraise")) aArgument.Truncate(index); } nsCOMPtr<nsIBrowserDOMWindow> bwin; // If it's OK to open a new browser window and a new window flag // wasn't passed in then try to find a current window. If that's // not found then go ahead and open a new window. // If we're trying to open a new tab, we'll fall back to opening // a new window if there's no browser window open, so look for it // here. if (aOpenBrowser && (!newWindow || newTab)) { nsCOMPtr<nsIDOMWindowInternal> lastUsedWindow; FindWindow(NS_LITERAL_STRING("navigator:browser").get(), getter_AddRefs(lastUsedWindow)); if (lastUsedWindow) { finalWindow = lastUsedWindow; nsCOMPtr<nsIWebNavigation> navNav(do_GetInterface(finalWindow)); nsCOMPtr<nsIDocShellTreeItem> navItem(do_QueryInterface(navNav)); if (navItem) { nsCOMPtr<nsIDocShellTreeItem> rootItem; navItem->GetRootTreeItem(getter_AddRefs(rootItem)); nsCOMPtr<nsIDOMWindow> rootWin(do_GetInterface(rootItem)); nsCOMPtr<nsIDOMChromeWindow> chromeWin(do_QueryInterface(rootWin)); if (chromeWin) chromeWin->GetBrowserDOMWindow(getter_AddRefs(bwin)); } } if (!finalWindow || !bwin) newWindow = PR_TRUE; } // check if we can handle this type of URL if (!MayOpenURL(aArgument)) return NS_ERROR_ABORT; nsresult rv = NS_OK; // try to fixup the argument passed in nsString url; url.AssignWithConversion(aArgument.get()); nsCOMPtr<nsIURI> uri; NS_NewURI(getter_AddRefs(uri), url); if (newWindow) { nsXPIDLCString urlString; GetBrowserLocation(getter_Copies(urlString)); if (!urlString) return NS_ERROR_FAILURE; nsCOMPtr<nsISupportsString> arg; arg = do_CreateInstance(NS_SUPPORTS_STRING_CONTRACTID); if (!arg) return NS_ERROR_FAILURE; // save the url into the string object arg->SetData(url); nsCOMPtr<nsIDOMWindow> window; rv = OpenChromeWindow(finalWindow, urlString, "chrome,all,dialog=no", arg, getter_AddRefs(window)); } // if no new window flag was set but there's no parent then we have // to pass everything off to the uri loader else if (!finalWindow) { nsCOMPtr<nsIURILoader> loader; loader = do_GetService(NS_URI_LOADER_CONTRACTID); if (!loader) return NS_ERROR_FAILURE; XRemoteContentListener *listener; listener = new XRemoteContentListener(); if (!listener) return NS_ERROR_FAILURE; // we own it NS_ADDREF(listener); nsCOMPtr<nsISupports> listenerRef; listenerRef = do_QueryInterface(static_cast<nsIURIContentListener *> (listener)); // now the listenerref is the only reference NS_RELEASE(listener); // double-check our uri object if (!uri) return NS_ERROR_FAILURE; // open a channel nsCOMPtr<nsIChannel> channel; rv = NS_NewChannel(getter_AddRefs(channel), uri); if (NS_FAILED(rv)) return NS_ERROR_FAILURE; // load it rv = loader->OpenURI(channel, PR_TRUE, listener); } else if (newTab && aOpenBrowser) { if (bwin && uri) { nsCOMPtr<nsIDOMWindow> container; rv = bwin->OpenURI(uri, 0, nsIBrowserDOMWindow::OPEN_NEWTAB, nsIBrowserDOMWindow::OPEN_EXTERNAL, getter_AddRefs(container)); } else { NS_ERROR("failed to open remote URL in new tab"); return NS_ERROR_FAILURE; } } else if (bwin && uri) { // unspecified new browser URL; use prefs nsCOMPtr<nsIDOMWindow> container; rv = bwin->OpenURI(uri, 0, nsIBrowserDOMWindow::OPEN_DEFAULTWINDOW, nsIBrowserDOMWindow::OPEN_EXTERNAL, getter_AddRefs(container)); if (NS_SUCCEEDED(rv)) return NS_OK; } else { // non-browser URLs // find the primary content shell for the window that we've been // asked to load into. nsCOMPtr<nsPIDOMWindow> win(do_QueryInterface(finalWindow)); if (!win) { NS_WARNING("Failed to get script object for browser instance"); return NS_ERROR_FAILURE; } nsCOMPtr<nsIDocShell> docShell = win->GetDocShell(); if (!docShell) { NS_WARNING("Failed to get docshell object for browser instance"); return NS_ERROR_FAILURE; } nsCOMPtr<nsIDocShellTreeItem> item(do_QueryInterface(docShell)); if (!item) { NS_WARNING("failed to get doc shell tree item for browser instance"); return NS_ERROR_FAILURE; } nsCOMPtr<nsIDocShellTreeOwner> treeOwner; item->GetTreeOwner(getter_AddRefs(treeOwner)); if (!treeOwner) { NS_WARNING("failed to get tree owner"); return NS_ERROR_FAILURE; } nsCOMPtr<nsIDocShellTreeItem> primaryContent; treeOwner->GetPrimaryContentShell(getter_AddRefs(primaryContent)); docShell = do_QueryInterface(primaryContent); if (!docShell) { NS_WARNING("failed to get docshell from primary content item"); return NS_ERROR_FAILURE; } nsCOMPtr<nsIWebNavigation> webNav; webNav = do_GetInterface(docShell); if (!webNav) { NS_WARNING("failed to get web nav from inner docshell"); return NS_ERROR_FAILURE; } rv = webNav->LoadURI(url.get(), nsIWebNavigation::LOAD_FLAGS_NONE, nsnull, nsnull, nsnull); } return rv; }
NS_IMETHODIMP nsLocation::SetHref(const nsAString& aHref) { nsAutoString oldHref; nsresult rv = NS_OK; JSContext *cx = nsContentUtils::GetCurrentJSContext(); // According to HTML5 spec, |location.href = ...| must act as if // it were |location.replace(...)| before the page load finishes. // // http://www.w3.org/TR/2011/WD-html5-20110113/history.html#location // // > The href attribute must return the current address of the // > associated Document object, as an absolute URL. // > // > On setting, if the Location object's associated Document // > object has completely loaded, then the user agent must act // > as if the assign() method had been called with the new value // > as its argument. Otherwise, the user agent must act as if // > the replace() method had been called with the new value as its // > argument. // // Note: The spec says the condition is "Document object has completely // loaded", but that may break some websites. If the user was // willing to move from one page to another, and was able to do // so, we should not overwrite the session history entry even // if the loading has not finished yet. // // https://www.w3.org/Bugs/Public/show_bug.cgi?id=17041 // // See bug 39938, bug 72197, bug 178729 and bug 754029. // About other browsers: // http://lists.whatwg.org/pipermail/whatwg-whatwg.org/2010-July/027372.html bool replace = false; if (!nsEventStateManager::IsHandlingUserInput()) { // "completely loaded" is defined at: // // http://www.w3.org/TR/2012/WD-html5-20120329/the-end.html#completely-loaded // // > 7. document readiness to "complete", and fire "load". // > // > 8. "pageshow" // > // > 9. ApplicationCache // > // > 10. Print in the pending list. // > // > 12. Queue a task to mark the Document as completely loaded. // // Since Gecko doesn't (yet) have a flag corresponding to no. "12. // ... completely loaded", here the logic is a little tricky. nsCOMPtr<nsIDocShell> docShell(do_QueryReferent(mDocShell)); nsCOMPtr<nsIDocument> document(do_GetInterface(docShell)); if (document) { replace = nsIDocument::READYSTATE_COMPLETE != document->GetReadyStateEnum(); // nsIDocShell::isExecutingOnLoadHandler is true while // the document is handling "load", "pageshow", // "readystatechange" for "complete" and "beforeprint"/"afterprint". // // Maybe this API property needs a better name. if (!replace) { docShell->GetIsExecutingOnLoadHandler(&replace); } } } if (cx) { rv = SetHrefWithContext(cx, aHref, replace); } else { rv = GetHref(oldHref); if (NS_SUCCEEDED(rv)) { nsCOMPtr<nsIURI> oldUri; rv = NS_NewURI(getter_AddRefs(oldUri), oldHref); if (oldUri) { rv = SetHrefWithBase(aHref, oldUri, replace); } } } return rv; }
NS_IMETHODIMP nsNSSDialogs::ChooseCertificate(nsIInterfaceRequestor* ctx, const char16_t* cn, const char16_t* organization, const char16_t* issuer, const char16_t** certNickList, const char16_t** certDetailsList, uint32_t count, int32_t* selectedIndex, bool* canceled) { nsresult rv; uint32_t i; *canceled = false; // Get the parent window for the dialog nsCOMPtr<nsIDOMWindow> parent = do_GetInterface(ctx); nsCOMPtr<nsIDialogParamBlock> block = do_CreateInstance(NS_DIALOGPARAMBLOCK_CONTRACTID); if (!block) return NS_ERROR_FAILURE; block->SetNumberStrings(4+count*2); rv = block->SetString(0, cn); if (NS_FAILED(rv)) return rv; rv = block->SetString(1, organization); if (NS_FAILED(rv)) return rv; rv = block->SetString(2, issuer); if (NS_FAILED(rv)) return rv; for (i = 0; i < count; i++) { rv = block->SetString(i+3, certNickList[i]); if (NS_FAILED(rv)) return rv; } for (i = 0; i < count; i++) { rv = block->SetString(i+count+3, certDetailsList[i]); if (NS_FAILED(rv)) return rv; } rv = block->SetInt(0, count); if (NS_FAILED(rv)) return rv; rv = nsNSSDialogHelper::openDialog(nullptr, "chrome://pippki/content/clientauthask.xul", block); if (NS_FAILED(rv)) return rv; int32_t status; rv = block->GetInt(0, &status); if (NS_FAILED(rv)) return rv; nsCOMPtr<nsIClientAuthUserDecision> extraResult = do_QueryInterface(ctx); if (extraResult) { int32_t rememberSelection; rv = block->GetInt(2, &rememberSelection); if (NS_SUCCEEDED(rv)) { extraResult->SetRememberClientAuthCertificate(rememberSelection!=0); } } *canceled = (status == 0)?true:false; if (!*canceled) { // retrieve the nickname rv = block->GetInt(1, selectedIndex); } return rv; }
nsLocation::nsLocation(nsIDocShell *aDocShell) { mDocShell = do_GetWeakReference(aDocShell); nsCOMPtr<nsIDOMWindow> outer = do_GetInterface(aDocShell); mOuter = do_GetWeakReference(outer); }
NS_IMETHODIMP nsFormSigningDialog::ConfirmSignText(nsIInterfaceRequestor *aContext, const nsAString &aHost, const nsAString &aSignText, const PRUnichar **aCertNickList, const PRUnichar **aCertDetailsList, PRUint32 aCount, PRInt32 *aSelectedIndex, nsAString &aPassword, bool *aCanceled) { *aCanceled = true; // Get the parent window for the dialog nsCOMPtr<nsIDOMWindow> parent = do_GetInterface(aContext); nsresult rv; nsCOMPtr<nsIDialogParamBlock> block = do_CreateInstance(NS_DIALOGPARAMBLOCK_CONTRACTID, &rv); NS_ENSURE_SUCCESS(rv, rv); block->SetNumberStrings(3 + aCount * 2); rv = block->SetString(0, PromiseFlatString(aHost).get()); NS_ENSURE_SUCCESS(rv, rv); rv = block->SetString(1, PromiseFlatString(aSignText).get()); NS_ENSURE_SUCCESS(rv, rv); PRUint32 i; for (i = 0; i < aCount; ++i) { rv = block->SetString(2 + 2 * i, aCertNickList[i]); NS_ENSURE_SUCCESS(rv, rv); rv = block->SetString(2 + (2 * i + 1), aCertDetailsList[i]); NS_ENSURE_SUCCESS(rv, rv); } rv = block->SetInt(0, aCount); NS_ENSURE_SUCCESS(rv, rv); rv = nsNSSDialogHelper::openDialog(parent, "chrome://pippki/content/formsigning.xul", block); NS_ENSURE_SUCCESS(rv, rv); PRInt32 status; rv = block->GetInt(0, &status); NS_ENSURE_SUCCESS(rv, rv); if (status == 0) { *aCanceled = true; } else { *aCanceled = false; rv = block->GetInt(1, aSelectedIndex); NS_ENSURE_SUCCESS(rv, rv); nsXPIDLString pw; rv = block->GetString(0, getter_Copies(pw)); NS_ENSURE_SUCCESS(rv, rv); aPassword = pw; } return NS_OK; }
NS_IMETHODIMP nsHTTPIndex::OnStartRequest(nsIRequest *request, nsISupports* aContext) { nsresult rv; mParser = do_CreateInstance(NS_DIRINDEXPARSER_CONTRACTID, &rv); if (NS_FAILED(rv)) return rv; rv = mParser->SetEncoding(mEncoding.get()); if (NS_FAILED(rv)) return rv; rv = mParser->SetListener(this); if (NS_FAILED(rv)) return rv; rv = mParser->OnStartRequest(request,aContext); if (NS_FAILED(rv)) return rv; // This should only run once... // Unless we don't have a container to start with // (ie called from bookmarks as an rdf datasource) if (mBindToGlobalObject && mRequestor) { mBindToGlobalObject = PR_FALSE; // Now get the content viewer container's script object. nsCOMPtr<nsIScriptGlobalObject> scriptGlobal(do_GetInterface(mRequestor)); NS_ENSURE_TRUE(scriptGlobal, NS_ERROR_FAILURE); nsIScriptContext *context = scriptGlobal->GetContext(); NS_ENSURE_TRUE(context, NS_ERROR_FAILURE); JSContext* cx = reinterpret_cast<JSContext*> (context->GetNativeContext()); JSObject* global = JS_GetGlobalObject(cx); // Using XPConnect, wrap the HTTP index object... static NS_DEFINE_CID(kXPConnectCID, NS_XPCONNECT_CID); nsCOMPtr<nsIXPConnect> xpc(do_GetService(kXPConnectCID, &rv)); if (NS_FAILED(rv)) return rv; nsCOMPtr<nsIXPConnectJSObjectHolder> wrapper; rv = xpc->WrapNative(cx, global, static_cast<nsIHTTPIndex*>(this), NS_GET_IID(nsIHTTPIndex), getter_AddRefs(wrapper)); NS_ASSERTION(NS_SUCCEEDED(rv), "unable to xpconnect-wrap http-index"); if (NS_FAILED(rv)) return rv; JSObject* jsobj; rv = wrapper->GetJSObject(&jsobj); NS_ASSERTION(NS_SUCCEEDED(rv), "unable to get jsobj from xpconnect wrapper"); if (NS_FAILED(rv)) return rv; jsval jslistener = OBJECT_TO_JSVAL(jsobj); // ...and stuff it into the global context PRBool ok; JSAutoRequest ar(cx); ok = JS_SetProperty(cx, global, "HTTPIndex", &jslistener); NS_ASSERTION(ok, "unable to set Listener property"); if (! ok) return NS_ERROR_FAILURE; } if (!aContext) { nsCOMPtr<nsIChannel> channel(do_QueryInterface(request)); NS_ASSERTION(channel, "request should be a channel"); // lets hijack the notifications: channel->SetNotificationCallbacks(this); // now create the top most resource nsCOMPtr<nsIURI> uri; channel->GetURI(getter_AddRefs(uri)); nsCAutoString entryuriC; uri->GetSpec(entryuriC); nsCOMPtr<nsIRDFResource> entry; rv = mDirRDF->GetResource(entryuriC, getter_AddRefs(entry)); NS_ConvertUTF8toUTF16 uriUnicode(entryuriC); nsCOMPtr<nsIRDFLiteral> URLVal; rv = mDirRDF->GetLiteral(uriUnicode.get(), getter_AddRefs(URLVal)); Assert(entry, kNC_URL, URLVal, PR_TRUE); mDirectory = do_QueryInterface(entry); } else { // Get the directory from the context mDirectory = do_QueryInterface(aContext); } if (!mDirectory) { request->Cancel(NS_BINDING_ABORTED); return NS_BINDING_ABORTED; } // Mark the directory as "loading" rv = Assert(mDirectory, kNC_Loading, kTrueLiteral, PR_TRUE); if (NS_FAILED(rv)) return rv; return NS_OK; }
// // FUNCTION: BrowserDlgProc() // // PURPOSE: Browser dialog windows message handler. // // COMMENTS: // // The code for handling buttons and menu actions is here. // BOOL CALLBACK BrowserDlgProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) { // Get the browser and other pointers since they are used a lot below HWND hwndBrowser = GetDlgItem(hwndDlg, IDC_BROWSER); nsIWebBrowserChrome *chrome = nsnull ; if (hwndBrowser) { chrome = (nsIWebBrowserChrome *) GetWindowLong(hwndBrowser, GWL_USERDATA); } nsCOMPtr<nsIWebBrowser> webBrowser; nsCOMPtr<nsIWebNavigation> webNavigation; nsCOMPtr<nsIWebBrowserPrint> webBrowserPrint; if (chrome) { chrome->GetWebBrowser(getter_AddRefs(webBrowser)); webNavigation = do_QueryInterface(webBrowser); webBrowserPrint = do_GetInterface(webBrowser); } // Test the message switch (uMsg) { case WM_INITDIALOG: return TRUE; case WM_INITMENU: UpdateUI(chrome); return TRUE; case WM_SYSCOMMAND: if (wParam == SC_CLOSE) { WebBrowserChromeUI::Destroy(chrome); return TRUE; } break; case WM_DESTROY: return TRUE; case WM_COMMAND: if (!webBrowser) { return TRUE; } // Test which command was selected switch (LOWORD(wParam)) { case IDC_ADDRESS: if (HIWORD(wParam) == CBN_EDITCHANGE || HIWORD(wParam) == CBN_SELCHANGE) { // User has changed the address field so enable the Go button EnableWindow(GetDlgItem(hwndDlg, IDC_GO), TRUE); } break; case IDC_GO: { TCHAR szURL[2048]; memset(szURL, 0, sizeof(szURL)); GetDlgItemText(hwndDlg, IDC_ADDRESS, szURL, sizeof(szURL) / sizeof(szURL[0]) - 1); webNavigation->LoadURI( NS_ConvertASCIItoUCS2(szURL).get(), nsIWebNavigation::LOAD_FLAGS_NONE, nsnull, nsnull, nsnull); } break; case IDC_STOP: webNavigation->Stop(nsIWebNavigation::STOP_ALL); UpdateUI(chrome); break; case IDC_RELOAD: webNavigation->Reload(nsIWebNavigation::LOAD_FLAGS_NONE); break; case IDM_EXIT: PostMessage(hwndDlg, WM_SYSCOMMAND, SC_CLOSE, 0); break; // File menu commands case MOZ_NewBrowser: OpenWebPage(gFirstURL); break; case MOZ_Save: SaveWebPage(webBrowser); break; case MOZ_Print: { // NOTE: Embedding code shouldn't need to get the docshell or // contentviewer AT ALL. This code below will break one // day but will have to do until the embedding API has // a cleaner way to do the same thing. if (webBrowserPrint) { nsCOMPtr<nsIPrintSettings> printSettings; webBrowserPrint->GetGlobalPrintSettings(getter_AddRefs(printSettings)); NS_ASSERTION(printSettings, "You can't PrintPreview without a PrintSettings!"); if (printSettings) { printSettings->SetPrintSilent(PR_TRUE); webBrowserPrint->Print(printSettings, (nsIWebProgressListener*)nsnull); } } } break; // Edit menu commands case MOZ_Cut: { nsCOMPtr<nsIClipboardCommands> clipCmds = do_GetInterface(webBrowser); clipCmds->CutSelection(); } break; case MOZ_Copy: { nsCOMPtr<nsIClipboardCommands> clipCmds = do_GetInterface(webBrowser); clipCmds->CopySelection(); } break; case MOZ_Paste: { nsCOMPtr<nsIClipboardCommands> clipCmds = do_GetInterface(webBrowser); clipCmds->Paste(); } break; case MOZ_SelectAll: { nsCOMPtr<nsIClipboardCommands> clipCmds = do_GetInterface(webBrowser); clipCmds->SelectAll(); } break; case MOZ_SelectNone: { nsCOMPtr<nsIClipboardCommands> clipCmds = do_GetInterface(webBrowser); clipCmds->SelectNone(); } break; // Go menu commands case IDC_BACK: case MOZ_GoBack: webNavigation->GoBack(); UpdateUI(chrome); break; case IDC_FORWARD: case MOZ_GoForward: webNavigation->GoForward(); UpdateUI(chrome); break; // Help menu commands case MOZ_About: { TCHAR szAboutTitle[MAX_LOADSTRING]; TCHAR szAbout[MAX_LOADSTRING]; LoadString(ghInstanceResources, IDS_ABOUT_TITLE, szAboutTitle, MAX_LOADSTRING); LoadString(ghInstanceResources, IDS_ABOUT, szAbout, MAX_LOADSTRING); MessageBox(NULL, szAbout, szAboutTitle, MB_OK); } break; } return TRUE; case WM_ACTIVATE: { nsCOMPtr<nsIWebBrowserFocus> focus(do_GetInterface(webBrowser)); if(focus) { switch (wParam) { case WA_ACTIVE: focus->Activate(); break; case WA_INACTIVE: focus->Deactivate(); break; default: break; } } } break; case WM_SIZE: { UINT newDlgWidth = LOWORD(lParam); UINT newDlgHeight = HIWORD(lParam); // TODO Reposition the control bar - for the moment it's fixed size // Reposition the status area. Status bar // gets any space that the fixed size progress bar doesn't use. int progressWidth; int statusWidth; int statusHeight; HWND hwndStatus = GetDlgItem(hwndDlg, IDC_STATUS); if (hwndStatus) { RECT rcStatus; GetWindowRect(hwndStatus, &rcStatus); statusHeight = rcStatus.bottom - rcStatus.top; } else statusHeight = 0; HWND hwndProgress = GetDlgItem(hwndDlg, IDC_PROGRESS); if (hwndProgress) { RECT rcProgress; GetWindowRect(hwndProgress, &rcProgress); progressWidth = rcProgress.right - rcProgress.left; } else progressWidth = 0; statusWidth = newDlgWidth - progressWidth; if (hwndStatus) SetWindowPos(hwndStatus, HWND_TOP, 0, newDlgHeight - statusHeight, statusWidth, statusHeight, SWP_NOZORDER); if (hwndProgress) SetWindowPos(hwndProgress, HWND_TOP, statusWidth, newDlgHeight - statusHeight, 0, 0, SWP_NOSIZE | SWP_NOZORDER); // Resize the browser area (assuming the browse is // sandwiched between the control bar and status area) RECT rcBrowser; POINT ptBrowser; GetWindowRect(hwndBrowser, &rcBrowser); ptBrowser.x = rcBrowser.left; ptBrowser.y = rcBrowser.top; ScreenToClient(hwndDlg, &ptBrowser); int browserHeight = newDlgHeight - ptBrowser.y - statusHeight; if (browserHeight < 1) { browserHeight = 1; } SetWindowPos(hwndBrowser, HWND_TOP, 0, 0, newDlgWidth, newDlgHeight - ptBrowser.y - statusHeight, SWP_NOMOVE | SWP_NOZORDER); } return TRUE; } return FALSE; }
NS_IMETHODIMP nsAbContentHandler::HandleContent(const char *aContentType, nsIInterfaceRequestor *aWindowContext, nsIRequest *request) { NS_ENSURE_ARG_POINTER(request); nsresult rv = NS_OK; // First of all, get the content type and make sure it is a content type we know how to handle! if (PL_strcasecmp(aContentType, "application/x-addvcard") == 0) { nsCOMPtr<nsIURI> uri; nsCOMPtr<nsIChannel> aChannel = do_QueryInterface(request); if (!aChannel) return NS_ERROR_FAILURE; rv = aChannel->GetURI(getter_AddRefs(uri)); if (uri) { nsCAutoString path; rv = uri->GetPath(path); NS_ENSURE_SUCCESS(rv,rv); const char *startOfVCard = strstr(path.get(), "add?vcard="); if (startOfVCard) { nsCString unescapedData; // XXX todo, explain why we is escaped twice MsgUnescapeString(nsDependentCString(startOfVCard + strlen("add?vcard=")), 0, unescapedData); if (!aWindowContext) return NS_ERROR_FAILURE; nsCOMPtr<nsIDOMWindow> parentWindow = do_GetInterface(aWindowContext); if (!parentWindow) return NS_ERROR_FAILURE; nsCOMPtr<nsIAbManager> ab = do_GetService(NS_ABMANAGER_CONTRACTID, &rv); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr <nsIAbCard> cardFromVCard; rv = ab->EscapedVCardToAbCard(unescapedData.get(), getter_AddRefs(cardFromVCard)); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr<nsISupportsInterfacePointer> ifptr = do_CreateInstance(NS_SUPPORTS_INTERFACE_POINTER_CONTRACTID, &rv); NS_ENSURE_SUCCESS(rv, rv); ifptr->SetData(cardFromVCard); ifptr->SetDataIID(&NS_GET_IID(nsIAbCard)); nsCOMPtr<nsIDOMWindow> dialogWindow; rv = parentWindow->OpenDialog( NS_LITERAL_STRING("chrome://messenger/content/addressbook/abNewCardDialog.xul"), EmptyString(), NS_LITERAL_STRING("chrome,resizable=no,titlebar,modal,centerscreen"), ifptr, getter_AddRefs(dialogWindow)); NS_ENSURE_SUCCESS(rv, rv); } rv = NS_OK; } } else if (PL_strcasecmp(aContentType, "text/x-vcard") == 0) { // create a vcard stream listener that can parse the data stream // and bring up the appropriate UI // (1) cancel the current load operation. We'll restart it request->Cancel(NS_ERROR_ABORT); // get the url we were trying to open nsCOMPtr<nsIURI> uri; nsCOMPtr<nsIChannel> channel = do_QueryInterface(request); NS_ENSURE_TRUE(channel, NS_ERROR_FAILURE); rv = channel->GetURI(getter_AddRefs(uri)); NS_ENSURE_SUCCESS(rv, rv); // create a stream loader to handle the v-card data nsCOMPtr<nsIStreamLoader> streamLoader; rv = NS_NewStreamLoader(getter_AddRefs(streamLoader), uri, this, aWindowContext); NS_ENSURE_SUCCESS(rv, rv); } else // The content-type was not application/x-addvcard... return NS_ERROR_WONT_HANDLE_CONTENT; return rv; }