/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* A namespace class for static layout utilities. */ #include "mozilla/DebugOnly.h" #include "mozilla/Util.h" #include "mozilla/Likely.h" #include "jsapi.h" #include "jsdbgapi.h" #include "jsfriendapi.h" #include #include "Layers.h" #include "nsJSUtils.h" #include "nsCOMPtr.h" #include "nsAString.h" #include "nsPrintfCString.h" #include "nsIScriptGlobalObject.h" #include "nsIScriptContext.h" #include "nsDOMCID.h" #include "nsContentUtils.h" #include "nsIXPConnect.h" #include "nsIContent.h" #include "mozilla/dom/Element.h" #include "nsIDocument.h" #include "nsINodeInfo.h" #include "nsIIdleService.h" #include "nsIDOMDocument.h" #include "nsIDOMNodeList.h" #include "nsIDOMNode.h" #include "nsIIOService.h" #include "nsNetCID.h" #include "nsNetUtil.h" #include "nsIScriptSecurityManager.h" #include "nsPIDOMWindow.h" #include "nsIJSContextStack.h" #include "nsIDocShell.h" #include "nsIDocShellTreeItem.h" #include "nsParserCIID.h" #include "nsIParser.h" #include "nsIFragmentContentSink.h" #include "nsIContentSink.h" #include "nsContentList.h" #include "nsIHTMLDocument.h" #include "nsIDOMHTMLFormElement.h" #include "nsIDOMHTMLElement.h" #include "nsIForm.h" #include "nsIFormControl.h" #include "nsGkAtoms.h" #include "imgINotificationObserver.h" #include "imgRequestProxy.h" #include "imgIContainer.h" #include "imgLoader.h" #include "nsDocShellCID.h" #include "nsIImageLoadingContent.h" #include "nsIInterfaceRequestor.h" #include "nsIInterfaceRequestorUtils.h" #include "nsILoadGroup.h" #include "nsIObserver.h" #include "nsIObserverService.h" #include "nsContentPolicyUtils.h" #include "nsNodeInfoManager.h" #include "nsCRT.h" #include "nsIDOMEvent.h" #include "nsIDOMEventTarget.h" #include "nsIMIMEService.h" #include "nsLWBrkCIID.h" #include "nsILineBreaker.h" #include "nsIWordBreaker.h" #include "nsUnicodeProperties.h" #include "harfbuzz/hb.h" #include "nsIJSRuntimeService.h" #include "nsBindingManager.h" #include "nsIURI.h" #include "nsIURL.h" #include "nsICharsetConverterManager.h" #include "nsEventListenerManager.h" #include "nsAttrName.h" #include "nsIDOMUserDataHandler.h" #include "nsContentCreatorFunctions.h" #include "nsMutationEvent.h" #include "nsIMEStateManager.h" #include "nsError.h" #include "nsUnicharUtilCIID.h" #include "nsINativeKeyBindings.h" #include "nsXULPopupManager.h" #include "nsIPermissionManager.h" #include "nsIScriptObjectPrincipal.h" #include "nsNullPrincipal.h" #include "nsIRunnable.h" #include "nsDOMJSUtils.h" #include "nsGenericHTMLElement.h" #include "nsAttrValue.h" #include "nsAttrValueInlines.h" #include "nsReferencedElement.h" #include "nsIDragService.h" #include "nsIChannelEventSink.h" #include "nsIAsyncVerifyRedirectCallback.h" #include "nsIOfflineCacheUpdate.h" #include "nsCPrefetchService.h" #include "nsIChromeRegistry.h" #include "nsEventDispatcher.h" #include "nsIDOMXULCommandEvent.h" #include "nsDOMDataTransfer.h" #include "nsHtml5Module.h" #include "nsPresContext.h" #include "nsLayoutStatics.h" #include "nsFocusManager.h" #include "nsTextEditorState.h" #include "nsIPluginHost.h" #include "nsICategoryManager.h" #include "nsViewManager.h" #include "nsEventStateManager.h" #include "nsIDOMHTMLInputElement.h" #include "nsParserConstants.h" #include "nsIWebNavigation.h" #include "nsILoadContext.h" #include "nsTextFragment.h" #include "mozilla/Selection.h" #include #ifdef IBMBIDI #include "nsIBidiKeyboard.h" #endif #include "nsCycleCollectionParticipant.h" // for ReportToConsole #include "nsIStringBundle.h" #include "nsIScriptError.h" #include "nsIConsoleService.h" #include "mozAutoDocUpdate.h" #include "imgICache.h" #include "imgLoader.h" #include "xpcprivate.h" // nsXPConnect #include "nsScriptSecurityManager.h" #include "nsIChannelPolicy.h" #include "nsChannelPolicy.h" #include "nsIContentSecurityPolicy.h" #include "nsContentDLF.h" #ifdef MOZ_MEDIA #include "nsHTMLMediaElement.h" #endif #include "nsDOMTouchEvent.h" #include "nsIContentViewer.h" #include "nsIObjectLoadingContent.h" #include "nsCCUncollectableMarker.h" #include "mozilla/Base64.h" #include "mozilla/Preferences.h" #include "nsDOMMutationObserver.h" #include "nsIDOMDocumentType.h" #include "nsCharSeparatedTokenizer.h" #include "nsICharsetDetector.h" #include "nsICharsetDetectionObserver.h" #include "nsIPlatformCharset.h" #include "nsIEditor.h" #include "nsIEditorDocShell.h" #include "mozilla/Attributes.h" #include "nsIParserService.h" #include "nsIDOMScriptObjectFactory.h" #include "nsSandboxFlags.h" #include "nsSVGFeatures.h" #include "MediaDecoder.h" #include "DecoderTraits.h" #include "nsWrapperCacheInlines.h" #include "nsViewportInfo.h" extern "C" int MOZ_XMLTranslateEntity(const char* ptr, const char* end, const char** next, PRUnichar* result); extern "C" int MOZ_XMLCheckQName(const char* ptr, const char* end, int ns_aware, const char** colon); class imgLoader; using namespace mozilla::dom; using namespace mozilla::layers; using namespace mozilla::widget; using namespace mozilla; const char kLoadAsData[] = "loadAsData"; nsIDOMScriptObjectFactory *nsContentUtils::sDOMScriptObjectFactory = nullptr; nsIXPConnect *nsContentUtils::sXPConnect; nsIScriptSecurityManager *nsContentUtils::sSecurityManager; nsIThreadJSContextStack *nsContentUtils::sThreadJSContextStack; nsIParserService *nsContentUtils::sParserService = nullptr; nsINameSpaceManager *nsContentUtils::sNameSpaceManager; nsIIOService *nsContentUtils::sIOService; imgLoader *nsContentUtils::sImgLoader; imgLoader *nsContentUtils::sPrivateImgLoader; imgICache *nsContentUtils::sImgCache; imgICache *nsContentUtils::sPrivateImgCache; nsIConsoleService *nsContentUtils::sConsoleService; nsDataHashtable* nsContentUtils::sAtomEventTable = nullptr; nsDataHashtable* nsContentUtils::sStringEventTable = nullptr; nsCOMArray* nsContentUtils::sUserDefinedEvents = nullptr; nsIStringBundleService *nsContentUtils::sStringBundleService; nsIStringBundle *nsContentUtils::sStringBundles[PropertiesFile_COUNT]; nsIContentPolicy *nsContentUtils::sContentPolicyService; bool nsContentUtils::sTriedToGetContentPolicy = false; nsILineBreaker *nsContentUtils::sLineBreaker; nsIWordBreaker *nsContentUtils::sWordBreaker; #ifdef IBMBIDI nsIBidiKeyboard *nsContentUtils::sBidiKeyboard = nullptr; #endif uint32_t nsContentUtils::sScriptBlockerCount = 0; #ifdef DEBUG uint32_t nsContentUtils::sDOMNodeRemovedSuppressCount = 0; #endif uint32_t nsContentUtils::sMicroTaskLevel = 0; nsTArray< nsCOMPtr >* nsContentUtils::sBlockedScriptRunners = nullptr; uint32_t nsContentUtils::sRunnersCountAtFirstBlocker = 0; nsIInterfaceRequestor* nsContentUtils::sSameOriginChecker = nullptr; bool nsContentUtils::sIsHandlingKeyBoardEvent = false; bool nsContentUtils::sAllowXULXBL_for_file = false; nsString* nsContentUtils::sShiftText = nullptr; nsString* nsContentUtils::sControlText = nullptr; nsString* nsContentUtils::sMetaText = nullptr; nsString* nsContentUtils::sOSText = nullptr; nsString* nsContentUtils::sAltText = nullptr; nsString* nsContentUtils::sModifierSeparator = nullptr; bool nsContentUtils::sInitialized = false; bool nsContentUtils::sIsFullScreenApiEnabled = false; bool nsContentUtils::sTrustedFullScreenOnly = true; bool nsContentUtils::sIsIdleObserverAPIEnabled = false; uint32_t nsContentUtils::sHandlingInputTimeout = 1000; nsHtml5StringParser* nsContentUtils::sHTMLFragmentParser = nullptr; nsIParser* nsContentUtils::sXMLFragmentParser = nullptr; nsIFragmentContentSink* nsContentUtils::sXMLFragmentSink = nullptr; bool nsContentUtils::sFragmentParsingActive = false; namespace { static const char kJSStackContractID[] = "@mozilla.org/js/xpc/ContextStack;1"; static NS_DEFINE_CID(kParserServiceCID, NS_PARSERSERVICE_CID); static NS_DEFINE_CID(kCParserCID, NS_PARSER_CID); static PLDHashTable sEventListenerManagersHash; class DOMEventListenerManagersHashReporter MOZ_FINAL : public MemoryReporterBase { public: DOMEventListenerManagersHashReporter() : MemoryReporterBase( "explicit/dom/event-listener-managers-hash", KIND_HEAP, UNITS_BYTES, "Memory used by the event listener manager's hash table.") {} private: int64_t Amount() { // We don't measure the |nsEventListenerManager| objects pointed to by the // entries because those references are non-owning. return sEventListenerManagersHash.ops ? PL_DHashTableSizeOfExcludingThis(&sEventListenerManagersHash, nullptr, MallocSizeOf) : 0; } }; class EventListenerManagerMapEntry : public PLDHashEntryHdr { public: EventListenerManagerMapEntry(const void *aKey) : mKey(aKey) { } ~EventListenerManagerMapEntry() { NS_ASSERTION(!mListenerManager, "caller must release and disconnect ELM"); } protected: // declared protected to silence clang warnings const void *mKey; // must be first, to look like PLDHashEntryStub public: nsRefPtr mListenerManager; }; static bool EventListenerManagerHashInitEntry(PLDHashTable *table, PLDHashEntryHdr *entry, const void *key) { // Initialize the entry with placement new new (entry) EventListenerManagerMapEntry(key); return true; } static void EventListenerManagerHashClearEntry(PLDHashTable *table, PLDHashEntryHdr *entry) { EventListenerManagerMapEntry *lm = static_cast(entry); // Let the EventListenerManagerMapEntry clean itself up... lm->~EventListenerManagerMapEntry(); } class SameOriginChecker MOZ_FINAL : public nsIChannelEventSink, public nsIInterfaceRequestor { NS_DECL_ISUPPORTS NS_DECL_NSICHANNELEVENTSINK NS_DECL_NSIINTERFACEREQUESTOR }; class CharsetDetectionObserver MOZ_FINAL : public nsICharsetDetectionObserver { public: NS_DECL_ISUPPORTS NS_IMETHOD Notify(const char *aCharset, nsDetectionConfident aConf) { mCharset = aCharset; return NS_OK; } const nsACString& GetResult() const { return mCharset; } private: nsCString mCharset; }; } // anonymous namespace /* static */ TimeDuration nsContentUtils::HandlingUserInputTimeout() { return TimeDuration::FromMilliseconds(sHandlingInputTimeout); } // static nsresult nsContentUtils::Init() { if (sInitialized) { NS_WARNING("Init() called twice"); return NS_OK; } nsresult rv = NS_GetNameSpaceManager(&sNameSpaceManager); NS_ENSURE_SUCCESS(rv, rv); nsXPConnect* xpconnect = nsXPConnect::GetXPConnect(); NS_ENSURE_TRUE(xpconnect, NS_ERROR_FAILURE); sXPConnect = xpconnect; sThreadJSContextStack = xpconnect; sSecurityManager = nsScriptSecurityManager::GetScriptSecurityManager(); if(!sSecurityManager) return NS_ERROR_FAILURE; NS_ADDREF(sSecurityManager); rv = CallGetService(NS_IOSERVICE_CONTRACTID, &sIOService); if (NS_FAILED(rv)) { // This makes life easier, but we can live without it. sIOService = nullptr; } rv = CallGetService(NS_LBRK_CONTRACTID, &sLineBreaker); NS_ENSURE_SUCCESS(rv, rv); rv = CallGetService(NS_WBRK_CONTRACTID, &sWordBreaker); NS_ENSURE_SUCCESS(rv, rv); if (!InitializeEventTable()) return NS_ERROR_FAILURE; if (!sEventListenerManagersHash.ops) { static PLDHashTableOps hash_table_ops = { PL_DHashAllocTable, PL_DHashFreeTable, PL_DHashVoidPtrKeyStub, PL_DHashMatchEntryStub, PL_DHashMoveEntryStub, EventListenerManagerHashClearEntry, PL_DHashFinalizeStub, EventListenerManagerHashInitEntry }; if (!PL_DHashTableInit(&sEventListenerManagersHash, &hash_table_ops, nullptr, sizeof(EventListenerManagerMapEntry), 16)) { sEventListenerManagersHash.ops = nullptr; return NS_ERROR_OUT_OF_MEMORY; } NS_RegisterMemoryReporter(new DOMEventListenerManagersHashReporter); } sBlockedScriptRunners = new nsTArray< nsCOMPtr >; Preferences::AddBoolVarCache(&sAllowXULXBL_for_file, "dom.allow_XUL_XBL_for_file"); Preferences::AddBoolVarCache(&sIsFullScreenApiEnabled, "full-screen-api.enabled"); Preferences::AddBoolVarCache(&sTrustedFullScreenOnly, "full-screen-api.allow-trusted-requests-only"); sIsIdleObserverAPIEnabled = Preferences::GetBool("dom.idle-observers-api.enabled", true); Preferences::AddUintVarCache(&sHandlingInputTimeout, "dom.event.handling-user-input-time-limit", 1000); Element::InitCCCallbacks(); sInitialized = true; return NS_OK; } void nsContentUtils::GetShiftText(nsAString& text) { if (!sShiftText) InitializeModifierStrings(); text.Assign(*sShiftText); } void nsContentUtils::GetControlText(nsAString& text) { if (!sControlText) InitializeModifierStrings(); text.Assign(*sControlText); } void nsContentUtils::GetMetaText(nsAString& text) { if (!sMetaText) InitializeModifierStrings(); text.Assign(*sMetaText); } void nsContentUtils::GetOSText(nsAString& text) { if (!sOSText) { InitializeModifierStrings(); } text.Assign(*sOSText); } void nsContentUtils::GetAltText(nsAString& text) { if (!sAltText) InitializeModifierStrings(); text.Assign(*sAltText); } void nsContentUtils::GetModifierSeparatorText(nsAString& text) { if (!sModifierSeparator) InitializeModifierStrings(); text.Assign(*sModifierSeparator); } void nsContentUtils::InitializeModifierStrings() { //load the display strings for the keyboard accelerators nsCOMPtr bundleService = mozilla::services::GetStringBundleService(); nsCOMPtr bundle; DebugOnly rv = NS_OK; if (bundleService) { rv = bundleService->CreateBundle( "chrome://global-platform/locale/platformKeys.properties", getter_AddRefs(bundle)); } NS_ASSERTION(NS_SUCCEEDED(rv) && bundle, "chrome://global/locale/platformKeys.properties could not be loaded"); nsXPIDLString shiftModifier; nsXPIDLString metaModifier; nsXPIDLString osModifier; nsXPIDLString altModifier; nsXPIDLString controlModifier; nsXPIDLString modifierSeparator; if (bundle) { //macs use symbols for each modifier key, so fetch each from the bundle, which also covers i18n bundle->GetStringFromName(NS_LITERAL_STRING("VK_SHIFT").get(), getter_Copies(shiftModifier)); bundle->GetStringFromName(NS_LITERAL_STRING("VK_META").get(), getter_Copies(metaModifier)); bundle->GetStringFromName(NS_LITERAL_STRING("VK_WIN").get(), getter_Copies(osModifier)); bundle->GetStringFromName(NS_LITERAL_STRING("VK_ALT").get(), getter_Copies(altModifier)); bundle->GetStringFromName(NS_LITERAL_STRING("VK_CONTROL").get(), getter_Copies(controlModifier)); bundle->GetStringFromName(NS_LITERAL_STRING("MODIFIER_SEPARATOR").get(), getter_Copies(modifierSeparator)); } //if any of these don't exist, we get an empty string sShiftText = new nsString(shiftModifier); sMetaText = new nsString(metaModifier); sOSText = new nsString(osModifier); sAltText = new nsString(altModifier); sControlText = new nsString(controlModifier); sModifierSeparator = new nsString(modifierSeparator); } bool nsContentUtils::sImgLoaderInitialized; void nsContentUtils::InitImgLoader() { sImgLoaderInitialized = true; // Ignore failure and just don't load images sImgLoader = imgLoader::Create(); NS_ABORT_IF_FALSE(sImgLoader, "Creation should have succeeded"); sPrivateImgLoader = imgLoader::Create(); NS_ABORT_IF_FALSE(sPrivateImgLoader, "Creation should have succeeded"); NS_ADDREF(sImgCache = sImgLoader); NS_ADDREF(sPrivateImgCache = sPrivateImgLoader); sPrivateImgCache->RespectPrivacyNotifications(); } bool nsContentUtils::InitializeEventTable() { NS_ASSERTION(!sAtomEventTable, "EventTable already initialized!"); NS_ASSERTION(!sStringEventTable, "EventTable already initialized!"); static const EventNameMapping eventArray[] = { #define EVENT(name_, _id, _type, _struct) \ { nsGkAtoms::on##name_, _id, _type, _struct }, #define WINDOW_ONLY_EVENT EVENT #define NON_IDL_EVENT EVENT #include "nsEventNameList.h" #undef WINDOW_ONLY_EVENT #undef EVENT { nullptr } }; sAtomEventTable = new nsDataHashtable; sStringEventTable = new nsDataHashtable; sUserDefinedEvents = new nsCOMArray(64); sAtomEventTable->Init(int(ArrayLength(eventArray) / 0.75) + 1); sStringEventTable->Init(int(ArrayLength(eventArray) / 0.75) + 1); // Subtract one from the length because of the trailing null for (uint32_t i = 0; i < ArrayLength(eventArray) - 1; ++i) { sAtomEventTable->Put(eventArray[i].mAtom, eventArray[i]); sStringEventTable->Put(Substring(nsDependentAtomString(eventArray[i].mAtom), 2), eventArray[i]); } return true; } void nsContentUtils::InitializeTouchEventTable() { static bool sEventTableInitialized = false; if (!sEventTableInitialized && sAtomEventTable && sStringEventTable) { sEventTableInitialized = true; static const EventNameMapping touchEventArray[] = { #define EVENT(name_, _id, _type, _struct) #define TOUCH_EVENT(name_, _id, _type, _struct) \ { nsGkAtoms::on##name_, _id, _type, _struct }, #include "nsEventNameList.h" #undef TOUCH_EVENT #undef EVENT { nullptr } }; // Subtract one from the length because of the trailing null for (uint32_t i = 0; i < ArrayLength(touchEventArray) - 1; ++i) { sAtomEventTable->Put(touchEventArray[i].mAtom, touchEventArray[i]); sStringEventTable->Put(Substring(nsDependentAtomString(touchEventArray[i].mAtom), 2), touchEventArray[i]); } } } static bool Is8bit(const nsAString& aString) { static const PRUnichar EIGHT_BIT = PRUnichar(~0x00FF); nsAString::const_iterator done_reading; aString.EndReading(done_reading); // for each chunk of |aString|... uint32_t fragmentLength = 0; nsAString::const_iterator iter; for (aString.BeginReading(iter); iter != done_reading; iter.advance(int32_t(fragmentLength))) { fragmentLength = uint32_t(iter.size_forward()); const PRUnichar* c = iter.get(); const PRUnichar* fragmentEnd = c + fragmentLength; // for each character in this chunk... while (c < fragmentEnd) { if (*c++ & EIGHT_BIT) { return false; } } } return true; } nsresult nsContentUtils::Btoa(const nsAString& aBinaryData, nsAString& aAsciiBase64String) { if (!Is8bit(aBinaryData)) { aAsciiBase64String.Truncate(); return NS_ERROR_DOM_INVALID_CHARACTER_ERR; } return Base64Encode(aBinaryData, aAsciiBase64String); } nsresult nsContentUtils::Atob(const nsAString& aAsciiBase64String, nsAString& aBinaryData) { if (!Is8bit(aAsciiBase64String)) { aBinaryData.Truncate(); return NS_ERROR_DOM_INVALID_CHARACTER_ERR; } nsresult rv = Base64Decode(aAsciiBase64String, aBinaryData); if (NS_FAILED(rv) && rv == NS_ERROR_INVALID_ARG) { return NS_ERROR_DOM_INVALID_CHARACTER_ERR; } return rv; } bool nsContentUtils::IsAutocompleteEnabled(nsIDOMHTMLInputElement* aInput) { NS_PRECONDITION(aInput, "aInput should not be null!"); nsAutoString autocomplete; aInput->GetAutocomplete(autocomplete); if (autocomplete.IsEmpty()) { nsCOMPtr form; aInput->GetForm(getter_AddRefs(form)); if (!form) { return true; } form->GetAutocomplete(autocomplete); } return autocomplete.EqualsLiteral("on"); } #define SKIP_WHITESPACE(iter, end_iter, end_res) \ while ((iter) != (end_iter) && nsCRT::IsAsciiSpace(*(iter))) { \ ++(iter); \ } \ if ((iter) == (end_iter)) { \ return (end_res); \ } #define SKIP_ATTR_NAME(iter, end_iter) \ while ((iter) != (end_iter) && !nsCRT::IsAsciiSpace(*(iter)) && \ *(iter) != '=') { \ ++(iter); \ } bool nsContentUtils::GetPseudoAttributeValue(const nsString& aSource, nsIAtom *aName, nsAString& aValue) { aValue.Truncate(); const PRUnichar *start = aSource.get(); const PRUnichar *end = start + aSource.Length(); const PRUnichar *iter; while (start != end) { SKIP_WHITESPACE(start, end, false) iter = start; SKIP_ATTR_NAME(iter, end) if (start == iter) { return false; } // Remember the attr name. const nsDependentSubstring & attrName = Substring(start, iter); // Now check whether this is a valid name="value" pair. start = iter; SKIP_WHITESPACE(start, end, false) if (*start != '=') { // No '=', so this is not a name="value" pair. We don't know // what it is, and we have no way to handle it. return false; } // Have to skip the value. ++start; SKIP_WHITESPACE(start, end, false) PRUnichar q = *start; if (q != kQuote && q != kApostrophe) { // Not a valid quoted value, so bail. return false; } ++start; // Point to the first char of the value. iter = start; while (iter != end && *iter != q) { ++iter; } if (iter == end) { // Oops, unterminated quoted string. return false; } // At this point attrName holds the name of the "attribute" and // the value is between start and iter. if (aName->Equals(attrName)) { // We'll accumulate as many characters as possible (until we hit either // the end of the string or the beginning of an entity). Chunks will be // delimited by start and chunkEnd. const PRUnichar *chunkEnd = start; while (chunkEnd != iter) { if (*chunkEnd == kLessThan) { aValue.Truncate(); return false; } if (*chunkEnd == kAmpersand) { aValue.Append(start, chunkEnd - start); // Point to first character after the ampersand. ++chunkEnd; const PRUnichar *afterEntity = nullptr; PRUnichar result[2]; uint32_t count = MOZ_XMLTranslateEntity(reinterpret_cast(chunkEnd), reinterpret_cast(iter), reinterpret_cast(&afterEntity), result); if (count == 0) { aValue.Truncate(); return false; } aValue.Append(result, count); // Advance to after the entity and begin a new chunk. start = chunkEnd = afterEntity; } else { ++chunkEnd; } } // Append remainder. aValue.Append(start, iter - start); return true; } // Resume scanning after the end of the attribute value (past the quote // char). start = iter + 1; } return false; } bool nsContentUtils::IsJavaScriptLanguage(const nsString& aName, uint32_t *aFlags) { JSVersion version = JSVERSION_UNKNOWN; if (aName.LowerCaseEqualsLiteral("javascript") || aName.LowerCaseEqualsLiteral("livescript") || aName.LowerCaseEqualsLiteral("mocha") || aName.LowerCaseEqualsLiteral("javascript1.0") || aName.LowerCaseEqualsLiteral("javascript1.1") || aName.LowerCaseEqualsLiteral("javascript1.2") || aName.LowerCaseEqualsLiteral("javascript1.3") || aName.LowerCaseEqualsLiteral("javascript1.4") || aName.LowerCaseEqualsLiteral("javascript1.5")) { version = JSVERSION_DEFAULT; } else if (aName.LowerCaseEqualsLiteral("javascript1.6")) { version = JSVERSION_1_6; } else if (aName.LowerCaseEqualsLiteral("javascript1.7")) { version = JSVERSION_1_7; } else if (aName.LowerCaseEqualsLiteral("javascript1.8")) { version = JSVERSION_1_8; } if (version == JSVERSION_UNKNOWN) { return false; } *aFlags = version; return true; } JSVersion nsContentUtils::ParseJavascriptVersion(const nsAString& aVersionStr) { if (aVersionStr.Length() != 3 || aVersionStr[0] != '1' || aVersionStr[1] != '.') { return JSVERSION_UNKNOWN; } switch (aVersionStr[2]) { case '0': /* fall through */ case '1': /* fall through */ case '2': /* fall through */ case '3': /* fall through */ case '4': /* fall through */ case '5': return JSVERSION_DEFAULT; case '6': return JSVERSION_1_6; case '7': return JSVERSION_1_7; case '8': return JSVERSION_1_8; default: return JSVERSION_UNKNOWN; } } void nsContentUtils::SplitMimeType(const nsAString& aValue, nsString& aType, nsString& aParams) { aType.Truncate(); aParams.Truncate(); int32_t semiIndex = aValue.FindChar(PRUnichar(';')); if (-1 != semiIndex) { aType = Substring(aValue, 0, semiIndex); aParams = Substring(aValue, semiIndex + 1, aValue.Length() - (semiIndex + 1)); aParams.StripWhitespace(); } else { aType = aValue; } aType.StripWhitespace(); } nsresult nsContentUtils::IsUserIdle(uint32_t aRequestedIdleTimeInMS, bool* aUserIsIdle) { nsresult rv; nsCOMPtr idleService = do_GetService("@mozilla.org/widget/idleservice;1", &rv); NS_ENSURE_SUCCESS(rv, rv); uint32_t idleTimeInMS; rv = idleService->GetIdleTime(&idleTimeInMS); NS_ENSURE_SUCCESS(rv, rv); *aUserIsIdle = idleTimeInMS >= aRequestedIdleTimeInMS; return NS_OK; } /** * Access a cached parser service. Don't addref. We need only one * reference to it and this class has that one. */ /* static */ nsIParserService* nsContentUtils::GetParserService() { // XXX: This isn't accessed from several threads, is it? if (!sParserService) { // Lock, recheck sCachedParserService and aquire if this should be // safe for multiple threads. nsresult rv = CallGetService(kParserServiceCID, &sParserService); if (NS_FAILED(rv)) { sParserService = nullptr; } } return sParserService; } /** * A helper function that parses a sandbox attribute (of an