NS_IMETHODIMP XULContentSinkImpl::HandleStartElement(const PRUnichar *aName, const PRUnichar **aAtts, uint32_t aAttsCount, int32_t aIndex, uint32_t aLineNumber) { // XXX Hopefully the parser will flag this before we get here. If // we're in the epilog, there should be no new elements NS_PRECONDITION(mState != eInEpilog, "tag in XUL doc epilog"); NS_PRECONDITION(aIndex >= -1, "Bogus aIndex"); NS_PRECONDITION(aAttsCount % 2 == 0, "incorrect aAttsCount"); // Adjust aAttsCount so it's the actual number of attributes aAttsCount /= 2; if (mState == eInEpilog) return NS_ERROR_UNEXPECTED; if (mState != eInScript) { FlushText(); } int32_t nameSpaceID; nsCOMPtr<nsIAtom> prefix, localName; nsContentUtils::SplitExpatName(aName, getter_AddRefs(prefix), getter_AddRefs(localName), &nameSpaceID); nsCOMPtr<nsINodeInfo> nodeInfo; nodeInfo = mNodeInfoManager->GetNodeInfo(localName, prefix, nameSpaceID, nsIDOMNode::ELEMENT_NODE); NS_ENSURE_TRUE(nodeInfo, NS_ERROR_OUT_OF_MEMORY); nsresult rv = NS_OK; switch (mState) { case eInProlog: // We're the root document element rv = OpenRoot(aAtts, aAttsCount, nodeInfo); break; case eInDocumentElement: rv = OpenTag(aAtts, aAttsCount, aLineNumber, nodeInfo); break; case eInEpilog: case eInScript: PR_LOG(gLog, PR_LOG_WARNING, ("xul: warning: unexpected tags in epilog at line %d", aLineNumber)); rv = NS_ERROR_UNEXPECTED; // XXX break; } // Set the ID attribute atom on the node info object for this node if (aIndex != -1 && NS_SUCCEEDED(rv)) { nsCOMPtr<nsIAtom> IDAttr = do_GetAtom(aAtts[aIndex]); if (IDAttr) { nodeInfo->SetIDAttributeAtom(IDAttr); } } return rv; }
void nsHtml5Parser::MarkAsNotScriptCreated() { NS_PRECONDITION(!mStreamParser, "Must not call this twice."); mStreamParser = new nsHtml5StreamParser(mExecutor, this); }
NS_IMETHODIMP nsViewManager::InsertChild(nsIView *aParent, nsIView *aChild, nsIView *aSibling, bool aAfter) { nsView* parent = static_cast<nsView*>(aParent); nsView* child = static_cast<nsView*>(aChild); nsView* sibling = static_cast<nsView*>(aSibling); NS_PRECONDITION(nullptr != parent, "null ptr"); NS_PRECONDITION(nullptr != child, "null ptr"); NS_ASSERTION(sibling == nullptr || sibling->GetParent() == parent, "tried to insert view with invalid sibling"); NS_ASSERTION(!IsViewInserted(child), "tried to insert an already-inserted view"); if ((nullptr != parent) && (nullptr != child)) { // if aAfter is set, we will insert the child after 'prev' (i.e. after 'kid' in document // order, otherwise after 'kid' (i.e. before 'kid' in document order). #if 1 if (nullptr == aSibling) { if (aAfter) { // insert at end of document order, i.e., before first view // this is the common case, by far parent->InsertChild(child, nullptr); ReparentWidgets(child, parent); } else { // insert at beginning of document order, i.e., after last view nsView *kid = parent->GetFirstChild(); nsView *prev = nullptr; while (kid) { prev = kid; kid = kid->GetNextSibling(); } // prev is last view or null if there are no children parent->InsertChild(child, prev); ReparentWidgets(child, parent); } } else { nsView *kid = parent->GetFirstChild(); nsView *prev = nullptr; while (kid && sibling != kid) { //get the next sibling view prev = kid; kid = kid->GetNextSibling(); } NS_ASSERTION(kid != nullptr, "couldn't find sibling in child list"); if (aAfter) { // insert after 'kid' in document order, i.e. before in view order parent->InsertChild(child, prev); ReparentWidgets(child, parent); } else { // insert before 'kid' in document order, i.e. after in view order parent->InsertChild(child, kid); ReparentWidgets(child, parent); } } #else // don't keep consistent document order, but order things by z-index instead // essentially we're emulating the old InsertChild(parent, child, zindex) PRInt32 zIndex = child->GetZIndex(); while (nullptr != kid) { PRInt32 idx = kid->GetZIndex(); if (CompareZIndex(zIndex, child->IsTopMost(), child->GetZIndexIsAuto(), idx, kid->IsTopMost(), kid->GetZIndexIsAuto()) >= 0) break; prev = kid; kid = kid->GetNextSibling(); } parent->InsertChild(child, prev); ReparentWidgets(child, parent); #endif // if the parent view is marked as "floating", make the newly added view float as well. if (parent->GetFloating()) child->SetFloating(true); //and mark this area as dirty if the view is visible... if (nsViewVisibility_kHide != child->GetVisibility()) child->GetViewManager()->InvalidateView(child); } return NS_OK; }
/** * Handle 'in', 'inout', and 'out' params */ nsresult nsJavaXPTCStub::SetupJavaParams(const nsXPTParamInfo &aParamInfo, const XPTMethodDescriptor* aMethodInfo, PRUint16 aMethodIndex, nsXPTCMiniVariant* aDispatchParams, nsXPTCMiniVariant &aVariant, jvalue &aJValue, nsACString &aMethodSig) { nsresult rv = NS_OK; JNIEnv* env = GetJNIEnv(); const nsXPTType &type = aParamInfo.GetType(); PRUint8 tag = type.TagPart(); switch (tag) { case nsXPTType::T_I8: { if (!aParamInfo.IsOut()) { // 'in' aJValue.b = aVariant.val.i8; aMethodSig.Append('B'); } else { // 'inout' & 'out' if (aVariant.val.p) { jbyteArray array = env->NewByteArray(1); if (!array) { rv = NS_ERROR_OUT_OF_MEMORY; break; } env->SetByteArrayRegion(array, 0, 1, (jbyte*) aVariant.val.p); aJValue.l = array; } else { aJValue.l = nsnull; } aMethodSig.AppendLiteral("[B"); } } break; case nsXPTType::T_I16: case nsXPTType::T_U8: { if (!aParamInfo.IsOut()) { // 'in' aJValue.s = (tag == nsXPTType::T_I16) ? aVariant.val.i16 : aVariant.val.u8; aMethodSig.Append('S'); } else { // 'inout' & 'out' if (aVariant.val.p) { jshortArray array = env->NewShortArray(1); if (!array) { rv = NS_ERROR_OUT_OF_MEMORY; break; } env->SetShortArrayRegion(array, 0, 1, (jshort*) aVariant.val.p); aJValue.l = array; } else { aJValue.l = nsnull; } aMethodSig.AppendLiteral("[S"); } } break; case nsXPTType::T_I32: case nsXPTType::T_U16: { if (!aParamInfo.IsOut()) { // 'in' aJValue.i = (tag == nsXPTType::T_I32) ? aVariant.val.i32 : aVariant.val.u16; aMethodSig.Append('I'); } else { // 'inout' & 'out' if (aVariant.val.p) { jintArray array = env->NewIntArray(1); if (!array) { rv = NS_ERROR_OUT_OF_MEMORY; break; } env->SetIntArrayRegion(array, 0, 1, (jint*) aVariant.val.p); aJValue.l = array; } else { aJValue.l = nsnull; } aMethodSig.AppendLiteral("[I"); } } break; case nsXPTType::T_I64: case nsXPTType::T_U32: { if (!aParamInfo.IsOut()) { // 'in' aJValue.j = (tag == nsXPTType::T_I64) ? aVariant.val.i64 : aVariant.val.u32; aMethodSig.Append('J'); } else { // 'inout' & 'out' if (aVariant.val.p) { jlongArray array = env->NewLongArray(1); if (!array) { rv = NS_ERROR_OUT_OF_MEMORY; break; } env->SetLongArrayRegion(array, 0, 1, (jlong*) aVariant.val.p); aJValue.l = array; } else { aJValue.l = nsnull; } aMethodSig.AppendLiteral("[J"); } } break; case nsXPTType::T_FLOAT: { if (!aParamInfo.IsOut()) { // 'in' aJValue.f = aVariant.val.f; aMethodSig.Append('F'); } else { // 'inout' & 'out' if (aVariant.val.p) { jfloatArray array = env->NewFloatArray(1); if (!array) { rv = NS_ERROR_OUT_OF_MEMORY; break; } env->SetFloatArrayRegion(array, 0, 1, (jfloat*) aVariant.val.p); aJValue.l = array; } else { aJValue.l = nsnull; } aMethodSig.AppendLiteral("[F"); } } break; // XXX how do we handle unsigned 64-bit values? case nsXPTType::T_U64: case nsXPTType::T_DOUBLE: { if (!aParamInfo.IsOut()) { // 'in' aJValue.d = (tag == nsXPTType::T_DOUBLE) ? aVariant.val.d : aVariant.val.u64; aMethodSig.Append('D'); } else { // 'inout' & 'out' if (aVariant.val.p) { jdoubleArray array = env->NewDoubleArray(1); if (!array) { rv = NS_ERROR_OUT_OF_MEMORY; break; } env->SetDoubleArrayRegion(array, 0, 1, (jdouble*) aVariant.val.p); aJValue.l = array; } else { aJValue.l = nsnull; } aMethodSig.AppendLiteral("[D"); } } break; case nsXPTType::T_BOOL: { if (!aParamInfo.IsOut()) { // 'in' aJValue.z = aVariant.val.b; aMethodSig.Append('Z'); } else { // 'inout' & 'out' if (aVariant.val.p) { jbooleanArray array = env->NewBooleanArray(1); if (!array) { rv = NS_ERROR_OUT_OF_MEMORY; break; } env->SetBooleanArrayRegion(array, 0, 1, (jboolean*) aVariant.val.p); aJValue.l = array; } else { aJValue.l = nsnull; } aMethodSig.AppendLiteral("[Z"); } } break; case nsXPTType::T_CHAR: case nsXPTType::T_WCHAR: { if (!aParamInfo.IsOut()) { // 'in' if (tag == nsXPTType::T_CHAR) aJValue.c = aVariant.val.c; else aJValue.c = aVariant.val.wc; aMethodSig.Append('C'); } else { // 'inout' & 'out' if (aVariant.val.p) { jcharArray array = env->NewCharArray(1); if (!array) { rv = NS_ERROR_OUT_OF_MEMORY; break; } env->SetCharArrayRegion(array, 0, 1, (jchar*) aVariant.val.p); aJValue.l = array; } else { aJValue.l = nsnull; } aMethodSig.AppendLiteral("[C"); } } break; case nsXPTType::T_CHAR_STR: case nsXPTType::T_WCHAR_STR: { void* ptr = nsnull; if (!aParamInfo.IsOut()) { // 'in' ptr = aVariant.val.p; } else if (aVariant.val.p) { // 'inout' & 'out' void** variant = static_cast<void**>(aVariant.val.p); ptr = *variant; } jobject str; if (ptr) { if (tag == nsXPTType::T_CHAR_STR) { str = env->NewStringUTF((const char*) ptr); } else { const PRUnichar* buf = (const PRUnichar*) ptr; str = env->NewString(buf, nsCRT::strlen(buf)); } if (!str) { rv = NS_ERROR_OUT_OF_MEMORY; break; } } else { str = nsnull; } if (!aParamInfo.IsOut()) { // 'in' aJValue.l = str; aMethodSig.AppendLiteral("Ljava/lang/String;"); } else { // 'inout' & 'out' if (aVariant.val.p) { aJValue.l = env->NewObjectArray(1, stringClass, str); if (aJValue.l == nsnull) { rv = NS_ERROR_OUT_OF_MEMORY; break; } } else { aJValue.l = nsnull; } aMethodSig.AppendLiteral("[Ljava/lang/String;"); } } break; case nsXPTType::T_IID: { nsID* iid = nsnull; if (!aParamInfo.IsOut()) { // 'in' iid = static_cast<nsID*>(aVariant.val.p); } else if (aVariant.val.p) { // 'inout' & 'out' nsID** variant = static_cast<nsID**>(aVariant.val.p); iid = *variant; } jobject str = nsnull; if (iid) { char iid_str[NSID_LENGTH]; iid->ToProvidedString(iid_str); str = env->NewStringUTF(iid_str); if (!str) { rv = NS_ERROR_OUT_OF_MEMORY; break; } } if (!aParamInfo.IsOut()) { // 'in' aJValue.l = str; aMethodSig.AppendLiteral("Ljava/lang/String;"); } else { // 'inout' & 'out' if (aVariant.val.p) { aJValue.l = env->NewObjectArray(1, stringClass, str); if (aJValue.l == nsnull) { rv = NS_ERROR_OUT_OF_MEMORY; break; } } else { aJValue.l = nsnull; } aMethodSig.AppendLiteral("[Ljava/lang/String;"); } } break; case nsXPTType::T_INTERFACE: case nsXPTType::T_INTERFACE_IS: { nsISupports* xpcom_obj = nsnull; if (!aParamInfo.IsOut()) { // 'in' xpcom_obj = static_cast<nsISupports*>(aVariant.val.p); } else if (aVariant.val.p) { // 'inout' & 'out' nsISupports** variant = static_cast<nsISupports**>(aVariant.val.p); xpcom_obj = *variant; } nsID iid; rv = GetIIDForMethodParam(mIInfo, aMethodInfo, aParamInfo, aParamInfo.GetType().TagPart(), aMethodIndex, aDispatchParams, PR_FALSE, iid); if (NS_FAILED(rv)) break; // get name of interface char* iface_name = nsnull; nsCOMPtr<nsIInterfaceInfoManager> iim(do_GetService(NS_INTERFACEINFOMANAGER_SERVICE_CONTRACTID, &rv)); if (NS_FAILED(rv)) break; rv = iim->GetNameForIID(&iid, &iface_name); if (NS_FAILED(rv) || !iface_name) break; jobject java_stub = nsnull; if (xpcom_obj) { // Get matching Java object for given xpcom object jobject objLoader = env->CallObjectMethod(mJavaWeakRef, getReferentMID); rv = NativeInterfaceToJavaObject(env, xpcom_obj, iid, objLoader, &java_stub); if (NS_FAILED(rv)) break; } if (!aParamInfo.IsOut()) { // 'in' aJValue.l = java_stub; } else { // 'inout' & 'out' if (aVariant.val.p) { aJValue.l = env->NewObjectArray(1, nsISupportsClass, java_stub); if (aJValue.l == nsnull) { rv = NS_ERROR_OUT_OF_MEMORY; break; } } else { aJValue.l = nsnull; } aMethodSig.Append('['); } if (tag != nsXPTType::T_INTERFACE_IS) { aMethodSig.AppendLiteral("Lorg/mozilla/interfaces/"); aMethodSig.AppendASCII(iface_name); aMethodSig.Append(';'); } else { aMethodSig.AppendLiteral("Lorg/mozilla/interfaces/nsISupports;"); } nsMemory::Free(iface_name); } break; case nsXPTType::T_ASTRING: case nsXPTType::T_DOMSTRING: { // This only handle 'in' or 'in dipper' params. In XPIDL, the 'out' // descriptor is mapped to 'in dipper'. NS_PRECONDITION(aParamInfo.IsIn(), "unexpected param descriptor"); if (!aParamInfo.IsIn()) { rv = NS_ERROR_UNEXPECTED; break; } nsString* str = static_cast<nsString*>(aVariant.val.p); if (!str) { rv = NS_ERROR_FAILURE; break; } jstring jstr = nsnull; if (!str->IsVoid()) { jstr = env->NewString(str->get(), str->Length()); if (!jstr) { rv = NS_ERROR_OUT_OF_MEMORY; break; } } aJValue.l = jstr; aMethodSig.AppendLiteral("Ljava/lang/String;"); } break; case nsXPTType::T_UTF8STRING: case nsXPTType::T_CSTRING: { // This only handle 'in' or 'in dipper' params. In XPIDL, the 'out' // descriptor is mapped to 'in dipper'. NS_PRECONDITION(aParamInfo.IsIn(), "unexpected param descriptor"); if (!aParamInfo.IsIn()) { rv = NS_ERROR_UNEXPECTED; break; } nsCString* str = static_cast<nsCString*>(aVariant.val.p); if (!str) { rv = NS_ERROR_FAILURE; break; } jstring jstr = nsnull; if (!str->IsVoid()) { jstr = env->NewStringUTF(str->get()); if (!jstr) { rv = NS_ERROR_OUT_OF_MEMORY; break; } } aJValue.l = jstr; aMethodSig.AppendLiteral("Ljava/lang/String;"); } break; // Pass the 'void*' address as a long case nsXPTType::T_VOID: { if (!aParamInfo.IsOut()) { // 'in' aJValue.j = reinterpret_cast<jlong>(aVariant.val.p); aMethodSig.Append('J'); } else { // 'inout' & 'out' if (aVariant.val.p) { jlongArray array = env->NewLongArray(1); if (!array) { rv = NS_ERROR_OUT_OF_MEMORY; break; } env->SetLongArrayRegion(array, 0, 1, (jlong*) aVariant.val.p); aJValue.l = array; } else { aJValue.l = nsnull; } aMethodSig.AppendLiteral("[J"); } } break; case nsXPTType::T_ARRAY: NS_WARNING("array types are not yet supported"); return NS_ERROR_NOT_IMPLEMENTED; break; case nsXPTType::T_PSTRING_SIZE_IS: case nsXPTType::T_PWSTRING_SIZE_IS: default: NS_WARNING("unexpected parameter type"); return NS_ERROR_UNEXPECTED; } return rv; }
NS_IMETHODIMP nsHtml5Parser::Parse(const nsAString& aSourceBuffer, void* aKey, const nsACString& aContentType, // ignored bool aLastCall, nsDTDMode aMode) // ignored { NS_PRECONDITION(!mExecutor->IsFragmentMode(), "Document.write called in fragment mode!"); if (mExecutor->IsBroken()) { return NS_ERROR_OUT_OF_MEMORY; } if (aSourceBuffer.Length() > PR_INT32_MAX) { mExecutor->MarkAsBroken(); return NS_ERROR_OUT_OF_MEMORY; } // Maintain a reference to ourselves so we don't go away // till we're completely done. The old parser grips itself in this method. nsCOMPtr<nsIParser> kungFuDeathGrip(this); // Gripping the other objects just in case, since the other old grip // required grips to these, too. nsRefPtr<nsHtml5StreamParser> streamKungFuDeathGrip(mStreamParser); nsRefPtr<nsHtml5TreeOpExecutor> treeOpKungFuDeathGrip(mExecutor); if (!mExecutor->HasStarted()) { NS_ASSERTION(!mStreamParser, "Had stream parser but document.write started life cycle."); // This is the first document.write() on a document.open()ed document mExecutor->SetParser(this); mTreeBuilder->setScriptingEnabled(mExecutor->IsScriptEnabled()); mTokenizer->start(); mExecutor->Start(); /* * If you move the following line, be very careful not to cause * WillBuildModel to be called before the document has had its * script global object set. */ mExecutor->WillBuildModel(eDTDMode_unknown); } // Return early if the parser has processed EOF if (mExecutor->IsComplete()) { return NS_OK; } if (aLastCall && aSourceBuffer.IsEmpty() && aKey == GetRootContextKey()) { // document.close() NS_ASSERTION(!mStreamParser, "Had stream parser but got document.close()."); mDocumentClosed = true; if (!mBlocked) { ParseUntilBlocked(); } return NS_OK; } NS_ASSERTION(IsInsertionPointDefined(), "Doc.write reached parser with undefined insertion point."); NS_ASSERTION(!(mStreamParser && !aKey), "Got a null key in a non-script-created parser"); if (aSourceBuffer.IsEmpty()) { return NS_OK; } nsHtml5DependentUTF16Buffer stackBuffer(aSourceBuffer); while (!mBlocked && stackBuffer.hasMore()) { stackBuffer.adjust(mLastWasCR); mLastWasCR = false; if (stackBuffer.hasMore()) { PRInt32 lineNumberSave; bool inRootContext = (!mStreamParser && (aKey == mRootContextKey)); if (inRootContext) { mTokenizer->setLineNumber(mRootContextLineNumber); } else { // we aren't the root context, so save the line number on the // *stack* so that we can restore it. lineNumberSave = mTokenizer->getLineNumber(); } mLastWasCR = mTokenizer->tokenizeBuffer(&stackBuffer); if (inRootContext) { mRootContextLineNumber = mTokenizer->getLineNumber(); } else { mTokenizer->setLineNumber(lineNumberSave); } if (mTreeBuilder->HasScript()) { mTreeBuilder->Flush(); // Move ops to the executor mExecutor->FlushDocumentWrite(); // run the ops } // Ignore suspension requests } } nsRefPtr<nsHtml5OwningUTF16Buffer> heapBuffer; if (stackBuffer.hasMore()) { // The buffer wasn't tokenized to completion. Create a copy of the tail // on the heap. heapBuffer = stackBuffer.FalliblyCopyAsOwningBuffer(); if (!heapBuffer) { // Allocation failed. The parser is now broken. mExecutor->MarkAsBroken(); return NS_ERROR_OUT_OF_MEMORY; } } // The buffer is inserted to the stream here in case it won't be parsed // to completion. // The script is identified by aKey. If there's nothing in the buffer // chain for that key, we'll insert at the head of the queue. // When the script leaves something in the queue, a zero-length // key-holder "buffer" is inserted in the queue. If the same script // leaves something in the chain again, it will be inserted immediately // before the old key holder belonging to the same script. nsHtml5OwningUTF16Buffer* prevSearchBuf = nsnull; nsHtml5OwningUTF16Buffer* searchBuf = mFirstBuffer; // after document.open, the first level of document.write has null key if (aKey) { while (searchBuf != mLastBuffer) { if (searchBuf->key == aKey) { // found a key holder // now insert the new buffer between the previous buffer // and the key holder if we have a buffer left. if (heapBuffer) { heapBuffer->next = searchBuf; if (prevSearchBuf) { prevSearchBuf->next = heapBuffer; } else { mFirstBuffer = heapBuffer; } } break; } prevSearchBuf = searchBuf; searchBuf = searchBuf->next; } if (searchBuf == mLastBuffer) { // key was not found nsHtml5OwningUTF16Buffer* keyHolder = new nsHtml5OwningUTF16Buffer(aKey); keyHolder->next = mFirstBuffer; if (heapBuffer) { heapBuffer->next = keyHolder; mFirstBuffer = heapBuffer; } else { mFirstBuffer = keyHolder; } } } else if (heapBuffer) { // we have a first level document.write after document.open() // insert immediately before mLastBuffer while (searchBuf != mLastBuffer) { prevSearchBuf = searchBuf; searchBuf = searchBuf->next; } heapBuffer->next = mLastBuffer; if (prevSearchBuf) { prevSearchBuf->next = heapBuffer; } else { mFirstBuffer = heapBuffer; } } if (!mBlocked) { // buffer was tokenized to completion NS_ASSERTION(!stackBuffer.hasMore(), "Buffer wasn't tokenized to completion?"); // Scripting semantics require a forced tree builder flush here mTreeBuilder->Flush(); // Move ops to the executor mExecutor->FlushDocumentWrite(); // run the ops } else if (stackBuffer.hasMore()) { // The buffer wasn't tokenized to completion. Tokenize the untokenized // content in order to preload stuff. This content will be retokenized // later for normal parsing. if (!mDocWriteSpeculatorActive) { mDocWriteSpeculatorActive = true; if (!mDocWriteSpeculativeTreeBuilder) { // Lazily initialize if uninitialized mDocWriteSpeculativeTreeBuilder = new nsHtml5TreeBuilder(nsnull, mExecutor->GetStage()); mDocWriteSpeculativeTreeBuilder->setScriptingEnabled( mTreeBuilder->isScriptingEnabled()); mDocWriteSpeculativeTokenizer = new nsHtml5Tokenizer(mDocWriteSpeculativeTreeBuilder); mDocWriteSpeculativeTokenizer->setInterner(&mAtomTable); mDocWriteSpeculativeTokenizer->start(); } mDocWriteSpeculativeTokenizer->resetToDataState(); mDocWriteSpeculativeTreeBuilder->loadState(mTreeBuilder, &mAtomTable); mDocWriteSpeculativeLastWasCR = false; } // Note that with multilevel document.write if we didn't just activate the // speculator, it's possible that the speculator is now in the wrong state. // That's OK for the sake of simplicity. The worst that can happen is // that the speculative loads aren't exactly right. The content will be // reparsed anyway for non-preload purposes. // The buffer position for subsequent non-speculative parsing now lives // in heapBuffer, so it's ok to let the buffer position of stackBuffer // to be overwritten and not restored below. while (stackBuffer.hasMore()) { stackBuffer.adjust(mDocWriteSpeculativeLastWasCR); if (stackBuffer.hasMore()) { mDocWriteSpeculativeLastWasCR = mDocWriteSpeculativeTokenizer->tokenizeBuffer(&stackBuffer); } } mDocWriteSpeculativeTreeBuilder->Flush(); mDocWriteSpeculativeTreeBuilder->DropHandles(); mExecutor->FlushSpeculativeLoads(); } return NS_OK; }
nsresult nsXBLProtoImplAnonymousMethod::Execute(nsIContent* aBoundElement) { NS_PRECONDITION(IsCompiled(), "Can't execute uncompiled method"); if (!mJSMethodObject) { // Nothing to do here return NS_OK; } // Get the script context the same way // nsXBLProtoImpl::InstallImplementation does. nsIDocument* document = aBoundElement->GetOwnerDoc(); if (!document) { return NS_OK; } nsIScriptGlobalObject* global = document->GetScriptGlobalObject(); if (!global) { return NS_OK; } nsCOMPtr<nsIScriptContext> context = global->GetContext(); if (!context) { return NS_OK; } JSContext* cx = (JSContext*) context->GetNativeContext(); JSObject* globalObject = global->GetGlobalJSObject(); nsCOMPtr<nsIXPConnectJSObjectHolder> wrapper; jsval v; nsresult rv = nsContentUtils::WrapNative(cx, globalObject, aBoundElement, &v, getter_AddRefs(wrapper)); NS_ENSURE_SUCCESS(rv, rv); JSObject* thisObject = JSVAL_TO_OBJECT(v); JSAutoRequest ar(cx); JSAutoEnterCompartment ac; if (!ac.enter(cx, thisObject)) return NS_ERROR_UNEXPECTED; // Clone the function object, using thisObject as the parent so "this" is in // the scope chain of the resulting function (for backwards compat to the // days when this was an event handler). JSObject* method = ::JS_CloneFunctionObject(cx, mJSMethodObject, thisObject); if (!method) return NS_ERROR_OUT_OF_MEMORY; // Now call the method // Use nsCxPusher to make sure we call ScriptEvaluated when we're done. nsCxPusher pusher; NS_ENSURE_STATE(pusher.Push(aBoundElement)); // Check whether it's OK to call the method. rv = nsContentUtils::GetSecurityManager()->CheckFunctionAccess(cx, method, thisObject); JSBool ok = JS_TRUE; if (NS_SUCCEEDED(rv)) { jsval retval; ok = ::JS_CallFunctionValue(cx, thisObject, OBJECT_TO_JSVAL(method), 0 /* argc */, nsnull /* argv */, &retval); } if (!ok) { // If a constructor or destructor threw an exception, it doesn't stop // anything else. We just report it. Note that we need to set aside the // frame chain here, since the constructor invocation is not related to // whatever is on the stack right now, really. JSBool saved = JS_SaveFrameChain(cx); JS_ReportPendingException(cx); if (saved) JS_RestoreFrameChain(cx); return NS_ERROR_FAILURE; } return NS_OK; }
NS_IMETHODIMP AsyncEncodeAndWriteIcon::Run() { NS_PRECONDITION(!NS_IsMainThread(), "Should not be called on the main thread."); // Get the recommended icon width and height, or if failure to obtain // these settings, fall back to 16x16 ICOs. These values can be different // if the user has a different DPI setting other than 100%. // Windows would scale the 16x16 icon themselves, but it's better // we let our ICO encoder do it. nsCOMPtr<nsIInputStream> iconStream; nsRefPtr<imgIEncoder> encoder = do_CreateInstance("@mozilla.org/image/encoder;2?" "type=image/vnd.microsoft.icon"); NS_ENSURE_TRUE(encoder, NS_ERROR_FAILURE); nsresult rv = encoder->InitFromData(mBuffer, mBufferLength, mWidth, mHeight, mStride, imgIEncoder::INPUT_FORMAT_HOSTARGB, EmptyString()); NS_ENSURE_SUCCESS(rv, rv); CallQueryInterface(encoder.get(), getter_AddRefs(iconStream)); if (!iconStream) { return NS_ERROR_FAILURE; } NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr<nsIFile> icoFile = do_CreateInstance("@mozilla.org/file/local;1"); NS_ENSURE_TRUE(icoFile, NS_ERROR_FAILURE); rv = icoFile->InitWithPath(mIconPath); // Setup the output stream for the ICO file on disk nsCOMPtr<nsIOutputStream> outputStream; rv = NS_NewLocalFileOutputStream(getter_AddRefs(outputStream), icoFile); NS_ENSURE_SUCCESS(rv, rv); // Obtain the ICO buffer size from the re-encoded ICO stream uint64_t bufSize64; rv = iconStream->Available(&bufSize64); NS_ENSURE_SUCCESS(rv, rv); NS_ENSURE_TRUE(bufSize64 <= UINT32_MAX, NS_ERROR_FILE_TOO_BIG); uint32_t bufSize = (uint32_t)bufSize64; // Setup a buffered output stream from the stream object // so that we can simply use WriteFrom with the stream object nsCOMPtr<nsIOutputStream> bufferedOutputStream; rv = NS_NewBufferedOutputStream(getter_AddRefs(bufferedOutputStream), outputStream, bufSize); NS_ENSURE_SUCCESS(rv, rv); // Write out the icon stream to disk and make sure we wrote everything uint32_t wrote; rv = bufferedOutputStream->WriteFrom(iconStream, bufSize, &wrote); NS_ASSERTION(bufSize == wrote, "Icon wrote size should be equal to requested write size"); // Cleanup bufferedOutputStream->Close(); outputStream->Close(); if (mURLShortcut) { SendMessage(HWND_BROADCAST, WM_SETTINGCHANGE, SPI_SETNONCLIENTMETRICS, 0); } return rv; }
nsresult nsXBLProtoImplMethod::CompileMember(nsIScriptContext* aContext, const nsCString& aClassStr, JSObject* aClassObject) { NS_PRECONDITION(!IsCompiled(), "Trying to compile an already-compiled method"); NS_PRECONDITION(aClassObject, "Must have class object to compile"); nsXBLUncompiledMethod* uncompiledMethod = GetUncompiledMethod(); // No parameters or body was supplied, so don't install method. if (!uncompiledMethod) { // Early return after which we consider ourselves compiled. mJSMethodObject = nullptr; return NS_OK; } // Don't install method if no name was supplied. if (!mName) { delete uncompiledMethod; // Early return after which we consider ourselves compiled. mJSMethodObject = nullptr; return NS_OK; } // We have a method. // Allocate an array for our arguments. int32_t paramCount = uncompiledMethod->GetParameterCount(); char** args = nullptr; if (paramCount > 0) { args = new char*[paramCount]; if (!args) return NS_ERROR_OUT_OF_MEMORY; // Add our parameters to our args array. int32_t argPos = 0; for (nsXBLParameter* curr = uncompiledMethod->mParameters; curr; curr = curr->mNext) { args[argPos] = curr->mName; argPos++; } } // Get the body nsDependentString body; PRUnichar *bodyText = uncompiledMethod->mBodyText.GetText(); if (bodyText) body.Rebind(bodyText); // Now that we have a body and args, compile the function // and then define it. NS_ConvertUTF16toUTF8 cname(mName); nsAutoCString functionUri(aClassStr); int32_t hash = functionUri.RFindChar('#'); if (hash != kNotFound) { functionUri.Truncate(hash); } JSObject* methodObject = nullptr; JSContext* cx = aContext->GetNativeContext(); JSAutoRequest ar(cx); JSAutoCompartment ac(cx, aClassObject); JS::CompileOptions options(cx); options.setFileAndLine(functionUri.get(), uncompiledMethod->mBodyText.GetLineNumber()) .setVersion(JSVERSION_LATEST) .setUserBit(true); // Flag us as XBL js::RootedObject rootedNull(cx, nullptr); // See bug 781070. nsresult rv = nsJSUtils::CompileFunction(cx, rootedNull, options, cname, paramCount, const_cast<const char**>(args), body, &methodObject); // Destroy our uncompiled method and delete our arg list. delete uncompiledMethod; delete [] args; if (NS_FAILED(rv)) { SetUncompiledMethod(nullptr); return rv; } mJSMethodObject = methodObject; return NS_OK; }
nsresult nsXBLProtoImplProperty::CompileMember(nsIScriptContext* aContext, const nsCString& aClassStr, void* aClassObject) { NS_PRECONDITION(!mIsCompiled, "Trying to compile an already-compiled property"); NS_PRECONDITION(aClassObject, "Must have class object to compile"); if (!mName) return NS_ERROR_FAILURE; // Without a valid name, we can't install the member. // We have a property. nsresult rv = NS_OK; nsCAutoString functionUri; if (mGetterText || mSetterText) { functionUri = aClassStr; PRInt32 hash = functionUri.RFindChar('#'); if (hash != kNotFound) { functionUri.Truncate(hash); } } PRBool deletedGetter = PR_FALSE; if (mGetterText && mGetterText->GetText()) { nsDependentString getter(mGetterText->GetText()); if (!getter.IsEmpty()) { // Compile into a temp object so we don't wipe out mGetterText JSObject* getterObject = nsnull; rv = aContext->CompileFunction(aClassObject, NS_LITERAL_CSTRING("get_") + NS_ConvertUTF16toUTF8(mName), 0, nsnull, getter, functionUri.get(), mGetterText->GetLineNumber(), JSVERSION_LATEST, PR_TRUE, (void **) &getterObject); // Make sure we free mGetterText here before setting mJSGetterObject, since // that'll overwrite mGetterText delete mGetterText; deletedGetter = PR_TRUE; mJSGetterObject = getterObject; if (mJSGetterObject && NS_SUCCEEDED(rv)) { mJSAttributes |= JSPROP_GETTER | JSPROP_SHARED; } if (NS_FAILED(rv)) { mJSGetterObject = nsnull; mJSAttributes &= ~JSPROP_GETTER; /*chaining to return failure*/ } } } // if getter is not empty if (!deletedGetter) { // Empty getter delete mGetterText; mJSGetterObject = nsnull; } if (NS_FAILED(rv)) { // We failed to compile our getter. So either we've set it to null, or // it's still set to the text object. In either case, it's safe to return // the error here, since then we'll be cleaned up as uncompiled and that // will be ok. Going on and compiling the setter and _then_ returning an // error, on the other hand, will try to clean up a compiled setter as // uncompiled and crash. return rv; } PRBool deletedSetter = PR_FALSE; if (mSetterText && mSetterText->GetText()) { nsDependentString setter(mSetterText->GetText()); if (!setter.IsEmpty()) { // Compile into a temp object so we don't wipe out mSetterText JSObject* setterObject = nsnull; rv = aContext->CompileFunction(aClassObject, NS_LITERAL_CSTRING("set_") + NS_ConvertUTF16toUTF8(mName), 1, gPropertyArgs, setter, functionUri.get(), mSetterText->GetLineNumber(), JSVERSION_LATEST, PR_TRUE, (void **) &setterObject); // Make sure we free mSetterText here before setting mJSGetterObject, since // that'll overwrite mSetterText delete mSetterText; deletedSetter = PR_TRUE; mJSSetterObject = setterObject; if (mJSSetterObject && NS_SUCCEEDED(rv)) { mJSAttributes |= JSPROP_SETTER | JSPROP_SHARED; } if (NS_FAILED(rv)) { mJSSetterObject = nsnull; mJSAttributes &= ~JSPROP_SETTER; /*chaining to return failure*/ } } } // if setter wasn't empty.... if (!deletedSetter) { // Empty setter delete mSetterText; mJSSetterObject = nsnull; } #ifdef DEBUG mIsCompiled = NS_SUCCEEDED(rv); #endif return rv; }
nsresult nsTextControlFrame::UpdateValueDisplay(bool aNotify, bool aBeforeEditorInit, const nsAString *aValue) { if (!IsSingleLineTextControl()) // textareas don't use this return NS_OK; nsCOMPtr<nsITextControlElement> txtCtrl = do_QueryInterface(GetContent()); NS_ASSERTION(txtCtrl, "Content not a text control element"); nsIContent* rootNode = txtCtrl->GetRootEditorNode(); NS_PRECONDITION(rootNode, "Must have a div content\n"); NS_PRECONDITION(!mUseEditor, "Do not call this after editor has been initialized"); NS_ASSERTION(!mUsePlaceholder || txtCtrl->GetPlaceholderNode(), "A placeholder div must exist"); nsIContent *textContent = rootNode->GetChildAt(0); if (!textContent) { // Set up a textnode with our value nsCOMPtr<nsIContent> textNode; nsresult rv = NS_NewTextNode(getter_AddRefs(textNode), mContent->NodeInfo()->NodeInfoManager()); NS_ENSURE_SUCCESS(rv, rv); NS_ASSERTION(textNode, "Must have textcontent!\n"); rootNode->AppendChildTo(textNode, aNotify); textContent = textNode; } NS_ENSURE_TRUE(textContent, NS_ERROR_UNEXPECTED); // Get the current value of the textfield from the content. nsAutoString value; if (aValue) { value = *aValue; } else { txtCtrl->GetTextEditorValue(value, true); } // Update the display of the placeholder value if needed. // We don't need to do this if we're about to initialize the // editor, since EnsureEditorInitialized takes care of this. if (mUsePlaceholder && !aBeforeEditorInit) { nsWeakFrame weakFrame(this); txtCtrl->SetPlaceholderClass(value.IsEmpty(), aNotify); NS_ENSURE_STATE(weakFrame.IsAlive()); } if (aBeforeEditorInit && value.IsEmpty()) { rootNode->RemoveChildAt(0, true); return NS_OK; } if (!value.IsEmpty() && IsPasswordTextControl()) { nsTextEditRules::FillBufWithPWChars(&value, value.Length()); } return textContent->SetText(value, aNotify); }
NS_IMETHODIMP LocalSearchDataSource::GetTarget(nsIRDFResource *source, nsIRDFResource *property, PRBool tv, nsIRDFNode **target /* out */) { NS_PRECONDITION(source != nsnull, "null ptr"); if (! source) return NS_ERROR_NULL_POINTER; NS_PRECONDITION(property != nsnull, "null ptr"); if (! property) return NS_ERROR_NULL_POINTER; NS_PRECONDITION(target != nsnull, "null ptr"); if (! target) return NS_ERROR_NULL_POINTER; nsresult rv = NS_RDF_NO_VALUE; // we only have positive assertions in the find data source. if (! tv) return rv; if (isFindURI(source)) { if (property == kNC_Name) { // rv = GetName(source, &array); } else if (property == kNC_URL) { // note: lie and say there is no URL // rv = GetURL(source, &array); nsAutoString url; nsIRDFLiteral *literal; gRDFService->GetLiteral(url.get(), &literal); *target = literal; return(NS_OK); } else if (property == kRDF_type) { const char *uri = nsnull; rv = kNC_FindObject->GetValueConst(&uri); if (NS_FAILED(rv)) return rv; nsAutoString url; url.AssignWithConversion(uri); nsIRDFLiteral *literal; gRDFService->GetLiteral(url.get(), &literal); *target = literal; return(NS_OK); } else if (property == kNC_pulse) { nsAutoString pulse(NS_LITERAL_STRING("15")); nsIRDFLiteral *pulseLiteral; rv = gRDFService->GetLiteral(pulse.get(), &pulseLiteral); if (NS_FAILED(rv)) return rv; *target = pulseLiteral; return(NS_OK); } else if (property == kNC_Child) { // fake out the generic builder (i.e. return anything in this case) // so that search containers never appear to be empty *target = source; NS_ADDREF(*target); return(NS_OK); } } return NS_RDF_NO_VALUE; }
txExecutionState::TemplateRule* txExecutionState::getCurrentTemplateRule() { NS_PRECONDITION(!mTemplateRules.IsEmpty(), "No current rule!"); return &mTemplateRules[mTemplateRules.Length() - 1]; }
void txExecutionState::popTemplateRule() { NS_PRECONDITION(!mTemplateRules.IsEmpty(), "No rules to pop"); mTemplateRules.RemoveElementAt(mTemplateRules.Length() - 1); }
NS_IMETHODIMP XULContentSinkImpl::ReportError(const PRUnichar* aErrorText, const PRUnichar* aSourceText, nsIScriptError *aError, bool *_retval) { NS_PRECONDITION(aError && aSourceText && aErrorText, "Check arguments!!!"); // The expat driver should report the error. *_retval = true; nsresult rv = NS_OK; // make sure to empty the context stack so that // <parsererror> could become the root element. mContextStack.Clear(); mState = eInProlog; // Clear any buffered-up text we have. It's enough to set the length to 0. // The buffer itself is allocated when we're created and deleted in our // destructor, so don't mess with it. mTextLength = 0; nsCOMPtr<nsIXULDocument> doc = do_QueryReferent(mDocument); if (doc && !doc->OnDocumentParserError()) { // The overlay was broken. Don't add a messy element to the master doc. return NS_OK; } const PRUnichar* noAtts[] = { 0, 0 }; NS_NAMED_LITERAL_STRING(errorNs, "http://www.mozilla.org/newlayout/xml/parsererror.xml"); nsAutoString parsererror(errorNs); parsererror.Append((PRUnichar)0xFFFF); parsererror.AppendLiteral("parsererror"); rv = HandleStartElement(parsererror.get(), noAtts, 0, -1, 0); NS_ENSURE_SUCCESS(rv,rv); rv = HandleCharacterData(aErrorText, NS_strlen(aErrorText)); NS_ENSURE_SUCCESS(rv,rv); nsAutoString sourcetext(errorNs); sourcetext.Append((PRUnichar)0xFFFF); sourcetext.AppendLiteral("sourcetext"); rv = HandleStartElement(sourcetext.get(), noAtts, 0, -1, 0); NS_ENSURE_SUCCESS(rv,rv); rv = HandleCharacterData(aSourceText, NS_strlen(aSourceText)); NS_ENSURE_SUCCESS(rv,rv); rv = HandleEndElement(sourcetext.get()); NS_ENSURE_SUCCESS(rv,rv); rv = HandleEndElement(parsererror.get()); NS_ENSURE_SUCCESS(rv,rv); return rv; }
// // Called by nsCSSFrameConstructor when listitem content is removed. // void nsListBoxBodyFrame::OnContentRemoved(nsPresContext* aPresContext, nsIContent* aContainer, nsIFrame* aChildFrame, nsIContent* aOldNextSibling) { NS_ASSERTION(!aChildFrame || aChildFrame->GetParent() == this, "Removing frame that's not our child... Not good"); if (mRowCount >= 0) --mRowCount; if (aContainer) { if (!aChildFrame) { // The row we are removing is out of view, so we need to try to // determine the index of its next sibling. int32_t siblingIndex = -1; if (aOldNextSibling) { nsCOMPtr<nsIContent> nextSiblingContent; GetListItemNextSibling(aOldNextSibling, getter_AddRefs(nextSiblingContent), siblingIndex); } // if the row being removed is off-screen and above the top frame, we need to // adjust our top index and tell the scrollbar to shift up one row. if (siblingIndex >= 0 && siblingIndex-1 < mCurrentIndex) { NS_PRECONDITION(mCurrentIndex > 0, "mCurrentIndex > 0"); --mCurrentIndex; mYPosition = mCurrentIndex*mRowHeight; VerticalScroll(mYPosition); } } else if (mCurrentIndex > 0) { // At this point, we know we have a scrollbar, and we need to know // if we are scrolled to the last row. In this case, the behavior // of the scrollbar is to stay locked to the bottom. Since we are // removing visible content, the first visible row will have to move // down by one, and we will have to insert a new frame at the top. // if the last content node has a frame, we are scrolled to the bottom ChildIterator iter, last; ChildIterator::Init(mContent, &iter, &last); if (iter != last) { iter = last; --iter; nsIContent *lastChild = *iter; nsIFrame* lastChildFrame = lastChild->GetPrimaryFrame(); if (lastChildFrame) { mTopFrame = nullptr; mRowsToPrepend = 1; --mCurrentIndex; mYPosition = mCurrentIndex*mRowHeight; VerticalScroll(mYPosition); } } } } // if we're removing the top row, the new top row is the next row if (mTopFrame && mTopFrame == aChildFrame) mTopFrame = mTopFrame->GetNextSibling(); // Go ahead and delete the frame. nsBoxLayoutState state(aPresContext); if (aChildFrame) { RemoveChildFrame(state, aChildFrame); } PresContext()->PresShell()-> FrameNeedsReflow(this, nsIPresShell::eTreeChange, NS_FRAME_HAS_DIRTY_CHILDREN); }
NS_IMETHODIMP nsVideoFrame::Reflow(nsPresContext* aPresContext, nsHTMLReflowMetrics& aMetrics, const nsHTMLReflowState& aReflowState, nsReflowStatus& aStatus) { DO_GLOBAL_REFLOW_COUNT("nsVideoFrame"); DISPLAY_REFLOW(aPresContext, this, aReflowState, aMetrics, aStatus); NS_FRAME_TRACE(NS_FRAME_TRACE_CALLS, ("enter nsVideoFrame::Reflow: availSize=%d,%d", aReflowState.availableWidth, aReflowState.availableHeight)); NS_PRECONDITION(mState & NS_FRAME_IN_REFLOW, "frame is not in reflow"); aStatus = NS_FRAME_COMPLETE; aMetrics.width = aReflowState.ComputedWidth(); aMetrics.height = aReflowState.ComputedHeight(); // stash this away so we can compute our inner area later mBorderPadding = aReflowState.mComputedBorderPadding; aMetrics.width += mBorderPadding.left + mBorderPadding.right; aMetrics.height += mBorderPadding.top + mBorderPadding.bottom; // Reflow the child frames. We may have up to two, an image frame // which is the poster, and a box frame, which is the video controls. for (nsIFrame *child = mFrames.FirstChild(); child; child = child->GetNextSibling()) { if (child->GetType() == nsGkAtoms::imageFrame) { // Reflow the poster frame. nsImageFrame* imageFrame = static_cast<nsImageFrame*>(child); nsHTMLReflowMetrics kidDesiredSize; nsSize availableSize = nsSize(aReflowState.availableWidth, aReflowState.availableHeight); nsHTMLReflowState kidReflowState(aPresContext, aReflowState, imageFrame, availableSize, aMetrics.width, aMetrics.height); if (ShouldDisplayPoster()) { kidReflowState.SetComputedWidth(aReflowState.ComputedWidth()); kidReflowState.SetComputedHeight(aReflowState.ComputedHeight()); } else { kidReflowState.SetComputedWidth(0); kidReflowState.SetComputedHeight(0); } ReflowChild(imageFrame, aPresContext, kidDesiredSize, kidReflowState, mBorderPadding.left, mBorderPadding.top, 0, aStatus); FinishReflowChild(imageFrame, aPresContext, &kidReflowState, kidDesiredSize, mBorderPadding.left, mBorderPadding.top, 0); } else if (child->GetType() == nsGkAtoms::boxFrame) { // Reflow the video controls frame. nsBoxLayoutState boxState(PresContext(), aReflowState.rendContext); nsBoxFrame::LayoutChildAt(boxState, child, nsRect(mBorderPadding.left, mBorderPadding.top, aReflowState.ComputedWidth(), aReflowState.ComputedHeight())); } } aMetrics.mOverflowArea.SetRect(0, 0, aMetrics.width, aMetrics.height); FinishAndStoreOverflow(&aMetrics); if (mRect.width != aMetrics.width || mRect.height != aMetrics.height) { Invalidate(nsRect(0, 0, mRect.width, mRect.height)); } NS_FRAME_TRACE(NS_FRAME_TRACE_CALLS, ("exit nsVideoFrame::Reflow: size=%d,%d", aMetrics.width, aMetrics.height)); NS_FRAME_SET_TRUNCATION(aStatus, aReflowState, aMetrics); return NS_OK; }
nsresult nsXBLProtoImplMethod::CompileMember(nsIScriptContext* aContext, const nsCString& aClassStr, void* aClassObject) { NS_TIME_FUNCTION_MIN(5); NS_PRECONDITION(!IsCompiled(), "Trying to compile an already-compiled method"); NS_PRECONDITION(aClassObject, "Must have class object to compile"); nsXBLUncompiledMethod* uncompiledMethod = GetUncompiledMethod(); // No parameters or body was supplied, so don't install method. if (!uncompiledMethod) { // Early return after which we consider ourselves compiled. mJSMethodObject = nsnull; return NS_OK; } // Don't install method if no name was supplied. if (!mName) { delete uncompiledMethod; // Early return after which we consider ourselves compiled. mJSMethodObject = nsnull; return NS_OK; } // We have a method. // Allocate an array for our arguments. PRInt32 paramCount = uncompiledMethod->GetParameterCount(); char** args = nsnull; if (paramCount > 0) { args = new char*[paramCount]; if (!args) return NS_ERROR_OUT_OF_MEMORY; // Add our parameters to our args array. PRInt32 argPos = 0; for (nsXBLParameter* curr = uncompiledMethod->mParameters; curr; curr = curr->mNext) { args[argPos] = curr->mName; argPos++; } } // Get the body nsDependentString body; PRUnichar *bodyText = uncompiledMethod->mBodyText.GetText(); if (bodyText) body.Rebind(bodyText); // Now that we have a body and args, compile the function // and then define it. NS_ConvertUTF16toUTF8 cname(mName); nsCAutoString functionUri(aClassStr); PRInt32 hash = functionUri.RFindChar('#'); if (hash != kNotFound) { functionUri.Truncate(hash); } JSObject* methodObject = nsnull; nsresult rv = aContext->CompileFunction(aClassObject, cname, paramCount, (const char**)args, body, functionUri.get(), uncompiledMethod->mBodyText.GetLineNumber(), JSVERSION_LATEST, PR_TRUE, (void **) &methodObject); // Destroy our uncompiled method and delete our arg list. delete uncompiledMethod; delete [] args; if (NS_FAILED(rv)) { SetUncompiledMethod(nsnull); return rv; } mJSMethodObject = methodObject; return NS_OK; }
NS_IMETHODIMP nsLineIterator::FindFrameAt(PRInt32 aLineNumber, nscoord aX, nsIFrame** aFrameFound, PRBool* aXIsBeforeFirstFrame, PRBool* aXIsAfterLastFrame) { NS_PRECONDITION(aFrameFound && aXIsBeforeFirstFrame && aXIsAfterLastFrame, "null OUT ptr"); if (!aFrameFound || !aXIsBeforeFirstFrame || !aXIsAfterLastFrame) { return NS_ERROR_NULL_POINTER; } if ((aLineNumber < 0) || (aLineNumber >= mNumLines)) { return NS_ERROR_INVALID_ARG; } nsLineBox* line = mLines[aLineNumber]; if (!line) { *aFrameFound = nsnull; *aXIsBeforeFirstFrame = PR_TRUE; *aXIsAfterLastFrame = PR_FALSE; return NS_OK; } if (line->mBounds.width == 0 && line->mBounds.height == 0) return NS_ERROR_FAILURE; nsIFrame* frame = line->mFirstChild; nsIFrame* closestFromLeft = nsnull; nsIFrame* closestFromRight = nsnull; PRInt32 n = line->GetChildCount(); while (n--) { nsRect rect = frame->GetRect(); if (rect.width > 0) { // If aX is inside this frame - this is it if (rect.x <= aX && rect.XMost() > aX) { closestFromLeft = closestFromRight = frame; break; } if (rect.x < aX) { if (!closestFromLeft || rect.XMost() > closestFromLeft->GetRect().XMost()) closestFromLeft = frame; } else { if (!closestFromRight || rect.x < closestFromRight->GetRect().x) closestFromRight = frame; } } frame = frame->GetNextSibling(); } if (!closestFromLeft && !closestFromRight) { // All frames were zero-width. Just take the first one. closestFromLeft = closestFromRight = line->mFirstChild; } *aXIsBeforeFirstFrame = mRightToLeft ? !closestFromRight : !closestFromLeft; *aXIsAfterLastFrame = mRightToLeft ? !closestFromLeft : !closestFromRight; if (closestFromLeft == closestFromRight) { *aFrameFound = closestFromLeft; } else if (!closestFromLeft) { *aFrameFound = closestFromRight; } else if (!closestFromRight) { *aFrameFound = closestFromLeft; } else { // we're between two frames nscoord delta = closestFromRight->GetRect().x - closestFromLeft->GetRect().XMost(); if (aX < closestFromLeft->GetRect().XMost() + delta/2) *aFrameFound = closestFromLeft; else *aFrameFound = closestFromRight; } return NS_OK; }
// XXXldb This behavior doesn't quite fit with CSS1 and CSS2 -- // technically we're supposed let the current line flow around the // float as well unless it won't fit next to what we already have. // But nobody else implements it that way... PRBool nsBlockReflowState::AddFloat(nsLineLayout& aLineLayout, nsPlaceholderFrame* aPlaceholder, PRBool aInitialReflow, nsReflowStatus& aReflowStatus) { NS_PRECONDITION(mBlock->end_lines() != mCurrentLine, "null ptr"); aReflowStatus = NS_FRAME_COMPLETE; // Allocate a nsFloatCache for the float nsFloatCache* fc = mFloatCacheFreeList.Alloc(); fc->mPlaceholder = aPlaceholder; PRBool placed; // Now place the float immediately if possible. Otherwise stash it // away in mPendingFloats and place it later. if (aLineLayout.CanPlaceFloatNow()) { // Because we are in the middle of reflowing a placeholder frame // within a line (and possibly nested in an inline frame or two // that's a child of our block) we need to restore the space // manager's translation to the space that the block resides in // before placing the float. nscoord ox, oy; mSpaceManager->GetTranslation(ox, oy); nscoord dx = ox - mSpaceManagerX; nscoord dy = oy - mSpaceManagerY; mSpaceManager->Translate(-dx, -dy); // And then place it PRBool isLeftFloat; // force it to fit if we're at the top of the block and we can't // break before this PRBool forceFit = IsAdjacentWithTop() && !aLineLayout.LineIsBreakable(); placed = FlowAndPlaceFloat(fc, &isLeftFloat, aReflowStatus, forceFit); NS_ASSERTION(placed || !forceFit, "If we asked for force-fit, it should have been placed"); if (forceFit || (placed && !NS_FRAME_IS_TRUNCATED(aReflowStatus))) { // Pass on updated available space to the current inline reflow engine GetAvailableSpace(mY, forceFit); aLineLayout.UpdateBand(mAvailSpaceRect.x + BorderPadding().left, mY, mAvailSpaceRect.width, mAvailSpaceRect.height, isLeftFloat, aPlaceholder->GetOutOfFlowFrame()); // Record this float in the current-line list mCurrentLineFloats.Append(fc); // If we can't break here, hide the fact that it's truncated // XXX We can probably do this more cleanly aReflowStatus &= ~NS_FRAME_TRUNCATED; } else { if (IsAdjacentWithTop()) { // Pushing the line to the next page won't give us any more space; // therefore, we break. NS_ASSERTION(aLineLayout.LineIsBreakable(), "We can't get here unless forceFit is false"); aReflowStatus = NS_INLINE_LINE_BREAK_BEFORE(); } else { // Make sure we propagate the truncated status; this signals the // block to push the line to the next page. aReflowStatus |= NS_FRAME_TRUNCATED; } delete fc; } // Restore coordinate system mSpaceManager->Translate(dx, dy); } else { // Always claim to be placed; we don't know whether we fit yet, so we // deal with this in PlaceBelowCurrentLineFloats placed = PR_TRUE; // This float will be placed after the line is done (it is a // below-current-line float). mBelowCurrentLineFloats.Append(fc); if (aPlaceholder->GetNextInFlow()) { // If the float might not be complete, mark it incomplete now to // prevent its next-in-flow placeholders being torn down. We will destroy any // placeholders later if PlaceBelowCurrentLineFloats finds the // float is complete. // Note that we could have unconstrained height and yet have // a next-in-flow placeholder --- for example columns can switch // from constrained height to unconstrained height. if (aPlaceholder->GetSplittableType() != NS_FRAME_NOT_SPLITTABLE) { aReflowStatus = NS_FRAME_NOT_COMPLETE; } } } return placed; }
void nsSprocketLayout::AlignChildren(nsIFrame* aBox, nsBoxLayoutState& aState) { nsFrameState frameState = nsFrameState(0); GetFrameState(aBox, frameState); bool isHorizontal = (frameState & NS_STATE_IS_HORIZONTAL) != 0; nsRect clientRect; aBox->GetClientRect(clientRect); NS_PRECONDITION(!(frameState & NS_STATE_AUTO_STRETCH), "Only AlignChildren() with non-stretch alignment"); // These are only calculated if needed nsIFrame::Halignment halign; nsIFrame::Valignment valign; nscoord maxAscent; bool isLTR; if (isHorizontal) { valign = aBox->GetVAlign(); if (valign == nsBoxFrame::vAlign_BaseLine) { maxAscent = aBox->GetBoxAscent(aState); } } else { isLTR = GetFrameDirection(aBox) == NS_STYLE_DIRECTION_LTR; halign = aBox->GetHAlign(); } nsIFrame* child = nsBox::GetChildBox(aBox); while (child) { nsMargin margin; child->GetMargin(margin); nsRect childRect = child->GetRect(); if (isHorizontal) { const nscoord startAlign = clientRect.y + margin.top; const nscoord endAlign = clientRect.YMost() - margin.bottom - childRect.height; nscoord y; switch (valign) { case nsBoxFrame::vAlign_Top: y = startAlign; break; case nsBoxFrame::vAlign_Middle: // Should this center the border box? // This centers the margin box, the historical behavior. y = (startAlign + endAlign) / 2; break; case nsBoxFrame::vAlign_Bottom: y = endAlign; break; case nsBoxFrame::vAlign_BaseLine: // Alignments don't force the box to grow (only sizes do), // so keep the children within the box. y = maxAscent - child->GetBoxAscent(aState); y = std::max(startAlign, y); y = std::min(y, endAlign); break; } childRect.y = y; } else { // vertical box const nscoord leftAlign = clientRect.x + margin.left; const nscoord rightAlign = clientRect.XMost() - margin.right - childRect.width; nscoord x; switch (halign) { case nsBoxFrame::hAlign_Left: // start x = isLTR ? leftAlign : rightAlign; break; case nsBoxFrame::hAlign_Center: x = (leftAlign + rightAlign) / 2; break; case nsBoxFrame::hAlign_Right: // end x = isLTR ? rightAlign : leftAlign; break; } childRect.x = x; } if (childRect.TopLeft() != child->GetPosition()) { child->SetBounds(aState, childRect); } child = nsBox::GetNextBox(child); } }
/** * Handle 'inout', 'out', and 'retval' params */ nsresult nsJavaXPTCStub::FinalizeJavaParams(const nsXPTParamInfo &aParamInfo, const XPTMethodDescriptor *aMethodInfo, PRUint16 aMethodIndex, nsXPTCMiniVariant* aDispatchParams, nsXPTCMiniVariant &aVariant, jvalue &aJValue) { nsresult rv = NS_OK; JNIEnv* env = GetJNIEnv(); const nsXPTType &type = aParamInfo.GetType(); PRUint8 tag = type.TagPart(); switch (tag) { case nsXPTType::T_I8: { jbyte value; if (aParamInfo.IsRetval()) { // 'retval' value = aJValue.b; } else if (aJValue.l) { // 'inout' & 'out' env->GetByteArrayRegion((jbyteArray) aJValue.l, 0, 1, &value); } if (aVariant.val.p) *((PRInt8 *) aVariant.val.p) = value; } break; case nsXPTType::T_U8: case nsXPTType::T_I16: { jshort value = 0; if (aParamInfo.IsRetval()) { // 'retval' value = aJValue.s; } else if (aJValue.l) { // 'inout' & 'out' env->GetShortArrayRegion((jshortArray) aJValue.l, 0, 1, &value); } if (aVariant.val.p) { if (tag == nsXPTType::T_U8) *((PRUint8 *) aVariant.val.p) = value; else *((PRInt16 *) aVariant.val.p) = value; } } break; case nsXPTType::T_U16: case nsXPTType::T_I32: { jint value = 0; if (aParamInfo.IsRetval()) { // 'retval' value = aJValue.i; } else if (aJValue.l) { // 'inout' & 'out' env->GetIntArrayRegion((jintArray) aJValue.l, 0, 1, &value); } if (aVariant.val.p) { if (tag == nsXPTType::T_U16) *((PRUint16 *) aVariant.val.p) = value; else *((PRInt32 *) aVariant.val.p) = value; } } break; case nsXPTType::T_U32: case nsXPTType::T_I64: { jlong value = 0; if (aParamInfo.IsRetval()) { // 'retval' value = aJValue.j; } else if (aJValue.l) { // 'inout' & 'out' env->GetLongArrayRegion((jlongArray) aJValue.l, 0, 1, &value); } if (aVariant.val.p) { if (tag == nsXPTType::T_U32) *((PRUint32 *) aVariant.val.p) = value; else *((PRInt64 *) aVariant.val.p) = value; } } break; case nsXPTType::T_FLOAT: { if (aParamInfo.IsRetval()) { // 'retval' *((float *) aVariant.val.p) = aJValue.f; } else if (aJValue.l) { // 'inout' & 'out' env->GetFloatArrayRegion((jfloatArray) aJValue.l, 0, 1, (jfloat*) aVariant.val.p); } } break; // XXX how do we handle 64-bit values? case nsXPTType::T_U64: case nsXPTType::T_DOUBLE: { jdouble value = 0; if (aParamInfo.IsRetval()) { // 'retval' value = aJValue.d; } else if (aJValue.l) { // 'inout' & 'out' env->GetDoubleArrayRegion((jdoubleArray) aJValue.l, 0, 1, &value); } if (aVariant.val.p) { if (tag == nsXPTType::T_DOUBLE) *((double *) aVariant.val.p) = value; else *((PRUint64 *) aVariant.val.p) = static_cast<PRUint64>(value); } } break; case nsXPTType::T_BOOL: { if (aParamInfo.IsRetval()) { // 'retval' *((PRBool *) aVariant.val.p) = aJValue.z; } else if (aJValue.l) { // 'inout' & 'out' env->GetBooleanArrayRegion((jbooleanArray) aJValue.l, 0, 1, (jboolean*) aVariant.val.p); } } break; case nsXPTType::T_CHAR: case nsXPTType::T_WCHAR: { if (aParamInfo.IsRetval()) { // 'retval' if (type.TagPart() == nsXPTType::T_CHAR) *((char *) aVariant.val.p) = aJValue.c; else *((PRUnichar *) aVariant.val.p) = aJValue.c; } else if (aJValue.l) { // 'inout' & 'out' jchar* array = env->GetCharArrayElements((jcharArray) aJValue.l, nsnull); if (!array) { rv = NS_ERROR_OUT_OF_MEMORY; break; } if (type.TagPart() == nsXPTType::T_CHAR) *((char *) aVariant.val.p) = array[0]; else *((PRUnichar *) aVariant.val.p) = array[0]; env->ReleaseCharArrayElements((jcharArray) aJValue.l, array, JNI_ABORT); } } break; case nsXPTType::T_CHAR_STR: { jstring str = nsnull; if (aParamInfo.IsRetval()) { // 'retval' str = (jstring) aJValue.l; } else { // 'inout' & 'out' str = (jstring) env->GetObjectArrayElement((jobjectArray) aJValue.l, 0); } char** variant = static_cast<char**>(aVariant.val.p); if (str) { // Get string buffer const char* char_ptr = env->GetStringUTFChars(str, nsnull); if (!char_ptr) { rv = NS_ERROR_OUT_OF_MEMORY; break; } // If new string is different from one passed in, free old string // and replace with new string. if (aParamInfo.IsRetval() || *variant == nsnull || strcmp(*variant, char_ptr) != 0) { if (!aParamInfo.IsRetval() && *variant) PR_Free(*variant); *variant = strdup(char_ptr); if (*variant == nsnull) { rv = NS_ERROR_OUT_OF_MEMORY; // don't 'break'; fall through to release chars } } // Release string buffer env->ReleaseStringUTFChars(str, char_ptr); } else { // If we were passed in a string, delete it now, and set to null. // (Only for 'inout' & 'out' params) if (*variant && !aParamInfo.IsRetval()) { PR_Free(*variant); } *variant = nsnull; } } break; case nsXPTType::T_WCHAR_STR: { jstring str = nsnull; if (aParamInfo.IsRetval()) { // 'retval' str = (jstring) aJValue.l; } else { // 'inout' & 'out' str = (jstring) env->GetObjectArrayElement((jobjectArray) aJValue.l, 0); } PRUnichar** variant = static_cast<PRUnichar**>(aVariant.val.p); if (str) { // Get string buffer const jchar* wchar_ptr = env->GetStringChars(str, nsnull); if (!wchar_ptr) { rv = NS_ERROR_OUT_OF_MEMORY; break; } // If new string is different from one passed in, free old string // and replace with new string. We if (aParamInfo.IsRetval() || *variant == nsnull || nsCRT::strcmp(*variant, wchar_ptr) != 0) { if (!aParamInfo.IsRetval() && *variant) PR_Free(*variant); PRUint32 length = nsCRT::strlen(wchar_ptr); *variant = (PRUnichar*) PR_Malloc((length + 1) * sizeof(PRUnichar)); if (*variant) { memcpy(*variant, wchar_ptr, length * sizeof(PRUnichar)); (*variant)[length] = 0; } else { rv = NS_ERROR_OUT_OF_MEMORY; // don't 'break'; fall through to release chars } } // Release string buffer env->ReleaseStringChars(str, wchar_ptr); } else { // If we were passed in a string, delete it now, and set to null. // (Only for 'inout' & 'out' params) if (*variant && !aParamInfo.IsRetval()) { PR_Free(*variant); } *variant = nsnull; } } break; case nsXPTType::T_IID: { jstring str = nsnull; if (aParamInfo.IsRetval()) { // 'retval' str = (jstring) aJValue.l; } else { // 'inout' & 'out' str = (jstring) env->GetObjectArrayElement((jobjectArray) aJValue.l, 0); } nsID** variant = static_cast<nsID**>(aVariant.val.p); if (str) { // Get string buffer const char* char_ptr = env->GetStringUTFChars(str, nsnull); if (!char_ptr) { rv = NS_ERROR_OUT_OF_MEMORY; break; } if (!aParamInfo.IsRetval() && *variant) { // If we were given an nsID, set it to the new string nsID* oldIID = *variant; oldIID->Parse(char_ptr); } else { // If the argument that was passed in was null, then we need to // create a new nsID. nsID* newIID = new nsID; if (newIID) { newIID->Parse(char_ptr); *variant = newIID; } else { rv = NS_ERROR_OUT_OF_MEMORY; // don't 'break'; fall through to release chars } } // Release string buffer env->ReleaseStringUTFChars(str, char_ptr); } else { // If we were passed in an nsID, delete it now, and set to null. // (Free only 'inout' & 'out' params) if (*variant && !aParamInfo.IsRetval()) { delete *variant; } *variant = nsnull; } } break; case nsXPTType::T_INTERFACE: case nsXPTType::T_INTERFACE_IS: { jobject java_obj = nsnull; if (aParamInfo.IsRetval()) { // 'retval' java_obj = aJValue.l; } else if (aJValue.l) { // 'inout' & 'out' java_obj = env->GetObjectArrayElement((jobjectArray) aJValue.l, 0); } void* xpcom_obj = nsnull; if (java_obj) { // Get IID for this param nsID iid; rv = GetIIDForMethodParam(mIInfo, aMethodInfo, aParamInfo, aParamInfo.GetType().TagPart(), aMethodIndex, aDispatchParams, PR_FALSE, iid); if (NS_FAILED(rv)) break; // If the requested interface is nsIWeakReference, then we look for or // create a stub for the nsISupports interface. Then we create a weak // reference from that stub. PRBool isWeakRef; if (iid.Equals(NS_GET_IID(nsIWeakReference))) { isWeakRef = PR_TRUE; iid = NS_GET_IID(nsISupports); } else { isWeakRef = PR_FALSE; } rv = JavaObjectToNativeInterface(env, java_obj, iid, &xpcom_obj); if (NS_FAILED(rv)) break; rv = ((nsISupports*) xpcom_obj)->QueryInterface(iid, &xpcom_obj); if (NS_FAILED(rv)) break; // If the function expects a weak reference, then we need to // create it here. if (isWeakRef) { nsISupports* isupports = (nsISupports*) xpcom_obj; nsCOMPtr<nsISupportsWeakReference> supportsweak = do_QueryInterface(isupports); if (supportsweak) { nsWeakPtr weakref; supportsweak->GetWeakReference(getter_AddRefs(weakref)); NS_RELEASE(isupports); xpcom_obj = weakref; NS_ADDREF((nsISupports*) xpcom_obj); } else { xpcom_obj = nsnull; } } } // For 'inout' params, if the resulting xpcom value is different than the // one passed in, then we must release the incoming xpcom value. nsISupports** variant = static_cast<nsISupports**>(aVariant.val.p); if (aParamInfo.IsIn() && *variant) { nsCOMPtr<nsISupports> in = do_QueryInterface(*variant); nsCOMPtr<nsISupports> out = do_QueryInterface((nsISupports*) xpcom_obj); if (in != out) { NS_RELEASE(*variant); } } *(static_cast<void**>(aVariant.val.p)) = xpcom_obj; } break; case nsXPTType::T_ASTRING: case nsXPTType::T_DOMSTRING: { NS_PRECONDITION(aParamInfo.IsDipper(), "string argument is not dipper"); if (!aParamInfo.IsDipper()) { rv = NS_ERROR_UNEXPECTED; break; } jstring jstr = (jstring) aJValue.l; nsString* variant = static_cast<nsString*>(aVariant.val.p); if (jstr) { // Get string buffer const jchar* wchar_ptr = env->GetStringChars(jstr, nsnull); if (!wchar_ptr) { rv = NS_ERROR_OUT_OF_MEMORY; break; } variant->Assign(wchar_ptr); // release String buffer env->ReleaseStringChars(jstr, wchar_ptr); } else { variant->SetIsVoid(PR_TRUE); } } break; case nsXPTType::T_UTF8STRING: case nsXPTType::T_CSTRING: { NS_PRECONDITION(aParamInfo.IsDipper(), "string argument is not dipper"); if (!aParamInfo.IsDipper()) { rv = NS_ERROR_UNEXPECTED; break; } jstring jstr = (jstring) aJValue.l; nsCString* variant = static_cast<nsCString*>(aVariant.val.p); if (jstr) { // Get string buffer const char* char_ptr = env->GetStringUTFChars(jstr, nsnull); if (!char_ptr) { rv = NS_ERROR_OUT_OF_MEMORY; break; } variant->Assign(char_ptr); // release String buffer env->ReleaseStringUTFChars(jstr, char_ptr); } else { variant->SetIsVoid(PR_TRUE); } } break; case nsXPTType::T_VOID: { if (aParamInfo.IsRetval()) { // 'retval' aVariant.val.p = reinterpret_cast<void*>(aJValue.j); } else if (aJValue.l) { // 'inout' & 'out' env->GetLongArrayRegion((jlongArray) aJValue.l, 0, 1, (jlong*) aVariant.val.p); } } break; default: NS_WARNING("unexpected parameter type"); return NS_ERROR_UNEXPECTED; } return rv; }
nsresult NS_NewSVGElement(nsIContent** aResult, nsINodeInfo *aNodeInfo, PRBool aFromParser) { NS_PRECONDITION(NS_SVGEnabled(), "creating an SVG element while SVG disabled"); static const char kSVGStyleSheetURI[] = "resource://gre/res/svg.css"; // this bit of code is to load svg.css on demand nsIDocument *doc = aNodeInfo->GetDocument(); if (doc) doc->EnsureCatalogStyleSheet(kSVGStyleSheetURI); nsIAtom *name = aNodeInfo->NameAtom(); if (name == nsGkAtoms::a) return NS_NewSVGAElement(aResult, aNodeInfo); if (name == nsGkAtoms::polyline) return NS_NewSVGPolylineElement(aResult, aNodeInfo); if (name == nsGkAtoms::polygon) return NS_NewSVGPolygonElement(aResult, aNodeInfo); if (name == nsGkAtoms::circle) return NS_NewSVGCircleElement(aResult, aNodeInfo); if (name == nsGkAtoms::ellipse) return NS_NewSVGEllipseElement(aResult, aNodeInfo); if (name == nsGkAtoms::line) return NS_NewSVGLineElement(aResult, aNodeInfo); if (name == nsGkAtoms::rect) return NS_NewSVGRectElement(aResult, aNodeInfo); if (name == nsGkAtoms::svg) return NS_NewSVGSVGElement(aResult, aNodeInfo, aFromParser); if (name == nsGkAtoms::g) return NS_NewSVGGElement(aResult, aNodeInfo); if (name == nsGkAtoms::foreignObject) return NS_NewSVGForeignObjectElement(aResult, aNodeInfo); if (name == nsGkAtoms::path) return NS_NewSVGPathElement(aResult, aNodeInfo); if (name == nsGkAtoms::text) return NS_NewSVGTextElement(aResult, aNodeInfo); if (name == nsGkAtoms::tspan) return NS_NewSVGTSpanElement(aResult, aNodeInfo); if (name == nsGkAtoms::image) return NS_NewSVGImageElement(aResult, aNodeInfo); if (name == nsGkAtoms::style) return NS_NewSVGStyleElement(aResult, aNodeInfo); if (name == nsGkAtoms::linearGradient) return NS_NewSVGLinearGradientElement(aResult, aNodeInfo); if (name == nsGkAtoms::metadata) return NS_NewSVGMetadataElement(aResult, aNodeInfo); if (name == nsGkAtoms::radialGradient) return NS_NewSVGRadialGradientElement(aResult, aNodeInfo); if (name == nsGkAtoms::stop) return NS_NewSVGStopElement(aResult, aNodeInfo); if (name == nsGkAtoms::defs) return NS_NewSVGDefsElement(aResult, aNodeInfo); if (name == nsGkAtoms::desc) return NS_NewSVGDescElement(aResult, aNodeInfo); if (name == nsGkAtoms::script) return NS_NewSVGScriptElement(aResult, aNodeInfo); if (name == nsGkAtoms::use) return NS_NewSVGUseElement(aResult, aNodeInfo); if (name == nsGkAtoms::symbol) return NS_NewSVGSymbolElement(aResult, aNodeInfo); if (name == nsGkAtoms::marker) return NS_NewSVGMarkerElement(aResult, aNodeInfo); if (name == nsGkAtoms::title) return NS_NewSVGTitleElement(aResult, aNodeInfo); if (name == nsGkAtoms::clipPath) return NS_NewSVGClipPathElement(aResult, aNodeInfo); if (name == nsGkAtoms::textPath) return NS_NewSVGTextPathElement(aResult, aNodeInfo); if (name == nsGkAtoms::filter) return NS_NewSVGFilterElement(aResult, aNodeInfo); if (name == nsGkAtoms::feBlend) return NS_NewSVGFEBlendElement(aResult, aNodeInfo); if (name == nsGkAtoms::feColorMatrix) return NS_NewSVGFEColorMatrixElement(aResult, aNodeInfo); if (name == nsGkAtoms::feComponentTransfer) return NS_NewSVGFEComponentTransferElement(aResult, aNodeInfo); if (name == nsGkAtoms::feComposite) return NS_NewSVGFECompositeElement(aResult, aNodeInfo); if (name == nsGkAtoms::feFuncR) return NS_NewSVGFEFuncRElement(aResult, aNodeInfo); if (name == nsGkAtoms::feFuncG) return NS_NewSVGFEFuncGElement(aResult, aNodeInfo); if (name == nsGkAtoms::feFuncB) return NS_NewSVGFEFuncBElement(aResult, aNodeInfo); if (name == nsGkAtoms::feFuncA) return NS_NewSVGFEFuncAElement(aResult, aNodeInfo); if (name == nsGkAtoms::feGaussianBlur) return NS_NewSVGFEGaussianBlurElement(aResult, aNodeInfo); if (name == nsGkAtoms::feMerge) return NS_NewSVGFEMergeElement(aResult, aNodeInfo); if (name == nsGkAtoms::feMergeNode) return NS_NewSVGFEMergeNodeElement(aResult, aNodeInfo); if (name == nsGkAtoms::feMorphology) return NS_NewSVGFEMorphologyElement(aResult, aNodeInfo); if (name == nsGkAtoms::feOffset) return NS_NewSVGFEOffsetElement(aResult, aNodeInfo); if (name == nsGkAtoms::feFlood) return NS_NewSVGFEFloodElement(aResult, aNodeInfo); if (name == nsGkAtoms::feTile) return NS_NewSVGFETileElement(aResult, aNodeInfo); if (name == nsGkAtoms::feTurbulence) return NS_NewSVGFETurbulenceElement(aResult, aNodeInfo); if (name == nsGkAtoms::feConvolveMatrix) return NS_NewSVGFEConvolveMatrixElement(aResult, aNodeInfo); if (name == nsGkAtoms::feDistantLight) return NS_NewSVGFEDistantLightElement(aResult, aNodeInfo); if (name == nsGkAtoms::fePointLight) return NS_NewSVGFEPointLightElement(aResult, aNodeInfo); if (name == nsGkAtoms::feSpotLight) return NS_NewSVGFESpotLightElement(aResult, aNodeInfo); if (name == nsGkAtoms::feDiffuseLighting) return NS_NewSVGFEDiffuseLightingElement(aResult, aNodeInfo); if (name == nsGkAtoms::feSpecularLighting) return NS_NewSVGFESpecularLightingElement(aResult, aNodeInfo); if (name == nsGkAtoms::feImage) return NS_NewSVGFEImageElement(aResult, aNodeInfo); if (name == nsGkAtoms::feDisplacementMap) return NS_NewSVGFEDisplacementMapElement(aResult, aNodeInfo); if (name == nsGkAtoms::pattern) return NS_NewSVGPatternElement(aResult, aNodeInfo); if (name == nsGkAtoms::mask) return NS_NewSVGMaskElement(aResult, aNodeInfo); if (name == nsGkAtoms::svgSwitch) return NS_NewSVGSwitchElement(aResult, aNodeInfo); #ifdef MOZ_SMIL if (NS_SMILEnabled()) { if (name == nsGkAtoms::animate) return NS_NewSVGAnimateElement(aResult, aNodeInfo); if (name == nsGkAtoms::animateTransform) return NS_NewSVGAnimateTransformElement(aResult, aNodeInfo); if (name == nsGkAtoms::set) return NS_NewSVGSetElement(aResult, aNodeInfo); } #endif // MOZ_SMIL // if we don't know what to create, just create a standard xml element: return NS_NewXMLElement(aResult, aNodeInfo); }
// same version of the above, but with correct casting and endian swapping static NS_METHOD WriteSegmentToString(nsIInputStream* aStream, void *aClosure, const char* aFromSegment, PRUint32 aToOffset, PRUint32 aCount, PRUint32 *aWriteCount) { NS_PRECONDITION(aCount > 0, "Why are we being told to write 0 bytes?"); NS_PRECONDITION(sizeof(PRUnichar) == 2, "We can't handle other sizes!"); WriteStringClosure* closure = static_cast<WriteStringClosure*>(aClosure); PRUnichar *cursor = closure->mWriteCursor; // we're always going to consume the whole buffer no matter what // happens, so take care of that right now.. that allows us to // tweak aCount later. Do NOT move this! *aWriteCount = aCount; // if the last Write had an odd-number of bytes read, then if (closure->mHasCarryoverByte) { // re-create the two-byte sequence we want to work with char bytes[2] = { closure->mCarryoverByte, *aFromSegment }; *cursor = *(PRUnichar*)bytes; // Now the little endianness dance #ifdef IS_LITTLE_ENDIAN *cursor = (PRUnichar) NS_SWAP16(*cursor); #endif ++cursor; // now skip past the first byte of the buffer.. code from here // can assume normal operations, but should not assume aCount // is relative to the ORIGINAL buffer ++aFromSegment; --aCount; closure->mHasCarryoverByte = false; } // this array is possibly unaligned... be careful how we access it! const PRUnichar *unicodeSegment = reinterpret_cast<const PRUnichar*>(aFromSegment); // calculate number of full characters in segment (aCount could be odd!) PRUint32 segmentLength = aCount / sizeof(PRUnichar); // copy all data into our aligned buffer. byte swap if necessary. memcpy(cursor, unicodeSegment, segmentLength * sizeof(PRUnichar)); PRUnichar *end = cursor + segmentLength; #ifdef IS_LITTLE_ENDIAN for (; cursor < end; ++cursor) *cursor = (PRUnichar) NS_SWAP16(*cursor); #endif closure->mWriteCursor = end; // remember this is the modifed aCount and aFromSegment, // so that will take into account the fact that we might have // skipped the first byte in the buffer if (aCount % sizeof(PRUnichar) != 0) { // we must have had a carryover byte, that we'll need the next // time around closure->mCarryoverByte = aFromSegment[aCount - 1]; closure->mHasCarryoverByte = true; } return NS_OK; }
NS_IMETHODIMP nsEudoraImport::GetImportInterface( const char *pImportType, nsISupports **ppInterface) { NS_PRECONDITION(pImportType != nsnull, "null ptr"); if (! pImportType) return NS_ERROR_NULL_POINTER; NS_PRECONDITION(ppInterface != nsnull, "null ptr"); if (! ppInterface) return NS_ERROR_NULL_POINTER; *ppInterface = nsnull; nsresult rv; if (!strcmp( pImportType, "mail")) { // create the nsIImportMail interface and return it! nsIImportMail * pMail = nsnull; nsIImportGeneric *pGeneric = nsnull; rv = ImportEudoraMailImpl::Create( &pMail); if (NS_SUCCEEDED( rv)) { nsCOMPtr<nsIImportService> impSvc(do_GetService(NS_IMPORTSERVICE_CONTRACTID, &rv)); if (NS_SUCCEEDED( rv)) { rv = impSvc->CreateNewGenericMail( &pGeneric); if (NS_SUCCEEDED( rv)) { pGeneric->SetData( "mailInterface", pMail); nsString name; nsEudoraStringBundle::GetStringByID( EUDORAIMPORT_NAME, name); nsCOMPtr<nsISupportsString> nameString (do_CreateInstance(NS_SUPPORTS_STRING_CONTRACTID, &rv)); if (NS_SUCCEEDED(rv)) { nameString->SetData(name); pGeneric->SetData( "name", nameString); rv = pGeneric->QueryInterface( kISupportsIID, (void **)ppInterface); } } } } NS_IF_RELEASE( pMail); NS_IF_RELEASE( pGeneric); return( rv); } if (!strcmp( pImportType, "addressbook")) { // create the nsIImportMail interface and return it! nsIImportAddressBooks * pAddress = nsnull; nsIImportGeneric * pGeneric = nsnull; rv = ImportEudoraAddressImpl::Create( &pAddress); if (NS_SUCCEEDED( rv)) { nsCOMPtr<nsIImportService> impSvc(do_GetService(NS_IMPORTSERVICE_CONTRACTID, &rv)); if (NS_SUCCEEDED( rv)) { rv = impSvc->CreateNewGenericAddressBooks( &pGeneric); if (NS_SUCCEEDED( rv)) { pGeneric->SetData( "addressInterface", pAddress); rv = pGeneric->QueryInterface( kISupportsIID, (void **)ppInterface); } } } NS_IF_RELEASE( pAddress); NS_IF_RELEASE( pGeneric); return( rv); } if (!strcmp( pImportType, "settings")) { nsIImportSettings *pSettings = nsnull; rv = nsEudoraSettings::Create( &pSettings); if (NS_SUCCEEDED( rv)) pSettings->QueryInterface( kISupportsIID, (void **)ppInterface); NS_IF_RELEASE( pSettings); return( rv); } if (!strcmp( pImportType, "filters")) { nsIImportFilters *pFilters = nsnull; rv = nsEudoraFilters::Create( &pFilters); if (NS_SUCCEEDED( rv)) pFilters->QueryInterface( kISupportsIID, (void **)ppInterface); NS_IF_RELEASE( pFilters); return( rv); } return( NS_ERROR_NOT_AVAILABLE); }
nsresult nsHtml5Parser::ParseHtml5Fragment(const nsAString& aSourceBuffer, nsIContent* aTargetNode, nsIAtom* aContextLocalName, PRInt32 aContextNamespace, bool aQuirks, bool aPreventScriptExecution) { NS_ENSURE_TRUE(aSourceBuffer.Length() <= PR_INT32_MAX, NS_ERROR_OUT_OF_MEMORY); nsIDocument* doc = aTargetNode->OwnerDoc(); nsIURI* uri = doc->GetDocumentURI(); NS_ENSURE_TRUE(uri, NS_ERROR_NOT_AVAILABLE); mExecutor->EnableFragmentMode(aPreventScriptExecution); Initialize(doc, uri, nsnull, nsnull); mExecutor->SetParser(this); mExecutor->SetNodeInfoManager(doc->NodeInfoManager()); nsIContent* target = aTargetNode; mTreeBuilder->setFragmentContext(aContextLocalName, aContextNamespace, &target, aQuirks); #ifdef DEBUG if (!aPreventScriptExecution) { NS_ASSERTION(!aTargetNode->IsInDoc(), "If script execution isn't prevented, " "the target node must not be in doc."); nsCOMPtr<nsIDOMDocumentFragment> domFrag = do_QueryInterface(aTargetNode); NS_ASSERTION(domFrag, "If script execution isn't prevented, must parse to DOM fragment."); } #endif NS_PRECONDITION(!mExecutor->HasStarted(), "Tried to start parse without initializing the parser."); mTreeBuilder->setScriptingEnabled(mExecutor->IsScriptEnabled()); mTokenizer->start(); mExecutor->Start(); // Don't call WillBuildModel in fragment case if (!aSourceBuffer.IsEmpty()) { bool lastWasCR = false; nsHtml5DependentUTF16Buffer buffer(aSourceBuffer); while (buffer.hasMore()) { buffer.adjust(lastWasCR); lastWasCR = false; if (buffer.hasMore()) { lastWasCR = mTokenizer->tokenizeBuffer(&buffer); if (mTreeBuilder->HasScript()) { // Flush on each script, because the execution prevention code // can handle at most one script per flush. mTreeBuilder->Flush(); // Move ops to the executor mExecutor->FlushDocumentWrite(); // run the ops } } } } mTokenizer->eof(); mTreeBuilder->StreamEnded(); mTreeBuilder->Flush(); mExecutor->FlushDocumentWrite(); mTokenizer->end(); mExecutor->DropParserAndPerfHint(); mExecutor->DropHeldElements(); mTreeBuilder->DropHandles(); mAtomTable.Clear(); return NS_OK; }
NS_IMETHODIMP ImportEudoraMailImpl::ImportMailbox(nsIImportMailboxDescriptor *pSource, nsIFile *pDestination, PRUnichar **pErrorLog, PRUnichar **pSuccessLog, bool *fatalError) { NS_PRECONDITION(pSource != nsnull, "null ptr"); NS_PRECONDITION(pDestination != nsnull, "null ptr"); NS_PRECONDITION(fatalError != nsnull, "null ptr"); nsString success; nsString error; if (!pSource || !pDestination || !fatalError) { IMPORT_LOG0( "*** Bad param passed to eudora mailbox import\n"); nsEudoraStringBundle::GetStringByID( EUDORAIMPORT_MAILBOX_BADPARAM, error); if (fatalError) *fatalError = true; SetLogs( success, error, pErrorLog, pSuccessLog); return NS_ERROR_NULL_POINTER; } bool abort = false; nsString name; PRUnichar * pName; if (NS_SUCCEEDED( pSource->GetDisplayName( &pName))) { name = pName; NS_Free( pName); } PRUint32 mailSize = 0; pSource->GetSize( &mailSize); if (mailSize == 0) { IMPORT_LOG0( "Mailbox size is 0, skipping mailbox.\n"); ReportSuccess( name, 0, &success); SetLogs( success, error, pErrorLog, pSuccessLog); return( NS_OK); } nsCOMPtr <nsILocalFile> inFile; if (NS_FAILED(pSource->GetFile( getter_AddRefs(inFile)))) { ReportError( EUDORAIMPORT_MAILBOX_BADSOURCEFILE, name, &error); SetLogs( success, error, pErrorLog, pSuccessLog); return( NS_ERROR_FAILURE); } #ifdef IMPORT_DEBUG nsCString pPath; inFile->GetNativePath(pPath); IMPORT_LOG1( "Import mailbox: %s\n", pPath.get()); #endif PRInt32 msgCount = 0; nsresult rv = NS_OK; m_bytes = 0; rv = m_eudora.ImportMailbox( &m_bytes, &abort, name.get(), inFile, pDestination, &msgCount); if (NS_SUCCEEDED( rv)) ReportSuccess( name, msgCount, &success); else ReportError( EUDORAIMPORT_MAILBOX_CONVERTERROR, name, &error); SetLogs( success, error, pErrorLog, pSuccessLog); IMPORT_LOG0( "*** Returning from eudora mailbox import\n"); return( rv); }
// not from interface void nsHtml5Parser::ParseUntilBlocked() { NS_PRECONDITION(!mExecutor->IsFragmentMode(), "ParseUntilBlocked called in fragment mode."); if (mBlocked || mExecutor->IsComplete() || mExecutor->IsBroken()) { return; } NS_ASSERTION(mExecutor->HasStarted(), "Bad life cycle."); mDocWriteSpeculatorActive = false; for (;;) { if (!mFirstBuffer->hasMore()) { if (mFirstBuffer == mLastBuffer) { if (mExecutor->IsComplete()) { // something like cache manisfests stopped the parse in mid-flight return; } if (mDocumentClosed) { NS_ASSERTION(!mStreamParser, "This should only happen with script-created parser."); mTokenizer->eof(); mTreeBuilder->StreamEnded(); mTreeBuilder->Flush(); mExecutor->FlushDocumentWrite(); mTokenizer->end(); return; } // never release the last buffer. NS_ASSERTION(!mLastBuffer->getStart() && !mLastBuffer->getEnd(), "Sentinel buffer had its indeces changed."); if (mStreamParser) { if (mReturnToStreamParserPermitted && !mExecutor->IsScriptExecuting()) { mTreeBuilder->Flush(); mReturnToStreamParserPermitted = false; mStreamParser->ContinueAfterScripts(mTokenizer, mTreeBuilder, mLastWasCR); } } else { // Script-created parser mTreeBuilder->Flush(); // No need to flush the executor, because the executor is already // in a flush NS_ASSERTION(mExecutor->IsInFlushLoop(), "How did we come here without being in the flush loop?"); } return; // no more data for now but expecting more } mFirstBuffer = mFirstBuffer->next; continue; } if (mBlocked || mExecutor->IsComplete()) { return; } // now we have a non-empty buffer mFirstBuffer->adjust(mLastWasCR); mLastWasCR = false; if (mFirstBuffer->hasMore()) { bool inRootContext = (!mStreamParser && (mFirstBuffer->key == mRootContextKey)); if (inRootContext) { mTokenizer->setLineNumber(mRootContextLineNumber); } mLastWasCR = mTokenizer->tokenizeBuffer(mFirstBuffer); if (inRootContext) { mRootContextLineNumber = mTokenizer->getLineNumber(); } if (mTreeBuilder->HasScript()) { mTreeBuilder->Flush(); mExecutor->FlushDocumentWrite(); } if (mBlocked) { return; } } continue; } }
NS_IMETHODIMP ImportEudoraAddressImpl::ImportAddressBook(nsIImportABDescriptor *pSource, nsIAddrDatabase *pDestination, nsIImportFieldMap *fieldMap, nsISupports *aSupportService, PRUnichar **pErrorLog, PRUnichar **pSuccessLog, bool *fatalError) { NS_PRECONDITION(pSource != nsnull, "null ptr"); NS_PRECONDITION(pDestination != nsnull, "null ptr"); NS_PRECONDITION(fatalError != nsnull, "null ptr"); nsString success; nsString error; if (!pSource || !pDestination || !fatalError) { IMPORT_LOG0( "*** Bad param passed to eudora address import\n"); nsEudoraStringBundle::GetStringByID(EUDORAIMPORT_ADDRESS_BADPARAM, error); if (fatalError) *fatalError = true; ImportEudoraMailImpl::SetLogs( success, error, pErrorLog, pSuccessLog); return NS_ERROR_NULL_POINTER; } bool abort = false; nsString name; pSource->GetPreferredName(name); PRUint32 addressSize = 0; pSource->GetSize( &addressSize); if (addressSize == 0) { IMPORT_LOG0( "Address book size is 0, skipping mailbox.\n"); ReportSuccess( name, &success); ImportEudoraMailImpl::SetLogs( success, error, pErrorLog, pSuccessLog); return( NS_OK); } nsCOMPtr<nsIFile> inFile; if (NS_FAILED(pSource->GetAbFile(getter_AddRefs(inFile)))) { ImportEudoraMailImpl::ReportError( EUDORAIMPORT_ADDRESS_BADSOURCEFILE, name, &error); ImportEudoraMailImpl::SetLogs( success, error, pErrorLog, pSuccessLog); return( NS_ERROR_FAILURE); } #ifdef IMPORT_DEBUG nsCString path; inFile->GetNativePath(path); IMPORT_LOG1( "Import address book: %s\n", path.get()); #endif nsresult rv = NS_OK; m_bytes = 0; rv = m_eudora.ImportAddresses( &m_bytes, &abort, name.get(), inFile, pDestination, error); if (NS_SUCCEEDED( rv) && error.IsEmpty()) { ReportSuccess( name, &success); } else { ImportEudoraMailImpl::ReportError( EUDORAIMPORT_ADDRESS_CONVERTERROR, name, &error); } ImportEudoraMailImpl::SetLogs( success, error, pErrorLog, pSuccessLog); IMPORT_LOG0( "*** Returning from eudora address import\n"); return( rv); }
NS_IMETHODIMP nsHTMLButtonControlFrame::Reflow(nsPresContext* aPresContext, nsHTMLReflowMetrics& aDesiredSize, const nsHTMLReflowState& aReflowState, nsReflowStatus& aStatus) { DO_GLOBAL_REFLOW_COUNT("nsHTMLButtonControlFrame"); DISPLAY_REFLOW(aPresContext, this, aReflowState, aDesiredSize, aStatus); NS_PRECONDITION(aReflowState.ComputedWidth() != NS_INTRINSICSIZE, "Should have real computed width by now"); if (mState & NS_FRAME_FIRST_REFLOW) { nsFormControlFrame::RegUnRegAccessKey(static_cast<nsIFrame*>(this), PR_TRUE); } // Reflow the child nsIFrame* firstKid = mFrames.FirstChild(); // XXXbz Eventually we may want to check-and-bail if // !aReflowState.ShouldReflowAllKids() && // !NS_SUBTREE_DIRTY(firstKid). // We'd need to cache our ascent for that, of course. nsMargin focusPadding = mRenderer.GetAddedButtonBorderAndPadding(); // Reflow the contents of the button. ReflowButtonContents(aPresContext, aDesiredSize, aReflowState, firstKid, focusPadding, aStatus); aDesiredSize.width = aReflowState.ComputedWidth(); // If computed use the computed value. if (aReflowState.ComputedHeight() != NS_INTRINSICSIZE) aDesiredSize.height = aReflowState.ComputedHeight(); else aDesiredSize.height += focusPadding.TopBottom(); aDesiredSize.width += aReflowState.mComputedBorderPadding.LeftRight(); aDesiredSize.height += aReflowState.mComputedBorderPadding.TopBottom(); // Make sure we obey min/max-height. Note that we do this after adjusting // for borderpadding, since buttons have border-box sizing... // XXXbz unless someone overrides that, of course! We should really consider // exposing nsHTMLReflowState::AdjustComputed* or something. aDesiredSize.height = NS_CSS_MINMAX(aDesiredSize.height, aReflowState.mComputedMinHeight, aReflowState.mComputedMaxHeight); aDesiredSize.ascent += aReflowState.mComputedBorderPadding.top + focusPadding.top; aDesiredSize.mOverflowArea = nsRect(0, 0, aDesiredSize.width, aDesiredSize.height); ConsiderChildOverflow(aDesiredSize.mOverflowArea, firstKid); FinishAndStoreOverflow(&aDesiredSize); aStatus = NS_FRAME_COMPLETE; NS_FRAME_SET_TRUNCATION(aStatus, aReflowState, aDesiredSize); return NS_OK; }
NS_IMETHODIMP nsChromeProtocolHandler::NewChannel(nsIURI* aURI, nsIChannel* *aResult) { nsresult rv; NS_ENSURE_ARG_POINTER(aURI); NS_PRECONDITION(aResult, "Null out param"); #ifdef DEBUG // Check that the uri we got is already canonified nsresult debug_rv; nsCOMPtr<nsIURI> debugClone; debug_rv = aURI->Clone(getter_AddRefs(debugClone)); if (NS_SUCCEEDED(debug_rv)) { nsCOMPtr<nsIURL> debugURL (do_QueryInterface(debugClone)); debug_rv = nsChromeRegistry::Canonify(debugURL); if (NS_SUCCEEDED(debug_rv)) { bool same; debug_rv = aURI->Equals(debugURL, &same); if (NS_SUCCEEDED(debug_rv)) { NS_ASSERTION(same, "Non-canonified chrome uri passed to nsChromeProtocolHandler::NewChannel!"); } } } #endif nsCOMPtr<nsIChannel> result; if (!nsChromeRegistry::gChromeRegistry) { // We don't actually want this ref, we just want the service to // initialize if it hasn't already. nsCOMPtr<nsIChromeRegistry> reg = mozilla::services::GetChromeRegistryService(); NS_ENSURE_TRUE(nsChromeRegistry::gChromeRegistry, NS_ERROR_FAILURE); } nsCOMPtr<nsIURI> resolvedURI; rv = nsChromeRegistry::gChromeRegistry->ConvertChromeURL(aURI, getter_AddRefs(resolvedURI)); if (NS_FAILED(rv)) { #ifdef DEBUG nsAutoCString spec; aURI->GetSpec(spec); printf("Couldn't convert chrome URL: %s\n", spec.get()); #endif return rv; } nsCOMPtr<nsIIOService> ioServ(do_GetIOService(&rv)); NS_ENSURE_SUCCESS(rv, rv); rv = ioServ->NewChannelFromURI(resolvedURI, getter_AddRefs(result)); if (NS_FAILED(rv)) return rv; #ifdef DEBUG nsCOMPtr<nsIFileChannel> fileChan(do_QueryInterface(result)); if (fileChan) { nsCOMPtr<nsIFile> file; fileChan->GetFile(getter_AddRefs(file)); bool exists = false; file->Exists(&exists); if (!exists) { nsAutoCString path; file->GetNativePath(path); printf("Chrome file doesn't exist: %s\n", path.get()); } } #endif // Make sure that the channel remembers where it was // originally loaded from. nsLoadFlags loadFlags = 0; result->GetLoadFlags(&loadFlags); result->SetLoadFlags(loadFlags & ~nsIChannel::LOAD_REPLACE); rv = result->SetOriginalURI(aURI); if (NS_FAILED(rv)) return rv; // Get a system principal for content files and set the owner // property of the result nsCOMPtr<nsIURL> url = do_QueryInterface(aURI); nsAutoCString path; rv = url->GetPath(path); if (StringBeginsWith(path, NS_LITERAL_CSTRING("/content/"))) { nsCOMPtr<nsIScriptSecurityManager> securityManager = do_GetService(NS_SCRIPTSECURITYMANAGER_CONTRACTID, &rv); if (NS_FAILED(rv)) return rv; nsCOMPtr<nsIPrincipal> principal; rv = securityManager->GetSystemPrincipal(getter_AddRefs(principal)); if (NS_FAILED(rv)) return rv; nsCOMPtr<nsISupports> owner = do_QueryInterface(principal); result->SetOwner(owner); } // XXX Removed dependency-tracking code from here, because we're not // tracking them anyways (with fastload we checked only in DEBUG // and with startupcache not at all), but this is where we would start // if we need to re-add. // See bug 531886, bug 533038. result->SetContentCharset(NS_LITERAL_CSTRING("UTF-8")); *aResult = result; NS_ADDREF(*aResult); return NS_OK; }