Пример #1
0
int processFile(char *inputFile, char *outputString, int lineNumber)
{
	FILE *infile;
	int stringSize = 80;		// max size of one line in file 
	char inputStr[stringSize];
	struct stat fileStatus;
	int fileSize=0;
	int lineCount=0;
	  
	if (lineNumber < 0)
		  return (-1);

	if ((infile = fopen (inputFile, "r")) == NULL) {
	    printf ("Fatal error opening file %s\n",inputFile);
	    return (0);
	}
    memset (&fileStatus, 0, sizeof(fileStatus));
    if (!stat(inputFile, &fileStatus)) {
      if (S_ISREG(fileStatus.st_mode)) {
        fileSize = fileStatus.st_size;
      }
    }

  while (!feof(infile)) {
    if (fgets (inputStr, stringSize, infile) != NULL) {
      // Skip empty lines
      if (emptyString(inputStr))
        continue;
      // Skip comment lines
      if (inputStr[0] == '#' || inputStr[0] == '!')
        continue;

      lineCount++;
      if (lineNumber == 0)
        continue;
      else
      {
    	  if (lineCount == lineNumber)
    		  break;
      }
    }
  }

  // close file 
  fclose (infile);
  // if number lines requested return the count
  if (lineNumber == 0)
	  return (lineCount);
  // check for input out of range
  if (lineNumber > lineCount)
	  return (-1);
  // return the line selected
  if (lineCount) {
    stripString(inputStr);
    strcpy(outputString, inputStr);
    return(lineCount);
  } 
  else {
    return(-1);
  }
}
Пример #2
0
String InputMethodContext::locale() const
{
    // FIXME: Implement this.
    return emptyString();
}
String HTMLAnchorElement::search() const
{
    String query = href().query();
    return query.isEmpty() ? emptyString() : "?" + query;
}
Пример #4
0
String NavigatorBase::platform() const
{
#if OS(LINUX)
    if (!String(WEBCORE_NAVIGATOR_PLATFORM).isEmpty())
        return WEBCORE_NAVIGATOR_PLATFORM;
    struct utsname osname;
    DEPRECATED_DEFINE_STATIC_LOCAL(String, platformName, (uname(&osname) >= 0 ? String(osname.sysname) + String(" ") + String(osname.machine) : emptyString()));
    return platformName;
#else
    return WEBCORE_NAVIGATOR_PLATFORM;
#endif
}
Пример #5
0
WebCLGetInfo WebCLDevice::getInfo(CCenum infoType, ExceptionObject& exception)
{
    if (!WebCLInputChecker::isValidDeviceInfoType(infoType)) {
        setExceptionFromComputeErrorCode(ComputeContext::INVALID_VALUE, exception);
        return WebCLGetInfo();
    }

    CCerror err = 0;
    switch (infoType) {
    case ComputeContext::DEVICE_PROFILE:
        return WebCLGetInfo(String("WEBCL_PROFILE"));
    case ComputeContext::DEVICE_VERSION:
        return WebCLGetInfo(String("WebCL 1.0"));
    case ComputeContext::DEVICE_OPENCL_C_VERSION:
        return WebCLGetInfo(String("WebCL C 1.0"));
    case ComputeContext::DRIVER_VERSION: // Vendor specific. Will return a empty string.
    case ComputeContext::DEVICE_NAME:
    case ComputeContext::DEVICE_VENDOR:
    case ComputeContext::DEVICE_EXTENSIONS:
        return WebCLGetInfo(emptyString());
    case ComputeContext::DEVICE_VENDOR_ID: // Vendor specific.
        return WebCLGetInfo(static_cast<CCuint>(0));
    case ComputeContext::DEVICE_IMAGE_SUPPORT:
    case ComputeContext::DEVICE_AVAILABLE:
    case ComputeContext::DEVICE_COMPILER_AVAILABLE:
        return WebCLGetInfo(true);
    case ComputeContext::DEVICE_MAX_WORK_ITEM_SIZES: { // size_t[]
        Vector<size_t> workItemSizes;
        err = platformObject()->getDeviceInfo(infoType, &workItemSizes);
        if (err == ComputeContext::SUCCESS) {
            Vector<CCuint, 3> values;
            for (size_t i = 0; i < workItemSizes.size(); ++i)
                values.uncheckedAppend(workItemSizes[i]);
            return WebCLGetInfo(values);
        }
        break;
    }
    case ComputeContext::DEVICE_MAX_WORK_GROUP_SIZE: 
    case ComputeContext::DEVICE_MAX_PARAMETER_SIZE:
    case ComputeContext::DEVICE_PROFILING_TIMER_RESOLUTION:
    case ComputeContext::DEVICE_IMAGE2D_MAX_HEIGHT:
    case ComputeContext::DEVICE_IMAGE2D_MAX_WIDTH:
    case ComputeContext::DEVICE_IMAGE3D_MAX_HEIGHT:
    case ComputeContext::DEVICE_IMAGE3D_MAX_DEPTH:
    case ComputeContext::DEVICE_IMAGE3D_MAX_WIDTH: {
        size_t infoValue = 0;
        err = platformObject()->getDeviceInfo(infoType, &infoValue);
        if (err == ComputeContext::SUCCESS)
            return WebCLGetInfo(static_cast<CCuint>(infoValue));
        break;
    }
    case ComputeContext::DEVICE_MAX_WORK_ITEM_DIMENSIONS:
    case ComputeContext::DEVICE_PREFERRED_VECTOR_WIDTH_CHAR:
    case ComputeContext::DEVICE_PREFERRED_VECTOR_WIDTH_SHORT:
    case ComputeContext::DEVICE_PREFERRED_VECTOR_WIDTH_INT:
    case ComputeContext::DEVICE_PREFERRED_VECTOR_WIDTH_LONG:
    case ComputeContext::DEVICE_PREFERRED_VECTOR_WIDTH_FLOAT:
    case ComputeContext::DEVICE_NATIVE_VECTOR_WIDTH_CHAR:
    case ComputeContext::DEVICE_NATIVE_VECTOR_WIDTH_SHORT:
    case ComputeContext::DEVICE_NATIVE_VECTOR_WIDTH_INT:
    case ComputeContext::DEVICE_NATIVE_VECTOR_WIDTH_LONG:
    case ComputeContext::DEVICE_NATIVE_VECTOR_WIDTH_FLOAT:
    case ComputeContext::DEVICE_MAX_CLOCK_FREQUENCY:
    case ComputeContext::DEVICE_MAX_READ_IMAGE_ARGS:
    case ComputeContext::DEVICE_MAX_WRITE_IMAGE_ARGS:
    case ComputeContext::DEVICE_MAX_SAMPLERS:
    case ComputeContext::DEVICE_MEM_BASE_ADDR_ALIGN:
    case ComputeContext::DEVICE_GLOBAL_MEM_CACHELINE_SIZE:
    case ComputeContext::DEVICE_MAX_CONSTANT_ARGS:
    case ComputeContext::DEVICE_ADDRESS_BITS:
    case ComputeContext::DEVICE_MAX_COMPUTE_UNITS: {
        CCuint infoValue = 0;
        err = platformObject()->getDeviceInfo(infoType, &infoValue);
        if (err == ComputeContext::SUCCESS)
            return WebCLGetInfo(static_cast<CCuint>(infoValue));
        break;
    }
    case ComputeContext::DEVICE_NATIVE_VECTOR_WIDTH_DOUBLE:
    case ComputeContext::DEVICE_PREFERRED_VECTOR_WIDTH_DOUBLE: {
        if (!isEnabledExtension("KHR_fp64"))
            return WebCLGetInfo(0);
        CCuint infoValue = 0;
        err = platformObject()->getDeviceInfo(infoType, &infoValue);
        if (err == ComputeContext::SUCCESS)
            return WebCLGetInfo(static_cast<CCuint>(infoValue));
        break;
    }
    case ComputeContext::DEVICE_NATIVE_VECTOR_WIDTH_HALF:
    case ComputeContext::DEVICE_PREFERRED_VECTOR_WIDTH_HALF: {
        if (!isEnabledExtension("KHR_fp16"))
            return WebCLGetInfo(0);
        CCuint infoValue = 0;
        err = platformObject()->getDeviceInfo(infoType, &infoValue);
        if (err == ComputeContext::SUCCESS)
            return WebCLGetInfo(static_cast<CCuint>(infoValue));
        break;
    }
    case ComputeContext::DEVICE_LOCAL_MEM_SIZE:
    case ComputeContext::DEVICE_MAX_CONSTANT_BUFFER_SIZE:
    case ComputeContext::DEVICE_GLOBAL_MEM_SIZE:
    case ComputeContext::DEVICE_GLOBAL_MEM_CACHE_SIZE:
    case ComputeContext::DEVICE_MAX_MEM_ALLOC_SIZE: {
        CCulong infoValue = 0;
        err = platformObject()->getDeviceInfo(infoType, &infoValue);
        if (err == ComputeContext::SUCCESS)
            return WebCLGetInfo(static_cast<CCulong>(infoValue));
        break;
    }
    case ComputeContext::DEVICE_HOST_UNIFIED_MEMORY:
    case ComputeContext::DEVICE_ENDIAN_LITTLE:
    case ComputeContext::DEVICE_ERROR_CORRECTION_SUPPORT: {
        CCbool infoValue = 0;
        err = platformObject()->getDeviceInfo(infoType, &infoValue);
        if (err == ComputeContext::SUCCESS)
            return WebCLGetInfo(static_cast<bool>(infoValue));
        break;
    }
    case ComputeContext::DEVICE_GLOBAL_MEM_CACHE_TYPE: {
        CCDeviceMemCachetype type = 0;
        err = platformObject()->getDeviceInfo(infoType, &type);
        if (err == ComputeContext::SUCCESS)
            return WebCLGetInfo(static_cast<CCenum>(type));
        break;
    }
    case ComputeContext::DEVICE_TYPE: {
        CCDeviceType type = 0;
        err = platformObject()->getDeviceInfo(infoType, &type);
        if (err == ComputeContext::SUCCESS)
            return WebCLGetInfo(static_cast<CCenum>(type));
        break;
    }
    case ComputeContext::DEVICE_SINGLE_FP_CONFIG: {
        CCDeviceFPConfig deviceFPConfig = 0;
        err = platformObject()->getDeviceInfo(infoType, &deviceFPConfig);
        if (err == ComputeContext::SUCCESS)
            return WebCLGetInfo(static_cast<CCenum>(deviceFPConfig));
        break;
    }
    case ComputeContext::DEVICE_LOCAL_MEM_TYPE: {
        CCDeviceLocalMemType localMemoryType = 0;
        err = platformObject()->getDeviceInfo(infoType, &localMemoryType);
        if (err == ComputeContext::SUCCESS)
            return WebCLGetInfo(static_cast<CCenum>(localMemoryType));
        break;
    }
    case ComputeContext::DEVICE_QUEUE_PROPERTIES: {
        CCCommandQueueProperties queueProperties = 0;
        err = platformObject()->getDeviceInfo(infoType,  &queueProperties);
        if (err == ComputeContext::SUCCESS)
            return WebCLGetInfo(static_cast<CCenum>(queueProperties));
        break;
    }
    case ComputeContext::DEVICE_EXECUTION_CAPABILITIES:
        return WebCLGetInfo(static_cast<CCenum>(ComputeContext::EXEC_KERNEL));
    case ComputeContext::DEVICE_PLATFORM:
        return WebCLGetInfo(m_platform);
    default:
        setExceptionFromComputeErrorCode(ComputeContext::INVALID_VALUE, exception);
    }
    ASSERT(err != ComputeContext::SUCCESS);
    setExceptionFromComputeErrorCode(err, exception);
    return WebCLGetInfo();
}
String WorkerLocation::search() const
{
    return m_url.query().isEmpty() ? emptyString() : "?" + m_url.query();
}
void MediaPlaybackTargetPickerMock::invalidatePlaybackTargets()
{
    LOG(Media, "MediaPlaybackTargetPickerMock::invalidatePlaybackTargets");
    setState(emptyString(), MediaPlaybackTargetContext::Unknown);
}
Пример #8
0
String DOMURLUtilsReadOnly::port(const KURL& kurl) {
  if (kurl.hasPort())
    return String::number(kurl.port());

  return emptyString();
}
Пример #9
0
String DOMURLUtilsReadOnly::search(const KURL& kurl) {
  String query = kurl.query();
  return query.isEmpty() ? emptyString() : "?" + query;
}
Пример #10
0
void SubresourceLoader::didReceiveResponse(const ResourceResponse& response)
{
    ASSERT(!response.isNull());
    ASSERT(m_state == Initialized);

    // We want redirect responses to be processed through willSendRequestInternal. The only exception is redirection with no Location headers.
    ASSERT(response.httpStatusCode() < 300 || response.httpStatusCode() >= 400 || response.httpStatusCode() == 304 || !response.httpHeaderField(HTTPHeaderName::Location));

    // Reference the object in this method since the additional processing can do
    // anything including removing the last reference to this object; one example of this is 3266216.
    Ref<SubresourceLoader> protectedThis(*this);

    if (shouldIncludeCertificateInfo())
        response.includeCertificateInfo();

    if (m_resource->resourceToRevalidate()) {
        if (response.httpStatusCode() == 304) {
            // 304 Not modified / Use local copy
            // Existing resource is ok, just use it updating the expiration time.
            m_resource->setResponse(response);
            MemoryCache::singleton().revalidationSucceeded(*m_resource, response);
            if (m_frame && m_frame->page())
                m_frame->page()->diagnosticLoggingClient().logDiagnosticMessageWithResult(DiagnosticLoggingKeys::cachedResourceRevalidationKey(), emptyString(), DiagnosticLoggingResultPass, ShouldSample::Yes);
            if (!reachedTerminalState())
                ResourceLoader::didReceiveResponse(response);
            return;
        }
        // Did not get 304 response, continue as a regular resource load.
        MemoryCache::singleton().revalidationFailed(*m_resource);
        if (m_frame && m_frame->page())
            m_frame->page()->diagnosticLoggingClient().logDiagnosticMessageWithResult(DiagnosticLoggingKeys::cachedResourceRevalidationKey(), emptyString(), DiagnosticLoggingResultFail, ShouldSample::Yes);
    }

    String errorDescription;
    if (!checkResponseCrossOriginAccessControl(response, errorDescription)) {
        if (m_frame && m_frame->document())
            m_frame->document()->addConsoleMessage(MessageSource::Security, MessageLevel::Error, errorDescription);
        cancel(ResourceError(String(), 0, request().url(), errorDescription, ResourceError::Type::AccessControl));
        return;
    }

    m_resource->responseReceived(response);
    if (reachedTerminalState())
        return;

    ResourceLoader::didReceiveResponse(response);
    if (reachedTerminalState())
        return;

    // FIXME: Main resources have a different set of rules for multipart than images do.
    // Hopefully we can merge those 2 paths.
    if (response.isMultipart() && m_resource->type() != CachedResource::MainResource) {
        m_loadingMultipartContent = true;

        // We don't count multiParts in a CachedResourceLoader's request count
        m_requestCountTracker = Nullopt;
        if (!m_resource->isImage()) {
            cancel();
            return;
        }
    }

    auto* buffer = resourceData();
    if (m_loadingMultipartContent && buffer && buffer->size()) {
        // The resource data will change as the next part is loaded, so we need to make a copy.
        m_resource->finishLoading(buffer->copy().ptr());
        clearResourceData();
        // Since a subresource loader does not load multipart sections progressively, data was delivered to the loader all at once.
        // After the first multipart section is complete, signal to delegates that this load is "finished"
        m_documentLoader->subresourceLoaderFinishedLoadingOnePart(this);
        didFinishLoadingOnePart(0);
    }

    checkForHTTPStatusCodeError();
}
Пример #11
0
String TextCodecLatin1::decode(const char* bytes, size_t length, FlushBehavior, bool, bool&)
{
    LChar* characters;
    if (!length)
        return emptyString();
    String result = String::createUninitialized(length, characters);

    const uint8_t* source = reinterpret_cast<const uint8_t*>(bytes);
    const uint8_t* end = reinterpret_cast<const uint8_t*>(bytes + length);
    const uint8_t* alignedEnd = alignToMachineWord(end);
    LChar* destination = characters;

    while (source < end) {
        if (isASCII(*source)) {
            // Fast path for ASCII. Most Latin-1 text will be ASCII.
            if (isAlignedToMachineWord(source)) {
                while (source < alignedEnd) {
                    MachineWord chunk = *reinterpret_cast_ptr<const MachineWord*>(source);

                    if (!isAllASCII<LChar>(chunk))
                        goto useLookupTable;

                    copyASCIIMachineWord(destination, source);
                    source += sizeof(MachineWord);
                    destination += sizeof(MachineWord);
                }

                if (source == end)
                    break;
            }
            *destination = *source;
        } else {
useLookupTable:
            if (table[*source] > 0xff)
                goto upConvertTo16Bit;

            *destination = static_cast<LChar>(table[*source]);
        }

        ++source;
        ++destination;
    }

    return result;

upConvertTo16Bit:
    UChar* characters16;
    String result16 = String::createUninitialized(length, characters16);

    UChar* destination16 = characters16;

    // Zero extend and copy already processed 8 bit data
    LChar* ptr8 = characters;
    LChar* endPtr8 = destination;

    while (ptr8 < endPtr8)
        *destination16++ = *ptr8++;

    // Handle the character that triggered the 16 bit path
    *destination16 = table[*source];
    ++source;
    ++destination16;

    while (source < end) {
        if (isASCII(*source)) {
            // Fast path for ASCII. Most Latin-1 text will be ASCII.
            if (isAlignedToMachineWord(source)) {
                while (source < alignedEnd) {
                    MachineWord chunk = *reinterpret_cast_ptr<const MachineWord*>(source);

                    if (!isAllASCII<LChar>(chunk))
                        goto useLookupTable16;

                    copyASCIIMachineWord(destination16, source);
                    source += sizeof(MachineWord);
                    destination16 += sizeof(MachineWord);
                }

                if (source == end)
                    break;
            }
            *destination16 = *source;
        } else {
useLookupTable16:
            *destination16 = table[*source];
        }

        ++source;
        ++destination16;
    }

    return result16;
}
Пример #12
0
void SubresourceLoader::willSendRequestInternal(ResourceRequest& newRequest, const ResourceResponse& redirectResponse)
{
    // Store the previous URL because the call to ResourceLoader::willSendRequest will modify it.
    URL previousURL = request().url();
    Ref<SubresourceLoader> protectedThis(*this);

    if (!newRequest.url().isValid()) {
        cancel(cannotShowURLError());
        return;
    }

    if (newRequest.requester() != ResourceRequestBase::Requester::Main)
        ResourceLoadObserver::sharedObserver().logSubresourceLoading(m_frame.get(), newRequest, redirectResponse);

    ASSERT(!newRequest.isNull());
    if (!redirectResponse.isNull()) {
        if (options().redirect != FetchOptions::Redirect::Follow) {
            if (options().redirect == FetchOptions::Redirect::Error) {
                cancel();
                return;
            }

            ResourceResponse opaqueRedirectedResponse;
            opaqueRedirectedResponse.setURL(redirectResponse.url());
            opaqueRedirectedResponse.setType(ResourceResponse::Type::Opaqueredirect);
            m_resource->responseReceived(opaqueRedirectedResponse);
            didFinishLoading(currentTime());
            return;
        } else if (m_redirectCount++ >= options().maxRedirectCount) {
            cancel(ResourceError(String(), 0, request().url(), ASCIILiteral("Too many redirections"), ResourceError::Type::General));
            return;
        }

        // CachedResources are keyed off their original request URL.
        // Requesting the same original URL a second time can redirect to a unique second resource.
        // Therefore, if a redirect to a different destination URL occurs, we should no longer consider this a revalidation of the first resource.
        // Doing so would have us reusing the resource from the first request if the second request's revalidation succeeds.
        if (newRequest.isConditional() && m_resource->resourceToRevalidate() && newRequest.url() != m_resource->resourceToRevalidate()->response().url()) {
            newRequest.makeUnconditional();
            MemoryCache::singleton().revalidationFailed(*m_resource);
            if (m_frame && m_frame->page())
                m_frame->page()->diagnosticLoggingClient().logDiagnosticMessageWithResult(DiagnosticLoggingKeys::cachedResourceRevalidationKey(), emptyString(), DiagnosticLoggingResultFail, ShouldSample::Yes);
        }

        if (!m_documentLoader->cachedResourceLoader().updateRequestAfterRedirection(m_resource->type(), newRequest, options())) {
            cancel();
            return;
        }

        String errorDescription;
        if (!checkRedirectionCrossOriginAccessControl(request(), redirectResponse, newRequest, errorDescription)) {
            String errorMessage = "Cross-origin redirection to " + newRequest.url().string() + " denied by Cross-Origin Resource Sharing policy: " + errorDescription;
            if (m_frame && m_frame->document())
                m_frame->document()->addConsoleMessage(MessageSource::Security, MessageLevel::Error, errorMessage);
            cancel(ResourceError(String(), 0, request().url(), errorMessage, ResourceError::Type::AccessControl));
            return;
        }

        if (m_resource->isImage() && m_documentLoader->cachedResourceLoader().shouldDeferImageLoad(newRequest.url())) {
            cancel();
            return;
        }
        m_loadTiming.addRedirect(redirectResponse.url(), newRequest.url());
        m_resource->redirectReceived(newRequest, redirectResponse);
    }

    if (newRequest.isNull() || reachedTerminalState())
        return;

    ResourceLoader::willSendRequestInternal(newRequest, redirectResponse);
    if (newRequest.isNull()) {
        cancel();
        return;
    }

    if (m_resource->type() == CachedResource::MainResource && !redirectResponse.isNull())
        m_documentLoader->willContinueMainResourceLoadAfterRedirect(newRequest);
}
String SharedBufferChunkReader::nextChunkAsUTF8StringWithLatin1Fallback(bool includeSeparator)
{
    Vector<char> data;
    if (!nextChunk(data, includeSeparator))
        return String();

    return data.size() ? String::fromUTF8WithLatin1Fallback(data.data(), data.size()) : emptyString();
}
Пример #14
0
PassRefPtr<DocumentFragment> Pasteboard::documentFragment(Frame& frame, Range& context, bool allowPlainText, bool& chosePlainText)
{
    if (m_gtkClipboard)
        PasteboardHelper::defaultPasteboardHelper()->getClipboardContents(m_gtkClipboard);

    chosePlainText = false;

    if (m_dataObject->hasMarkup()) {
        if (frame.document()) {
            RefPtr<DocumentFragment> fragment = createFragmentFromMarkup(*frame.document(), m_dataObject->markup(), emptyString(), DisallowScriptingAndPluginContent);
            if (fragment)
                return fragment.release();
        }
    }

    if (!allowPlainText)
        return 0;

    if (m_dataObject->hasText()) {
        chosePlainText = true;
        RefPtr<DocumentFragment> fragment = createFragmentFromText(context, m_dataObject->text());
        if (fragment)
            return fragment.release();
    }

    return 0;
}
Пример #15
0
void WebCLMemoryUtil::ensureMemory(WebCLMemoryObject* memoryObject, WebCLCommandQueue* commandQueue, ExceptionState& es)
{
    cl_int err = CL_SUCCESS;
    // The program and kernels are used to intialize OpenCL memory to 0.
    // Every created OpenCL memory should call this function to intialize.
    // TODO(junmin-zhu): Move intialization from buffer creation to buffer operations, such as: enqueueRead/Write/Copy* and enqueueNDRangeKernel function
    // after the third_party WebCL-validator integrated.
    if (!m_program) {
        cl_program clProgramId = clCreateProgramWithSource(m_context->getContext(), 1, (const char**)&programSource, nullptr, &err);
        if (err != CL_SUCCESS) {
            WebCLException::throwException(err, es);
            return;
        }

        m_program = WebCLProgram::create(clProgramId, m_context, String(programSource));
        m_program->build(m_context->getDevices(), emptyString(), nullptr, es);

        cl_kernel clKernelId16 = clCreateKernel(clProgramId, "init16", &err);
        if (err != CL_SUCCESS) {
            WebCLException::throwException(err, es);
            return;
        }

        m_kernelChar16 = WebCLKernel::create(clKernelId16, m_context, m_program.get(), String("init16"));
        cl_kernel clKernelId = clCreateKernel(clProgramId, "init", &err);
        if (err != CL_SUCCESS) {
            WebCLException::throwException(err, es);
            return;
        }

        m_kernelChar = WebCLKernel::create(clKernelId, m_context, m_program.get(), String("init"));
    }

    unsigned count = memoryObject->sizeInBytes() / 16;
    if (count) {
        m_kernelChar16->setArg(0, memoryObject, es);
        if (es.hadException())
            return;

        m_kernelChar16->setArg(1, sizeof(unsigned), &count, es);
        if (es.hadException())
            return;

        Vector<double> globalWorkSize;
        globalWorkSize.append(count);
        Vector<double> globalWorkOffset;
        Vector<double> localWorkSize;

        commandQueue->enqueueNDRangeKernel(m_kernelChar16.get(), globalWorkSize.size(), globalWorkOffset, globalWorkSize, localWorkSize, Vector<RefPtr<WebCLEvent>>(), nullptr, es);
    }

    unsigned remainingBytes = memoryObject->sizeInBytes() % 16;
    if (remainingBytes) {
        m_kernelChar->setArg(0, memoryObject, es);
        if (es.hadException())
            return;

        unsigned offset = count * 16;
        m_kernelChar->setArg(1, sizeof(unsigned), &offset, es);
        if (es.hadException())
            return;

        unsigned totalSize = memoryObject->sizeInBytes();
        m_kernelChar->setArg(2, sizeof(unsigned), &totalSize, es);
        if (es.hadException())
            return;

        Vector<double> globalWorkSize;
        globalWorkSize.append(remainingBytes);
        Vector<double> globalWorkOffset;
        Vector<double> localWorkSize;

        commandQueue->enqueueNDRangeKernel(m_kernelChar.get(), globalWorkSize.size(), globalWorkOffset, globalWorkSize, localWorkSize, Vector<RefPtr<WebCLEvent>>(), nullptr, es);
    }

    commandQueue->finishCommandQueues(WebCLCommandQueue::SyncMethod::SYNC);
}
Пример #16
0
String DOMURLUtilsReadOnly::hash(const KURL& kurl) {
  String fragmentIdentifier = kurl.fragmentIdentifier();
  if (fragmentIdentifier.isEmpty())
    return emptyString();
  return AtomicString(String("#" + fragmentIdentifier));
}
Пример #17
0
String KURL::stringForInvalidComponent() const
{
    if (m_string.isNull())
        return String();
    return emptyString();
}
Пример #18
0
void VTTCue::setCueSettings(const String& inputString)
{
    VTTScanner input(inputString);

    while (!input.isAtEnd()) {

        // The WebVTT cue settings part of a WebVTT cue consists of zero or more of the following components, in any order, 
        // separated from each other by one or more U+0020 SPACE characters or U+0009 CHARACTER TABULATION (tab) characters.
        input.skipWhile<WebVTTParser::isValidSettingDelimiter>();
        if (input.isAtEnd())
            break;

        // When the user agent is to parse the WebVTT settings given by a string input for a text track cue cue, 
        // the user agent must run the following steps:
        // 1. Let settings be the result of splitting input on spaces.
        // 2. For each token setting in the list settings, run the following substeps:
        //    1. If setting does not contain a U+003A COLON character (:), or if the first U+003A COLON character (:) 
        //       in setting is either the first or last character of setting, then jump to the step labeled next setting.
        //    2. Let name be the leading substring of setting up to and excluding the first U+003A COLON character (:) in that string.
        CueSetting name = settingName(input);

        // 3. Let value be the trailing substring of setting starting from the character immediately after the first U+003A COLON character (:) in that string.
        VTTScanner::Run valueRun = input.collectUntil<WebVTTParser::isValidSettingDelimiter>();

        // 4. Run the appropriate substeps that apply for the value of name, as follows:
        switch (name) {
        case Vertical: {
            // If name is a case-sensitive match for "vertical"
            // 1. If value is a case-sensitive match for the string "rl", then let cue's text track cue writing direction 
            //    be vertical growing left.
            if (input.scanRun(valueRun, verticalGrowingLeftKeyword()))
                m_writingDirection = VerticalGrowingLeft;
            
            // 2. Otherwise, if value is a case-sensitive match for the string "lr", then let cue's text track cue writing 
            //    direction be vertical growing right.
            else if (input.scanRun(valueRun, verticalGrowingRightKeyword()))
                m_writingDirection = VerticalGrowingRight;
            break;
        }
        case Line: {
            // 1-2 - Collect chars that are either '-', '%', or a digit.
            // 1. If value contains any characters other than U+002D HYPHEN-MINUS characters (-), U+0025 PERCENT SIGN 
            //    characters (%), and characters in the range U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9), then jump
            //    to the step labeled next setting.
            bool isNegative = input.scan('-');
            int linePosition;
            unsigned numDigits = input.scanDigits(linePosition);
            bool isPercentage = input.scan('%');

            if (!input.isAt(valueRun.end()))
                break;

            // 2. If value does not contain at least one character in the range U+0030 DIGIT ZERO (0) to U+0039 DIGIT 
            //    NINE (9), then jump to the step labeled next setting.
            // 3. If any character in value other than the first character is a U+002D HYPHEN-MINUS character (-), then 
            //    jump to the step labeled next setting.
            // 4. If any character in value other than the last character is a U+0025 PERCENT SIGN character (%), then
            //    jump to the step labeled next setting.
            // 5. If the first character in value is a U+002D HYPHEN-MINUS character (-) and the last character in value is a 
            //    U+0025 PERCENT SIGN character (%), then jump to the step labeled next setting.
            if (!numDigits || (isPercentage && isNegative))
                break;

            // 6. Ignoring the trailing percent sign, if any, interpret value as a (potentially signed) integer, and 
            //    let number be that number. 
            // 7. If the last character in value is a U+0025 PERCENT SIGN character (%), but number is not in the range 
            //    0 ≤ number ≤ 100, then jump to the step labeled next setting.
            // 8. Let cue's text track cue line position be number.
            // 9. If the last character in value is a U+0025 PERCENT SIGN character (%), then let cue's text track cue 
            //    snap-to-lines flag be false. Otherwise, let it be true.
            if (isPercentage) {
                if (linePosition < 0 || linePosition > 100)
                    break;

                // 10 - If '%' then set snap-to-lines flag to false.
                m_snapToLines = false;
            } else {
                if (isNegative)
                    linePosition = -linePosition;

                m_snapToLines = true;
            }

            m_linePosition = linePosition;
            break;
        }
        case Position: {
            int number;
            // Steps 1 - 6.
            if (!scanPercentage(input, valueRun, number))            
                break;

            // 7. Let cue's text track cue text position be number.
            m_textPosition = number;
            break;
        }
        case Size: {
            int number;
            // Steps 1 - 6.
            if (!scanPercentage(input, valueRun, number))            
                break;

            // 7. Let cue's text track cue size be number.
            m_cueSize = number;
            break;
        }
        case Align: {
            // 1. If value is a case-sensitive match for the string "start", then let cue's text track cue alignment be start alignment.
            if (input.scanRun(valueRun, startKeyword()))
                m_cueAlignment = Start;

            // 2. If value is a case-sensitive match for the string "middle", then let cue's text track cue alignment be middle alignment.
            else if (input.scanRun(valueRun, middleKeyword()))
                m_cueAlignment = Middle;

            // 3. If value is a case-sensitive match for the string "end", then let cue's text track cue alignment be end alignment.
            else if (input.scanRun(valueRun, endKeyword()))
                m_cueAlignment = End;

            // 4. If value is a case-sensitive match for the string "left", then let cue's text track cue alignment be left alignment.
            else if (input.scanRun(valueRun, leftKeyword()))
                m_cueAlignment = Left;

            // 5. If value is a case-sensitive match for the string "right", then let cue's text track cue alignment be right alignment.
            else if (input.scanRun(valueRun, rightKeyword()))
                m_cueAlignment = Right;
            break;
        }
#if ENABLE(WEBVTT_REGIONS)
        case RegionId:
            m_regionId = input.extractString(valueRun);
            break;
#endif
        case None:
            break;
        }

        // Make sure the entire run is consumed.
        input.skipRun(valueRun);
    }
#if ENABLE(WEBVTT_REGIONS)
    // If cue's line position is not auto or cue's size is not 100 or cue's
    // writing direction is not horizontal, but cue's region identifier is not
    // the empty string, let cue's region identifier be the empty string.
    if (m_regionId.isEmpty())
        return;

    if (m_linePosition != undefinedPosition || m_cueSize != 100 || m_writingDirection != Horizontal)
        m_regionId = emptyString();
#endif
}
String WorkerLocation::hash() const
{
    return m_url.fragmentIdentifier().isEmpty() ? emptyString() : "#" + m_url.fragmentIdentifier();
}
Пример #20
0
void SubresourceLoader::willSendRequestInternal(ResourceRequest& newRequest, const ResourceResponse& redirectResponse)
{
    // Store the previous URL because the call to ResourceLoader::willSendRequest will modify it.
    URL previousURL = request().url();
    Ref<SubresourceLoader> protectedThis(*this);

    if (!newRequest.url().isValid()) {
        cancel(cannotShowURLError());
        return;
    }

    ASSERT(!newRequest.isNull());
    if (!redirectResponse.isNull()) {
        if (options().fetchOptions().redirect != FetchOptions::Redirect::Follow) {
            if (options().fetchOptions().redirect == FetchOptions::Redirect::Error) {
                cancel();
                return;
            }
            m_resource->setOpaqueRedirect();
            m_resource->responseReceived({ });
            didFinishLoading(currentTime());
            return;
        }

        // CachedResources are keyed off their original request URL.
        // Requesting the same original URL a second time can redirect to a unique second resource.
        // Therefore, if a redirect to a different destination URL occurs, we should no longer consider this a revalidation of the first resource.
        // Doing so would have us reusing the resource from the first request if the second request's revalidation succeeds.
        if (newRequest.isConditional() && m_resource->resourceToRevalidate() && newRequest.url() != m_resource->resourceToRevalidate()->response().url()) {
            newRequest.makeUnconditional();
            MemoryCache::singleton().revalidationFailed(*m_resource);
            if (m_frame && m_frame->page())
                m_frame->page()->diagnosticLoggingClient().logDiagnosticMessageWithResult(DiagnosticLoggingKeys::cachedResourceRevalidationKey(), emptyString(), DiagnosticLoggingResultFail, ShouldSample::Yes);
        }

        if (!m_documentLoader->cachedResourceLoader().canRequest(m_resource->type(), newRequest.url(), options(), false /* forPreload */, true /* didReceiveRedirectResponse */)) {
            cancel();
            return;
        }

        if (options().requestOriginPolicy() == PotentiallyCrossOriginEnabled && !checkCrossOriginAccessControl(request(), redirectResponse, newRequest)) {
            cancel();
            return;
        }

        if (m_resource->isImage() && m_documentLoader->cachedResourceLoader().shouldDeferImageLoad(newRequest.url())) {
            cancel();
            return;
        }
        m_resource->redirectReceived(newRequest, redirectResponse);
    }

    if (newRequest.isNull() || reachedTerminalState())
        return;

    ResourceLoader::willSendRequestInternal(newRequest, redirectResponse);
    if (newRequest.isNull())
        cancel();

    ResourceLoadObserver::sharedObserver().logSubresourceLoading(m_frame.get(), newRequest, redirectResponse);
}
Пример #21
0
bool Database::performOpenAndVerify(bool shouldSetVersionInNewDatabase, DatabaseError& error, String& errorMessage)
{
    DoneCreatingDatabaseOnExitCaller onExitCaller(this);
    ASSERT(errorMessage.isEmpty());
    ASSERT(error == DatabaseError::None); // Better not have any errors already.
    // Presumed failure. We'll clear it if we succeed below.
    error = DatabaseError::InvalidDatabaseState;

    const int maxSqliteBusyWaitTime = 30000;

    if (!m_sqliteDatabase.open(m_filename)) {
        reportOpenDatabaseResult(1, InvalidStateError, m_sqliteDatabase.lastError());
        errorMessage = formatErrorMessage("unable to open database", m_sqliteDatabase.lastError(), m_sqliteDatabase.lastErrorMsg());
        return false;
    }
    if (!m_sqliteDatabase.turnOnIncrementalAutoVacuum())
        WTF_LOG_ERROR("Unable to turn on incremental auto-vacuum (%d %s)", m_sqliteDatabase.lastError(), m_sqliteDatabase.lastErrorMsg());

    m_sqliteDatabase.setBusyTimeout(maxSqliteBusyWaitTime);

    String currentVersion;
    {
        SafePointAwareMutexLocker locker(guidMutex());

        GuidVersionMap::iterator entry = guidToVersionMap().find(m_guid);
        if (entry != guidToVersionMap().end()) {
            // Map null string to empty string (see updateGuidVersionMap()).
            currentVersion = entry->value.isNull() ? emptyString() : entry->value.isolatedCopy();
            WTF_LOG(StorageAPI, "Current cached version for guid %i is %s", m_guid, currentVersion.ascii().data());

            // Note: In multi-process browsers the cached value may be
            // inaccurate, but we cannot read the actual version from the
            // database without potentially inducing a form of deadlock, a
            // busytimeout error when trying to access the database. So we'll
            // use the cached value if we're unable to read the value from the
            // database file without waiting.
            // FIXME: Add an async openDatabase method to the DatabaseAPI.
            const int noSqliteBusyWaitTime = 0;
            m_sqliteDatabase.setBusyTimeout(noSqliteBusyWaitTime);
            String versionFromDatabase;
            if (getVersionFromDatabase(versionFromDatabase, false)) {
                currentVersion = versionFromDatabase;
                updateGuidVersionMap(m_guid, currentVersion);
            }
            m_sqliteDatabase.setBusyTimeout(maxSqliteBusyWaitTime);
        } else {
            WTF_LOG(StorageAPI, "No cached version for guid %i", m_guid);

            SQLiteTransaction transaction(m_sqliteDatabase);
            transaction.begin();
            if (!transaction.inProgress()) {
                reportOpenDatabaseResult(2, InvalidStateError, m_sqliteDatabase.lastError());
                errorMessage = formatErrorMessage("unable to open database, failed to start transaction", m_sqliteDatabase.lastError(), m_sqliteDatabase.lastErrorMsg());
                m_sqliteDatabase.close();
                return false;
            }

            String tableName(infoTableName);
            if (!m_sqliteDatabase.tableExists(tableName)) {
                m_new = true;

                if (!m_sqliteDatabase.executeCommand("CREATE TABLE " + tableName + " (key TEXT NOT NULL ON CONFLICT FAIL UNIQUE ON CONFLICT REPLACE,value TEXT NOT NULL ON CONFLICT FAIL);")) {
                    reportOpenDatabaseResult(3, InvalidStateError, m_sqliteDatabase.lastError());
                    errorMessage = formatErrorMessage("unable to open database, failed to create 'info' table", m_sqliteDatabase.lastError(), m_sqliteDatabase.lastErrorMsg());
                    transaction.rollback();
                    m_sqliteDatabase.close();
                    return false;
                }
            } else if (!getVersionFromDatabase(currentVersion, false)) {
                reportOpenDatabaseResult(4, InvalidStateError, m_sqliteDatabase.lastError());
                errorMessage = formatErrorMessage("unable to open database, failed to read current version", m_sqliteDatabase.lastError(), m_sqliteDatabase.lastErrorMsg());
                transaction.rollback();
                m_sqliteDatabase.close();
                return false;
            }

            if (currentVersion.length()) {
                WTF_LOG(StorageAPI, "Retrieved current version %s from database %s", currentVersion.ascii().data(), databaseDebugName().ascii().data());
            } else if (!m_new || shouldSetVersionInNewDatabase) {
                WTF_LOG(StorageAPI, "Setting version %s in database %s that was just created", m_expectedVersion.ascii().data(), databaseDebugName().ascii().data());
                if (!setVersionInDatabase(m_expectedVersion, false)) {
                    reportOpenDatabaseResult(5, InvalidStateError, m_sqliteDatabase.lastError());
                    errorMessage = formatErrorMessage("unable to open database, failed to write current version", m_sqliteDatabase.lastError(), m_sqliteDatabase.lastErrorMsg());
                    transaction.rollback();
                    m_sqliteDatabase.close();
                    return false;
                }
                currentVersion = m_expectedVersion;
            }
            updateGuidVersionMap(m_guid, currentVersion);
            transaction.commit();
        }
    }

    if (currentVersion.isNull()) {
        WTF_LOG(StorageAPI, "Database %s does not have its version set", databaseDebugName().ascii().data());
        currentVersion = "";
    }

    // If the expected version isn't the empty string, ensure that the current
    // database version we have matches that version. Otherwise, set an
    // exception.
    // If the expected version is the empty string, then we always return with
    // whatever version of the database we have.
    if ((!m_new || shouldSetVersionInNewDatabase) && m_expectedVersion.length() && m_expectedVersion != currentVersion) {
        reportOpenDatabaseResult(6, InvalidStateError, 0);
        errorMessage = "unable to open database, version mismatch, '" + m_expectedVersion + "' does not match the currentVersion of '" + currentVersion + "'";
        m_sqliteDatabase.close();
        return false;
    }

    ASSERT(m_databaseAuthorizer);
    m_sqliteDatabase.setAuthorizer(m_databaseAuthorizer.get());

    // See comment at the top this file regarding calling addOpenDatabase().
    DatabaseTracker::tracker().addOpenDatabase(this);
    m_opened = true;

    // Declare success:
    error = DatabaseError::None; // Clear the presumed error from above.
    onExitCaller.setOpenSucceeded();

    if (m_new && !shouldSetVersionInNewDatabase) {
        // The caller provided a creationCallback which will set the expected
        // version.
        m_expectedVersion = "";
    }

    reportOpenDatabaseResult(0, -1, 0); // OK

    if (databaseContext()->databaseThread())
        databaseContext()->databaseThread()->recordDatabaseOpen(this);
    return true;
}
Пример #22
0
void SubresourceLoader::didReceiveResponse(const ResourceResponse& response)
{
    ASSERT(!response.isNull());
    ASSERT(m_state == Initialized);

    // Reference the object in this method since the additional processing can do
    // anything including removing the last reference to this object; one example of this is 3266216.
    Ref<SubresourceLoader> protectedThis(*this);

    if (shouldIncludeCertificateInfo())
        response.includeCertificateInfo();

    if (response.isHttpVersion0_9()) {
        if (m_frame) {
            String message = "Sandboxing '" + response.url().string() + "' because it is using HTTP/0.9.";
            m_frame->document()->addConsoleMessage(MessageSource::Security, MessageLevel::Error, message, identifier());
            frameLoader()->forceSandboxFlags(SandboxScripts | SandboxPlugins);
        }
    }

    if (m_resource->resourceToRevalidate()) {
        if (response.httpStatusCode() == 304) {
            // 304 Not modified / Use local copy
            // Existing resource is ok, just use it updating the expiration time.
            m_resource->setResponse(response);
            MemoryCache::singleton().revalidationSucceeded(*m_resource, response);
            if (m_frame && m_frame->page())
                m_frame->page()->diagnosticLoggingClient().logDiagnosticMessageWithResult(DiagnosticLoggingKeys::cachedResourceRevalidationKey(), emptyString(), DiagnosticLoggingResultPass, ShouldSample::Yes);
            if (!reachedTerminalState())
                ResourceLoader::didReceiveResponse(response);
            return;
        }
        // Did not get 304 response, continue as a regular resource load.
        MemoryCache::singleton().revalidationFailed(*m_resource);
        if (m_frame && m_frame->page())
            m_frame->page()->diagnosticLoggingClient().logDiagnosticMessageWithResult(DiagnosticLoggingKeys::cachedResourceRevalidationKey(), emptyString(), DiagnosticLoggingResultFail, ShouldSample::Yes);
    }

    m_resource->responseReceived(response);
    if (reachedTerminalState())
        return;

    ResourceLoader::didReceiveResponse(response);
    if (reachedTerminalState())
        return;

    // FIXME: Main resources have a different set of rules for multipart than images do.
    // Hopefully we can merge those 2 paths.
    if (response.isMultipart() && m_resource->type() != CachedResource::MainResource) {
        m_loadingMultipartContent = true;

        // We don't count multiParts in a CachedResourceLoader's request count
        m_requestCountTracker = nullptr;
        if (!m_resource->isImage()) {
            cancel();
            return;
        }
    }

    auto* buffer = resourceData();
    if (m_loadingMultipartContent && buffer && buffer->size()) {
        // The resource data will change as the next part is loaded, so we need to make a copy.
        m_resource->finishLoading(buffer->copy().ptr());
        clearResourceData();
        // Since a subresource loader does not load multipart sections progressively, data was delivered to the loader all at once.        
        // After the first multipart section is complete, signal to delegates that this load is "finished" 
        m_documentLoader->subresourceLoaderFinishedLoadingOnePart(this);
        didFinishLoadingOnePart(0);
    }

    checkForHTTPStatusCodeError();
}
Пример #23
0
void SVGTextMetricsBuilder::advanceSimpleText()
{
#if PLATFORM(QT) && !HAVE(QRAWFONT)
    ASSERT_NOT_REACHED();
#else
    unsigned metricsLength = m_simpleWidthIterator->advance(m_textPosition + 1);
    if (!metricsLength) {
        m_currentMetrics = SVGTextMetrics();
        return;
    }

    if (currentCharacterStartsSurrogatePair())
        ASSERT(metricsLength == 2);

    float currentWidth = m_simpleWidthIterator->runWidthSoFar() - m_totalWidth;
    m_totalWidth = m_simpleWidthIterator->runWidthSoFar();

#if ENABLE(SVG_FONTS)
    m_currentMetrics = SVGTextMetrics(m_text, m_textPosition, metricsLength, currentWidth, m_simpleWidthIterator->lastGlyphName());
#else
    m_currentMetrics = SVGTextMetrics(m_text, m_textPosition, metricsLength, currentWidth, emptyString());
#endif
#endif
}
Пример #24
0
void VTTCue::parseSettings(const String& inputString)
{
    VTTScanner input(inputString);

    while (!input.isAtEnd()) {

        // The WebVTT cue settings part of a WebVTT cue consists of zero or more of the following components, in any order,
        // separated from each other by one or more U+0020 SPACE characters or U+0009 CHARACTER TABULATION (tab) characters.
        input.skipWhile<VTTParser::isValidSettingDelimiter>();

        if (input.isAtEnd())
            break;

        // When the user agent is to parse the WebVTT settings given by a string input for a text track cue cue,
        // the user agent must run the following steps:
        // 1. Let settings be the result of splitting input on spaces.
        // 2. For each token setting in the list settings, run the following substeps:
        //    1. If setting does not contain a U+003A COLON character (:), or if the first U+003A COLON character (:)
        //       in setting is either the first or last character of setting, then jump to the step labeled next setting.
        //    2. Let name be the leading substring of setting up to and excluding the first U+003A COLON character (:) in that string.
        CueSetting name = settingName(input);

        // 3. Let value be the trailing substring of setting starting from the character immediately after the first U+003A COLON character (:) in that string.
        VTTScanner::Run valueRun = input.collectUntil<VTTParser::isValidSettingDelimiter>();

        // 4. Run the appropriate substeps that apply for the value of name, as follows:
        switch (name) {
        case Vertical: {
            // If name is a case-sensitive match for "vertical"
            // 1. If value is a case-sensitive match for the string "rl", then
            //    let cue's WebVTT cue writing direction be vertical
            //    growing left.
            if (input.scanRun(valueRun, verticalGrowingLeftKeyword()))
                m_writingDirection = VerticalGrowingLeft;

            // 2. Otherwise, if value is a case-sensitive match for the string
            //    "lr", then let cue's WebVTT cue writing direction be
            //    vertical growing right.
            else if (input.scanRun(valueRun, verticalGrowingRightKeyword()))
                m_writingDirection = VerticalGrowingRight;
            break;
        }
        case Line: {
            // If name is a case-sensitive match for "line"
            // Steps 1 - 2 skipped.
            float number;
            // 3. If linepos does not contain at least one ASCII digit, then
            //    jump to the step labeled next setting.
            // 4. If the last character in linepos is a U+0025 PERCENT SIGN character (%)
            //
            //    If parse a percentage string from linepos doesn't fail, let
            //    number be the returned percentage, otherwise jump to the step
            //    labeled next setting.
            bool isPercentage = scanPercentage(input, number);
            if (!isPercentage) {
                // Otherwise
                //
                // 1. If linepos contains any characters other than U+002D
                //    HYPHEN-MINUS characters (-) and ASCII digits, then jump to
                //    the step labeled next setting.
                // 2. If any character in linepos other than the first character is
                //    a U+002D HYPHEN-MINUS character (-), then jump to the step
                //    labeled next setting.
                bool isNegative = input.scan('-');
                int intLinePosition;
                if (!input.scanDigits(intLinePosition))
                    break;
                // 3. Interpret linepos as a (potentially signed) integer, and let
                //    number be that number.
                number = isNegative ? -intLinePosition : intLinePosition;
            }
            if (!input.isAt(valueRun.end()))
                break;
            // 5. Let cue's WebVTT cue line be number.
            m_linePosition = number;
            // 6. If the last character in linepos is a U+0025 PERCENT SIGN
            //    character (%), then let cue's WebVTT cue snap-to-lines
            //    flag be false. Otherwise, let it be true.
            m_snapToLines = !isPercentage;
            // Steps 7 - 9 skipped.
            break;
        }
        case Position: {
            // If name is a case-sensitive match for "position".
            float number;
            // Steps 1 - 2 skipped.
            // 3. If parse a percentage string from colpos doesn't fail, let
            //    number be the returned percentage, otherwise jump to the step
            //    labeled next setting (text track cue text position's value
            //    remains the special value auto).
            if (!scanPercentage(input, number))
                break;
            if (!input.isAt(valueRun.end()))
                break;
            // 4. Let cue's cue position be number.
            m_textPosition = number;
            // Steps 5 - 7 skipped.
            break;
        }
        case Size: {
            // If name is a case-sensitive match for "size"
            float number;
            // 1. If parse a percentage string from value doesn't fail, let
            //    number be the returned percentage, otherwise jump to the step
            //    labeled next setting.
            if (!scanPercentage(input, number))
                break;
            if (!input.isAt(valueRun.end()))
                break;
            // 2. Let cue's WebVTT cue size be number.
            m_cueSize = number;
            break;
        }
        case Align: {
            // If name is a case-sensitive match for "align"
            // 1. If value is a case-sensitive match for the string "start",
            //    then let cue's WebVTT cue text alignment be start alignment.
            if (input.scanRun(valueRun, startKeyword()))
                m_cueAlignment = Start;

            // 2. If value is a case-sensitive match for the string "middle",
            //    then let cue's WebVTT cue text alignment be middle alignment.
            else if (input.scanRun(valueRun, middleKeyword()))
                m_cueAlignment = Middle;

            // 3. If value is a case-sensitive match for the string "end", then
            //    let cue's WebVTT cue text alignment be end alignment.
            else if (input.scanRun(valueRun, endKeyword()))
                m_cueAlignment = End;

            // 4. If value is a case-sensitive match for the string "left",
            //    then let cue's WebVTT cue text alignment be left alignment.
            else if (input.scanRun(valueRun, leftKeyword()))
                m_cueAlignment = Left;

            // 5. If value is a case-sensitive match for the string "right",
            //    then let cue's WebVTT cue text alignment be right alignment.
            else if (input.scanRun(valueRun, rightKeyword()))
                m_cueAlignment = Right;
            break;
        }
        case RegionId:
            m_regionId = input.extractString(valueRun);
            break;
        case None:
            break;
        }

        // Make sure the entire run is consumed.
        input.skipRun(valueRun);
    }

    // If cue's line position is not auto or cue's size is not 100 or cue's
    // writing direction is not horizontal, but cue's region identifier is not
    // the empty string, let cue's region identifier be the empty string.
    if (m_regionId.isEmpty())
        return;

    if (!lineIsAuto() || m_cueSize != 100 || m_writingDirection != Horizontal)
        m_regionId = emptyString();
}
Пример #25
0
static const String& horizontalKeyword()
{
    return emptyString();
}
Пример #26
0
PassRefPtr<LegacyWebArchive> LegacyWebArchive::create(const String& markupString, Frame* frame, const Vector<Node*>& nodes, FrameFilter* frameFilter)
{
    ASSERT(frame);
    
    const ResourceResponse& response = frame->loader().documentLoader()->response();
    URL responseURL = response.url();
    
    // it's possible to have a response without a URL here
    // <rdar://problem/5454935>
    if (responseURL.isNull())
        responseURL = URL(ParsedURLString, emptyString());
        
    RefPtr<ArchiveResource> mainResource = ArchiveResource::create(utf8Buffer(markupString), responseURL, response.mimeType(), "UTF-8", frame->tree().uniqueName());

    Vector<PassRefPtr<LegacyWebArchive>> subframeArchives;
    Vector<PassRefPtr<ArchiveResource>> subresources;
    HashSet<URL> uniqueSubresources;

    size_t nodesSize = nodes.size();    
    for (size_t i = 0; i < nodesSize; ++i) {
        Node& node = *nodes[i];
        Frame* childFrame;
        if ((isHTMLFrameElement(node) || isHTMLIFrameElement(node) || isHTMLObjectElement(node))
            && (childFrame = toHTMLFrameOwnerElement(node).contentFrame())) {
            if (frameFilter && !frameFilter->shouldIncludeSubframe(childFrame))
                continue;
                
            RefPtr<LegacyWebArchive> subframeArchive = create(childFrame->document(), frameFilter);
            
            if (subframeArchive)
                subframeArchives.append(subframeArchive);
            else
                LOG_ERROR("Unabled to archive subframe %s", childFrame->tree().uniqueName().string().utf8().data());
        } else {
            ListHashSet<URL> subresourceURLs;
            node.getSubresourceURLs(subresourceURLs);
            
            DocumentLoader* documentLoader = frame->loader().documentLoader();
            ListHashSet<URL>::iterator iterEnd = subresourceURLs.end();
            for (ListHashSet<URL>::iterator iter = subresourceURLs.begin(); iter != iterEnd; ++iter) {
                const URL& subresourceURL = *iter;
                if (uniqueSubresources.contains(subresourceURL))
                    continue;

                uniqueSubresources.add(subresourceURL);

                RefPtr<ArchiveResource> resource = documentLoader->subresource(subresourceURL);
                if (resource) {
                    subresources.append(resource.release());
                    continue;
                }

                ResourceRequest request(subresourceURL);
#if ENABLE(CACHE_PARTITIONING)
                request.setCachePartition(frame->document()->topOrigin()->cachePartition());
#endif
                CachedResource* cachedResource = memoryCache()->resourceForRequest(request);
                if (cachedResource) {
                    ResourceBuffer* data = cachedResource->resourceBuffer();
                    resource = ArchiveResource::create(data ? data->sharedBuffer() : 0, subresourceURL, cachedResource->response());
                    if (resource) {
                        subresources.append(resource.release());
                        continue;
                    }
                }

                // FIXME: should do something better than spew to console here
                LOG_ERROR("Failed to archive subresource for %s", subresourceURL.string().utf8().data());
            }
        }
    }

    // Add favicon if one exists for this page, if we are archiving the entire page.
    if (nodesSize && nodes[0]->isDocumentNode() && iconDatabase().isEnabled()) {
        const String& iconURL = iconDatabase().synchronousIconURLForPageURL(responseURL);
        if (!iconURL.isEmpty() && iconDatabase().synchronousIconDataKnownForIconURL(iconURL)) {
            if (Image* iconImage = iconDatabase().synchronousIconForPageURL(responseURL, IntSize(16, 16))) {
                if (RefPtr<ArchiveResource> resource = ArchiveResource::create(iconImage->data(), URL(ParsedURLString, iconURL), "image/x-icon", "", ""))
                    subresources.append(resource.release());
            }
        }
    }

    return create(mainResource.release(), subresources, subframeArchives);
}
String HTMLAnchorElement::hash() const
{
    String fragmentIdentifier = href().fragmentIdentifier();
    return fragmentIdentifier.isEmpty() ? emptyString() : "#" + fragmentIdentifier;
}
PassRefPtr<SpeechRecognitionError> SpeechRecognitionError::create()
{
    return adoptRef(new SpeechRecognitionError(emptyString(), emptyString()));
}
Пример #29
0
cut::exceptions::UnitTestSuccess::UnitTestSuccess() :
	ExpectionBase(nullptr, 0, emptyString())
{

}
Пример #30
0
String NumberInputType::sanitizeValue(const String& proposedValue) const
{
    if (proposedValue.isEmpty())
        return proposedValue;
    return std::isfinite(parseToDoubleForNumberType(proposedValue)) ? proposedValue : emptyString();
}