RawPtr<Text> Text::replaceWholeText(const String& newText) { // Remove all adjacent text nodes, and replace the contents of this one. // Protect startText and endText against mutation event handlers removing the last ref RawPtr<Text> startText = const_cast<Text*>(earliestLogicallyAdjacentTextNode(this)); RawPtr<Text> endText = const_cast<Text*>(latestLogicallyAdjacentTextNode(this)); RawPtr<Text> protectedThis(this); // Mutation event handlers could cause our last ref to go away RawPtr<ContainerNode> parent = parentNode(); // Protect against mutation handlers moving this node during traversal for (RawPtr<Node> n = startText; n && n != this && n->isTextNode() && n->parentNode() == parent;) { RawPtr<Node> nodeToRemove(n.release()); n = nodeToRemove->nextSibling(); parent->removeChild(nodeToRemove.get(), IGNORE_EXCEPTION); } if (this != endText) { Node* onePastEndText = endText->nextSibling(); for (RawPtr<Node> n = nextSibling(); n && n != onePastEndText && n->isTextNode() && n->parentNode() == parent;) { RawPtr<Node> nodeToRemove(n.release()); n = nodeToRemove->nextSibling(); parent->removeChild(nodeToRemove.get(), IGNORE_EXCEPTION); } } if (newText.isEmpty()) { if (parent && parentNode() == parent) parent->removeChild(this, IGNORE_EXCEPTION); return nullptr; } setData(newText); return protectedThis.release(); }
void WorkerGlobalScope::addConsoleMessage(RawPtr<ConsoleMessage> prpConsoleMessage) { ASSERT(isContextThread()); RawPtr<ConsoleMessage> consoleMessage = prpConsoleMessage; thread()->workerReportingProxy().reportConsoleMessage(consoleMessage); addMessageToWorkerConsole(consoleMessage.release()); }
RawPtr<DateTimeWeekFieldElement> DateTimeWeekFieldElement::create(Document& document, FieldOwner& fieldOwner, const Range& range) { DEFINE_STATIC_LOCAL(AtomicString, weekPseudoId, ("-webkit-datetime-edit-week-field")); RawPtr<DateTimeWeekFieldElement> field = new DateTimeWeekFieldElement(document, fieldOwner, range); field->initialize(weekPseudoId, queryString(WebLocalizedString::AXWeekOfYearFieldText)); return field.release(); }
RawPtr<DateTimeDayFieldElement> DateTimeDayFieldElement::create(Document& document, FieldOwner& fieldOwner, const String& placeholder, const Range& range) { DEFINE_STATIC_LOCAL(AtomicString, dayPseudoId, ("-webkit-datetime-edit-day-field")); RawPtr<DateTimeDayFieldElement> field = new DateTimeDayFieldElement(document, fieldOwner, placeholder.isEmpty() ? "--" : placeholder, range); field->initialize(dayPseudoId, queryString(WebLocalizedString::AXDayOfMonthFieldText)); return field.release(); }
RawPtr<Text> GranularityStrategyTest::setupRotate(String str) { setInnerHTML( "<html>" "<head>" "<style>" "div {" "transform: translate(0px,600px) rotate(90deg);" "}" "</style>" "</head>" "<body>" "<div id='mytext'></div>" "</body>" "</html>"); RawPtr<Text> text = document().createTextNode(str); Element* div = document().getElementById("mytext"); div->appendChild(text); document().view()->updateAllLifecyclePhases(); parseText(text.get()); return text.release(); }
RawPtr<SVGPropertyBase> SVGAngleInterpolationType::appliedSVGValue(const InterpolableValue& interpolableValue, const NonInterpolableValue*) const { double doubleValue = toInterpolableNumber(interpolableValue).value(); RawPtr<SVGAngle> result = SVGAngle::create(); result->newValueSpecifiedUnits(SVGAngle::SVG_ANGLETYPE_DEG, doubleValue); return result.release(); }
void revoke() { ExecutionContext* executionContext = m_scriptState->getExecutionContext(); if (!executionContext) return; ScriptState::Scope scope(m_scriptState); v8::Local<v8::Value> value = m_promise.newLocal(m_scriptState->isolate()); v8::Local<v8::Value> reason = m_exception.newLocal(m_scriptState->isolate()); // Either collected or https://crbug.com/450330 if (value.IsEmpty() || !value->IsPromise()) return; EventTarget* target = executionContext->errorEventTarget(); if (RuntimeEnabledFeatures::promiseRejectionEventEnabled() && target && !executionContext->shouldSanitizeScriptError(m_resourceName, m_corsStatus)) { PromiseRejectionEventInit init; init.setPromise(ScriptPromise(m_scriptState, value)); init.setReason(ScriptValue(m_scriptState, reason)); RawPtr<PromiseRejectionEvent> event = PromiseRejectionEvent::create(m_scriptState, EventTypeNames::rejectionhandled, init); target->dispatchEvent(event); } if (m_shouldLogToConsole) { RawPtr<ConsoleMessage> consoleMessage = ConsoleMessage::create(JSMessageSource, RevokedErrorMessageLevel, "Handler added to rejected promise"); consoleMessage->setRelatedMessageId(m_consoleMessageId); executionContext->addConsoleMessage(consoleMessage.release()); } }
RawPtr<Element> InsertParagraphSeparatorCommand::cloneHierarchyUnderNewBlock(const HeapVector<Member<Element>>& ancestors, RawPtr<Element> blockToInsert, EditingState* editingState) { // Make clones of ancestors in between the start node and the start block. RawPtr<Element> parent = blockToInsert; for (size_t i = ancestors.size(); i != 0; --i) { RawPtr<Element> child = ancestors[i - 1]->cloneElementWithoutChildren(); // It should always be okay to remove id from the cloned elements, since the originals are not deleted. child->removeAttribute(idAttr); appendNode(child, parent, editingState); if (editingState->isAborted()) return nullptr; parent = child.release(); } return parent.release(); }
RawPtr<HTMLVideoElement> HTMLVideoElement::create(Document& document) { RawPtr<HTMLVideoElement> video = new HTMLVideoElement(document); video->ensureUserAgentShadowRoot(); video->suspendIfNeeded(); return video.release(); }
RawPtr<DateTimeYearFieldElement> DateTimeYearFieldElement::create(Document& document, FieldOwner& fieldOwner, const DateTimeYearFieldElement::Parameters& parameters) { DEFINE_STATIC_LOCAL(AtomicString, yearPseudoId, ("-webkit-datetime-edit-year-field")); RawPtr<DateTimeYearFieldElement> field = new DateTimeYearFieldElement(document, fieldOwner, parameters); field->initialize(yearPseudoId, queryString(WebLocalizedString::AXYearFieldText)); return field.release(); }
RawPtr<DateTimeAMPMFieldElement> DateTimeAMPMFieldElement::create(Document& document, FieldOwner& fieldOwner, const Vector<String>& ampmLabels) { DEFINE_STATIC_LOCAL(AtomicString, ampmPseudoId, ("-webkit-datetime-edit-ampm-field")); RawPtr<DateTimeAMPMFieldElement> field = new DateTimeAMPMFieldElement(document, fieldOwner, ampmLabels); field->initialize(ampmPseudoId, queryString(WebLocalizedString::AXAMPMFieldText)); return field.release(); }
RawPtr<DateTimeSymbolicMonthFieldElement> DateTimeSymbolicMonthFieldElement::create(Document& document, FieldOwner& fieldOwner, const Vector<String>& labels, int minimum, int maximum) { DEFINE_STATIC_LOCAL(AtomicString, monthPseudoId, ("-webkit-datetime-edit-month-field")); RawPtr<DateTimeSymbolicMonthFieldElement> field = new DateTimeSymbolicMonthFieldElement(document, fieldOwner, labels, minimum, maximum); field->initialize(monthPseudoId, queryString(WebLocalizedString::AXMonthFieldText)); return field.release(); }
RawPtr<DateTimeSecondFieldElement> DateTimeSecondFieldElement::create(Document& document, FieldOwner& fieldOwner, const Range& range, const Step& step) { DEFINE_STATIC_LOCAL(AtomicString, secondPseudoId, ("-webkit-datetime-edit-second-field")); RawPtr<DateTimeSecondFieldElement> field = new DateTimeSecondFieldElement(document, fieldOwner, range, step); field->initialize(secondPseudoId, queryString(WebLocalizedString::AXSecondFieldText)); return field.release(); }
RawPtr<Text> Text::splitText(unsigned offset, ExceptionState& exceptionState) { // IndexSizeError: Raised if the specified offset is negative or greater than // the number of 16-bit units in data. if (offset > length()) { exceptionState.throwDOMException(IndexSizeError, "The offset " + String::number(offset) + " is larger than the Text node's length."); return nullptr; } EventQueueScope scope; String oldStr = data(); RawPtr<Text> newText = cloneWithData(oldStr.substring(offset)); setDataWithoutUpdate(oldStr.substring(0, offset)); didModifyData(oldStr, CharacterData::UpdateFromNonParser); if (parentNode()) parentNode()->insertBefore(newText.get(), nextSibling(), exceptionState); if (exceptionState.hadException()) return nullptr; if (layoutObject()) layoutObject()->setTextWithOffset(dataImpl(), 0, oldStr.length()); if (parentNode()) document().didSplitTextNode(*this); return newText.release(); }
void ConsoleBase::timeEnd(ScriptState* scriptState, const String& title) { TRACE_EVENT_COPY_ASYNC_END0("blink.console", title.utf8().data(), this); // Follow Firebug's behavior of requiring a title that is not null or // undefined for timing functions if (title.isNull()) return; HashMap<String, double>::iterator it = m_times.find(title); if (it == m_times.end()) return; double startTime = it->value; m_times.remove(it); double elapsed = monotonicallyIncreasingTime() - startTime; String message = title + String::format(": %.3fms", elapsed * 1000); RawPtr<ConsoleMessage> consoleMessage = ConsoleMessage::create(ConsoleAPIMessageSource, DebugMessageLevel, message); consoleMessage->setType(TimeEndMessageType); consoleMessage->setScriptState(scriptState); consoleMessage->setCallStack(ScriptCallStack::capture(1)); reportMessageToConsole(consoleMessage.release()); }
static RawPtr<EditingStyle> styleFromMatchedRulesAndInlineDecl(const HTMLElement* element) { RawPtr<EditingStyle> style = EditingStyle::create(element->inlineStyle()); // FIXME: Having to const_cast here is ugly, but it is quite a bit of work to untangle // the non-const-ness of styleFromMatchedRulesForElement. style->mergeStyleFromRules(const_cast<HTMLElement*>(element)); return style.release(); }
RawPtr<DateTimeHour23FieldElement> DateTimeHour23FieldElement::create(Document& document, FieldOwner& fieldOwner, const Range& hour23Range, const Step& step) { ASSERT(hour23Range.minimum >= 0); ASSERT(hour23Range.maximum <= 23); ASSERT(hour23Range.minimum <= hour23Range.maximum); RawPtr<DateTimeHour23FieldElement> field = new DateTimeHour23FieldElement(document, fieldOwner, hour23Range, step); field->initialize(); return field.release(); }
void SourceBuffer::scheduleEvent(const AtomicString& eventName) { ASSERT(m_asyncEventQueue); RawPtr<Event> event = Event::create(eventName); event->setTarget(this); m_asyncEventQueue->enqueueEvent(event.release()); }
static void entriesMethod(const v8::FunctionCallbackInfo<v8::Value>& info) { ExceptionState exceptionState(ExceptionState::ExecutionContext, "entries", "TestInterface3", info.Holder(), info.GetIsolate()); TestInterface3* impl = V8TestInterface3::toImpl(info.Holder()); ScriptState* scriptState = ScriptState::current(info.GetIsolate()); RawPtr<Iterator> result = impl->entriesForBinding(scriptState, exceptionState); if (exceptionState.hadException()) { exceptionState.throwIfNeeded(); return; } v8SetReturnValue(info, result.release()); }
void report() { if (!m_scriptState->contextIsValid()) return; // If execution termination has been triggered, quietly bail out. if (m_scriptState->isolate()->IsExecutionTerminating()) return; ExecutionContext* executionContext = m_scriptState->getExecutionContext(); if (!executionContext) return; ScriptState::Scope scope(m_scriptState); v8::Local<v8::Value> value = m_promise.newLocal(m_scriptState->isolate()); v8::Local<v8::Value> reason = m_exception.newLocal(m_scriptState->isolate()); // Either collected or https://crbug.com/450330 if (value.IsEmpty() || !value->IsPromise()) return; ASSERT(!hasHandler()); EventTarget* target = executionContext->errorEventTarget(); if (RuntimeEnabledFeatures::promiseRejectionEventEnabled() && target && !executionContext->shouldSanitizeScriptError(m_resourceName, m_corsStatus)) { PromiseRejectionEventInit init; init.setPromise(ScriptPromise(m_scriptState, value)); init.setReason(ScriptValue(m_scriptState, reason)); init.setCancelable(true); RawPtr<PromiseRejectionEvent> event = PromiseRejectionEvent::create(m_scriptState, EventTypeNames::unhandledrejection, init); // Log to console if event was not canceled. m_shouldLogToConsole = target->dispatchEvent(event) == DispatchEventResult::NotCanceled; } if (m_shouldLogToConsole) { const String errorMessage = "Uncaught (in promise)"; Vector<ScriptValue> args; args.append(ScriptValue(m_scriptState, v8String(m_scriptState->isolate(), errorMessage))); args.append(ScriptValue(m_scriptState, reason)); RawPtr<ScriptArguments> arguments = ScriptArguments::create(m_scriptState, args); String embedderErrorMessage = m_errorMessage; if (embedderErrorMessage.isEmpty()) embedderErrorMessage = errorMessage; else if (embedderErrorMessage.startsWith("Uncaught ")) embedderErrorMessage.insert(" (in promise)", 8); RawPtr<ConsoleMessage> consoleMessage = ConsoleMessage::create(JSMessageSource, ErrorMessageLevel, embedderErrorMessage, m_resourceName, m_lineNumber, m_columnNumber); consoleMessage->setScriptArguments(arguments); consoleMessage->setCallStack(m_callStack); consoleMessage->setScriptId(m_scriptId); m_consoleMessageId = consoleMessage->assignMessageId(); executionContext->addConsoleMessage(consoleMessage.release()); } m_callStack.clear(); }
static void iteratorMethod(const v8::FunctionCallbackInfo<v8::Value>& info) { ExceptionState exceptionState(ExceptionState::ExecutionContext, "iterator", "TestInterfaceGarbageCollected", info.Holder(), info.GetIsolate()); TestInterfaceGarbageCollected* impl = V8TestInterfaceGarbageCollected::toImpl(info.Holder()); ScriptState* scriptState = ScriptState::current(info.GetIsolate()); RawPtr<Iterator> result = impl->iterator(scriptState, exceptionState); if (exceptionState.hadException()) { exceptionState.throwIfNeeded(); return; } v8SetReturnValue(info, result.release()); }
RawPtr<CSSValue> CSSVariableResolver::resolveVariableReferences(StyleVariableData* styleVariableData, CSSPropertyID id, const CSSVariableReferenceValue& value) { ASSERT(!isShorthandProperty(id)); CSSVariableResolver resolver(styleVariableData); Vector<CSSParserToken> tokens; if (!resolver.resolveTokenRange(value.variableDataValue()->tokens(), tokens)) return cssValuePool().createUnsetValue(); RawPtr<CSSValue> result = CSSPropertyParser::parseSingleValue(id, tokens, strictCSSParserContext()); if (!result) return cssValuePool().createUnsetValue(); return result.release(); }
String CSSContentDistributionValue::customCSSText() const { RawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated(); if (m_distribution != CSSValueInvalid) list->append(distribution()); if (m_position != CSSValueInvalid) list->append(position()); if (m_overflow != CSSValueInvalid) list->append(overflow()); return list.release()->customCSSText(); }
RawPtr<DateTimeHour11FieldElement> DateTimeHour11FieldElement::create(Document& document, FieldOwner& fieldOwner, const Range& hour23Range, const Step& step) { ASSERT(hour23Range.minimum >= 0); ASSERT(hour23Range.maximum <= 23); ASSERT(hour23Range.minimum <= hour23Range.maximum); Range range(0, 11); if (hour23Range.maximum < 12) range = hour23Range; else if (hour23Range.minimum >= 12) { range.minimum = hour23Range.minimum - 12; range.maximum = hour23Range.maximum - 12; } RawPtr<DateTimeHour11FieldElement> field = new DateTimeHour11FieldElement(document, fieldOwner, range, step); field->initialize(); return field.release(); }
static void constructor(const v8::FunctionCallbackInfo<v8::Value>& info) { v8::Isolate* isolate = info.GetIsolate(); if (UNLIKELY(info.Length() < 1)) { throwMinimumArityTypeErrorForConstructor("TestInterfaceGarbageCollected", 1, info.Length(), info.GetIsolate()); return; } V8StringResource<> str; { TOSTRING_VOID_INTERNAL(str, info[0]); } RawPtr<TestInterfaceGarbageCollected> impl = TestInterfaceGarbageCollected::create(str); v8::Handle<v8::Object> wrapper = info.Holder(); V8DOMWrapper::associateObjectWithWrapper<V8TestInterfaceGarbageCollected>(impl.release(), &V8TestInterfaceGarbageCollected::wrapperTypeInfo, wrapper, isolate, WrapperConfiguration::Independent); v8SetReturnValue(info, wrapper); }
PassOwnPtr<TestCompositorWorkerThread> createCompositorWorker(WaitableEvent* startEvent) { TestCompositorWorkerThread* workerThread = new TestCompositorWorkerThread(nullptr, *m_objectProxy, 0, startEvent); RawPtr<WorkerClients> clients = nullptr; workerThread->start(WorkerThreadStartupData::create( KURL(ParsedURLString, "http://fake.url/"), "fake user agent", "//fake source code", nullptr, DontPauseWorkerGlobalScopeOnStart, adoptPtr(new Vector<CSPHeaderAndType>()), m_securityOrigin.get(), clients.release(), WebAddressSpaceLocal, V8CacheOptionsDefault)); return adoptPtr(workerThread); }
RawPtr<ClickHandlingState> CheckboxInputType::willDispatchClick() { // An event handler can use preventDefault or "return false" to reverse the checking we do here. // The ClickHandlingState object contains what we need to undo what we did here in didDispatchClick. RawPtr<ClickHandlingState> state = new ClickHandlingState; state->checked = element().checked(); state->indeterminate = element().indeterminate(); if (state->indeterminate) element().setIndeterminate(false); element().setChecked(!state->checked, DispatchChangeEvent); m_isInClickHandler = true; return state.release(); }
void WorkerGlobalScope::importScripts(const Vector<String>& urls, ExceptionState& exceptionState) { ASSERT(contentSecurityPolicy()); ASSERT(getExecutionContext()); ExecutionContext& executionContext = *this->getExecutionContext(); Vector<KURL> completedURLs; for (const String& urlString : urls) { const KURL& url = executionContext.completeURL(urlString); if (!url.isValid()) { exceptionState.throwDOMException(SyntaxError, "The URL '" + urlString + "' is invalid."); return; } if (!contentSecurityPolicy()->allowScriptFromSource(url)) { exceptionState.throwDOMException(NetworkError, "The script at '" + url.elidedString() + "' failed to load."); return; } completedURLs.append(url); } for (const KURL& completeURL : completedURLs) { RefPtr<WorkerScriptLoader> scriptLoader(WorkerScriptLoader::create()); scriptLoader->setRequestContext(WebURLRequest::RequestContextScript); scriptLoader->loadSynchronously(executionContext, completeURL, AllowCrossOriginRequests, executionContext.securityContext().addressSpace()); // If the fetching attempt failed, throw a NetworkError exception and abort all these steps. if (scriptLoader->failed()) { exceptionState.throwDOMException(NetworkError, "The script at '" + completeURL.elidedString() + "' failed to load."); return; } InspectorInstrumentation::scriptImported(&executionContext, scriptLoader->identifier(), scriptLoader->script()); scriptLoaded(scriptLoader->script().length(), scriptLoader->cachedMetadata() ? scriptLoader->cachedMetadata()->size() : 0); RawPtr<ErrorEvent> errorEvent = nullptr; OwnPtr<Vector<char>> cachedMetaData(scriptLoader->releaseCachedMetadata()); RawPtr<CachedMetadataHandler> handler(createWorkerScriptCachedMetadataHandler(completeURL, cachedMetaData.get())); m_scriptController->evaluate(ScriptSourceCode(scriptLoader->script(), scriptLoader->responseURL()), &errorEvent, handler.get(), m_v8CacheOptions); if (errorEvent) { m_scriptController->rethrowExceptionFromImportedScript(errorEvent.release(), exceptionState); return; } } }
void V8LazyEventListener::fireErrorEvent(v8::Local<v8::Context> v8Context, ExecutionContext* executionContext, v8::Local<v8::Message> message) { String messageText = toCoreStringWithNullCheck(message->Get()); int lineNumber = 0; int columnNumber = 0; if (v8Call(message->GetLineNumber(v8Context), lineNumber) && v8Call(message->GetStartColumn(v8Context), columnNumber)) ++columnNumber; RawPtr<ErrorEvent> event = ErrorEvent::create(messageText, m_sourceURL, lineNumber, columnNumber, &world()); AccessControlStatus accessControlStatus = NotSharableCrossOrigin; if (message->IsOpaque()) accessControlStatus = OpaqueResource; else if (message->IsSharedCrossOrigin()) accessControlStatus = SharableCrossOrigin; executionContext->reportException(event.release(), 0, nullptr, accessControlStatus); }
void ConsoleBase::internalAddMessage(MessageType type, MessageLevel level, ScriptState* scriptState, RawPtr<ScriptArguments> scriptArguments, bool acceptNoArguments) { RawPtr<ScriptArguments> arguments = scriptArguments; if (!acceptNoArguments && (!arguments || !arguments->argumentCount())) return; if (scriptState && !scriptState->contextIsValid()) arguments.clear(); String message; if (arguments) arguments->getFirstArgumentAsString(message); RawPtr<ConsoleMessage> consoleMessage = ConsoleMessage::create(ConsoleAPIMessageSource, level, message); consoleMessage->setType(type); consoleMessage->setScriptState(scriptState); consoleMessage->setScriptArguments(arguments); consoleMessage->setCallStack(ScriptCallStack::captureForConsole()); reportMessageToConsole(consoleMessage.release()); }