void FrameLoaderClient::dispatchDecidePolicyForResponse(FramePolicyFunction policyFunction, const ResourceResponse& response, const ResourceRequest& resourceRequest)
{
    ASSERT(policyFunction);
    if (!policyFunction)
        return;

    if (resourceRequest.isNull()) {
        (core(m_frame)->loader()->policyChecker()->*policyFunction)(PolicyIgnore);
        return;
    }

    WebKitWebView* page = getViewFromFrame(m_frame);
    GRefPtr<WebKitNetworkRequest> request(adoptGRef(kitNew(resourceRequest)));

    WebKitWebPolicyDecision* policyDecision = webkit_web_policy_decision_new(m_frame, policyFunction);
    if (m_policyDecision)
        g_object_unref(m_policyDecision);
    m_policyDecision = policyDecision;

    String mimeType = response.mimeType();

    gboolean isHandled = false;
    g_signal_emit_by_name(page, "mime-type-policy-decision-requested", m_frame, request.get(), mimeType.utf8().data(), policyDecision, &isHandled);

    if (isHandled)
        return;

    GRefPtr<WebKitNetworkResponse> networkResponse(adoptGRef(webkit_web_frame_get_network_response(m_frame)));
    if (networkResponse) {
        ResourceResponse response = core(networkResponse.get());
        if (response.isAttachment()) {
            webkit_web_policy_decision_download(policyDecision);
            return;
        }
    }

    if (canShowMIMEType(mimeType))
        webkit_web_policy_decision_use(policyDecision);
    else
        webkit_web_policy_decision_ignore(policyDecision);
}
Example #2
0
void ChromeClientEfl::runJavaScriptAlert(Frame* frame, const String& message)
{
    ewk_view_run_javascript_alert(m_view, kit(frame), message.utf8().data());
}
Example #3
0
void ChromeClientEfl::setStatusbarText(const String& string)
{
    ewk_view_statusbar_text_set(m_view, string.utf8().data());
}
Example #4
0
PassRefPtr<ParsedCookie> CookieManager::parseOneCookie(const URL& url, const String& cookie)
{
    unsigned start = 0;
    unsigned end = cookie.length();

    double curTime = currentTime();
    RefPtr<ParsedCookie> res = ParsedCookie::create(curTime);

    res->setProtocol(url.protocol());

    unsigned tokenEnd = start; // Token end contains the position of the '=' or the end of a token
    unsigned pairEnd = start; // Pair end contains always the position of the ';'

    // Find the first ';' which is not double-quoted and the '=' (if they exist).
    bool foundEqual = false;
    while (pairEnd < end && cookie[pairEnd] != ';') {
        if (cookie[pairEnd] == '=') {
            if (tokenEnd == start) {
                tokenEnd = pairEnd;
                foundEqual = true;
            }
        } else if (cookie[pairEnd] == '"') {
            size_t secondQuotePosition = cookie.find('"', pairEnd + 1);
            if (secondQuotePosition != notFound && secondQuotePosition <= end) {
                pairEnd = secondQuotePosition + 1;
                continue;
            }
        }
        pairEnd++;
    }

    unsigned tokenStart = start;

    bool hasName = false; // This is a hack to avoid changing too much in this brutally brittle code.
    if (tokenEnd != start) {
        // There is a '=' so parse the NAME
        unsigned nameEnd = tokenEnd;

        // The tokenEnd is the position of the '=' so the nameEnd is one less
        nameEnd--;

        // Remove lightweight spaces.
        while (nameEnd && isLightweightSpace(cookie[nameEnd]))
            nameEnd--;

        while (tokenStart < nameEnd && isLightweightSpace(cookie[tokenStart]))
            tokenStart++;

        if (nameEnd + 1 <= tokenStart)
            LOG_ERROR_AND_RETURN("Empty name. Rejecting the cookie");

        String name = cookie.substring(tokenStart, nameEnd + 1 - start);
        res->setName(name);
        hasName = true;
    }

    // Now parse the VALUE
    tokenStart = tokenEnd + 1;
    if (!hasName)
        --tokenStart;

    // Skip lightweight spaces in our token
    while (tokenStart < pairEnd && isLightweightSpace(cookie[tokenStart]))
        tokenStart++;

    tokenEnd = pairEnd;
    while (tokenEnd > tokenStart && isLightweightSpace(cookie[tokenEnd - 1]))
        tokenEnd--;

    String value;
    if (tokenEnd == tokenStart) {
        // Firefox accepts empty value so we will do the same
        value = String();
    } else
        value = cookie.substring(tokenStart, tokenEnd - tokenStart);

    if (hasName)
        res->setValue(value);
    else if (foundEqual)
        return ParsedCookie::create(curTime);
    else
        res->setName(value); // No NAME=VALUE, only NAME

    while (pairEnd < end) {
        // Switch to the next pair as pairEnd is on the ';' and fast-forward any lightweight spaces.
        pairEnd++;
        while (pairEnd < end && isLightweightSpace(cookie[pairEnd]))
            pairEnd++;

        tokenStart = pairEnd;
        tokenEnd = tokenStart; // initialize token end to catch first '='

        while (pairEnd < end && cookie[pairEnd] != ';') {
            if (tokenEnd == tokenStart && cookie[pairEnd] == '=')
                tokenEnd = pairEnd;
            pairEnd++;
        }

        // FIXME : should we skip lightweight spaces here ?

        unsigned length = tokenEnd - tokenStart;
        unsigned tokenStartSvg = tokenStart;

        String parsedValue;
        if (tokenStart != tokenEnd) {
            // There is an equal sign so remove lightweight spaces in VALUE
            tokenStart = tokenEnd + 1;
            while (tokenStart < pairEnd && isLightweightSpace(cookie[tokenStart]))
                tokenStart++;

            tokenEnd = pairEnd;
            while (tokenEnd > tokenStart && isLightweightSpace(cookie[tokenEnd - 1]))
                tokenEnd--;

            parsedValue = cookie.substring(tokenStart, tokenEnd - tokenStart);
        } else {
            // If the parsedValue is empty, initialise it in case we need it
            parsedValue = String();
            // Handle a token without value.
            length = pairEnd - tokenStart;
        }

        // Detect which "cookie-av" is parsed
        // Look at the first char then parse the whole for performance issue
        switch (cookie[tokenStartSvg]) {
        case 'P':
        case 'p' : {
            if (length >= 4 && ((cookie.find("ath", tokenStartSvg + 1, false) - tokenStartSvg) == 1)) {
                // We need the path to be decoded to match those returned from URL::path().
                // The path attribute may or may not include percent-encoded characters. Fortunately
                // if there are no percent-encoded characters, decoding the url is a no-op.
                res->setPath(curl_unescape(parsedValue.utf8().data(), parsedValue.length()));

                // We have to disable the following check because sites like Facebook and
                // Gmail currently do not follow the spec.

                // Check if path attribute is a prefix of the request URI.
                if (!url.path().startsWith(res->path()))
                    LOG_ERROR_AND_RETURN("Invalid cookie attribute %s (path): it does not math the URL", cookie.ascii().data());
            } else
                LOG_ERROR_AND_RETURN("Invalid cookie attribute %s (path)", cookie.ascii().data());
            break;
        }

        case 'D':
        case 'd' : {
            if (length >= 6 && ((cookie.find("omain", tokenStartSvg + 1, false) - tokenStartSvg) == 1)) {
                if (parsedValue.length() > 1 && parsedValue[0] == '"' && parsedValue[parsedValue.length() - 1] == '"')
                    parsedValue = parsedValue.substring(1, parsedValue.length() - 2);

                String host = url.host();

                // Check if the domain contains an embedded dot.
                size_t dotPosition = parsedValue.find(".", 1);
                if (dotPosition == notFound || dotPosition == parsedValue.length())
                    LOG_ERROR_AND_RETURN("Invalid cookie attribute %s (domain): it does not contain an embedded dot", cookie.ascii().data());

                if (isValidIPAddress(host)) {
                    if (parsedValue != host)
                        LOG_ERROR_AND_RETURN("Invalid cookie attribute %s (domain)", cookie.ascii().data());

                } else {
                    // If the domain does not start with a dot, add one for security checks and to distinguish it from host-only domains
                    // For example: ab.c.com dose not domain match b.c.com;
                    if (parsedValue[0] != '.')
                        parsedValue = "." + parsedValue;

                    host = "." + host;

                    if (!host.endsWith(parsedValue, false))
                        LOG_ERROR_AND_RETURN("Invalid cookie attribute %s (domain): it does not domain match the host (%s)", cookie.ascii().data(), host.ascii().data());
                }

                res->setDomain(parsedValue);
            } else
                LOG_ERROR_AND_RETURN("Invalid cookie attribute %s (domain)", cookie.ascii().data());
            break;
        }

        case 'E' :
        case 'e' : {
            if (length >= 7 && ((cookie.find("xpires", tokenStartSvg + 1, false) - tokenStartSvg) == 1))
                res->setExpiry(parsedValue);
            else
                LOG_ERROR_AND_RETURN("Invalid cookie attribute %s (expires)", cookie.ascii().data());
            break;
        }

        case 'M' :
        case 'm' : {
            if (length >= 7 && ((cookie.find("ax-age", tokenStartSvg + 1, false) - tokenStartSvg) == 1))
                res->setMaxAge(parsedValue);
            else
                LOG_ERROR_AND_RETURN("Invalid cookie attribute %s (max-age)", cookie.ascii().data());
            break;
        }

        case 'C' :
        case 'c' : {
            if (length >= 7 && ((cookie.find("omment", tokenStartSvg + 1, false) - tokenStartSvg) == 1))
                // We do not have room for the comment part (and so do Mozilla) so just log the comment.
                LOG(Network, "Comment %s for ParsedCookie : %s\n", parsedValue.ascii().data(), cookie.ascii().data());
            else
                LOG_ERROR_AND_RETURN("Invalid cookie attribute %s (comment)", cookie.ascii().data());
            break;
        }

        case 'V' :
        case 'v' : {
            if (length >= 7 && ((cookie.find("ersion", tokenStartSvg + 1, false) - tokenStartSvg) == 1)) {
                // Although the out-of-dated Cookie Spec(RFC2965, http://tools.ietf.org/html/rfc2965) defined
                // the value of version can only contain DIGIT, some random sites, e.g. https://devforums.apple.com
                // would use double quotation marks to quote the digit. So we need to get rid of them for compliance.
                if (parsedValue.length() > 1 && parsedValue[0] == '"' && parsedValue[parsedValue.length() - 1] == '"')
                    parsedValue = parsedValue.substring(1, parsedValue.length() - 2);

                if (parsedValue.toInt() != 1)
                    LOG_ERROR_AND_RETURN("ParsedCookie version %d not supported (only support version=1)", parsedValue.toInt());
            } else
                LOG_ERROR_AND_RETURN("Invalid cookie attribute %s (version)", cookie.ascii().data());
            break;
        }

        case 'S' :
        case 's' : {
            // Secure is a standalone token ("Secure;")
            if (length >= 6 && ((cookie.find("ecure", tokenStartSvg + 1, false) - tokenStartSvg) == 1))
                res->setSecureFlag(true);
            else
                LOG_ERROR_AND_RETURN("Invalid cookie attribute %s (secure)", cookie.ascii().data());
            break;
        }
        case 'H':
        case 'h': {
            // HttpOnly is a standalone token ("HttpOnly;")
            if (length >= 8 && ((cookie.find("ttpOnly", tokenStartSvg + 1, false) - tokenStartSvg) == 1))
                res->setIsHttpOnly(true);
            else
                LOG_ERROR_AND_RETURN("Invalid cookie attribute %s (HttpOnly)", cookie.ascii().data());
            break;
        }

        default : {
            // If length == 0, we should be at the end of the cookie (case : ";\r") so ignore it
            if (length)
                LOG_ERROR_AND_RETURN("Invalid token for cookie %s", cookie.ascii().data());
            break;
        }
        }
    }

    // Check if the cookie is valid with respect to the size limit.
    if (res->isOverSizeLimit())
        LOG_ERROR_AND_RETURN("ParsedCookie %s is above the 4kb in length : REJECTED", cookie.ascii().data());

    // If no domain was provided, set it to the host
    if (!res->domain())
        res->setDomain(url.host());

    // According to the Cookie Specificaiton (RFC6265, section 4.1.2.4 and 5.2.4, http://tools.ietf.org/html/rfc6265),
    // If no path was provided or the first character of the path value is not '/', set it to the host's path
    //
    // REFERENCE
    // 4.1.2.4. The Path Attribute
    //
    // The scope of each cookie is limited to a set of paths, controlled by
    // the Path attribute. If the server omits the Path attribute, the user
    // agent will use the "directory" of the request-uri's path component as
    // the default value. (See Section 5.1.4 for more details.)
    // ...........
    // 5.2.4. The Path Attribute
    //
    // If the attribute-name case-insensitively matches the string "Path",
    // the user agent MUST process the cookie-av as follows.
    //
    // If the attribute-value is empty or if the first character of the
    // attribute-value is not %x2F ("/"):
    //
    // Let cookie-path be the default-path.
    //
    // Otherwise:
    //
    // Let cookie-path be the attribute-value.
    //
    // Append an attribute to the cookie-attribute-list with an attribute-
    // name of Path and an attribute-value of cookie-path.
    if (!res->path() || !res->path().length() || !res->path().startsWith("/", false)) {
        String path = url.string().substring(url.pathStart(), url.pathAfterLastSlash() - url.pathStart() - 1);
        if (path.isEmpty())
            path = "/";
        // Since this is reading the raw url string, it could contain percent-encoded sequences. We
        // want it to be comparable to the return value of url.path(), which is not percent-encoded,
        // so we must remove the escape sequences.
        res->setPath(curl_unescape(path.utf8().data(), path.length()));
    }

    return res;
}
void GraphicsContext3D::bindAttribLocation(Platform3DObject program, GC3Duint index, const String& name)
{
    ASSERT(program);
    makeContextCurrent();
    glBindAttribLocation(program, index, name.utf8().data());
}
Example #6
0
void DOMPatchSupport::dumpMap(const ResultMap& map, const String& name)
{
    fprintf(stderr, "\n\n");
    for (size_t i = 0; i < map.size(); ++i)
        fprintf(stderr, "%s[%lu]: %s (%p) - [%lu]\n", name.utf8().data(), i, map[i].first ? nodeName(map[i].first->m_node).utf8().data() : "", map[i].first, map[i].second);
}
void VisualScriptBuiltinFunc::exec_func(BuiltinFunc p_func, const Variant **p_inputs, Variant *r_return, Variant::CallError &r_error, String &r_error_str) {

	switch (p_func) {
		case VisualScriptBuiltinFunc::MATH_SIN: {

			VALIDATE_ARG_NUM(0);
			*r_return = Math::sin((double)*p_inputs[0]);
		} break;
		case VisualScriptBuiltinFunc::MATH_COS: {

			VALIDATE_ARG_NUM(0);
			*r_return = Math::cos((double)*p_inputs[0]);
		} break;
		case VisualScriptBuiltinFunc::MATH_TAN: {

			VALIDATE_ARG_NUM(0);
			*r_return = Math::tan((double)*p_inputs[0]);
		} break;
		case VisualScriptBuiltinFunc::MATH_SINH: {

			VALIDATE_ARG_NUM(0);
			*r_return = Math::sinh((double)*p_inputs[0]);
		} break;
		case VisualScriptBuiltinFunc::MATH_COSH: {

			VALIDATE_ARG_NUM(0);
			*r_return = Math::cosh((double)*p_inputs[0]);
		} break;
		case VisualScriptBuiltinFunc::MATH_TANH: {

			VALIDATE_ARG_NUM(0);
			*r_return = Math::tanh((double)*p_inputs[0]);
		} break;
		case VisualScriptBuiltinFunc::MATH_ASIN: {

			VALIDATE_ARG_NUM(0);
			*r_return = Math::asin((double)*p_inputs[0]);
		} break;
		case VisualScriptBuiltinFunc::MATH_ACOS: {

			VALIDATE_ARG_NUM(0);
			*r_return = Math::acos((double)*p_inputs[0]);
		} break;
		case VisualScriptBuiltinFunc::MATH_ATAN: {

			VALIDATE_ARG_NUM(0);
			*r_return = Math::atan((double)*p_inputs[0]);
		} break;
		case VisualScriptBuiltinFunc::MATH_ATAN2: {

			VALIDATE_ARG_NUM(0);
			VALIDATE_ARG_NUM(1);
			*r_return = Math::atan2((double)*p_inputs[0], (double)*p_inputs[1]);
		} break;
		case VisualScriptBuiltinFunc::MATH_SQRT: {

			VALIDATE_ARG_NUM(0);
			*r_return = Math::sqrt((double)*p_inputs[0]);
		} break;
		case VisualScriptBuiltinFunc::MATH_FMOD: {

			VALIDATE_ARG_NUM(0);
			VALIDATE_ARG_NUM(1);
			*r_return = Math::fmod((double)*p_inputs[0], (double)*p_inputs[1]);
		} break;
		case VisualScriptBuiltinFunc::MATH_FPOSMOD: {

			VALIDATE_ARG_NUM(0);
			VALIDATE_ARG_NUM(1);
			*r_return = Math::fposmod((double)*p_inputs[0], (double)*p_inputs[1]);
		} break;
		case VisualScriptBuiltinFunc::MATH_FLOOR: {

			VALIDATE_ARG_NUM(0);
			*r_return = Math::floor((double)*p_inputs[0]);
		} break;
		case VisualScriptBuiltinFunc::MATH_CEIL: {

			VALIDATE_ARG_NUM(0);
			*r_return = Math::ceil((double)*p_inputs[0]);
		} break;
		case VisualScriptBuiltinFunc::MATH_ROUND: {

			VALIDATE_ARG_NUM(0);
			*r_return = Math::round((double)*p_inputs[0]);
		} break;
		case VisualScriptBuiltinFunc::MATH_ABS: {

			if (p_inputs[0]->get_type() == Variant::INT) {

				int64_t i = *p_inputs[0];
				*r_return = ABS(i);
			} else if (p_inputs[0]->get_type() == Variant::REAL) {

				real_t r = *p_inputs[0];
				*r_return = Math::abs(r);
			} else {

				r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
				r_error.argument = 0;
				r_error.expected = Variant::REAL;
			}
		} break;
		case VisualScriptBuiltinFunc::MATH_SIGN: {

			if (p_inputs[0]->get_type() == Variant::INT) {

				int64_t i = *p_inputs[0];
				*r_return = i < 0 ? -1 : (i > 0 ? +1 : 0);
			} else if (p_inputs[0]->get_type() == Variant::REAL) {

				real_t r = *p_inputs[0];
				*r_return = r < 0.0 ? -1.0 : (r > 0.0 ? +1.0 : 0.0);
			} else {

				r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
				r_error.argument = 0;
				r_error.expected = Variant::REAL;
			}
		} break;
		case VisualScriptBuiltinFunc::MATH_POW: {

			VALIDATE_ARG_NUM(0);
			VALIDATE_ARG_NUM(1);
			*r_return = Math::pow((double)*p_inputs[0], (double)*p_inputs[1]);
		} break;
		case VisualScriptBuiltinFunc::MATH_LOG: {

			VALIDATE_ARG_NUM(0);
			*r_return = Math::log((double)*p_inputs[0]);
		} break;
		case VisualScriptBuiltinFunc::MATH_EXP: {

			VALIDATE_ARG_NUM(0);
			*r_return = Math::exp((double)*p_inputs[0]);
		} break;
		case VisualScriptBuiltinFunc::MATH_ISNAN: {

			VALIDATE_ARG_NUM(0);
			*r_return = Math::is_nan((double)*p_inputs[0]);
		} break;
		case VisualScriptBuiltinFunc::MATH_ISINF: {

			VALIDATE_ARG_NUM(0);
			*r_return = Math::is_inf((double)*p_inputs[0]);
		} break;
		case VisualScriptBuiltinFunc::MATH_EASE: {

			VALIDATE_ARG_NUM(0);
			VALIDATE_ARG_NUM(1);
			*r_return = Math::ease((double)*p_inputs[0], (double)*p_inputs[1]);
		} break;
		case VisualScriptBuiltinFunc::MATH_DECIMALS: {

			VALIDATE_ARG_NUM(0);
			*r_return = Math::step_decimals((double)*p_inputs[0]);
		} break;
		case VisualScriptBuiltinFunc::MATH_STEPIFY: {

			VALIDATE_ARG_NUM(0);
			VALIDATE_ARG_NUM(1);
			*r_return = Math::stepify((double)*p_inputs[0], (double)*p_inputs[1]);
		} break;
		case VisualScriptBuiltinFunc::MATH_LERP: {

			VALIDATE_ARG_NUM(0);
			VALIDATE_ARG_NUM(1);
			VALIDATE_ARG_NUM(2);
			*r_return = Math::lerp((double)*p_inputs[0], (double)*p_inputs[1], (double)*p_inputs[2]);
		} break;
		case VisualScriptBuiltinFunc::MATH_INVERSE_LERP: {

			VALIDATE_ARG_NUM(0);
			VALIDATE_ARG_NUM(1);
			VALIDATE_ARG_NUM(2);
			*r_return = Math::inverse_lerp((double)*p_inputs[0], (double)*p_inputs[1], (double)*p_inputs[2]);
		} break;
		case VisualScriptBuiltinFunc::MATH_RANGE_LERP: {

			VALIDATE_ARG_NUM(0);
			VALIDATE_ARG_NUM(1);
			VALIDATE_ARG_NUM(2);
			VALIDATE_ARG_NUM(3);
			VALIDATE_ARG_NUM(4);
			*r_return = Math::range_lerp((double)*p_inputs[0], (double)*p_inputs[1], (double)*p_inputs[2], (double)*p_inputs[3], (double)*p_inputs[4]);
		} break;
		case VisualScriptBuiltinFunc::MATH_DECTIME: {

			VALIDATE_ARG_NUM(0);
			VALIDATE_ARG_NUM(1);
			VALIDATE_ARG_NUM(2);
			*r_return = Math::dectime((double)*p_inputs[0], (double)*p_inputs[1], (double)*p_inputs[2]);
		} break;
		case VisualScriptBuiltinFunc::MATH_RANDOMIZE: {
			Math::randomize();

		} break;
		case VisualScriptBuiltinFunc::MATH_RAND: {
			*r_return = Math::rand();
		} break;
		case VisualScriptBuiltinFunc::MATH_RANDF: {
			*r_return = Math::randf();
		} break;
		case VisualScriptBuiltinFunc::MATH_RANDOM: {

			VALIDATE_ARG_NUM(0);
			VALIDATE_ARG_NUM(1);
			*r_return = Math::random((double)*p_inputs[0], (double)*p_inputs[1]);
		} break;
		case VisualScriptBuiltinFunc::MATH_SEED: {

			VALIDATE_ARG_NUM(0);
			uint64_t seed = *p_inputs[0];
			Math::seed(seed);

		} break;
		case VisualScriptBuiltinFunc::MATH_RANDSEED: {

			VALIDATE_ARG_NUM(0);
			uint64_t seed = *p_inputs[0];
			int ret = Math::rand_from_seed(&seed);
			Array reta;
			reta.push_back(ret);
			reta.push_back(seed);
			*r_return = reta;

		} break;
		case VisualScriptBuiltinFunc::MATH_DEG2RAD: {

			VALIDATE_ARG_NUM(0);
			*r_return = Math::deg2rad((double)*p_inputs[0]);
		} break;
		case VisualScriptBuiltinFunc::MATH_RAD2DEG: {

			VALIDATE_ARG_NUM(0);
			*r_return = Math::rad2deg((double)*p_inputs[0]);
		} break;
		case VisualScriptBuiltinFunc::MATH_LINEAR2DB: {

			VALIDATE_ARG_NUM(0);
			*r_return = Math::linear2db((double)*p_inputs[0]);
		} break;
		case VisualScriptBuiltinFunc::MATH_DB2LINEAR: {

			VALIDATE_ARG_NUM(0);
			*r_return = Math::db2linear((double)*p_inputs[0]);
		} break;
		case VisualScriptBuiltinFunc::LOGIC_MAX: {

			if (p_inputs[0]->get_type() == Variant::INT && p_inputs[1]->get_type() == Variant::INT) {

				int64_t a = *p_inputs[0];
				int64_t b = *p_inputs[1];
				*r_return = MAX(a, b);
			} else {
				VALIDATE_ARG_NUM(0);
				VALIDATE_ARG_NUM(1);

				real_t a = *p_inputs[0];
				real_t b = *p_inputs[1];

				*r_return = MAX(a, b);
			}

		} break;
		case VisualScriptBuiltinFunc::LOGIC_MIN: {

			if (p_inputs[0]->get_type() == Variant::INT && p_inputs[1]->get_type() == Variant::INT) {

				int64_t a = *p_inputs[0];
				int64_t b = *p_inputs[1];
				*r_return = MIN(a, b);
			} else {
				VALIDATE_ARG_NUM(0);
				VALIDATE_ARG_NUM(1);

				real_t a = *p_inputs[0];
				real_t b = *p_inputs[1];

				*r_return = MIN(a, b);
			}
		} break;
		case VisualScriptBuiltinFunc::LOGIC_CLAMP: {

			if (p_inputs[0]->get_type() == Variant::INT && p_inputs[1]->get_type() == Variant::INT && p_inputs[2]->get_type() == Variant::INT) {

				int64_t a = *p_inputs[0];
				int64_t b = *p_inputs[1];
				int64_t c = *p_inputs[2];
				*r_return = CLAMP(a, b, c);
			} else {
				VALIDATE_ARG_NUM(0);
				VALIDATE_ARG_NUM(1);
				VALIDATE_ARG_NUM(2);

				real_t a = *p_inputs[0];
				real_t b = *p_inputs[1];
				real_t c = *p_inputs[2];

				*r_return = CLAMP(a, b, c);
			}
		} break;
		case VisualScriptBuiltinFunc::LOGIC_NEAREST_PO2: {

			VALIDATE_ARG_NUM(0);
			int64_t num = *p_inputs[0];
			*r_return = next_power_of_2(num);
		} break;
		case VisualScriptBuiltinFunc::OBJ_WEAKREF: {

			if (p_inputs[0]->get_type() != Variant::OBJECT) {

				r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
				r_error.argument = 0;
				r_error.expected = Variant::OBJECT;

				return;
			}

			if (p_inputs[0]->is_ref()) {

				REF r = *p_inputs[0];
				if (!r.is_valid()) {

					return;
				}

				Ref<WeakRef> wref = memnew(WeakRef);
				wref->set_ref(r);
				*r_return = wref;
			} else {
				Object *obj = *p_inputs[0];
				if (!obj) {

					return;
				}
				Ref<WeakRef> wref = memnew(WeakRef);
				wref->set_obj(obj);
				*r_return = wref;
			}

		} break;
		case VisualScriptBuiltinFunc::FUNC_FUNCREF: {

			if (p_inputs[0]->get_type() != Variant::OBJECT) {

				r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
				r_error.argument = 0;
				r_error.expected = Variant::OBJECT;

				return;
			}
			if (p_inputs[1]->get_type() != Variant::STRING && p_inputs[1]->get_type() != Variant::NODE_PATH) {

				r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
				r_error.argument = 1;
				r_error.expected = Variant::STRING;

				return;
			}

			Ref<FuncRef> fr = memnew(FuncRef);

			fr->set_instance(*p_inputs[0]);
			fr->set_function(*p_inputs[1]);

			*r_return = fr;

		} break;
		case VisualScriptBuiltinFunc::TYPE_CONVERT: {

			VALIDATE_ARG_NUM(1);
			int type = *p_inputs[1];
			if (type < 0 || type >= Variant::VARIANT_MAX) {

				r_error_str = RTR("Invalid type argument to convert(), use TYPE_* constants.");
				r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
				r_error.argument = 0;
				r_error.expected = Variant::INT;
				return;

			} else {

				*r_return = Variant::construct(Variant::Type(type), p_inputs, 1, r_error);
			}
		} break;
		case VisualScriptBuiltinFunc::TYPE_OF: {

			*r_return = p_inputs[0]->get_type();

		} break;
		case VisualScriptBuiltinFunc::TYPE_EXISTS: {

			*r_return = ClassDB::class_exists(*p_inputs[0]);

		} break;
		case VisualScriptBuiltinFunc::TEXT_CHAR: {

			CharType result[2] = { *p_inputs[0], 0 };

			*r_return = String(result);

		} break;
		case VisualScriptBuiltinFunc::TEXT_STR: {

			String str = *p_inputs[0];

			*r_return = str;

		} break;
		case VisualScriptBuiltinFunc::TEXT_PRINT: {

			String str = *p_inputs[0];
			print_line(str);

		} break;

		case VisualScriptBuiltinFunc::TEXT_PRINTERR: {

			String str = *p_inputs[0];

			//str+="\n";
			OS::get_singleton()->printerr("%s\n", str.utf8().get_data());

		} break;
		case VisualScriptBuiltinFunc::TEXT_PRINTRAW: {
			String str = *p_inputs[0];

			//str+="\n";
			OS::get_singleton()->print("%s", str.utf8().get_data());

		} break;
		case VisualScriptBuiltinFunc::VAR_TO_STR: {

			String vars;
			VariantWriter::write_to_string(*p_inputs[0], vars);
			*r_return = vars;
		} break;
		case VisualScriptBuiltinFunc::STR_TO_VAR: {

			if (p_inputs[0]->get_type() != Variant::STRING) {
				r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
				r_error.argument = 0;
				r_error.expected = Variant::STRING;

				return;
			}

			VariantParser::StreamString ss;
			ss.s = *p_inputs[0];

			String errs;
			int line;
			Error err = VariantParser::parse(&ss, *r_return, errs, line);

			if (err != OK) {
				r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
				r_error.argument = 0;
				r_error.expected = Variant::STRING;
				*r_return = "Parse error at line " + itos(line) + ": " + errs;
				return;
			}

		} break;
		case VisualScriptBuiltinFunc::VAR_TO_BYTES: {

			PoolByteArray barr;
			int len;
			Error err = encode_variant(*p_inputs[0], NULL, len);
			if (err) {
				r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
				r_error.argument = 0;
				r_error.expected = Variant::NIL;
				r_error_str = "Unexpected error encoding variable to bytes, likely unserializable type found (Object or RID).";
				return;
			}

			barr.resize(len);
			{
				PoolByteArray::Write w = barr.write();
				encode_variant(*p_inputs[0], w.ptr(), len);
			}
			*r_return = barr;
		} break;
		case VisualScriptBuiltinFunc::BYTES_TO_VAR: {

			if (p_inputs[0]->get_type() != Variant::POOL_BYTE_ARRAY) {
				r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
				r_error.argument = 0;
				r_error.expected = Variant::POOL_BYTE_ARRAY;

				return;
			}

			PoolByteArray varr = *p_inputs[0];
			Variant ret;
			{
				PoolByteArray::Read r = varr.read();
				Error err = decode_variant(ret, r.ptr(), varr.size(), NULL);
				if (err != OK) {
					r_error_str = RTR("Not enough bytes for decoding bytes, or invalid format.");
					r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
					r_error.argument = 0;
					r_error.expected = Variant::POOL_BYTE_ARRAY;
					return;
				}
			}

			*r_return = ret;

		} break;
		case VisualScriptBuiltinFunc::COLORN: {

			VALIDATE_ARG_NUM(1);

			Color color = Color::named(*p_inputs[0]);
			color.a = *p_inputs[1];

			*r_return = String(color);

		} break;
		default: {}
	}
}
Example #8
0
	void ok_pressed() {

		if (!_test_path())
			return;

		String dir;

		if (mode==MODE_IMPORT) {
			dir=project_path->get_text();


		} else {
			DirAccess *d = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);

			if (d->change_dir(project_path->get_text())!=OK) {
				error->set_text(TTR("Invalid project path (changed anything?)."));
				memdelete(d);
				return;
			}

			dir=d->get_current_dir();
			memdelete(d);

			if (mode==MODE_NEW) {




				FileAccess *f = FileAccess::open(dir.plus_file("/engine.cfg"),FileAccess::WRITE);
				if (!f) {
					error->set_text(TTR("Couldn't create engine.cfg in project path."));
				} else {

					f->store_line("; Engine configuration file.");
					f->store_line("; It's best edited using the editor UI and not directly,");
					f->store_line("; since the parameters that go here are not all obvious.");
					f->store_line("; ");
					f->store_line("; Format: ");
					f->store_line(";   [section] ; section goes between []");
					f->store_line(";   param=value ; assign values to parameters");
					f->store_line("\n");
					f->store_line("[application]");
					f->store_line("\n");
					f->store_line("name=\""+project_name->get_text()+"\"");
					f->store_line("icon=\"res://icon.png\"");

					memdelete(f);

					ResourceSaver::save(dir.plus_file("/icon.png"),get_icon("DefaultProjectIcon","EditorIcons"));
				}

			} else if (mode==MODE_INSTALL) {


				FileAccess *src_f=NULL;
				zlib_filefunc_def io = zipio_create_io_from_file(&src_f);

				unzFile pkg = unzOpen2(zip_path.utf8().get_data(), &io);
				if (!pkg) {

					dialog_error->set_text("Error opening package file, not in zip format.");
					return;
				}

				int ret = unzGoToFirstFile(pkg);

				Vector<String> failed_files;

				int idx=0;
				while(ret==UNZ_OK) {

					//get filename
					unz_file_info info;
					char fname[16384];
					ret = unzGetCurrentFileInfo(pkg,&info,fname,16384,NULL,0,NULL,0);

					String path=fname;

					int depth=1; //stuff from github comes with tag
					bool skip=false;
					while(depth>0) {
						int pp = path.find("/");
						if (pp==-1) {
							skip=true;
							break;
						}
						path=path.substr(pp+1,path.length());
						depth--;
					}


					if (skip || path==String()) {
						//
					} else if (path.ends_with("/")) { // a dir

						path=path.substr(0,path.length()-1);

						DirAccess *da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
						da->make_dir(dir.plus_file(path));
						memdelete(da);

					} else {

						Vector<uint8_t> data;
						data.resize(info.uncompressed_size);

						//read
						unzOpenCurrentFile(pkg);
						unzReadCurrentFile(pkg,data.ptr(),data.size());
						unzCloseCurrentFile(pkg);

						FileAccess *f=FileAccess::open(dir.plus_file(path),FileAccess::WRITE);

						if (f) {
							f->store_buffer(data.ptr(),data.size());
							memdelete(f);
						} else {
							failed_files.push_back(path);
						}


					}

					idx++;
					ret = unzGoToNextFile(pkg);
				}

				unzClose(pkg);

				if (failed_files.size()) {
					String msg=TTR("The following files failed extraction from package:")+"\n\n";
					for(int i=0;i<failed_files.size();i++) {

						if (i>15) {
							msg+="\nAnd "+itos(failed_files.size()-i)+" more files.";
							break;
						}
						msg+=failed_files[i]+"\n";
					}

					dialog_error->set_text(msg);
					dialog_error->popup_centered_minsize();

				} else {
					dialog_error->set_text(TTR("Package Installed Successfully!"));
					dialog_error->popup_centered_minsize();
				}

			}



		}

		dir=dir.replace("\\","/");
		if (dir.ends_with("/"))
			dir=dir.substr(0,dir.length()-1);
		String proj=dir.replace("/","::");
		EditorSettings::get_singleton()->set("projects/"+proj,dir);
		EditorSettings::get_singleton()->save();



		hide();
		emit_signal("project_created");

	}
Example #9
0
ExceptionOr<Ref<IDBObjectStore>> IDBDatabase::createObjectStore(const String& name, ObjectStoreParameters&& parameters)
{
    LOG(IndexedDB, "IDBDatabase::createObjectStore - (%s %s)", m_info.name().utf8().data(), name.utf8().data());

    ASSERT(currentThread() == originThreadID());
    ASSERT(!m_versionChangeTransaction || m_versionChangeTransaction->isVersionChange());

    if (!m_versionChangeTransaction)
        return Exception { IDBDatabaseException::InvalidStateError, ASCIILiteral("Failed to execute 'createObjectStore' on 'IDBDatabase': The database is not running a version change transaction.") };

    if (!m_versionChangeTransaction->isActive())
        return Exception { IDBDatabaseException::TransactionInactiveError };

    if (m_info.hasObjectStore(name))
        return Exception { IDBDatabaseException::ConstraintError, ASCIILiteral("Failed to execute 'createObjectStore' on 'IDBDatabase': An object store with the specified name already exists.") };

    auto& keyPath = parameters.keyPath;
    if (keyPath && !isIDBKeyPathValid(keyPath.value()))
        return Exception { IDBDatabaseException::SyntaxError, ASCIILiteral("Failed to execute 'createObjectStore' on 'IDBDatabase': The keyPath option is not a valid key path.") };

    if (keyPath && parameters.autoIncrement && ((WTF::holds_alternative<String>(keyPath.value()) && WTF::get<String>(keyPath.value()).isEmpty()) || WTF::holds_alternative<Vector<String>>(keyPath.value())))
        return Exception { IDBDatabaseException::InvalidAccessError, ASCIILiteral("Failed to execute 'createObjectStore' on 'IDBDatabase': The autoIncrement option was set but the keyPath option was empty or an array.") };

    // Install the new ObjectStore into the connection's metadata.
    auto info = m_info.createNewObjectStore(name, WTFMove(keyPath), parameters.autoIncrement);

    // Create the actual IDBObjectStore from the transaction, which also schedules the operation server side.
    return m_versionChangeTransaction->createObjectStore(info);
}
Example #10
0
	_FORCE_INLINE_ unsigned int buf_put_string(String p_val, uint8_t *p_buf) {
		for (int i = 0; i < p_val.length(); i++) {
			*p_buf++ = p_val.utf8().get(i);
		}
		return p_val.length();
	}
CString fileSystemRepresentation(const String& string)
{
    return string.utf8();
}
const char* WebSocketHandshake::readHTTPHeaders(const char* start, const char* end, HTTPHeaderMap* headers)
{
    Vector<char> name;
    Vector<char> value;
    for (const char* p = start; p < end; p++) {
        name.clear();
        value.clear();

        for (; p < end; p++) {
            switch (*p) {
            case '\r':
                if (name.isEmpty()) {
                    if (p + 1 < end && *(p + 1) == '\n')
                        return p + 2;
                    m_context->addMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, "CR doesn't follow LF at " + trimConsoleMessage(p, end - p), 0, clientOrigin());
                    return 0;
                }
                m_context->addMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, "Unexpected CR in name at " + trimConsoleMessage(p, end - p), 0, clientOrigin());
                return 0;
            case '\n':
                m_context->addMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, "Unexpected LF in name at " + trimConsoleMessage(p, end - p), 0, clientOrigin());
                return 0;
            case ':':
                break;
            default:
                if (*p >= 0x41 && *p <= 0x5a)
                    name.append(*p + 0x20);
                else
                    name.append(*p);
                continue;
            }
            if (*p == ':') {
                ++p;
                break;
            }
        }

        for (; p < end && *p == 0x20; p++) { }

        for (; p < end; p++) {
            switch (*p) {
            case '\r':
                break;
            case '\n':
                m_context->addMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, "Unexpected LF in value at " + trimConsoleMessage(p, end - p), 0, clientOrigin());
                return 0;
            default:
                value.append(*p);
            }
            if (*p == '\r') {
                ++p;
                break;
            }
        }
        if (p >= end || *p != '\n') {
            m_context->addMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, "CR doesn't follow LF after value at " + trimConsoleMessage(p, end - p), 0, clientOrigin());
            return 0;
        }
        AtomicString nameStr(String::fromUTF8(name.data(), name.size()));
        String valueStr = String::fromUTF8(value.data(), value.size());
        if (nameStr.isNull()) {
            m_context->addMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, "invalid UTF-8 sequence in header name", 0, clientOrigin());
            return 0;
        }
        if (valueStr.isNull()) {
            m_context->addMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, "invalid UTF-8 sequence in header value", 0, clientOrigin());
            return 0;
        }
        LOG(Network, "name=%s value=%s", nameStr.string().utf8().data(), valueStr.utf8().data());
        headers->add(nameStr, valueStr);
    }
    ASSERT_NOT_REACHED();
    return 0;
}
Example #13
0
void WebProcess::plugInDidStartFromOrigin(const String& pageOrigin, const String& pluginOrigin, const String& mimeType)
{
    if (pageOrigin.isEmpty()) {
        LOG(Plugins, "Not adding empty page origin");
        return;
    }

    unsigned plugInOriginHash = hashForPlugInOrigin(pageOrigin, pluginOrigin, mimeType);
    if (isPlugInAutoStartOriginHash(plugInOriginHash)) {
        LOG(Plugins, "Hash %x already exists as auto-start origin (request for %s)", plugInOriginHash, pageOrigin.utf8().data());
        return;
    }

    // We might attempt to start another plugin before the didAddPlugInAutoStartOrigin message
    // comes back from the parent process. Temporarily add this hash to the list with a thirty
    // second timeout. That way, even if the parent decides not to add it, we'll only be
    // incorrect for a little while.
    m_plugInAutoStartOriginHashes.set(plugInOriginHash, currentTime() + 30 * 1000);

    parentProcessConnection()->send(Messages::WebContext::AddPlugInAutoStartOriginHash(pageOrigin, plugInOriginHash), 0);
}
void FrameLoaderClient::dispatchDecidePolicyForNewWindowAction(FramePolicyFunction policyFunction, const NavigationAction& action, const ResourceRequest& resourceRequest, PassRefPtr<FormState>, const String& frameName)
{
    ASSERT(policyFunction);
    if (!policyFunction)
        return;

    if (resourceRequest.isNull()) {
        (core(m_frame)->loader()->policyChecker()->*policyFunction)(PolicyIgnore);
        return;
    }

    WebKitWebPolicyDecision* policyDecision = webkit_web_policy_decision_new(m_frame, policyFunction);

    if (m_policyDecision)
        g_object_unref(m_policyDecision);
    m_policyDecision = policyDecision;

    WebKitWebView* webView = getViewFromFrame(m_frame);
    GRefPtr<WebKitNetworkRequest> request(adoptGRef(webkit_network_request_new(resourceRequest.url().string().utf8().data())));
    GRefPtr<WebKitWebNavigationAction> navigationAction(adoptGRef(getNavigationAction(action, frameName.utf8().data())));
    gboolean isHandled = false;

    g_signal_emit_by_name(webView, "new-window-policy-decision-requested", m_frame, request.get(), navigationAction.get(), policyDecision, &isHandled);

    // FIXME: I think Qt version marshals this to another thread so when we
    // have multi-threaded download, we might need to do the same
    if (!isHandled)
        (core(m_frame)->loader()->policyChecker()->*policyFunction)(PolicyUse);
}
Example #15
0
void WebSocket::connect(const String& url, const Vector<String>& protocols, ExceptionCode& ec)
{
    LOG(Network, "WebSocket %p connect to %s", this, url.utf8().data());
    m_url = KURL(KURL(), url);

    if (!m_url.isValid()) {
        scriptExecutionContext()->addConsoleMessage(JSMessageSource, ErrorMessageLevel, "Invalid url for WebSocket " + m_url.elidedString());
        m_state = CLOSED;
        ec = SYNTAX_ERR;
        return;
    }

    if (!m_url.protocolIs("ws") && !m_url.protocolIs("wss")) {
        scriptExecutionContext()->addConsoleMessage(JSMessageSource, ErrorMessageLevel, "Wrong url scheme for WebSocket " + m_url.elidedString());
        m_state = CLOSED;
        ec = SYNTAX_ERR;
        return;
    }
    if (m_url.hasFragmentIdentifier()) {
        scriptExecutionContext()->addConsoleMessage(JSMessageSource, ErrorMessageLevel, "URL has fragment component " + m_url.elidedString());
        m_state = CLOSED;
        ec = SYNTAX_ERR;
        return;
    }
    if (!portAllowed(m_url)) {
        scriptExecutionContext()->addConsoleMessage(JSMessageSource, ErrorMessageLevel, "WebSocket port " + String::number(m_url.port()) + " blocked");
        m_state = CLOSED;
        ec = SECURITY_ERR;
        return;
    }

    // FIXME: Convert this to check the isolated world's Content Security Policy once webkit.org/b/104520 is solved.
    bool shouldBypassMainWorldContentSecurityPolicy = false;
    if (scriptExecutionContext()->isDocument()) {
        Document* document = static_cast<Document*>(scriptExecutionContext());
        shouldBypassMainWorldContentSecurityPolicy = document->frame()->script()->shouldBypassMainWorldContentSecurityPolicy();
    }
    if (!shouldBypassMainWorldContentSecurityPolicy && !scriptExecutionContext()->contentSecurityPolicy()->allowConnectToSource(m_url)) {
        m_state = CLOSED;

        // FIXME: Should this be throwing an exception?
        ec = SECURITY_ERR;
        return;
    }

    m_channel = ThreadableWebSocketChannel::create(scriptExecutionContext(), this);

    // FIXME: There is a disagreement about restriction of subprotocols between WebSocket API and hybi-10 protocol
    // draft. The former simply says "only characters in the range U+0021 to U+007E are allowed," while the latter
    // imposes a stricter rule: "the elements MUST be non-empty strings with characters as defined in [RFC2616],
    // and MUST all be unique strings."
    //
    // Here, we throw SYNTAX_ERR if the given protocols do not meet the latter criteria. This behavior does not
    // comply with WebSocket API specification, but it seems to be the only reasonable way to handle this conflict.
    for (size_t i = 0; i < protocols.size(); ++i) {
        if (!isValidProtocolString(protocols[i])) {
            scriptExecutionContext()->addConsoleMessage(JSMessageSource, ErrorMessageLevel, "Wrong protocol for WebSocket '" + encodeProtocolString(protocols[i]) + "'");
            m_state = CLOSED;
            ec = SYNTAX_ERR;
            return;
        }
    }
    HashSet<String> visited;
    for (size_t i = 0; i < protocols.size(); ++i) {
        if (visited.contains(protocols[i])) {
            scriptExecutionContext()->addConsoleMessage(JSMessageSource, ErrorMessageLevel, "WebSocket protocols contain duplicates: '" + encodeProtocolString(protocols[i]) + "'");
            m_state = CLOSED;
            ec = SYNTAX_ERR;
            return;
        }
        visited.add(protocols[i]);
    }

    String protocolString;
    if (!protocols.isEmpty())
        protocolString = joinStrings(protocols, subProtocolSeperator());

    m_channel->connect(m_url, protocolString);
    ActiveDOMObject::setPendingActivity(this);
}
Example #16
0
MainLoop* test() {

	{

	//	print_line("NUM: "+itos(237641278346127));
		print_line("NUM: "+itos(-128));
		return NULL;

	}


	{
		Vector3 v(1,2,3);
		v.normalize();
		float a=0.3;

		//Quat q(v,a);
		Matrix3 m(v,a);

		Vector3 v2(7,3,1);
		v2.normalize();
		float a2=0.8;

		//Quat q(v,a);
		Matrix3 m2(v2,a2);

		Quat q=m;
		Quat q2=m2;

		Matrix3 m3 = m.inverse() * m2;
		Quat q3 = (q.inverse() * q2);//.normalized();

		print_line(Quat(m3));
		print_line(q3);

		print_line("before v: "+v+" a: "+rtos(a));
		q.get_axis_and_angle(v,a);
		print_line("after v: "+v+" a: "+rtos(a));
	}

	return NULL;
	String ret;

	List<String> args;
	args.push_back("-l");
	Error err = OS::get_singleton()->execute("/bin/ls",args,true,NULL,&ret);
	print_line("error: "+itos(err));
	print_line(ret);

	return NULL;
	Matrix3 m3;
	m3.rotate(Vector3(1,0,0),0.2);
	m3.rotate(Vector3(0,1,0),1.77);
	m3.rotate(Vector3(0,0,1),212);
	Matrix3 m32;
	m32.set_euler(m3.get_euler());
	print_line("ELEULEEEEEEEEEEEEEEEEEER: "+m3.get_euler()+" vs "+m32.get_euler());


	return NULL;

	{

		Dictionary d;
		d["momo"]=1;
		Dictionary b=d;
		b["44"]=4;
	}



	return NULL;
	print_line("inters: "+rtos(Geometry::segment_intersects_circle(Vector2(-5,0),Vector2(-2,0),Vector2(),1.0)));



	print_line("cross: "+Vector3(1,2,3).cross(Vector3(4,5,7)));
	print_line("dot: "+rtos(Vector3(1,2,3).dot(Vector3(4,5,7))));
	print_line("abs: "+Vector3(-1,2,-3).abs());
	print_line("distance_to: "+rtos(Vector3(1,2,3).distance_to(Vector3(4,5,7))));
	print_line("distance_squared_to: "+rtos(Vector3(1,2,3).distance_squared_to(Vector3(4,5,7))));
	print_line("plus: "+(Vector3(1,2,3)+Vector3(Vector3(4,5,7))));
	print_line("minus: "+(Vector3(1,2,3)-Vector3(Vector3(4,5,7))));
	print_line("mul: "+(Vector3(1,2,3)*Vector3(Vector3(4,5,7))));
	print_line("div: "+(Vector3(1,2,3)/Vector3(Vector3(4,5,7))));
	print_line("mul scalar: "+(Vector3(1,2,3)*2));
	print_line("premul scalar: "+(2*Vector3(1,2,3)));
	print_line("div scalar: "+(Vector3(1,2,3)/3.0));
	print_line("length: "+rtos(Vector3(1,2,3).length()));
	print_line("length squared: "+rtos(Vector3(1,2,3).length_squared()));
	print_line("normalized: "+Vector3(1,2,3).normalized());
	print_line("inverse: "+Vector3(1,2,3).inverse());

	{
		Vector3 v(4,5,7);
		v.normalize();
		print_line("normalize: "+v);
	}

	{
		Vector3 v(4,5,7);
		v+=Vector3(1,2,3);
		print_line("+=: "+v);
	}

	{
		Vector3 v(4,5,7);
		v-=Vector3(1,2,3);
		print_line("-=: "+v);
	}

	{
		Vector3 v(4,5,7);
		v*=Vector3(1,2,3);
		print_line("*=: "+v);
	}

	{
		Vector3 v(4,5,7);
		v/=Vector3(1,2,3);
		print_line("/=: "+v);
	}

	{
		Vector3 v(4,5,7);
		v*=2.0;
		print_line("scalar *=: "+v);
	}

	{
		Vector3 v(4,5,7);
		v/=2.0;
		print_line("scalar /=: "+v);
	}



#if 0
	print_line(String("C:\\momo\\.\\popo\\..\\gongo").simplify_path());
	print_line(String("res://../popo/..//gongo").simplify_path());
	print_line(String("res://..").simplify_path());


	DVector<uint8_t> a;
	DVector<uint8_t> b;

	a.resize(20);
	b=a;
	b.resize(30);
	a=b;
#endif

#if 0
	String za = String::utf8("á");
	printf("unicode: %x\n",za[0]);
	CharString cs=za.utf8();
	for(int i=0;i<cs.size();i++) {
		uint32_t v = uint8_t(cs[i]);
		printf("%i - %x\n",i,v);
	}
	return NULL;

	print_line(String("C:\\window\\system\\momo").path_to("C:\\window\\momonga"));
	print_line(String("res://momo/sampler").path_to("res://pindonga"));
	print_line(String("/margarito/terere").path_to("/margarito/pilates"));
	print_line(String("/algo").path_to("/algo"));
	print_line(String("c:").path_to("c:\\"));
	print_line(String("/").path_to("/"));


	print_line(itos(sizeof(Variant)));
	return NULL;

	Vector<StringName> path;
	path.push_back("three");
	path.push_back("two");
	path.push_back("one");
	path.push_back("comeon");
	path.revert();

	NodePath np(path,true);

	print_line(np);


	return NULL;

	bool a=2;

	print_line(Variant(a));


	Matrix32 mat2_1;
	mat2_1.rotate(0.5);
	Matrix32 mat2_2;
	mat2_2.translate(Vector2(1,2));
	Matrix32 mat2_3 = mat2_1 * mat2_2;
	mat2_3.affine_invert();

	print_line(mat2_3.elements[0]);
	print_line(mat2_3.elements[1]);
	print_line(mat2_3.elements[2]);



	Transform mat3_1;
	mat3_1.basis.rotate(Vector3(0,0,1),0.5);
	Transform mat3_2;
	mat3_2.translate(Vector3(1,2,0));
	Transform mat3_3 = mat3_1 * mat3_2;
	mat3_3.affine_invert();

	print_line(mat3_3.basis.get_axis(0));
	print_line(mat3_3.basis.get_axis(1));
	print_line(mat3_3.origin);

#endif
	return NULL;

}
Example #17
0
static void addStringToSHA1(SHA1& sha1, const String& string)
{
    CString cString = string.utf8();
    sha1.addBytes(reinterpret_cast<const uint8_t*>(cString.data()), cString.length());
}
Example #18
0
bool ChromeClientEfl::runBeforeUnloadConfirmPanel(const String& message, Frame* frame)
{
    return ewk_view_run_before_unload_confirm(m_view, kit(frame), message.utf8().data());
}
void RemoteInspectorServer::sendWebInspectorEvent(ClientID clientID, const String& event)
{
    const CString message = event.utf8();
    m_server->send(clientID, reinterpret_cast<const uint8_t*>(message.data()), message.length());
}
Example #20
0
void ChromeClientEfl::addMessageToConsole(MessageSource, MessageLevel, const String& message,
                                          unsigned lineNumber, unsigned columnNumber, const String& sourceID)
{
    UNUSED_PARAM(columnNumber);
    ewk_view_add_console_message(m_view, message.utf8().data(), lineNumber, sourceID.utf8().data());
}
CString fileSystemRepresentation(const String& path)
{
    return path.utf8();
}
Example #22
0
static Vector<String> strongAliasesForFamily(const String& family)
{
    RefPtr<FcPattern> pattern = adoptRef(FcPatternCreate());
    if (!FcPatternAddString(pattern.get(), FC_FAMILY, reinterpret_cast<const FcChar8*>(family.utf8().data())))
        return Vector<String>();

    FcConfigSubstitute(nullptr, pattern.get(), FcMatchPattern);
    FcDefaultSubstitute(pattern.get());

    FcUniquePtr<FcObjectSet> familiesOnly(FcObjectSetBuild(FC_FAMILY, nullptr));
    RefPtr<FcPattern> minimal = adoptRef(FcPatternFilter(pattern.get(), familiesOnly.get()));

    // We really want to match strong (preferred) and same (acceptable) only here.
    // If a family name was specified, assume that any weak matches after the last strong match
    // are weak (default) and ignore them.
    // The reason for is that after substitution the pattern for 'sans-serif' looks like
    // "wwwwwwwwwwwwwwswww" where there are many weak but preferred names, followed by defaults.
    // So it is possible to have weakly matching but preferred names.
    // In aliases, bindings are weak by default, so this is easy and common.
    // If no family name was specified, we'll probably only get weak matches, but that's ok.
    int lastStrongId = -1;
    int numIds = 0;
    for (int id = 0; ; ++id) {
        AliasStrength result = strengthOfFirstAlias(*minimal);
        if (result == AliasStrength::Done) {
            numIds = id;
            break;
        }
        if (result == AliasStrength::Strong)
            lastStrongId = id;
        if (!FcPatternRemove(minimal.get(), FC_FAMILY, 0))
            return Vector<String>();
    }

    // If they were all weak, then leave the pattern alone.
    if (lastStrongId < 0)
        return Vector<String>();

    // Remove everything after the last strong.
    for (int id = lastStrongId + 1; id < numIds; ++id) {
        if (!FcPatternRemove(pattern.get(), FC_FAMILY, lastStrongId + 1)) {
            ASSERT_NOT_REACHED();
            return Vector<String>();
        }
    }

    // Take the resulting pattern and remove everything but the families.
    minimal = adoptRef(FcPatternFilter(pattern.get(), familiesOnly.get()));
    // Convert the pattern to a string, and cut out the non-family junk that gets added to the end.
    char* patternChars = reinterpret_cast<char*>(FcPatternFormat(pattern.get(), reinterpret_cast<const FcChar8*>("%{family}")));
    String patternString = String::fromUTF8(patternChars);
    free(patternChars);

    Vector<String> results;
    patternString.split(',', results);
    return results;
}
Example #23
0
void OS_Haiku::set_window_title(const String &p_title) {
	window->SetTitle(p_title.utf8().get_data());
}
Example #24
0
void WebSocket::connect(const String& url, const Vector<String>& protocols, ExceptionCode& ec)
{
    LOG(Network, "WebSocket %p connect to %s", this, url.utf8().data());
    m_url = KURL(KURL(), url);

    if (!m_url.isValid()) {
        scriptExecutionContext()->addConsoleMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, "Invalid url for WebSocket " + m_url.string(), scriptExecutionContext()->securityOrigin()->toString());
        m_state = CLOSED;
        ec = SYNTAX_ERR;
        return;
    }

    if (!m_url.protocolIs("ws") && !m_url.protocolIs("wss")) {
        scriptExecutionContext()->addConsoleMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, "Wrong url scheme for WebSocket " + m_url.string(), scriptExecutionContext()->securityOrigin()->toString());
        m_state = CLOSED;
        ec = SYNTAX_ERR;
        return;
    }
    if (m_url.hasFragmentIdentifier()) {
        scriptExecutionContext()->addConsoleMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, "URL has fragment component " + m_url.string(), scriptExecutionContext()->securityOrigin()->toString());
        m_state = CLOSED;
        ec = SYNTAX_ERR;
        return;
    }
    if (!portAllowed(m_url)) {
        scriptExecutionContext()->addConsoleMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, "WebSocket port " + String::number(m_url.port()) + " blocked", scriptExecutionContext()->securityOrigin()->toString());
        m_state = CLOSED;
        ec = SECURITY_ERR;
        return;
    }

    if (!scriptExecutionContext()->contentSecurityPolicy()->allowConnectFromSource(m_url)) {
        m_state = CLOSED;

        // FIXME: Should this be throwing an exception?
        ec = SECURITY_ERR;
        return;
    }

    m_channel = ThreadableWebSocketChannel::create(scriptExecutionContext(), this);
    m_useHixie76Protocol = m_channel->useHixie76Protocol();

    String protocolString;
    if (m_useHixie76Protocol) {
        if (!protocols.isEmpty()) {
            // Emulate JavaScript's Array.toString() behavior.
            protocolString = joinStrings(protocols, ",");
        }
        if (!isValidProtocolStringHixie76(protocolString)) {
            scriptExecutionContext()->addConsoleMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, "Wrong protocol for WebSocket '" + encodeProtocolString(protocolString) + "'", scriptExecutionContext()->securityOrigin()->toString());
            m_state = CLOSED;
            ec = SYNTAX_ERR;
            return;
        }
    } else {
        // FIXME: There is a disagreement about restriction of subprotocols between WebSocket API and hybi-10 protocol
        // draft. The former simply says "only characters in the range U+0021 to U+007E are allowed," while the latter
        // imposes a stricter rule: "the elements MUST be non-empty strings with characters as defined in [RFC2616],
        // and MUST all be unique strings."
        //
        // Here, we throw SYNTAX_ERR if the given protocols do not meet the latter criteria. This behavior does not
        // comply with WebSocket API specification, but it seems to be the only reasonable way to handle this conflict.
        for (size_t i = 0; i < protocols.size(); ++i) {
            if (!isValidProtocolString(protocols[i])) {
                scriptExecutionContext()->addConsoleMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, "Wrong protocol for WebSocket '" + encodeProtocolString(protocols[i]) + "'", scriptExecutionContext()->securityOrigin()->toString());
                m_state = CLOSED;
                ec = SYNTAX_ERR;
                return;
            }
        }
        HashSet<String> visited;
        for (size_t i = 0; i < protocols.size(); ++i) {
            if (visited.contains(protocols[i])) {
                scriptExecutionContext()->addConsoleMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, "WebSocket protocols contain duplicates: '" + encodeProtocolString(protocols[i]) + "'", scriptExecutionContext()->securityOrigin()->toString());
                m_state = CLOSED;
                ec = SYNTAX_ERR;
                return;
            }
            visited.add(protocols[i]);
        }

        if (!protocols.isEmpty())
            protocolString = joinStrings(protocols, ", ");
    }

    m_channel->connect(m_url, protocolString);
    ActiveDOMObject::setPendingActivity(this);
}
Example #25
0
void ChromeClientEfl::addMessageToConsole(MessageSource, MessageType, MessageLevel, const String& message,
                                          unsigned int lineNumber, const String& sourceID)
{
    ewk_view_add_console_message(m_view, message.utf8().data(), lineNumber, sourceID.utf8().data());
}
static AtkAttributeSet* getAttributeSetForAccessibilityObject(const AccessibilityObject* object)
{
    if (!object->isAccessibilityRenderObject())
        return 0;

    RenderObject* renderer = object->renderer();
    RenderStyle* style = renderer->style();

    AtkAttributeSet* result = 0;
    GOwnPtr<gchar> buffer(g_strdup_printf("%i", style->fontSize()));
    result = addToAtkAttributeSet(result, atk_text_attribute_get_name(ATK_TEXT_ATTR_SIZE), buffer.get());

    Color bgColor = style->visitedDependentColor(CSSPropertyBackgroundColor);
    if (bgColor.isValid()) {
        buffer.set(g_strdup_printf("%i,%i,%i", bgColor.red(), bgColor.green(), bgColor.blue()));
        result = addToAtkAttributeSet(result, atk_text_attribute_get_name(ATK_TEXT_ATTR_BG_COLOR), buffer.get());
    }

    Color fgColor = style->visitedDependentColor(CSSPropertyColor);
    if (fgColor.isValid()) {
        buffer.set(g_strdup_printf("%i,%i,%i", fgColor.red(), fgColor.green(), fgColor.blue()));
        result = addToAtkAttributeSet(result, atk_text_attribute_get_name(ATK_TEXT_ATTR_FG_COLOR), buffer.get());
    }

    int baselinePosition;
    bool includeRise = true;
    switch (style->verticalAlign()) {
    case SUB:
        baselinePosition = -1 * baselinePositionForRenderObject(renderer);
        break;
    case SUPER:
        baselinePosition = baselinePositionForRenderObject(renderer);
        break;
    case BASELINE:
        baselinePosition = 0;
        break;
    default:
        includeRise = false;
        break;
    }

    if (includeRise) {
        buffer.set(g_strdup_printf("%i", baselinePosition));
        result = addToAtkAttributeSet(result, atk_text_attribute_get_name(ATK_TEXT_ATTR_RISE), buffer.get());
    }

    if (!style->textIndent().isUndefined()) {
        int indentation = valueForLength(style->textIndent(), object->size().width(), renderer->view());
        buffer.set(g_strdup_printf("%i", indentation));
        result = addToAtkAttributeSet(result, atk_text_attribute_get_name(ATK_TEXT_ATTR_INDENT), buffer.get());
    }

    String fontFamilyName = style->font().family().family().string();
    if (fontFamilyName.left(8) == "-webkit-")
        fontFamilyName = fontFamilyName.substring(8);

    result = addToAtkAttributeSet(result, atk_text_attribute_get_name(ATK_TEXT_ATTR_FAMILY_NAME), fontFamilyName.utf8().data());

    int fontWeight = -1;
    switch (style->font().weight()) {
    case FontWeight100:
        fontWeight = 100;
        break;
    case FontWeight200:
        fontWeight = 200;
        break;
    case FontWeight300:
        fontWeight = 300;
        break;
    case FontWeight400:
        fontWeight = 400;
        break;
    case FontWeight500:
        fontWeight = 500;
        break;
    case FontWeight600:
        fontWeight = 600;
        break;
    case FontWeight700:
        fontWeight = 700;
        break;
    case FontWeight800:
        fontWeight = 800;
        break;
    case FontWeight900:
        fontWeight = 900;
    }
    if (fontWeight > 0) {
        buffer.set(g_strdup_printf("%i", fontWeight));
        result = addToAtkAttributeSet(result, atk_text_attribute_get_name(ATK_TEXT_ATTR_WEIGHT), buffer.get());
    }

    switch (style->textAlign()) {
    case TASTART:
    case TAEND:
        break;
    case LEFT:
    case WEBKIT_LEFT:
        result = addToAtkAttributeSet(result, atk_text_attribute_get_name(ATK_TEXT_ATTR_JUSTIFICATION), "left");
        break;
    case RIGHT:
    case WEBKIT_RIGHT:
        result = addToAtkAttributeSet(result, atk_text_attribute_get_name(ATK_TEXT_ATTR_JUSTIFICATION), "right");
        break;
    case CENTER:
    case WEBKIT_CENTER:
        result = addToAtkAttributeSet(result, atk_text_attribute_get_name(ATK_TEXT_ATTR_JUSTIFICATION), "center");
        break;
    case JUSTIFY:
        result = addToAtkAttributeSet(result, atk_text_attribute_get_name(ATK_TEXT_ATTR_JUSTIFICATION), "fill");
    }

    result = addToAtkAttributeSet(result, atk_text_attribute_get_name(ATK_TEXT_ATTR_UNDERLINE), (style->textDecoration() & UNDERLINE) ? "single" : "none");

    result = addToAtkAttributeSet(result, atk_text_attribute_get_name(ATK_TEXT_ATTR_STYLE), style->font().italic() ? "italic" : "normal");

    result = addToAtkAttributeSet(result, atk_text_attribute_get_name(ATK_TEXT_ATTR_STRIKETHROUGH), (style->textDecoration() & LINE_THROUGH) ? "true" : "false");

    result = addToAtkAttributeSet(result, atk_text_attribute_get_name(ATK_TEXT_ATTR_INVISIBLE), (style->visibility() == HIDDEN) ? "true" : "false");

    result = addToAtkAttributeSet(result, atk_text_attribute_get_name(ATK_TEXT_ATTR_EDITABLE), object->isReadOnly() ? "false" : "true");

    return result;
}
Example #27
0
bool ChromeClientEfl::runJavaScriptConfirm(Frame* frame, const String& message)
{
    return ewk_view_run_javascript_confirm(m_view, kit(frame), message.utf8().data());
}
static gchar* textForRenderer(RenderObject* renderer)
{
    GString* resultText = g_string_new(0);

    if (!renderer)
        return g_string_free(resultText, FALSE);

    // For RenderBlocks, piece together the text from the RenderText objects they contain.
    for (RenderObject* object = renderer->firstChild(); object; object = object->nextSibling()) {
        if (object->isBR()) {
            g_string_append(resultText, "\n");
            continue;
        }

        RenderText* renderText;
        if (object->isText())
            renderText = toRenderText(object);
        else {
            // List item's markers will be treated in an special way
            // later on this function, so ignore them here.
            if (object->isReplaced() && !object->isListMarker())
                g_string_append_unichar(resultText, objectReplacementCharacter);

            // We need to check children, if any, to consider when
            // current object is not a text object but some of its
            // children are, in order not to miss those portions of
            // text by not properly handling those situations
            if (object->firstChild())
                g_string_append(resultText, textForRenderer(object));

            continue;
        }

        InlineTextBox* box = renderText ? renderText->firstTextBox() : 0;
        while (box) {
            // WebCore introduces line breaks in the text that do not reflect
            // the layout you see on the screen, replace them with spaces.
            String text = String(renderText->characters(), renderText->textLength()).replace("\n", " ");
            g_string_append(resultText, text.substring(box->start(), box->end() - box->start() + 1).utf8().data());

            // Newline chars in the source result in separate text boxes, so check
            // before adding a newline in the layout. See bug 25415 comment #78.
            // If the next sibling is a BR, we'll add the newline when we examine that child.
            if (!box->nextOnLineExists() && !(object->nextSibling() && object->nextSibling()->isBR())) {
                // If there was a '\n' in the last position of the
                // current text box, it would have been converted to a
                // space in String::replace(), so remove it first.
                if (renderText->characters()[box->end()] == '\n')
                    g_string_erase(resultText, resultText->len - 1, -1);

                g_string_append(resultText, "\n");
            }
            box = box->nextTextBox();
        }
    }

    // Insert the text of the marker for list item in the right place, if present
    if (renderer->isListItem()) {
        String markerText = toRenderListItem(renderer)->markerTextWithSuffix();
        if (renderer->style()->direction() == LTR)
            g_string_prepend(resultText, markerText.utf8().data());
        else
            g_string_append(resultText, markerText.utf8().data());
    }

    return g_string_free(resultText, FALSE);
}
Example #29
0
void ChromeClientEfl::setToolTip(const String& toolTip, TextDirection)
{
    ewk_view_tooltip_text_set(m_view, toolTip.utf8().data());
}
Example #30
0
PassOwnPtr<Locale> Locale::create(const String& locale)
{
    return LocaleICU::create(locale.utf8().data());
}