Exemplo n.º 1
0
const AtomicString& HTMLElement::eventNameForAttributeName(const QualifiedName& attrName)
{
    if (!attrName.namespaceURI().isNull())
        return nullAtom;

    if (!attrName.localName().startsWith("on", TextCaseInsensitive))
        return nullAtom;

    typedef HashMap<AtomicString, AtomicString> StringToStringMap;
    DEFINE_STATIC_LOCAL(StringToStringMap, attributeNameToEventNameMap, ());
    if (!attributeNameToEventNameMap.size()) {
        struct AttrToEventName {
            const QualifiedName& attr;
            const AtomicString& event;
        };
        AttrToEventName attrToEventNames[] = {
            { onabortAttr, EventTypeNames::abort },
            { onanimationendAttr, EventTypeNames::animationend },
            { onanimationiterationAttr, EventTypeNames::animationiteration },
            { onanimationstartAttr, EventTypeNames::animationstart },
            { onautocompleteAttr, EventTypeNames::autocomplete },
            { onautocompleteerrorAttr, EventTypeNames::autocompleteerror },
            { onbeforecopyAttr, EventTypeNames::beforecopy },
            { onbeforecutAttr, EventTypeNames::beforecut },
            { onbeforepasteAttr, EventTypeNames::beforepaste },
            { onblurAttr, EventTypeNames::blur },
            { oncancelAttr, EventTypeNames::cancel },
            { oncanplayAttr, EventTypeNames::canplay },
            { oncanplaythroughAttr, EventTypeNames::canplaythrough },
            { onchangeAttr, EventTypeNames::change },
            { onclickAttr, EventTypeNames::click },
            { oncloseAttr, EventTypeNames::close },
            { oncontextmenuAttr, EventTypeNames::contextmenu },
            { oncopyAttr, EventTypeNames::copy },
            { oncuechangeAttr, EventTypeNames::cuechange },
            { oncutAttr, EventTypeNames::cut },
            { ondblclickAttr, EventTypeNames::dblclick },
            { ondragAttr, EventTypeNames::drag },
            { ondragendAttr, EventTypeNames::dragend },
            { ondragenterAttr, EventTypeNames::dragenter },
            { ondragleaveAttr, EventTypeNames::dragleave },
            { ondragoverAttr, EventTypeNames::dragover },
            { ondragstartAttr, EventTypeNames::dragstart },
            { ondropAttr, EventTypeNames::drop },
            { ondurationchangeAttr, EventTypeNames::durationchange },
            { onemptiedAttr, EventTypeNames::emptied },
            { onendedAttr, EventTypeNames::ended },
            { onerrorAttr, EventTypeNames::error },
            { onfocusAttr, EventTypeNames::focus },
            { onfocusinAttr, EventTypeNames::focusin },
            { onfocusoutAttr, EventTypeNames::focusout },
            { oninputAttr, EventTypeNames::input },
            { oninvalidAttr, EventTypeNames::invalid },
            { onkeydownAttr, EventTypeNames::keydown },
            { onkeypressAttr, EventTypeNames::keypress },
            { onkeyupAttr, EventTypeNames::keyup },
            { onloadAttr, EventTypeNames::load },
            { onloadeddataAttr, EventTypeNames::loadeddata },
            { onloadedmetadataAttr, EventTypeNames::loadedmetadata },
            { onloadstartAttr, EventTypeNames::loadstart },
            { onmousedownAttr, EventTypeNames::mousedown },
            { onmouseenterAttr, EventTypeNames::mouseenter },
            { onmouseleaveAttr, EventTypeNames::mouseleave },
            { onmousemoveAttr, EventTypeNames::mousemove },
            { onmouseoutAttr, EventTypeNames::mouseout },
            { onmouseoverAttr, EventTypeNames::mouseover },
            { onmouseupAttr, EventTypeNames::mouseup },
            { onmousewheelAttr, EventTypeNames::mousewheel },
            { onpasteAttr, EventTypeNames::paste },
            { onpauseAttr, EventTypeNames::pause },
            { onplayAttr, EventTypeNames::play },
            { onplayingAttr, EventTypeNames::playing },
            { onprogressAttr, EventTypeNames::progress },
            { onratechangeAttr, EventTypeNames::ratechange },
            { onresetAttr, EventTypeNames::reset },
            { onresizeAttr, EventTypeNames::resize },
            { onscrollAttr, EventTypeNames::scroll },
            { onseekedAttr, EventTypeNames::seeked },
            { onseekingAttr, EventTypeNames::seeking },
            { onselectAttr, EventTypeNames::select },
            { onselectstartAttr, EventTypeNames::selectstart },
            { onshowAttr, EventTypeNames::show },
            { onstalledAttr, EventTypeNames::stalled },
            { onsubmitAttr, EventTypeNames::submit },
            { onsuspendAttr, EventTypeNames::suspend },
            { ontimeupdateAttr, EventTypeNames::timeupdate },
            { ontoggleAttr, EventTypeNames::toggle },
            { ontouchcancelAttr, EventTypeNames::touchcancel },
            { ontouchendAttr, EventTypeNames::touchend },
            { ontouchmoveAttr, EventTypeNames::touchmove },
            { ontouchstartAttr, EventTypeNames::touchstart },
            { ontransitionendAttr, EventTypeNames::webkitTransitionEnd },
            { onvolumechangeAttr, EventTypeNames::volumechange },
            { onwaitingAttr, EventTypeNames::waiting },
            { onwebkitanimationendAttr, EventTypeNames::webkitAnimationEnd },
            { onwebkitanimationiterationAttr, EventTypeNames::webkitAnimationIteration },
            { onwebkitanimationstartAttr, EventTypeNames::webkitAnimationStart },
            { onwebkitfullscreenchangeAttr, EventTypeNames::webkitfullscreenchange },
            { onwebkitfullscreenerrorAttr, EventTypeNames::webkitfullscreenerror },
            { onwebkittransitionendAttr, EventTypeNames::webkitTransitionEnd },
            { onwheelAttr, EventTypeNames::wheel },
        };

        for (size_t i = 0; i < WTF_ARRAY_LENGTH(attrToEventNames); i++)
            attributeNameToEventNameMap.set(attrToEventNames[i].attr.localName(), attrToEventNames[i].event);
    }

    return attributeNameToEventNameMap.get(attrName.localName());
}
Exemplo n.º 2
0
void MarkupFormatter::appendCharactersReplacingEntities(StringBuilder& result, const String& source, unsigned offset, unsigned length, EntityMask entityMask)
{
    DEFINE_STATIC_LOCAL(const CString, ampReference, ("&amp;"));
    DEFINE_STATIC_LOCAL(const CString, ltReference, ("&lt;"));
    DEFINE_STATIC_LOCAL(const CString, gtReference, ("&gt;"));
    DEFINE_STATIC_LOCAL(const CString, quotReference, ("&quot;"));
    DEFINE_STATIC_LOCAL(const CString, nbspReference, ("&nbsp;"));
    DEFINE_STATIC_LOCAL(const CString, tabReference, ("&#9;"));
    DEFINE_STATIC_LOCAL(const CString, lineFeedReference, ("&#10;"));
    DEFINE_STATIC_LOCAL(const CString, carriageReturnReference, ("&#13;"));

    static const EntityDescription entityMaps[] = {
        { '&', ampReference, EntityAmp },
        { '<', ltReference, EntityLt },
        { '>', gtReference, EntityGt },
        { '"', quotReference, EntityQuot },
        { noBreakSpaceCharacter, nbspReference, EntityNbsp },
        { '\t', tabReference, EntityTab },
        { '\n', lineFeedReference, EntityLineFeed },
        { '\r', carriageReturnReference, EntityCarriageReturn },
    };

    if (!(offset + length))
        return;

    DCHECK_LE(offset + length, source.length());
    if (source.is8Bit())
        appendCharactersReplacingEntitiesInternal(result, source.characters8() + offset, length, entityMaps, WTF_ARRAY_LENGTH(entityMaps), entityMask);
    else
        appendCharactersReplacingEntitiesInternal(result, source.characters16() + offset, length, entityMaps, WTF_ARRAY_LENGTH(entityMaps), entityMask);
}
Exemplo n.º 3
0
// Given the desired base font, this will create a SimpleFontData for a specific
// font that can be used to render the given range of characters.
PassRefPtr<SimpleFontData> FontCache::fallbackFontForCharacter(
    const FontDescription& fontDescription, UChar32 character,
    const SimpleFontData* originalFontData)
{
    // First try the specified font with standard style & weight.
    if (fontDescription.style() == FontStyleItalic
        || fontDescription.weight() >= FontWeightBold) {
        RefPtr<SimpleFontData> fontData = fallbackOnStandardFontStyle(
            fontDescription, character);
        if (fontData)
            return fontData;
    }

    // FIXME: Consider passing fontDescription.dominantScript()
    // to GetFallbackFamily here.
    UScriptCode script;
    const wchar_t* family = getFallbackFamily(character,
        fontDescription.genericFamily(),
        &script,
        m_fontManager.get());
    FontPlatformData* data = 0;
    if (family) {
        FontFaceCreationParams createByFamily(AtomicString(family, wcslen(family)));
        data = getFontPlatformData(fontDescription, createByFamily);
    }

    // Last resort font list : PanUnicode. CJK fonts have a pretty
    // large repertoire. Eventually, we need to scan all the fonts
    // on the system to have a Firefox-like coverage.
    // Make sure that all of them are lowercased.
    const static wchar_t* const cjkFonts[] = {
        L"arial unicode ms",
        L"ms pgothic",
        L"simsun",
        L"gulim",
        L"pmingliu",
        L"wenquanyi zen hei", // Partial CJK Ext. A coverage but more widely known to Chinese users.
        L"ar pl shanheisun uni",
        L"ar pl zenkai uni",
        L"han nom a", // Complete CJK Ext. A coverage.
        L"code2000" // Complete CJK Ext. A coverage.
        // CJK Ext. B fonts are not listed here because it's of no use
        // with our current non-BMP character handling because we use
        // Uniscribe for it and that code path does not go through here.
    };

    const static wchar_t* const commonFonts[] = {
        L"tahoma",
        L"arial unicode ms",
        L"lucida sans unicode",
        L"microsoft sans serif",
        L"palatino linotype",
        // Six fonts below (and code2000 at the end) are not from MS, but
        // once installed, cover a very wide range of characters.
        L"dejavu serif",
        L"dejavu sasns",
        L"freeserif",
        L"freesans",
        L"gentium",
        L"gentiumalt",
        L"ms pgothic",
        L"simsun",
        L"gulim",
        L"pmingliu",
        L"code2000"
    };

    const wchar_t* const* panUniFonts = 0;
    int numFonts = 0;
    if (script == USCRIPT_HAN) {
        panUniFonts = cjkFonts;
        numFonts = WTF_ARRAY_LENGTH(cjkFonts);
    } else {
        panUniFonts = commonFonts;
        numFonts = WTF_ARRAY_LENGTH(commonFonts);
    }
    // Font returned from getFallbackFamily may not cover |character|
    // because it's based on script to font mapping. This problem is
    // critical enough for non-Latin scripts (especially Han) to
    // warrant an additional (real coverage) check with fontCotainsCharacter.
    int i;
    for (i = 0; (!data || !data->fontContainsCharacter(character)) && i < numFonts; ++i) {
        family = panUniFonts[i];
        FontFaceCreationParams createByFamily(AtomicString(family, wcslen(family)));
        data = getFontPlatformData(fontDescription, createByFamily);
    }

    // For font fallback we want to match the subpixel behavior of the original
    // font. Mixing subpixel and non-subpixel in the same text run looks really
    // odd and causes problems with preferred width calculations.
    if (data && originalFontData) {
        const FontPlatformData& platformData = originalFontData->platformData();
        data->setMinSizeForAntiAlias(platformData.minSizeForAntiAlias());
        data->setMinSizeForSubpixel(platformData.minSizeForSubpixel());
    }

    // When i-th font (0-base) in |panUniFonts| contains a character and
    // we get out of the loop, |i| will be |i + 1|. That is, if only the
    // last font in the array covers the character, |i| will be numFonts.
    // So, we have to use '<=" rather than '<' to see if we found a font
    // covering the character.
    if (i <= numFonts)
        return fontDataFromFontPlatformData(data, DoNotRetain);

    return nullptr;
}
Exemplo n.º 4
0
// When asked for a CJK font with a native name under a non-CJK locale or
// asked for a CJK font with a Romanized name under a CJK locale,
// |GetTextFace| (after |CreateFont*|) returns a 'bogus' value (e.g. Arial).
// This is not consistent with what MSDN says !!
// Therefore, before we call |CreateFont*|, we have to map a Romanized name to 
// the corresponding native name under a CJK locale and vice versa 
// under a non-CJK locale.
// See the corresponding gecko bugs at 
// https://bugzilla.mozilla.org/show_bug.cgi?id=373952
// https://bugzilla.mozilla.org/show_bug.cgi?id=231426
static bool LookupAltName(const String& name, String& altName)
{
    struct FontCodepage {
        WCHAR* name;
        int codePage;
    };

    struct NamePair {
        WCHAR* name;
        FontCodepage altNameCodepage;
    };

    const int japaneseCodepage = 932;
    const int simplifiedChineseCodepage = 936;
    const int koreanCodepage = 949;
    const int traditionalChineseCodepage = 950;

    // FIXME(jungshik) : This list probably covers 99% of cases.
    // To cover the remaining 1% and cut down the file size,
    // consider accessing 'NAME' table of a truetype font
    // using |GetFontData| and caching the mapping.
    // In the table below, the ASCII keys are all lower-cased for
    // case-insensitive matching.
    static const NamePair namePairs[] = {
        // MS Pゴシック, MS PGothic
        {L"\xFF2D\xFF33 \xFF30\x30B4\x30B7\x30C3\x30AF", {L"MS PGothic", japaneseCodepage}},
        {L"ms pgothic", {L"\xFF2D\xFF33 \xFF30\x30B4\x30B7\x30C3\x30AF", japaneseCodepage}},
        // MS P明朝, MS PMincho
        {L"\xFF2D\xFF33 \xFF30\x660E\x671D", {L"MS PMincho", japaneseCodepage}},
        {L"ms pmincho", {L"\xFF2D\xFF33 \xFF30\x660E\x671D", japaneseCodepage}},
        // MSゴシック, MS Gothic
        {L"\xFF2D\xFF33 \x30B4\x30B7\x30C3\x30AF", {L"MS Gothic", japaneseCodepage}},
        {L"ms gothic", {L"\xFF2D\xFF33 \x30B4\x30B7\x30C3\x30AF", japaneseCodepage}},
        // MS 明朝, MS Mincho
        {L"\xFF2D\xFF33 \x660E\x671D", {L"MS Mincho", japaneseCodepage}},
        {L"ms mincho", {L"\xFF2D\xFF33 \x660E\x671D", japaneseCodepage}},
        // メイリオ, Meiryo
        {L"\x30E1\x30A4\x30EA\x30AA", {L"Meiryo", japaneseCodepage}},
        {L"meiryo", {L"\x30E1\x30A4\x30EA\x30AA", japaneseCodepage}},
        // 바탕, Batang
        {L"\xBC14\xD0D5", {L"Batang", koreanCodepage}},
        {L"batang", {L"\xBC14\xD0D5", koreanCodepage}},
        // 바탕체, Batangche
        {L"\xBC14\xD0D5\xCCB4", {L"Batangche", koreanCodepage}},
        {L"batangche", {L"\xBC14\xD0D5\xCCB4", koreanCodepage}},
        // 굴림, Gulim
        {L"\xAD74\xB9BC", {L"Gulim", koreanCodepage}},
        {L"gulim", {L"\xAD74\xB9BC", koreanCodepage}},
        // 굴림체, Gulimche
        {L"\xAD74\xB9BC\xCCB4", {L"Gulimche", koreanCodepage}},
        {L"gulimche", {L"\xAD74\xB9BC\xCCB4", koreanCodepage}},
        // 돋움, Dotum
        {L"\xB3CB\xC6C0", {L"Dotum", koreanCodepage}},
        {L"dotum", {L"\xB3CB\xC6C0", koreanCodepage}},
        // 돋움체, Dotumche
        {L"\xB3CB\xC6C0\xCCB4", {L"Dotumche", koreanCodepage}},
        {L"dotumche", {L"\xB3CB\xC6C0\xCCB4", koreanCodepage}},
        // 궁서, Gungsuh
        {L"\xAD81\xC11C", {L"Gungsuh", koreanCodepage}},
        {L"gungsuh", {L"\xAD81\xC11C", koreanCodepage}},
        // 궁서체, Gungsuhche
        {L"\xAD81\xC11C\xCCB4", {L"Gungsuhche", koreanCodepage}},
        {L"gungsuhche", {L"\xAD81\xC11C\xCCB4", koreanCodepage}},
        // 맑은 고딕, Malgun Gothic
        {L"\xB9D1\xC740 \xACE0\xB515", {L"Malgun Gothic", koreanCodepage}},
        {L"malgun gothic", {L"\xB9D1\xC740 \xACE0\xB515", koreanCodepage}},
        // 宋体, SimSun
        {L"\x5B8B\x4F53", {L"SimSun", simplifiedChineseCodepage}},
        {L"simsun", {L"\x5B8B\x4F53", simplifiedChineseCodepage}},
        // 宋体-ExtB, SimSun-ExtB
        {L"\x5B8B\x4F53-ExtB", {L"SimSun-ExtB", simplifiedChineseCodepage}},
        {L"simsun-extb", {L"\x5B8B\x4F53-extb", simplifiedChineseCodepage}},
        // 黑体, SimHei
        {L"\x9ED1\x4F53", {L"SimHei", simplifiedChineseCodepage}},
        {L"simhei", {L"\x9ED1\x4F53", simplifiedChineseCodepage}},
        // 新宋体, NSimSun
        {L"\x65B0\x5B8B\x4F53", {L"NSimSun", simplifiedChineseCodepage}},
        {L"nsimsun", {L"\x65B0\x5B8B\x4F53", simplifiedChineseCodepage}},
        // 微软雅黑, Microsoft Yahei
        {L"\x5FAE\x8F6F\x96C5\x9ED1", {L"Microsoft Yahei", simplifiedChineseCodepage}},
        {L"microsoft yahei", {L"\x5FAE\x8F6F\x96C5\x9ED1", simplifiedChineseCodepage}},
        // 仿宋, FangSong
        {L"\x4EFF\x5B8B",  {L"FangSong", simplifiedChineseCodepage}},
        {L"fangsong", {L"\x4EFF\x5B8B", simplifiedChineseCodepage}},
        // 楷体, KaiTi
        {L"\x6977\x4F53", {L"KaiTi", simplifiedChineseCodepage}},
        {L"kaiti", {L"\x6977\x4F53", simplifiedChineseCodepage}},
        // 仿宋_GB2312, FangSong_GB2312
        {L"\x4EFF\x5B8B_GB2312",  {L"FangSong_GB2312", simplifiedChineseCodepage}},
        {L"fangsong_gb2312", {L"\x4EFF\x5B8B_gb2312", simplifiedChineseCodepage}},
        // 楷体_GB2312, KaiTi_GB2312
        {L"\x6977\x4F53", {L"KaiTi_GB2312", simplifiedChineseCodepage}},
        {L"kaiti_gb2312", {L"\x6977\x4F53_gb2312", simplifiedChineseCodepage}},
        // 新細明體, PMingLiu
        {L"\x65B0\x7D30\x660E\x9AD4", {L"PMingLiu", traditionalChineseCodepage}},
        {L"pmingliu", {L"\x65B0\x7D30\x660E\x9AD4", traditionalChineseCodepage}},
        // 新細明體-ExtB, PMingLiu-ExtB
        {L"\x65B0\x7D30\x660E\x9AD4-ExtB", {L"PMingLiu-ExtB", traditionalChineseCodepage}},
        {L"pmingliu-extb", {L"\x65B0\x7D30\x660E\x9AD4-extb", traditionalChineseCodepage}},
        // 細明體, MingLiu
        {L"\x7D30\x660E\x9AD4", {L"MingLiu", traditionalChineseCodepage}},
        {L"mingliu", {L"\x7D30\x660E\x9AD4", traditionalChineseCodepage}},
        // 細明體-ExtB, MingLiu-ExtB
        {L"\x7D30\x660E\x9AD4-ExtB", {L"MingLiu-ExtB", traditionalChineseCodepage}},
        {L"mingliu-extb", {L"x65B0\x7D30\x660E\x9AD4-extb", traditionalChineseCodepage}},
        // 微軟正黑體, Microsoft JhengHei
        {L"\x5FAE\x8EDF\x6B63\x9ED1\x9AD4", {L"Microsoft JhengHei", traditionalChineseCodepage}},
        {L"microsoft jhengHei", {L"\x5FAE\x8EDF\x6B63\x9ED1\x9AD4", traditionalChineseCodepage}},
        // 標楷體, DFKai-SB
        {L"\x6A19\x6977\x9AD4", {L"DFKai-SB", traditionalChineseCodepage}},
        {L"dfkai-sb", {L"\x6A19\x6977\x9AD4", traditionalChineseCodepage}},
        // WenQuanYi Zen Hei
        {L"\x6587\x6cc9\x9a5b\x6b63\x9ed1", {L"WenQuanYi Zen Hei", traditionalChineseCodepage}},
        {L"wenquanyi zen hei", {L"\x6587\x6cc9\x9a5b\x6b63\x9ed1", traditionalChineseCodepage}},
        // WenQuanYi Zen Hei
        {L"\x6587\x6cc9\x9a7f\x6b63\x9ed1", {L"WenQuanYi Zen Hei", simplifiedChineseCodepage}},
        {L"wenquanyi zen hei", {L"\x6587\x6cc9\x9a7f\x6b63\x9ed1", simplifiedChineseCodepage}},
        // AR PL ShanHeiSun Uni,
        {L"\x6587\x9f0e\x0050\x004c\x7d30\x4e0a\x6d77\x5b8b\x0055\x006e\x0069",
         {L"AR PL ShanHeiSun Uni", traditionalChineseCodepage}},
        {L"ar pl shanheisun uni",
         {L"\x6587\x9f0e\x0050\x004c\x7d30\x4e0a\x6d77\x5b8b\x0055\x006e\x0069", traditionalChineseCodepage}},
        // AR PL ShanHeiSun Uni,
        {L"\x6587\x9f0e\x0050\x004c\x7ec6\x4e0a\x6d77\x5b8b\x0055\x006e\x0069",
         {L"AR PL ShanHeiSun Uni", simplifiedChineseCodepage}},
        {L"ar pl shanheisun uni",
         {L"\x6587\x9f0e\x0050\x004c\x7ec6\x4e0a\x6d77\x5b8b\x0055\x006e\x0069", simplifiedChineseCodepage}},
        // AR PL ZenKai Uni
        // Traditional Chinese and Simplified Chinese names are
        // identical.
        {L"\x6587\x0050\x004C\x4E2D\x6977\x0055\x006E\x0069", {L"AR PL ZenKai Uni", traditionalChineseCodepage}},
        {L"ar pl zenkai uni", {L"\x6587\x0050\x004C\x4E2D\x6977\x0055\x006E\x0069", traditionalChineseCodepage}},
        {L"\x6587\x0050\x004C\x4E2D\x6977\x0055\x006E\x0069", {L"AR PL ZenKai Uni", simplifiedChineseCodepage}},
        {L"ar pl zenkai uni", {L"\x6587\x0050\x004C\x4E2D\x6977\x0055\x006E\x0069", simplifiedChineseCodepage}},
    };

    typedef HashMap<String, const FontCodepage*> NameMap;
    static NameMap* fontNameMap = 0;

    if (!fontNameMap) {
        fontNameMap = new NameMap;
        for (size_t i = 0; i < WTF_ARRAY_LENGTH(namePairs); ++i)
            fontNameMap->set(String(namePairs[i].name), &(namePairs[i].altNameCodepage));
    }

    bool isAscii = false; 
    String n;
    // use |lower| only for ASCII names 
    // For non-ASCII names, we don't want to invoke an expensive 
    // and unnecessary |lower|. 
    if (name.containsOnlyASCII()) {
        isAscii = true;
        n = name.lower();
    } else
        n = name;

    NameMap::iterator iter = fontNameMap->find(n);
    if (iter == fontNameMap->end())
        return false;

    static int systemCp = ::GetACP();
    int fontCp = iter->second->codePage;

    if ((isAscii && systemCp == fontCp) || (!isAscii && systemCp != fontCp)) {
        altName = String(iter->second->name);
        return true;
    }

    return false;
}
Exemplo n.º 5
0
bool SVGViewSpec::parseViewSpec(const String& viewSpec)
{
    const UChar* currViewSpec = viewSpec.characters();
    const UChar* end = currViewSpec + viewSpec.length();

    if (currViewSpec >= end || !m_contextElement)
        return false;

    if (!skipString(currViewSpec, end, svgViewSpec, WTF_ARRAY_LENGTH(svgViewSpec)))
        return false;

    if (currViewSpec >= end || *currViewSpec != '(')
        return false;
    currViewSpec++;

    while (currViewSpec < end && *currViewSpec != ')') {
        if (*currViewSpec == 'v') {
            if (skipString(currViewSpec, end, viewBoxSpec, WTF_ARRAY_LENGTH(viewBoxSpec))) {
                if (currViewSpec >= end || *currViewSpec != '(')
                    return false;
                currViewSpec++;
                FloatRect viewBox;
                if (!SVGFitToViewBox::parseViewBox(m_contextElement->document(), currViewSpec, end, viewBox, false))
                    return false;
                setViewBoxBaseValue(viewBox);
                if (currViewSpec >= end || *currViewSpec != ')')
                    return false;
                currViewSpec++;
            } else if (skipString(currViewSpec, end, viewTargetSpec, WTF_ARRAY_LENGTH(viewTargetSpec))) {
                if (currViewSpec >= end || *currViewSpec != '(')
                    return false;
                const UChar* viewTargetStart = ++currViewSpec;
                while (currViewSpec < end && *currViewSpec != ')')
                    currViewSpec++;
                if (currViewSpec >= end)
                    return false;
                setViewTargetString(String(viewTargetStart, currViewSpec - viewTargetStart));
                currViewSpec++;
            } else
                return false;
        } else if (*currViewSpec == 'z') {
            if (!skipString(currViewSpec, end, zoomAndPanSpec, WTF_ARRAY_LENGTH(zoomAndPanSpec)))
                return false;
            if (currViewSpec >= end || *currViewSpec != '(')
                return false;
            currViewSpec++;
            if (!parseZoomAndPan(currViewSpec, end, m_zoomAndPan))
                return false;
            if (currViewSpec >= end || *currViewSpec != ')')
                return false;
            currViewSpec++;
        } else if (*currViewSpec == 'p') {
            if (!skipString(currViewSpec, end, preserveAspectRatioSpec, WTF_ARRAY_LENGTH(preserveAspectRatioSpec)))
                return false;
            if (currViewSpec >= end || *currViewSpec != '(')
                return false;
            currViewSpec++;
            SVGPreserveAspectRatio preserveAspectRatio;
            if (!preserveAspectRatio.parse(currViewSpec, end, false))
                return false;
            setPreserveAspectRatioBaseValue(preserveAspectRatio);
            if (currViewSpec >= end || *currViewSpec != ')')
                return false;
            currViewSpec++;
        } else if (*currViewSpec == 't') {
            if (!skipString(currViewSpec, end, transformSpec, WTF_ARRAY_LENGTH(transformSpec)))
                return false;
            if (currViewSpec >= end || *currViewSpec != '(')
                return false;
            currViewSpec++;
            SVGTransformable::parseTransformAttribute(m_transform, currViewSpec, end, SVGTransformable::DoNotClearList);
            if (currViewSpec >= end || *currViewSpec != ')')
                return false;
            currViewSpec++;
        } else
            return false;

        if (currViewSpec < end && *currViewSpec == ';')
            currViewSpec++;
    }
    
    if (currViewSpec >= end || *currViewSpec != ')')
        return false;

    return true;
}
const StylePropertyShorthand& webkitAnimationShorthandForParsing()
{
    // When we parse the animation shorthand we need to look for animation-name
    // last because otherwise it might match against the keywords for fill mode,
    // timing functions and infinite iteration. This means that animation names
    // that are the same as keywords (e.g. 'forwards') won't always match in the
    // shorthand. In that case the authors should be using longhands (or
    // reconsidering their approach). This is covered by the animations spec
    // bug: https://www.w3.org/Bugs/Public/show_bug.cgi?id=14790
    // And in the spec (editor's draft) at:
    // http://dev.w3.org/csswg/css3-animations/#animation-shorthand-property
    static const CSSPropertyID animationPropertiesForParsing[] = {
        CSSPropertyWebkitAnimationDuration,
        CSSPropertyWebkitAnimationTimingFunction,
        CSSPropertyWebkitAnimationDelay,
        CSSPropertyWebkitAnimationIterationCount,
        CSSPropertyWebkitAnimationDirection,
        CSSPropertyWebkitAnimationFillMode,
        CSSPropertyWebkitAnimationPlayState,
        CSSPropertyWebkitAnimationName
    };
    DEFINE_STATIC_LOCAL(StylePropertyShorthand, webkitAnimationLonghandsForParsing, (CSSPropertyWebkitAnimation, animationPropertiesForParsing, WTF_ARRAY_LENGTH(animationPropertiesForParsing)));
    return webkitAnimationLonghandsForParsing;
}
Exemplo n.º 7
0
void DateExtension::setAllowSleep(bool allow, v8::Isolate* isolate)
{
    v8::Local<v8::Value> result = v8::Context::GetCurrent()->Global()->Get(v8::String::NewSymbol("Date"));
    if (result.IsEmpty() || !result->IsObject())
        return;

    v8::Handle<v8::Object> dateObject = v8::Handle<v8::Object>::Cast(result);
    if (dateObject.IsEmpty())
        return;

    v8::Local<v8::Value> sleepFunctionHandle = dateObject->GetHiddenValue(V8HiddenPropertyName::sleepFunction(isolate));
    if (sleepFunctionHandle.IsEmpty() || !sleepFunctionHandle->IsFunction())
        return;

    v8::Handle<v8::Value> argv[1];
    argv[0] = v8::Boolean::New(!allow);
    V8ScriptRunner::callInternalFunction(v8::Handle<v8::Function>::Cast(sleepFunctionHandle), v8::Object::New(), WTF_ARRAY_LENGTH(argv), argv, isolate);
}
Exemplo n.º 8
0
v8::Local<v8::Value> V8WorkerGlobalScopeEventListener::callListenerFunction(ScriptState* scriptState, v8::Local<v8::Value> jsEvent, Event* event)
{
    ASSERT(!jsEvent.IsEmpty());
    v8::Local<v8::Function> handlerFunction = getListenerFunction(scriptState);
    v8::Local<v8::Object> receiver = getReceiverObject(scriptState, event);
    if (handlerFunction.IsEmpty() || receiver.IsEmpty())
        return v8::Local<v8::Value>();

    v8::Local<v8::Value> parameters[1] = { jsEvent };
    v8::MaybeLocal<v8::Value> maybeResult = V8ScriptRunner::callFunction(handlerFunction, scriptState->executionContext(), receiver, WTF_ARRAY_LENGTH(parameters), parameters, isolate());

    TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "UpdateCounters", TRACE_EVENT_SCOPE_THREAD, "data", InspectorUpdateCountersEvent::data());

    v8::Local<v8::Value> result;
    if (!maybeResult.ToLocal(&result))
        return v8::Local<v8::Value>();
    return result;
}
Exemplo n.º 9
0
void MediaQueryListListener::queryChanged(MediaQueryList* query)
{
    if (m_scriptState->contextIsEmpty())
        return;
    ScriptState::Scope scope(m_scriptState.get());
    v8::Handle<v8::Value> args[] = { toV8(query, m_scriptState->context()->Global(), m_scriptState->isolate()) };
    ScriptController::callFunction(m_scriptState->executionContext(), v8::Handle<v8::Function>::Cast(m_function.v8Value()), m_scriptState->context()->Global(), WTF_ARRAY_LENGTH(args), args, m_scriptState->isolate());
}
Exemplo n.º 10
0
namespace WebCore {

static const char* const compositeOperatorNames[] = {
    "clear",
    "copy",
    "source-over",
    "source-in",
    "source-out",
    "source-atop",
    "destination-over",
    "destination-in",
    "destination-out",
    "destination-atop",
    "xor",
    "darker",
    "lighter"
};
const int numCompositeOperatorNames = WTF_ARRAY_LENGTH(compositeOperatorNames);

bool parseCompositeOperator(const String& s, CompositeOperator& op)
{
    for (int i = 0; i < numCompositeOperatorNames; i++)
        if (s == compositeOperatorNames[i]) {
            op = static_cast<CompositeOperator>(i);
            return true;
        }
    return false;
}

String compositeOperatorName(CompositeOperator op)
{
    ASSERT(op >= 0);
    ASSERT(op < numCompositeOperatorNames);
    return compositeOperatorNames[op];
}

bool parseLineCap(const String& s, LineCap& cap)
{
    if (s == "butt") {
        cap = ButtCap;
        return true;
    }
    if (s == "round") {
        cap = RoundCap;
        return true;
    }
    if (s == "square") {
        cap = SquareCap;
        return true;
    }
    return false;
}

String lineCapName(LineCap cap)
{
    ASSERT(cap >= 0);
    ASSERT(cap < 3);
    const char* const names[3] = { "butt", "round", "square" };
    return names[cap];
}

bool parseLineJoin(const String& s, LineJoin& join)
{
    if (s == "miter") {
        join = MiterJoin;
        return true;
    }
    if (s == "round") {
        join = RoundJoin;
        return true;
    }
    if (s == "bevel") {
        join = BevelJoin;
        return true;
    }
    return false;
}

String lineJoinName(LineJoin join)
{
    ASSERT(join >= 0);
    ASSERT(join < 3);
    const char* const names[3] = { "miter", "round", "bevel" };
    return names[join];
}

String textAlignName(TextAlign align)
{
    ASSERT(align >= 0);
    ASSERT(align < 5);
    const char* const names[5] = { "start", "end", "left", "center", "right" };
    return names[align];
}

bool parseTextAlign(const String& s, TextAlign& align)
{
    if (s == "start") {
        align = StartTextAlign;
        return true;
    }
    if (s == "end") {
        align = EndTextAlign;
        return true;
    }
    if (s == "left") {
        align = LeftTextAlign;
        return true;
    }
    if (s == "center") {
        align = CenterTextAlign;
        return true;
    }
    if (s == "right") {
        align = RightTextAlign;
        return true;
    }
    return false;
}

String textBaselineName(TextBaseline baseline)
{
    ASSERT(baseline >= 0);
    ASSERT(baseline < 6);
    const char* const names[6] = { "alphabetic", "top", "middle", "bottom", "ideographic", "hanging" };
    return names[baseline];
}

bool parseTextBaseline(const String& s, TextBaseline& baseline)
{
    if (s == "alphabetic") {
        baseline = AlphabeticTextBaseline;
        return true;
    }
    if (s == "top") {
        baseline = TopTextBaseline;
        return true;
    }
    if (s == "middle") {
        baseline = MiddleTextBaseline;
        return true;
    }
    if (s == "bottom") {
        baseline = BottomTextBaseline;
        return true;
    }
    if (s == "ideographic") {
        baseline = IdeographicTextBaseline;
        return true;
    }
    if (s == "hanging") {
        baseline = HangingTextBaseline;
        return true;
    }
    return false;
}

}
Exemplo n.º 11
0
namespace blink {

static const char* const compositeOperatorNames[] = {
    "clear",
    "copy",
    "source-over",
    "source-in",
    "source-out",
    "source-atop",
    "destination-over",
    "destination-in",
    "destination-out",
    "destination-atop",
    "xor",
    "darker",
    "lighter"
};

static const char* const blendOperatorNames[] = {
    "normal",
    "multiply",
    "screen",
    "overlay",
    "darken",
    "lighten",
    "color-dodge",
    "color-burn",
    "hard-light",
    "soft-light",
    "difference",
    "exclusion",
    "hue",
    "saturation",
    "color",
    "luminosity"
};
const int numCompositeOperatorNames = WTF_ARRAY_LENGTH(compositeOperatorNames);
const int numBlendOperatorNames = WTF_ARRAY_LENGTH(blendOperatorNames);

bool parseCompositeAndBlendOperator(const String& s, CompositeOperator& op, WebBlendMode& blendOp)
{
    for (int i = 0; i < numCompositeOperatorNames; i++) {
        if (s == compositeOperatorNames[i]) {
            op = static_cast<CompositeOperator>(i);
            blendOp = WebBlendModeNormal;
            return true;
        }
    }

    for (int i = 0; i < numBlendOperatorNames; i++) {
        if (s == blendOperatorNames[i]) {
            blendOp = static_cast<WebBlendMode>(i);
            op = CompositeSourceOver;
            return true;
        }
    }

    return false;
}

String compositeOperatorName(CompositeOperator op, WebBlendMode blendOp)
{
    ASSERT(op >= 0);
    ASSERT(op < numCompositeOperatorNames);
    ASSERT(blendOp >= 0);
    if (blendOp != WebBlendModeNormal)
        return blendOperatorNames[blendOp];
    return compositeOperatorNames[op];
}

bool parseLineCap(const String& s, LineCap& cap)
{
    if (s == "butt") {
        cap = ButtCap;
        return true;
    }
    if (s == "round") {
        cap = RoundCap;
        return true;
    }
    if (s == "square") {
        cap = SquareCap;
        return true;
    }
    return false;
}

String lineCapName(LineCap cap)
{
    ASSERT(cap >= 0);
    ASSERT(cap < 3);
    const char* const names[3] = { "butt", "round", "square" };
    return names[cap];
}

bool parseLineJoin(const String& s, LineJoin& join)
{
    if (s == "miter") {
        join = MiterJoin;
        return true;
    }
    if (s == "round") {
        join = RoundJoin;
        return true;
    }
    if (s == "bevel") {
        join = BevelJoin;
        return true;
    }
    return false;
}

String lineJoinName(LineJoin join)
{
    ASSERT(join >= 0);
    ASSERT(join < 3);
    const char* const names[3] = { "miter", "round", "bevel" };
    return names[join];
}

String textAlignName(TextAlign align)
{
    ASSERT(align >= 0);
    ASSERT(align < 5);
    const char* const names[5] = { "start", "end", "left", "center", "right" };
    return names[align];
}

bool parseTextAlign(const String& s, TextAlign& align)
{
    if (s == "start") {
        align = StartTextAlign;
        return true;
    }
    if (s == "end") {
        align = EndTextAlign;
        return true;
    }
    if (s == "left") {
        align = LeftTextAlign;
        return true;
    }
    if (s == "center") {
        align = CenterTextAlign;
        return true;
    }
    if (s == "right") {
        align = RightTextAlign;
        return true;
    }
    return false;
}

String textBaselineName(TextBaseline baseline)
{
    ASSERT(baseline >= 0);
    ASSERT(baseline < 6);
    const char* const names[6] = { "alphabetic", "top", "middle", "bottom", "ideographic", "hanging" };
    return names[baseline];
}

bool parseTextBaseline(const String& s, TextBaseline& baseline)
{
    if (s == "alphabetic") {
        baseline = AlphabeticTextBaseline;
        return true;
    }
    if (s == "top") {
        baseline = TopTextBaseline;
        return true;
    }
    if (s == "middle") {
        baseline = MiddleTextBaseline;
        return true;
    }
    if (s == "bottom") {
        baseline = BottomTextBaseline;
        return true;
    }
    if (s == "ideographic") {
        baseline = IdeographicTextBaseline;
        return true;
    }
    if (s == "hanging") {
        baseline = HangingTextBaseline;
        return true;
    }
    return false;
}

} // namespace blink
String ScriptPreprocessor::preprocessSourceCode(const String& sourceCode, const String& sourceName, v8::Handle<v8::Value> functionName)
{
    if (!isValid())
        return sourceCode;

    v8::HandleScope handleScope(m_isolate);
    v8::Context::Scope contextScope(m_context.newLocal(m_isolate));

    v8::Handle<v8::String> sourceCodeString = v8String(m_isolate, sourceCode);
    v8::Handle<v8::String> sourceNameString = v8String(m_isolate, sourceName);
    v8::Handle<v8::Value> argv[] = { sourceCodeString, sourceNameString, functionName};

    v8::TryCatch tryCatch;
    tryCatch.SetVerbose(true);
    TemporaryChange<bool> isPreprocessing(m_isPreprocessing, true);
    v8::Handle<v8::Value> resultValue = V8ScriptRunner::callAsFunction(m_preprocessorFunction.newLocal(m_isolate), m_context.newLocal(m_isolate)->Global(), WTF_ARRAY_LENGTH(argv), argv);

    if (!resultValue.IsEmpty() && resultValue->IsString())
        return toCoreStringWithNullCheck(resultValue.As<v8::String>());

    return sourceCode;
}
Exemplo n.º 13
0
v8::Local<v8::Value> V8ErrorHandler::callListenerFunction(v8::Handle<v8::Value> jsEvent, Event* event)
{
    if (!event->hasInterface(EventNames::ErrorEvent))
        return V8EventListener::callListenerFunction(jsEvent, event);

    ErrorEvent* errorEvent = static_cast<ErrorEvent*>(event);

    if (errorEvent->world() && errorEvent->world() != &world())
        return v8::Null(isolate());

    v8::Local<v8::Object> listener = getListenerObject(scriptState()->executionContext());
    v8::Local<v8::Value> returnValue;
    if (!listener.IsEmpty() && listener->IsFunction()) {
        v8::Local<v8::Function> callFunction = v8::Local<v8::Function>::Cast(listener);
        v8::Local<v8::Object> thisValue = scriptState()->context()->Global();

        v8::Local<v8::Value> error = V8HiddenValue::getHiddenValue(isolate(), jsEvent->ToObject(), V8HiddenValue::error(isolate()));
        if (error.IsEmpty())
            error = v8::Null(isolate());

        v8::Handle<v8::Value> parameters[5] = { v8String(isolate(), errorEvent->message()), v8String(isolate(), errorEvent->filename()), v8::Integer::New(isolate(), errorEvent->lineno()), v8::Integer::New(isolate(), errorEvent->colno()), error };
        v8::TryCatch tryCatch;
        tryCatch.SetVerbose(true);
        if (scriptState()->executionContext()->isWorkerGlobalScope())
            returnValue = V8ScriptRunner::callFunction(callFunction, scriptState()->executionContext(), thisValue, WTF_ARRAY_LENGTH(parameters), parameters, isolate());
        else
            returnValue = ScriptController::callFunction(scriptState()->executionContext(), callFunction, thisValue, WTF_ARRAY_LENGTH(parameters), parameters, isolate());
    }
    return returnValue;
}
v8::Local<v8::Value> V8WorkerGlobalScopeEventListener::callListenerFunction(ExecutionContext* context, v8::Handle<v8::Value> jsEvent, Event* event)
{
    v8::Local<v8::Function> handlerFunction = getListenerFunction(context);
    v8::Local<v8::Object> receiver = getReceiverObject(context, event);
    if (handlerFunction.IsEmpty() || receiver.IsEmpty())
        return v8::Local<v8::Value>();

    InspectorInstrumentationCookie cookie;
    if (InspectorInstrumentation::timelineAgentEnabled(context)) {
        String resourceName("undefined");
        int lineNumber = 1;
        v8::Handle<v8::Function> originalFunction = getBoundFunction(handlerFunction);
        v8::ScriptOrigin origin = originalFunction->GetScriptOrigin();
        if (!origin.ResourceName().IsEmpty()) {
            V8TRYCATCH_FOR_V8STRINGRESOURCE_RETURN(V8StringResource<>, stringResourceName, origin.ResourceName(), v8::Local<v8::Value>());
            resourceName = stringResourceName;
            lineNumber = originalFunction->GetScriptLineNumber() + 1;
        }
        cookie = InspectorInstrumentation::willCallFunction(context, resourceName, lineNumber);
    }

    v8::Isolate* isolate = toIsolate(context);
    v8::Handle<v8::Value> parameters[1] = { jsEvent };
    v8::Local<v8::Value> result = V8ScriptRunner::callFunction(handlerFunction, context, receiver, WTF_ARRAY_LENGTH(parameters), parameters, isolate);

    InspectorInstrumentation::didCallFunction(cookie);

    return result;
}
Exemplo n.º 15
0
#include <wtf/text/CString.h>

#if !LOG_DISABLED

namespace WebKit {

#define DEFINE_LOG_CHANNEL(name) \
    WTFLogChannel JOIN_LOG_CHANNEL_WITH_PREFIX(LOG_CHANNEL_PREFIX, name) = { WTFLogChannelOff, #name };
WEBKIT2_LOG_CHANNELS(DEFINE_LOG_CHANNEL)

#define LOG_CHANNEL_ADDRESS(name)  &JOIN_LOG_CHANNEL_WITH_PREFIX(LOG_CHANNEL_PREFIX, name),
static WTFLogChannel* logChannels[] = {
    WEBKIT2_LOG_CHANNELS(LOG_CHANNEL_ADDRESS)
};

const size_t logChannelCount = WTF_ARRAY_LENGTH(logChannels);

void initializeLogChannelsIfNecessary()
{
    static bool haveInitializedLogChannels = false;
    if (haveInitializedLogChannels)
        return;
    haveInitializedLogChannels = true;

    static bool haveInitializedLoggingChannels = false;
    if (haveInitializedLoggingChannels)
        return;
    haveInitializedLoggingChannels = true;
    
    WTFInitializeLogChannelStatesFromString(logChannels, logChannelCount, logLevelString().utf8().data());
}
Exemplo n.º 16
0
void JSGlobalObject::reset(JSValue prototype)
{
    ExecState* exec = JSGlobalObject::globalExec();

    // Prototypes

    m_functionPrototype.set(exec->globalData(), this, new (exec) FunctionPrototype(exec, this, FunctionPrototype::createStructure(exec->globalData(), jsNull()))); // The real prototype will be set once ObjectPrototype is created.
    m_functionStructure.set(exec->globalData(), this, JSFunction::createStructure(exec->globalData(), m_functionPrototype.get()));
    m_internalFunctionStructure.set(exec->globalData(), this, InternalFunction::createStructure(exec->globalData(), m_functionPrototype.get()));
    JSFunction* callFunction = 0;
    JSFunction* applyFunction = 0;
    m_functionPrototype->addFunctionProperties(exec, this, m_functionStructure.get(), &callFunction, &applyFunction);
    m_callFunction.set(exec->globalData(), this, callFunction);
    m_applyFunction.set(exec->globalData(), this, applyFunction);
    m_objectPrototype.set(exec->globalData(), this, new (exec) ObjectPrototype(exec, this, ObjectPrototype::createStructure(exec->globalData(), jsNull()), m_functionStructure.get()));
    m_functionPrototype->structure()->setPrototypeWithoutTransition(exec->globalData(), m_objectPrototype.get());

    m_emptyObjectStructure.set(exec->globalData(), this, m_objectPrototype->inheritorID(exec->globalData()));
    m_nullPrototypeObjectStructure.set(exec->globalData(), this, createEmptyObjectStructure(exec->globalData(), jsNull()));

    m_callbackFunctionStructure.set(exec->globalData(), this, JSCallbackFunction::createStructure(exec->globalData(), m_functionPrototype.get()));
    m_argumentsStructure.set(exec->globalData(), this, Arguments::createStructure(exec->globalData(), m_objectPrototype.get()));
    m_callbackConstructorStructure.set(exec->globalData(), this, JSCallbackConstructor::createStructure(exec->globalData(), m_objectPrototype.get()));
    m_callbackObjectStructure.set(exec->globalData(), this, JSCallbackObject<JSObjectWithGlobalObject>::createStructure(exec->globalData(), m_objectPrototype.get()));

    m_arrayPrototype.set(exec->globalData(), this, new (exec) ArrayPrototype(this, ArrayPrototype::createStructure(exec->globalData(), m_objectPrototype.get())));
    m_arrayStructure.set(exec->globalData(), this, JSArray::createStructure(exec->globalData(), m_arrayPrototype.get()));
    m_regExpMatchesArrayStructure.set(exec->globalData(), this, RegExpMatchesArray::createStructure(exec->globalData(), m_arrayPrototype.get()));

    m_stringPrototype.set(exec->globalData(), this, new (exec) StringPrototype(exec, this, StringPrototype::createStructure(exec->globalData(), m_objectPrototype.get())));
    m_stringObjectStructure.set(exec->globalData(), this, StringObject::createStructure(exec->globalData(), m_stringPrototype.get()));

    m_booleanPrototype.set(exec->globalData(), this, new (exec) BooleanPrototype(exec, this, BooleanPrototype::createStructure(exec->globalData(), m_objectPrototype.get()), m_functionStructure.get()));
    m_booleanObjectStructure.set(exec->globalData(), this, BooleanObject::createStructure(exec->globalData(), m_booleanPrototype.get()));

    m_numberPrototype.set(exec->globalData(), this, new (exec) NumberPrototype(exec, this, NumberPrototype::createStructure(exec->globalData(), m_objectPrototype.get()), m_functionStructure.get()));
    m_numberObjectStructure.set(exec->globalData(), this, NumberObject::createStructure(exec->globalData(), m_numberPrototype.get()));

    m_datePrototype.set(exec->globalData(), this, new (exec) DatePrototype(exec, this, DatePrototype::createStructure(exec->globalData(), m_objectPrototype.get())));
    m_dateStructure.set(exec->globalData(), this, DateInstance::createStructure(exec->globalData(), m_datePrototype.get()));

    m_regExpPrototype.set(exec->globalData(), this, new (exec) RegExpPrototype(exec, this, RegExpPrototype::createStructure(exec->globalData(), m_objectPrototype.get()), m_functionStructure.get()));
    m_regExpStructure.set(exec->globalData(), this, RegExpObject::createStructure(exec->globalData(), m_regExpPrototype.get()));

    m_methodCallDummy.set(exec->globalData(), this, constructEmptyObject(exec));

    ErrorPrototype* errorPrototype = new (exec) ErrorPrototype(exec, this, ErrorPrototype::createStructure(exec->globalData(), m_objectPrototype.get()), m_functionStructure.get());
    m_errorStructure.set(exec->globalData(), this, ErrorInstance::createStructure(exec->globalData(), errorPrototype));

    // Constructors

    JSCell* objectConstructor = new (exec) ObjectConstructor(exec, this, ObjectConstructor::createStructure(exec->globalData(), m_functionPrototype.get()), m_objectPrototype.get());
    JSCell* functionConstructor = new (exec) FunctionConstructor(exec, this, FunctionConstructor::createStructure(exec->globalData(), m_functionPrototype.get()), m_functionPrototype.get());
    JSCell* arrayConstructor = new (exec) ArrayConstructor(exec, this, ArrayConstructor::createStructure(exec->globalData(), m_functionPrototype.get()), m_arrayPrototype.get(), m_functionStructure.get());
    JSCell* stringConstructor = new (exec) StringConstructor(exec, this, StringConstructor::createStructure(exec->globalData(), m_functionPrototype.get()), m_functionStructure.get(), m_stringPrototype.get());
    JSCell* booleanConstructor = new (exec) BooleanConstructor(exec, this, BooleanConstructor::createStructure(exec->globalData(), m_functionPrototype.get()), m_booleanPrototype.get());
    JSCell* numberConstructor = new (exec) NumberConstructor(exec, this, NumberConstructor::createStructure(exec->globalData(), m_functionPrototype.get()), m_numberPrototype.get());
    JSCell* dateConstructor = new (exec) DateConstructor(exec, this, DateConstructor::createStructure(exec->globalData(), m_functionPrototype.get()), m_functionStructure.get(), m_datePrototype.get());

    m_regExpConstructor.set(exec->globalData(), this, new (exec) RegExpConstructor(exec, this, RegExpConstructor::createStructure(exec->globalData(), m_functionPrototype.get()), m_regExpPrototype.get()));

    m_errorConstructor.set(exec->globalData(), this, new (exec) ErrorConstructor(exec, this, ErrorConstructor::createStructure(exec->globalData(), m_functionPrototype.get()), errorPrototype));

    Structure* nativeErrorPrototypeStructure = NativeErrorPrototype::createStructure(exec->globalData(), errorPrototype);
    Structure* nativeErrorStructure = NativeErrorConstructor::createStructure(exec->globalData(), m_functionPrototype.get());
    m_evalErrorConstructor.set(exec->globalData(), this, new (exec) NativeErrorConstructor(exec, this, nativeErrorStructure, nativeErrorPrototypeStructure, "EvalError"));
    m_rangeErrorConstructor.set(exec->globalData(), this, new (exec) NativeErrorConstructor(exec, this, nativeErrorStructure, nativeErrorPrototypeStructure, "RangeError"));
    m_referenceErrorConstructor.set(exec->globalData(), this, new (exec) NativeErrorConstructor(exec, this, nativeErrorStructure, nativeErrorPrototypeStructure, "ReferenceError"));
    m_syntaxErrorConstructor.set(exec->globalData(), this, new (exec) NativeErrorConstructor(exec, this, nativeErrorStructure, nativeErrorPrototypeStructure, "SyntaxError"));
    m_typeErrorConstructor.set(exec->globalData(), this, new (exec) NativeErrorConstructor(exec, this, nativeErrorStructure, nativeErrorPrototypeStructure, "TypeError"));
    m_URIErrorConstructor.set(exec->globalData(), this, new (exec) NativeErrorConstructor(exec, this, nativeErrorStructure, nativeErrorPrototypeStructure, "URIError"));

    m_objectPrototype->putDirectFunctionWithoutTransition(exec->globalData(), exec->propertyNames().constructor, objectConstructor, DontEnum);
    m_functionPrototype->putDirectFunctionWithoutTransition(exec->globalData(), exec->propertyNames().constructor, functionConstructor, DontEnum);
    m_arrayPrototype->putDirectFunctionWithoutTransition(exec->globalData(), exec->propertyNames().constructor, arrayConstructor, DontEnum);
    m_booleanPrototype->putDirectFunctionWithoutTransition(exec->globalData(), exec->propertyNames().constructor, booleanConstructor, DontEnum);
    m_stringPrototype->putDirectFunctionWithoutTransition(exec->globalData(), exec->propertyNames().constructor, stringConstructor, DontEnum);
    m_numberPrototype->putDirectFunctionWithoutTransition(exec->globalData(), exec->propertyNames().constructor, numberConstructor, DontEnum);
    m_datePrototype->putDirectFunctionWithoutTransition(exec->globalData(), exec->propertyNames().constructor, dateConstructor, DontEnum);
    m_regExpPrototype->putDirectFunctionWithoutTransition(exec->globalData(), exec->propertyNames().constructor, m_regExpConstructor.get(), DontEnum);
    errorPrototype->putDirectFunctionWithoutTransition(exec->globalData(), exec->propertyNames().constructor, m_errorConstructor.get(), DontEnum);

    // Set global constructors

    // FIXME: These properties could be handled by a static hash table.

    putDirectFunctionWithoutTransition(exec->globalData(), Identifier(exec, "Object"), objectConstructor, DontEnum);
    putDirectFunctionWithoutTransition(exec->globalData(), Identifier(exec, "Function"), functionConstructor, DontEnum);
    putDirectFunctionWithoutTransition(exec->globalData(), Identifier(exec, "Array"), arrayConstructor, DontEnum);
    putDirectFunctionWithoutTransition(exec->globalData(), Identifier(exec, "Boolean"), booleanConstructor, DontEnum);
    putDirectFunctionWithoutTransition(exec->globalData(), Identifier(exec, "String"), stringConstructor, DontEnum);
    putDirectFunctionWithoutTransition(exec->globalData(), Identifier(exec, "Number"), numberConstructor, DontEnum);
    putDirectFunctionWithoutTransition(exec->globalData(), Identifier(exec, "Date"), dateConstructor, DontEnum);
    putDirectFunctionWithoutTransition(exec->globalData(), Identifier(exec, "RegExp"), m_regExpConstructor.get(), DontEnum);
    putDirectFunctionWithoutTransition(exec->globalData(), Identifier(exec, "Error"), m_errorConstructor.get(), DontEnum);
    putDirectFunctionWithoutTransition(exec->globalData(), Identifier(exec, "EvalError"), m_evalErrorConstructor.get(), DontEnum);
    putDirectFunctionWithoutTransition(exec->globalData(), Identifier(exec, "RangeError"), m_rangeErrorConstructor.get(), DontEnum);
    putDirectFunctionWithoutTransition(exec->globalData(), Identifier(exec, "ReferenceError"), m_referenceErrorConstructor.get(), DontEnum);
    putDirectFunctionWithoutTransition(exec->globalData(), Identifier(exec, "SyntaxError"), m_syntaxErrorConstructor.get(), DontEnum);
    putDirectFunctionWithoutTransition(exec->globalData(), Identifier(exec, "TypeError"), m_typeErrorConstructor.get(), DontEnum);
    putDirectFunctionWithoutTransition(exec->globalData(), Identifier(exec, "URIError"), m_URIErrorConstructor.get(), DontEnum);

    // Set global values.
    GlobalPropertyInfo staticGlobals[] = {
        GlobalPropertyInfo(Identifier(exec, "Math"), new (exec) MathObject(exec, this, MathObject::createStructure(exec->globalData(), m_objectPrototype.get())), DontEnum | DontDelete),
        GlobalPropertyInfo(Identifier(exec, "NaN"), jsNaN(), DontEnum | DontDelete | ReadOnly),
        GlobalPropertyInfo(Identifier(exec, "Infinity"), jsNumber(Inf), DontEnum | DontDelete | ReadOnly),
        GlobalPropertyInfo(Identifier(exec, "undefined"), jsUndefined(), DontEnum | DontDelete | ReadOnly),
        GlobalPropertyInfo(Identifier(exec, "JSON"), new (exec) JSONObject(this, JSONObject::createStructure(exec->globalData(), m_objectPrototype.get())), DontEnum | DontDelete)
    };

    addStaticGlobals(staticGlobals, WTF_ARRAY_LENGTH(staticGlobals));

    // Set global functions.

    m_evalFunction.set(exec->globalData(), this, new (exec) JSFunction(exec, this, m_functionStructure.get(), 1, exec->propertyNames().eval, globalFuncEval));
    putDirectFunctionWithoutTransition(exec, m_evalFunction.get(), DontEnum);
    putDirectFunctionWithoutTransition(exec, new (exec) JSFunction(exec, this, m_functionStructure.get(), 2, Identifier(exec, "parseInt"), globalFuncParseInt), DontEnum);
    putDirectFunctionWithoutTransition(exec, new (exec) JSFunction(exec, this, m_functionStructure.get(), 1, Identifier(exec, "parseFloat"), globalFuncParseFloat), DontEnum);
    putDirectFunctionWithoutTransition(exec, new (exec) JSFunction(exec, this, m_functionStructure.get(), 1, Identifier(exec, "isNaN"), globalFuncIsNaN), DontEnum);
    putDirectFunctionWithoutTransition(exec, new (exec) JSFunction(exec, this, m_functionStructure.get(), 1, Identifier(exec, "isFinite"), globalFuncIsFinite), DontEnum);
    putDirectFunctionWithoutTransition(exec, new (exec) JSFunction(exec, this, m_functionStructure.get(), 1, Identifier(exec, "escape"), globalFuncEscape), DontEnum);
    putDirectFunctionWithoutTransition(exec, new (exec) JSFunction(exec, this, m_functionStructure.get(), 1, Identifier(exec, "unescape"), globalFuncUnescape), DontEnum);
    putDirectFunctionWithoutTransition(exec, new (exec) JSFunction(exec, this, m_functionStructure.get(), 1, Identifier(exec, "decodeURI"), globalFuncDecodeURI), DontEnum);
    putDirectFunctionWithoutTransition(exec, new (exec) JSFunction(exec, this, m_functionStructure.get(), 1, Identifier(exec, "decodeURIComponent"), globalFuncDecodeURIComponent), DontEnum);
    putDirectFunctionWithoutTransition(exec, new (exec) JSFunction(exec, this, m_functionStructure.get(), 1, Identifier(exec, "encodeURI"), globalFuncEncodeURI), DontEnum);
    putDirectFunctionWithoutTransition(exec, new (exec) JSFunction(exec, this, m_functionStructure.get(), 1, Identifier(exec, "encodeURIComponent"), globalFuncEncodeURIComponent), DontEnum);
#ifndef NDEBUG
    putDirectFunctionWithoutTransition(exec, new (exec) JSFunction(exec, this, m_functionStructure.get(), 1, Identifier(exec, "jscprint"), globalFuncJSCPrint), DontEnum);
#endif

    resetPrototype(exec->globalData(), prototype);
}
const StylePropertyShorthand& borderShorthandForParsing()
{
    static const CSSPropertyID borderShorthandProperties[] = { CSSPropertyBorderWidth, CSSPropertyBorderStyle, CSSPropertyBorderColor };
    static const StylePropertyShorthand* propertiesForInitialization[] = {
        &borderWidthShorthand(),
        &borderStyleShorthand(),
        &borderColorShorthand(),
    };
    DEFINE_STATIC_LOCAL(StylePropertyShorthand, borderForParsingLonghands, (CSSPropertyBorder, borderShorthandProperties, propertiesForInitialization, WTF_ARRAY_LENGTH(borderShorthandProperties)));
    return borderForParsingLonghands;
}
Exemplo n.º 18
0
namespace blink {

const CompositingReasonStringMap kCompositingReasonStringMap[] = {
    {CompositingReasonNone, "Unknown", "No reason given"},
    {CompositingReason3DTransform, "transform3D", "Has a 3d transform"},
    {CompositingReasonVideo, "video", "Is an accelerated video"},
    {   CompositingReasonCanvas, "canvas",
        "Is an accelerated canvas, or is a display list backed canvas that was "
        "promoted to a layer based on a performance heuristic."
    },
    {CompositingReasonPlugin, "plugin", "Is an accelerated plugin"},
    {CompositingReasonIFrame, "iFrame", "Is an accelerated iFrame"},
    {   CompositingReasonBackfaceVisibilityHidden, "backfaceVisibilityHidden",
        "Has backface-visibility: hidden"
    },
    {   CompositingReasonActiveAnimation, "activeAnimation",
        "Has an active accelerated animation or transition"
    },
    {   CompositingReasonTransitionProperty, "transitionProperty",
        "Has an acceleratable transition property (active or inactive)"
    },
    {   CompositingReasonScrollDependentPosition, "scrollDependentPosition",
        "Is fixed or sticky position"
    },
    {   CompositingReasonOverflowScrollingTouch, "overflowScrollingTouch",
        "Is a scrollable overflow element"
    },
    {   CompositingReasonOverflowScrollingParent, "overflowScrollingParent",
        "Scroll parent is not an ancestor"
    },
    {   CompositingReasonOutOfFlowClipping, "outOfFlowClipping",
        "Has clipping ancestor"
    },
    {   CompositingReasonVideoOverlay, "videoOverlay",
        "Is overlay controls for video"
    },
    {   CompositingReasonWillChangeCompositingHint, "willChange",
        "Has a will-change compositing hint"
    },
    {   CompositingReasonBackdropFilter, "backdropFilter",
        "Has a backdrop filter"
    },
    {   CompositingReasonCompositorProxy, "compositorProxy",
        "Has a CompositorProxy object"
    },
    {   CompositingReasonAssumedOverlap, "assumedOverlap",
        "Might overlap other composited content"
    },
    {CompositingReasonOverlap, "overlap", "Overlaps other composited content"},
    {   CompositingReasonNegativeZIndexChildren, "negativeZIndexChildren",
        "Parent with composited negative z-index content"
    },
    {   CompositingReasonSquashingDisallowed, "squashingDisallowed",
        "Layer was separately composited because it could not be squashed."
    },
    {   CompositingReasonTransformWithCompositedDescendants,
        "transformWithCompositedDescendants",
        "Has a transform that needs to be known by compositor because of "
        "composited descendants"
    },
    {   CompositingReasonOpacityWithCompositedDescendants,
        "opacityWithCompositedDescendants",
        "Has opacity that needs to be applied by compositor because of composited "
        "descendants"
    },
    {   CompositingReasonMaskWithCompositedDescendants,
        "maskWithCompositedDescendants",
        "Has a mask that needs to be known by compositor because of composited "
        "descendants"
    },
    {   CompositingReasonReflectionWithCompositedDescendants,
        "reflectionWithCompositedDescendants",
        "Has a reflection that needs to be known by compositor because of "
        "composited descendants"
    },
    {   CompositingReasonFilterWithCompositedDescendants,
        "filterWithCompositedDescendants",
        "Has a filter effect that needs to be known by compositor because of "
        "composited descendants"
    },
    {   CompositingReasonBlendingWithCompositedDescendants,
        "blendingWithCompositedDescendants",
        "Has a blenidng effect that needs to be known by compositor because of "
        "composited descendants"
    },
    {   CompositingReasonClipsCompositingDescendants,
        "clipsCompositingDescendants",
        "Has a clip that needs to be known by compositor because of composited "
        "descendants"
    },
    {   CompositingReasonPerspectiveWith3DDescendants,
        "perspectiveWith3DDescendants",
        "Has a perspective transform that needs to be known by compositor because "
        "of 3d descendants"
    },
    {   CompositingReasonPreserve3DWith3DDescendants,
        "preserve3DWith3DDescendants",
        "Has a preserves-3d property that needs to be known by compositor because "
        "of 3d descendants"
    },
    {   CompositingReasonReflectionOfCompositedParent,
        "reflectionOfCompositedParent", "Is a reflection of a composited layer"
    },
    {   CompositingReasonIsolateCompositedDescendants,
        "isolateCompositedDescendants",
        "Should isolate descendants to apply a blend effect"
    },
    {   CompositingReasonPositionFixedWithCompositedDescendants,
        "positionFixedWithCompositedDescendants"
        "Is a position:fixed element with composited descendants"
    },
    {CompositingReasonRoot, "root", "Is the root layer"},
    {   CompositingReasonLayerForAncestorClip, "layerForAncestorClip",
        "Secondary layer, applies a clip due to a sibling in the compositing "
        "tree"
    },
    {   CompositingReasonLayerForDescendantClip, "layerForDescendantClip",
        "Secondary layer, to clip descendants of the owning layer"
    },
    {   CompositingReasonLayerForPerspective, "layerForPerspective",
        "Secondary layer, to house the perspective transform for all descendants"
    },
    {   CompositingReasonLayerForHorizontalScrollbar,
        "layerForHorizontalScrollbar",
        "Secondary layer, the horizontal scrollbar layer"
    },
    {   CompositingReasonLayerForVerticalScrollbar, "layerForVerticalScrollbar",
        "Secondary layer, the vertical scrollbar layer"
    },
    {   CompositingReasonLayerForOverflowControlsHost,
        "layerForOverflowControlsHost",
        "Secondary layer, the overflow controls host layer"
    },
    {   CompositingReasonLayerForScrollCorner, "layerForScrollCorner",
        "Secondary layer, the scroll corner layer"
    },
    {   CompositingReasonLayerForScrollingContents, "layerForScrollingContents",
        "Secondary layer, to house contents that can be scrolled"
    },
    {   CompositingReasonLayerForScrollingContainer, "layerForScrollingContainer",
        "Secondary layer, used to position the scrolling contents while "
        "scrolling"
    },
    {   CompositingReasonLayerForSquashingContents, "layerForSquashingContents",
        "Secondary layer, home for a group of squashable content"
    },
    {   CompositingReasonLayerForSquashingContainer, "layerForSquashingContainer",
        "Secondary layer, no-op layer to place the squashing layer correctly in "
        "the composited layer tree"
    },
    {   CompositingReasonLayerForForeground, "layerForForeground",
        "Secondary layer, to contain any normal flow and positive z-index "
        "contents on top of a negative z-index layer"
    },
    {   CompositingReasonLayerForBackground, "layerForBackground",
        "Secondary layer, to contain acceleratable background content"
    },
    {   CompositingReasonLayerForMask, "layerForMask",
        "Secondary layer, to contain the mask contents"
    },
    {   CompositingReasonLayerForClippingMask, "layerForClippingMask",
        "Secondary layer, for clipping mask"
    },
    {   CompositingReasonLayerForScrollingBlockSelection,
        "layerForScrollingBlockSelection",
        "Secondary layer, to house block selection gaps for composited scrolling "
        "with no scrolling contents"
    },
    {   CompositingReasonInlineTransform, "inlineTransform",
        "Has an inline transform, which causes subsequent layers to assume "
        "overlap"
    },
};

const size_t kNumberOfCompositingReasons =
    WTF_ARRAY_LENGTH(kCompositingReasonStringMap);

}  // namespace blink
// Similar to animations, we have property after timing-function and delay after duration
const StylePropertyShorthand& transitionShorthandForParsing()
{
    static const CSSPropertyID transitionProperties[] = {
        CSSPropertyTransitionDuration,
        CSSPropertyTransitionTimingFunction,
        CSSPropertyTransitionDelay,
        CSSPropertyTransitionProperty
    };
    DEFINE_STATIC_LOCAL(StylePropertyShorthand, transitionLonghands, (CSSPropertyTransition, transitionProperties, WTF_ARRAY_LENGTH(transitionProperties)));
    return transitionLonghands;
}
TEST_F(SubresourceIntegrityTest, Parsing)
{
    expectParseFailure("not_really_a_valid_anything");
    expectParseFailure("sha256-&&&foobar&&&");
    expectParseFailure("sha256-\x01\x02\x03\x04");
    expectParseFailure("sha256-!!! sha256-!!!");

    expectEmptyParseResult("foobar:///sha256-abcdefg");
    expectEmptyParseResult("ni://sha256-abcdefg");
    expectEmptyParseResult("ni:///sha256-abcdefg");
    expectEmptyParseResult("notsha256atall-abcdefg");

    expectParse(
        "sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=",
        "BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=",
        HashAlgorithmSha256);

    expectParse(
        "sha-256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=",
        "BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=",
        HashAlgorithmSha256);

    expectParse(
        "     sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=     ",
        "BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=",
        HashAlgorithmSha256);

    expectParse(
        "sha384-XVVXBGoYw6AJOh9J-Z8pBDMVVPfkBpngexkA7JqZu8d5GENND6TEIup_tA1v5GPr",
        "XVVXBGoYw6AJOh9J+Z8pBDMVVPfkBpngexkA7JqZu8d5GENND6TEIup/tA1v5GPr",
        HashAlgorithmSha384);

    expectParse(
        "sha-384-XVVXBGoYw6AJOh9J_Z8pBDMVVPfkBpngexkA7JqZu8d5GENND6TEIup_tA1v5GPr",
        "XVVXBGoYw6AJOh9J/Z8pBDMVVPfkBpngexkA7JqZu8d5GENND6TEIup/tA1v5GPr",
        HashAlgorithmSha384);

    expectParse(
        "sha512-tbUPioKbVBplr0b1ucnWB57SJWt4x9dOE0Vy2mzCXvH3FepqDZ-07yMK81ytlg0MPaIrPAjcHqba5csorDWtKg==",
        "tbUPioKbVBplr0b1ucnWB57SJWt4x9dOE0Vy2mzCXvH3FepqDZ+07yMK81ytlg0MPaIrPAjcHqba5csorDWtKg==",
        HashAlgorithmSha512);

    expectParse(
        "sha-512-tbUPioKbVBplr0b1ucnWB57SJWt4x9dOE0Vy2mzCXvH3FepqDZ-07yMK81ytlg0MPaIrPAjcHqba5csorDWtKg==",
        "tbUPioKbVBplr0b1ucnWB57SJWt4x9dOE0Vy2mzCXvH3FepqDZ+07yMK81ytlg0MPaIrPAjcHqba5csorDWtKg==",
        HashAlgorithmSha512);

    expectParse(
        "sha-512-tbUPioKbVBplr0b1ucnWB57SJWt4x9dOE0Vy2mzCXvH3FepqDZ-07yMK81ytlg0MPaIrPAjcHqba5csorDWtKg==?ct=application/javascript",
        "tbUPioKbVBplr0b1ucnWB57SJWt4x9dOE0Vy2mzCXvH3FepqDZ+07yMK81ytlg0MPaIrPAjcHqba5csorDWtKg==",
        HashAlgorithmSha512);

    expectParse(
        "sha-512-tbUPioKbVBplr0b1ucnWB57SJWt4x9dOE0Vy2mzCXvH3FepqDZ-07yMK81ytlg0MPaIrPAjcHqba5csorDWtKg==?ct=application/xhtml+xml",
        "tbUPioKbVBplr0b1ucnWB57SJWt4x9dOE0Vy2mzCXvH3FepqDZ+07yMK81ytlg0MPaIrPAjcHqba5csorDWtKg==",
        HashAlgorithmSha512);

    expectParse(
        "sha-512-tbUPioKbVBplr0b1ucnWB57SJWt4x9dOE0Vy2mzCXvH3FepqDZ-07yMK81ytlg0MPaIrPAjcHqba5csorDWtKg==?foo=bar?ct=application/xhtml+xml",
        "tbUPioKbVBplr0b1ucnWB57SJWt4x9dOE0Vy2mzCXvH3FepqDZ+07yMK81ytlg0MPaIrPAjcHqba5csorDWtKg==",
        HashAlgorithmSha512);

    expectParse(
        "sha-512-tbUPioKbVBplr0b1ucnWB57SJWt4x9dOE0Vy2mzCXvH3FepqDZ-07yMK81ytlg0MPaIrPAjcHqba5csorDWtKg==?ct=application/xhtml+xml?foo=bar",
        "tbUPioKbVBplr0b1ucnWB57SJWt4x9dOE0Vy2mzCXvH3FepqDZ+07yMK81ytlg0MPaIrPAjcHqba5csorDWtKg==",
        HashAlgorithmSha512);

    expectParse(
        "sha-512-tbUPioKbVBplr0b1ucnWB57SJWt4x9dOE0Vy2mzCXvH3FepqDZ-07yMK81ytlg0MPaIrPAjcHqba5csorDWtKg==?baz=foz?ct=application/xhtml+xml?foo=bar",
        "tbUPioKbVBplr0b1ucnWB57SJWt4x9dOE0Vy2mzCXvH3FepqDZ+07yMK81ytlg0MPaIrPAjcHqba5csorDWtKg==",
        HashAlgorithmSha512);

    expectParseMultipleHashes("", 0, 0);
    expectParseMultipleHashes("    ", 0, 0);

    const IntegrityMetadata kValidSha384AndSha512[] = {
        {"XVVXBGoYw6AJOh9J+Z8pBDMVVPfkBpngexkA7JqZu8d5GENND6TEIup/tA1v5GPr", HashAlgorithmSha384},
        {"tbUPioKbVBplr0b1ucnWB57SJWt4x9dOE0Vy2mzCXvH3FepqDZ+07yMK81ytlg0MPaIrPAjcHqba5csorDWtKg==", HashAlgorithmSha512}
    };
    expectParseMultipleHashes(
        "sha384-XVVXBGoYw6AJOh9J+Z8pBDMVVPfkBpngexkA7JqZu8d5GENND6TEIup/tA1v5GPr sha512-tbUPioKbVBplr0b1ucnWB57SJWt4x9dOE0Vy2mzCXvH3FepqDZ+07yMK81ytlg0MPaIrPAjcHqba5csorDWtKg==",
        kValidSha384AndSha512,
        WTF_ARRAY_LENGTH(kValidSha384AndSha512));

    const IntegrityMetadata kValidSha256AndSha256[] = {
        {"BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=", HashAlgorithmSha256},
        {"deadbeef", HashAlgorithmSha256}
    };
    expectParseMultipleHashes(
        "sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE= sha256-deadbeef",
        kValidSha256AndSha256,
        WTF_ARRAY_LENGTH(kValidSha256AndSha256));

    const IntegrityMetadata kValidSha256AndInvalidSha256[] = {
        {"BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=", HashAlgorithmSha256}
    };
    expectParseMultipleHashes(
        "sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE= sha256-!!!!",
        kValidSha256AndInvalidSha256,
        WTF_ARRAY_LENGTH(kValidSha256AndInvalidSha256));

    const IntegrityMetadata kInvalidSha256AndValidSha256[] = {
        {"BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=", HashAlgorithmSha256}
    };
    expectParseMultipleHashes(
        "sha256-!!! sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=",
        kInvalidSha256AndValidSha256,
        WTF_ARRAY_LENGTH(kInvalidSha256AndValidSha256));

    expectParse(
        "sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=?foo=bar",
        "BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=",
        HashAlgorithmSha256);

    expectParse(
        "sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=?foo=bar?baz=foz",
        "BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=",
        HashAlgorithmSha256);

    expectParse("sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=?",
        "BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=",
        HashAlgorithmSha256);
    expectParse("sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=?foo=bar",
        "BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=",
        HashAlgorithmSha256);
    expectParse("sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=?foo=bar?baz=foz",
        "BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=",
        HashAlgorithmSha256);
    expectParse("sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=?foo",
        "BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=",
        HashAlgorithmSha256);
    expectParse("sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=?foo=bar?",
        "BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=",
        HashAlgorithmSha256);
    expectParse("sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=?foo:bar",
        "BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=",
        HashAlgorithmSha256);
}
Exemplo n.º 21
0
// Given the desired base font, this will create a SimpleFontData for a specific
// font that can be used to render the given range of characters.
const SimpleFontData* FontCache::getFontDataForCharacters(const Font& font, const UChar* characters, int length)
{
    // FIXME: Consider passing fontDescription.dominantScript()
    // to GetFallbackFamily here.
    FontDescription fontDescription = font.fontDescription();
    UChar32 c;
    UScriptCode script;
    const wchar_t* family = getFallbackFamily(characters, length,
        fontDescription.genericFamily(), &c, &script);
    FontPlatformData* data = 0;
    if (family)
        data = getCachedFontPlatformData(font.fontDescription(),  AtomicString(family, wcslen(family)), false); 

    // Last resort font list : PanUnicode. CJK fonts have a pretty
    // large repertoire. Eventually, we need to scan all the fonts
    // on the system to have a Firefox-like coverage.
    // Make sure that all of them are lowercased.
    const static wchar_t* const cjkFonts[] = {
        L"arial unicode ms",
        L"ms pgothic",
        L"simsun",
        L"gulim",
        L"pmingliu",
        L"wenquanyi zen hei", // partial CJK Ext. A coverage but more
                              // widely known to Chinese users.
        L"ar pl shanheisun uni",
        L"ar pl zenkai uni",
        L"han nom a",  // Complete CJK Ext. A coverage
        L"code2000",   // Complete CJK Ext. A coverage
        // CJK Ext. B fonts are not listed here because it's of no use
        // with our current non-BMP character handling because we use
        // Uniscribe for it and that code path does not go through here.
    };

    const static wchar_t* const commonFonts[] = {
        L"tahoma",
        L"arial unicode ms",
        L"lucida sans unicode",
        L"microsoft sans serif",
        L"palatino linotype",
        // Six fonts below (and code2000 at the end) are not from MS, but
        // once installed, cover a very wide range of characters.
        L"dejavu serif",
        L"dejavu sasns",
        L"freeserif",
        L"freesans",
        L"gentium",
        L"gentiumalt",
        L"ms pgothic",
        L"simsun",
        L"gulim",
        L"pmingliu",
        L"code2000",
    };

    const wchar_t* const* panUniFonts = 0;
    int numFonts = 0;
    if (script == USCRIPT_HAN) {
        panUniFonts = cjkFonts;
        numFonts = WTF_ARRAY_LENGTH(cjkFonts);
    } else {
        panUniFonts = commonFonts;
        numFonts = WTF_ARRAY_LENGTH(commonFonts);
    }
    // Font returned from GetFallbackFamily may not cover |characters|
    // because it's based on script to font mapping. This problem is
    // critical enough for non-Latin scripts (especially Han) to
    // warrant an additional (real coverage) check with fontCotainsCharacter.
    int i;
    for (i = 0; (!data || !fontContainsCharacter(data, family, c)) && i < numFonts; ++i) {
        family = panUniFonts[i]; 
        data = getCachedFontPlatformData(font.fontDescription(), AtomicString(family, wcslen(family)));
    }
    // When i-th font (0-base) in |panUniFonts| contains a character and
    // we get out of the loop, |i| will be |i + 1|. That is, if only the
    // last font in the array covers the character, |i| will be numFonts.
    // So, we have to use '<=" rather than '<' to see if we found a font
    // covering the character.
    if (i <= numFonts)
        return getCachedFontData(data, DoNotRetain);

    return 0;

}
Exemplo n.º 22
0
void V8MutationCallback::call(const WillBeHeapVector<RefPtrWillBeMember<MutationRecord> >& mutations, MutationObserver* observer)
{
    if (!canInvokeCallback())
        return;

    v8::Isolate* isolate = m_scriptState->isolate();

    if (m_scriptState->contextIsEmpty())
        return;
    ScriptState::Scope scope(m_scriptState.get());

    if (m_callback.isEmpty())
        return;
    v8::Handle<v8::Value> observerHandle = toV8(observer, m_scriptState->context()->Global(), isolate);
    if (observerHandle.IsEmpty()) {
        if (!isScriptControllerTerminating())
            CRASH();
        return;
    }

    if (!observerHandle->IsObject())
        return;

    v8::Handle<v8::Object> thisObject = v8::Handle<v8::Object>::Cast(observerHandle);
    v8::Handle<v8::Value> argv[] = { v8Array(mutations, m_scriptState->context()->Global(), isolate), observerHandle };

    v8::TryCatch exceptionCatcher;
    exceptionCatcher.SetVerbose(true);
    ScriptController::callFunction(executionContext(), m_callback.newLocal(isolate), thisObject, WTF_ARRAY_LENGTH(argv), argv, isolate);
}
static void configureV8TestInterfaceDoNotCheckConstantsTemplate(v8::Handle<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate, WrapperWorldType currentWorldType)
{
    functionTemplate->ReadOnlyPrototype();

    v8::Local<v8::Signature> defaultSignature;
    defaultSignature = V8DOMConfiguration::installDOMClassTemplate(functionTemplate, "TestInterfaceDoNotCheckConstants", v8::Local<v8::FunctionTemplate>(), V8TestInterfaceDoNotCheckConstants::internalFieldCount,
        0, 0,
        0, 0,
        0, 0,
        isolate, currentWorldType);
    v8::Local<v8::ObjectTemplate> ALLOW_UNUSED instanceTemplate = functionTemplate->InstanceTemplate();
    v8::Local<v8::ObjectTemplate> ALLOW_UNUSED prototypeTemplate = functionTemplate->PrototypeTemplate();
    static const V8DOMConfiguration::ConstantConfiguration V8TestInterfaceDoNotCheckConstantsConstants[] = {
        {"CONST_VALUE_0", 0},
        {"CONST_JAVASCRIPT", 1},
    };
    V8DOMConfiguration::installConstants(functionTemplate, prototypeTemplate, V8TestInterfaceDoNotCheckConstantsConstants, WTF_ARRAY_LENGTH(V8TestInterfaceDoNotCheckConstantsConstants), isolate);

    // Custom toString template
    functionTemplate->Set(v8AtomicString(isolate, "toString"), V8PerIsolateData::current()->toStringTemplate());
}
Exemplo n.º 24
0
static const StylePropertyShorthand& borderDirections()
{
    static const CSSPropertyID properties[4] = { CSSPropertyBorderTop, CSSPropertyBorderRight, CSSPropertyBorderBottom, CSSPropertyBorderLeft };
    DEFINE_STATIC_LOCAL(StylePropertyShorthand, borderDirections, (properties, WTF_ARRAY_LENGTH(properties)));
    return borderDirections;
}
Exemplo n.º 25
0
ScriptValue InjectedScriptManager::createInjectedScript(const String& scriptSource, ScriptState* inspectedScriptState, int id)
{
    v8::Isolate* isolate = inspectedScriptState->isolate();
    ScriptState::Scope scope(inspectedScriptState);

    // Call custom code to create InjectedScripHost wrapper specific for the context
    // instead of calling toV8() that would create the
    // wrapper in the current context.
    // FIXME: make it possible to use generic bindings factory for InjectedScriptHost.
    v8::Local<v8::Object> scriptHostWrapper = createInjectedScriptHostV8Wrapper(m_injectedScriptHost.get(), inspectedScriptState->isolate());
    if (scriptHostWrapper.IsEmpty())
        return ScriptValue();

    // Inject javascript into the context. The compiled script is supposed to evaluate into
    // a single anonymous function(it's anonymous to avoid cluttering the global object with
    // inspector's stuff) the function is called a few lines below with InjectedScriptHost wrapper,
    // injected script id and explicit reference to the inspected global object. The function is expected
    // to create and configure InjectedScript instance that is going to be used by the inspector.
    v8::Local<v8::Value> value = V8ScriptRunner::compileAndRunInternalScript(v8String(isolate, scriptSource), isolate);
    ASSERT(!value.IsEmpty());
    ASSERT(value->IsFunction());

    v8::Local<v8::Object> windowGlobal = inspectedScriptState->context()->Global();
    v8::Handle<v8::Value> info[] = { scriptHostWrapper, windowGlobal, v8::Number::New(inspectedScriptState->isolate(), id) };
    v8::Local<v8::Value> injectedScriptValue = V8ScriptRunner::callInternalFunction(v8::Local<v8::Function>::Cast(value), windowGlobal, WTF_ARRAY_LENGTH(info), info, inspectedScriptState->isolate());
    return ScriptValue(inspectedScriptState, injectedScriptValue);
}
Exemplo n.º 26
0
void FEComponentTransfer::getValues(unsigned char rValues[256], unsigned char gValues[256], unsigned char bValues[256], unsigned char aValues[256])
{
    for (unsigned i = 0; i < 256; ++i)
        rValues[i] = gValues[i] = bValues[i] = aValues[i] = i;
    unsigned char* tables[] = { rValues, gValues, bValues, aValues };
    ComponentTransferFunction transferFunction[] = {m_redFunc, m_greenFunc, m_blueFunc, m_alphaFunc};
    TransferType callEffect[] = {identity, identity, table, discrete, linear, gamma};

    for (unsigned channel = 0; channel < 4; channel++) {
        ASSERT_WITH_SECURITY_IMPLICATION(static_cast<size_t>(transferFunction[channel].type) < WTF_ARRAY_LENGTH(callEffect));
        (*callEffect[transferFunction[channel].type])(tables[channel], transferFunction[channel]);
    }
}
Exemplo n.º 27
0
namespace WebCore {

static const char* const compositeOperatorNames[] = {
    "clear",
    "copy",
    "source-over",
    "source-in",
    "source-out",
    "source-atop",
    "destination-over",
    "destination-in",
    "destination-out",
    "destination-atop",
    "xor",
    "darker",
    "lighter",
    "difference"
};

static const char* const blendOperatorNames[] = {
    "normal",
    "multiply",
    "screen",
    "darken",
    "lighten",
    "overlay",
    "color-dodge",
    "color-burn",
    "hard-light",
    "soft-light",
    "difference",
    "exclusion",
    "hue",
    "saturation",
    "color",
    "luminosity",
    "plus-darker",
    "plus-lighter"
};
const int numCompositeOperatorNames = WTF_ARRAY_LENGTH(compositeOperatorNames);
const int numBlendOperatorNames = WTF_ARRAY_LENGTH(blendOperatorNames);

bool parseBlendMode(const String& s, BlendMode& blendMode)
{
    for (int i = 0; i < numBlendOperatorNames; i++) {
        if (s == blendOperatorNames[i]) {
            blendMode = static_cast<BlendMode>(i + BlendModeNormal);
            return true;
        }
    }
    
    return false;
}

bool parseCompositeAndBlendOperator(const String& s, CompositeOperator& op, BlendMode& blendOp)
{
    for (int i = 0; i < numCompositeOperatorNames; i++) {
        if (s == compositeOperatorNames[i]) {
            op = static_cast<CompositeOperator>(i);
            blendOp = BlendModeNormal;
            return true;
        }
    }
    
    if (parseBlendMode(s, blendOp)) {
        // For now, blending will always assume source-over. This will be fixed in the future
        op = CompositeSourceOver;
        return true;
    }
    
    return false;
}

// FIXME: when we support blend modes in combination with compositing other than source-over
// this routine needs to be updated.
String compositeOperatorName(CompositeOperator op, BlendMode blendOp)
{
    ASSERT(op >= 0);
    ASSERT(op < numCompositeOperatorNames);
    ASSERT(blendOp >= BlendModeNormal);
    ASSERT(blendOp <= numBlendOperatorNames);
    if (blendOp > BlendModeNormal)
        return blendOperatorNames[blendOp - BlendModeNormal];
    return compositeOperatorNames[op];
}

static String blendModeName(BlendMode blendOp)
{
    ASSERT(blendOp >= BlendModeNormal);
    ASSERT(blendOp <= BlendModePlusLighter);
    return blendOperatorNames[blendOp - BlendModeNormal];
}

bool parseLineCap(const String& s, LineCap& cap)
{
    if (s == "butt") {
        cap = ButtCap;
        return true;
    }
    if (s == "round") {
        cap = RoundCap;
        return true;
    }
    if (s == "square") {
        cap = SquareCap;
        return true;
    }
    return false;
}

String lineCapName(LineCap cap)
{
    ASSERT(cap >= 0);
    ASSERT(cap < 3);
    const char* const names[3] = { "butt", "round", "square" };
    return names[cap];
}

bool parseLineJoin(const String& s, LineJoin& join)
{
    if (s == "miter") {
        join = MiterJoin;
        return true;
    }
    if (s == "round") {
        join = RoundJoin;
        return true;
    }
    if (s == "bevel") {
        join = BevelJoin;
        return true;
    }
    return false;
}

String lineJoinName(LineJoin join)
{
    ASSERT(join >= 0);
    ASSERT(join < 3);
    const char* const names[3] = { "miter", "round", "bevel" };
    return names[join];
}

String textAlignName(TextAlign align)
{
    ASSERT(align >= 0);
    ASSERT(align < 5);
    const char* const names[5] = { "start", "end", "left", "center", "right" };
    return names[align];
}

bool parseTextAlign(const String& s, TextAlign& align)
{
    if (s == "start") {
        align = StartTextAlign;
        return true;
    }
    if (s == "end") {
        align = EndTextAlign;
        return true;
    }
    if (s == "left") {
        align = LeftTextAlign;
        return true;
    }
    if (s == "center") {
        align = CenterTextAlign;
        return true;
    }
    if (s == "right") {
        align = RightTextAlign;
        return true;
    }
    return false;
}

String textBaselineName(TextBaseline baseline)
{
    ASSERT(baseline >= 0);
    ASSERT(baseline < 6);
    const char* const names[6] = { "alphabetic", "top", "middle", "bottom", "ideographic", "hanging" };
    return names[baseline];
}

bool parseTextBaseline(const String& s, TextBaseline& baseline)
{
    if (s == "alphabetic") {
        baseline = AlphabeticTextBaseline;
        return true;
    }
    if (s == "top") {
        baseline = TopTextBaseline;
        return true;
    }
    if (s == "middle") {
        baseline = MiddleTextBaseline;
        return true;
    }
    if (s == "bottom") {
        baseline = BottomTextBaseline;
        return true;
    }
    if (s == "ideographic") {
        baseline = IdeographicTextBaseline;
        return true;
    }
    if (s == "hanging") {
        baseline = HangingTextBaseline;
        return true;
    }
    return false;
}

TextStream& operator<<(TextStream& ts, CompositeOperator op)
{
    return ts << compositeOperatorName(op, BlendModeNormal);
}

TextStream& operator<<(TextStream& ts, BlendMode blendMode)
{
    return ts << blendModeName(blendMode);
}

TextStream& operator<<(TextStream& ts, WindRule rule)
{
    switch (rule) {
    case RULE_NONZERO:
        ts << "NON-ZERO";
        break;
    case RULE_EVENODD:
        ts << "EVEN-ODD";
        break;
    }

    return ts;
}

TextStream& operator<<(TextStream& ts, LineCap capStyle)
{
    switch (capStyle) {
    case ButtCap:
        ts << "BUTT";
        break;
    case RoundCap:
        ts << "ROUND";
        break;
    case SquareCap:
        ts << "SQUARE";
        break;
    }
    return ts;
}

TextStream& operator<<(TextStream& ts, LineJoin joinStyle)
{
    switch (joinStyle) {
    case MiterJoin:
        ts << "MITER";
        break;
    case RoundJoin:
        ts << "ROUND";
        break;
    case BevelJoin:
        ts << "BEVEL";
        break;
    }
    return ts;
}


}
Exemplo n.º 28
0
void IntlDateTimeFormat::initializeDateTimeFormat(ExecState& exec, JSValue locales, JSValue originalOptions)
{
    VM& vm = exec.vm();
    auto scope = DECLARE_THROW_SCOPE(vm);

    // 12.1.1 InitializeDateTimeFormat (dateTimeFormat, locales, options) (ECMA-402 2.0)
    // 1. If dateTimeFormat.[[initializedIntlObject]] is true, throw a TypeError exception.
    // 2. Set dateTimeFormat.[[initializedIntlObject]] to true.

    // 3. Let requestedLocales be CanonicalizeLocaleList(locales).
    Vector<String> requestedLocales = canonicalizeLocaleList(exec, locales);
    // 4. ReturnIfAbrupt(requestedLocales),
    RETURN_IF_EXCEPTION(scope, void());

    // 5. Let options be ToDateTimeOptions(options, "any", "date").
    JSObject* options = toDateTimeOptionsAnyDate(exec, originalOptions);
    // 6. ReturnIfAbrupt(options).
    RETURN_IF_EXCEPTION(scope, void());

    // 7. Let opt be a new Record.
    HashMap<String, String> localeOpt;

    // 8. Let matcher be GetOption(options, "localeMatcher", "string", «"lookup", "best fit"», "best fit").
    String localeMatcher = intlStringOption(exec, options, vm.propertyNames->localeMatcher, { "lookup", "best fit" }, "localeMatcher must be either \"lookup\" or \"best fit\"", "best fit");
    // 9. ReturnIfAbrupt(matcher).
    RETURN_IF_EXCEPTION(scope, void());
    // 10. Set opt.[[localeMatcher]] to matcher.
    localeOpt.add(vm.propertyNames->localeMatcher.string(), localeMatcher);

    // 11. Let localeData be the value of %DateTimeFormat%.[[localeData]].
    // 12. Let r be ResolveLocale( %DateTimeFormat%.[[availableLocales]], requestedLocales, opt, %DateTimeFormat%.[[relevantExtensionKeys]], localeData).
    const HashSet<String> availableLocales = exec.callee()->globalObject()->intlDateTimeFormatAvailableLocales();
    HashMap<String, String> resolved = resolveLocale(exec, availableLocales, requestedLocales, localeOpt, relevantExtensionKeys, WTF_ARRAY_LENGTH(relevantExtensionKeys), localeData);

    // 13. Set dateTimeFormat.[[locale]] to the value of r.[[locale]].
    m_locale = resolved.get(vm.propertyNames->locale.string());
    if (m_locale.isEmpty()) {
        throwTypeError(&exec, scope, ASCIILiteral("failed to initialize DateTimeFormat due to invalid locale"));
        return;
    }
    // 14. Set dateTimeFormat.[[calendar]] to the value of r.[[ca]].
    m_calendar = resolved.get(ASCIILiteral("ca"));
    // Switch to preferred aliases.
    if (m_calendar == "gregory")
        m_calendar = ASCIILiteral("gregorian");
    else if (m_calendar == "islamicc")
        m_calendar = ASCIILiteral("islamic-civil");
    else if (m_calendar == "ethioaa")
        m_calendar = ASCIILiteral("ethiopic-amete-alem");
    // 15. Set dateTimeFormat.[[numberingSystem]] to the value of r.[[nu]].
    m_numberingSystem = resolved.get(ASCIILiteral("nu"));
    // 16. Let dataLocale be the value of r.[[dataLocale]].
    String dataLocale = resolved.get(ASCIILiteral("dataLocale"));

    // 17. Let tz be Get(options, "timeZone").
    JSValue tzValue = options->get(&exec, vm.propertyNames->timeZone);
    // 18. ReturnIfAbrupt(tz).
    RETURN_IF_EXCEPTION(scope, void());

    // 19. If tz is not undefined, then
    String tz;
    if (!tzValue.isUndefined()) {
        // a. Let tz be ToString(tz).
        String originalTz = tzValue.toWTFString(&exec);
        // b. ReturnIfAbrupt(tz).
        RETURN_IF_EXCEPTION(scope, void());
        // c. If the result of IsValidTimeZoneName(tz) is false, then i. Throw a RangeError exception.
        // d. Let tz be CanonicalizeTimeZoneName(tz).
        tz = canonicalizeTimeZoneName(originalTz);
        if (tz.isNull()) {
            throwRangeError(&exec, scope, String::format("invalid time zone: %s", originalTz.utf8().data()));
            return;
        }
    } else {
        // 20. Else,
        // a. Let tz be DefaultTimeZone().
        tz = defaultTimeZone();
    }

    // 21. Set dateTimeFormat.[[timeZone]] to tz.
    m_timeZone = tz;

    // 22. Let opt be a new Record.
    // Rather than building a record, build the skeleton pattern.
    StringBuilder skeletonBuilder;

    // 23. For each row of Table 3, except the header row, do:
    // a. Let prop be the name given in the Property column of the row.
    // b. Let value be GetOption(options, prop, "string", «the strings given in the Values column of the row», undefined).
    // c. ReturnIfAbrupt(value).
    // d. Set opt.[[<prop>]] to value.
    auto narrowShortLong = { "narrow", "short", "long" };
    auto twoDigitNumeric = { "2-digit", "numeric" };
    auto twoDigitNumericNarrowShortLong = { "2-digit", "numeric", "narrow", "short", "long" };
    auto shortLong = { "short", "long" };

    String weekday = intlStringOption(exec, options, vm.propertyNames->weekday, narrowShortLong, "weekday must be \"narrow\", \"short\", or \"long\"", nullptr);
    RETURN_IF_EXCEPTION(scope, void());
    if (!weekday.isNull()) {
        if (weekday == "narrow")
            skeletonBuilder.appendLiteral("EEEEE");
        else if (weekday == "short")
            skeletonBuilder.appendLiteral("EEE");
        else if (weekday == "long")
            skeletonBuilder.appendLiteral("EEEE");
    }

    String era = intlStringOption(exec, options, vm.propertyNames->era, narrowShortLong, "era must be \"narrow\", \"short\", or \"long\"", nullptr);
    RETURN_IF_EXCEPTION(scope, void());
    if (!era.isNull()) {
        if (era == "narrow")
            skeletonBuilder.appendLiteral("GGGGG");
        else if (era == "short")
            skeletonBuilder.appendLiteral("GGG");
        else if (era == "long")
            skeletonBuilder.appendLiteral("GGGG");
    }

    String year = intlStringOption(exec, options, vm.propertyNames->year, twoDigitNumeric, "year must be \"2-digit\" or \"numeric\"", nullptr);
    RETURN_IF_EXCEPTION(scope, void());
    if (!year.isNull()) {
        if (year == "2-digit")
            skeletonBuilder.appendLiteral("yy");
        else if (year == "numeric")
            skeletonBuilder.append('y');
    }

    String month = intlStringOption(exec, options, vm.propertyNames->month, twoDigitNumericNarrowShortLong, "month must be \"2-digit\", \"numeric\", \"narrow\", \"short\", or \"long\"", nullptr);
    RETURN_IF_EXCEPTION(scope, void());
    if (!month.isNull()) {
        if (month == "2-digit")
            skeletonBuilder.appendLiteral("MM");
        else if (month == "numeric")
            skeletonBuilder.append('M');
        else if (month == "narrow")
            skeletonBuilder.appendLiteral("MMMMM");
        else if (month == "short")
            skeletonBuilder.appendLiteral("MMM");
        else if (month == "long")
            skeletonBuilder.appendLiteral("MMMM");
    }

    String day = intlStringOption(exec, options, vm.propertyNames->day, twoDigitNumeric, "day must be \"2-digit\" or \"numeric\"", nullptr);
    RETURN_IF_EXCEPTION(scope, void());
    if (!day.isNull()) {
        if (day == "2-digit")
            skeletonBuilder.appendLiteral("dd");
        else if (day == "numeric")
            skeletonBuilder.append('d');
    }

    String hour = intlStringOption(exec, options, vm.propertyNames->hour, twoDigitNumeric, "hour must be \"2-digit\" or \"numeric\"", nullptr);
    RETURN_IF_EXCEPTION(scope, void());

    // We need hour12 to make the hour skeleton pattern decision, so do this early.
    // 32. Let hr12 be GetOption(options, "hour12", "boolean", undefined, undefined).
    bool isHour12Undefined;
    bool hr12 = intlBooleanOption(exec, options, vm.propertyNames->hour12, isHour12Undefined);
    // 33. ReturnIfAbrupt(hr12).
    RETURN_IF_EXCEPTION(scope, void());

    if (!hour.isNull()) {
        if (isHour12Undefined) {
            if (hour == "2-digit")
                skeletonBuilder.appendLiteral("jj");
            else if (hour == "numeric")
                skeletonBuilder.append('j');
        } else if (hr12) {
            if (hour == "2-digit")
                skeletonBuilder.appendLiteral("hh");
            else if (hour == "numeric")
                skeletonBuilder.append('h');
        } else {
            if (hour == "2-digit")
                skeletonBuilder.appendLiteral("HH");
            else if (hour == "numeric")
                skeletonBuilder.append('H');
        }
    }

    String minute = intlStringOption(exec, options, vm.propertyNames->minute, twoDigitNumeric, "minute must be \"2-digit\" or \"numeric\"", nullptr);
    RETURN_IF_EXCEPTION(scope, void());
    if (!minute.isNull()) {
        if (minute == "2-digit")
            skeletonBuilder.appendLiteral("mm");
        else if (minute == "numeric")
            skeletonBuilder.append('m');
    }

    String second = intlStringOption(exec, options, vm.propertyNames->second, twoDigitNumeric, "second must be \"2-digit\" or \"numeric\"", nullptr);
    RETURN_IF_EXCEPTION(scope, void());
    if (!second.isNull()) {
        if (second == "2-digit")
            skeletonBuilder.appendLiteral("ss");
        else if (second == "numeric")
            skeletonBuilder.append('s');
    }

    String timeZoneName = intlStringOption(exec, options, vm.propertyNames->timeZoneName, shortLong, "timeZoneName must be \"short\" or \"long\"", nullptr);
    RETURN_IF_EXCEPTION(scope, void());
    if (!timeZoneName.isNull()) {
        if (timeZoneName == "short")
            skeletonBuilder.append('z');
        else if (timeZoneName == "long")
            skeletonBuilder.appendLiteral("zzzz");
    }

    // 24. Let dataLocaleData be Get(localeData, dataLocale).
    // 25. Let formats be Get(dataLocaleData, "formats").
    // 26. Let matcher be GetOption(options, "formatMatcher", "string", «"basic", "best fit"», "best fit").
    intlStringOption(exec, options, vm.propertyNames->formatMatcher, { "basic", "best fit" }, "formatMatcher must be either \"basic\" or \"best fit\"", "best fit");
    // 27. ReturnIfAbrupt(matcher).
    RETURN_IF_EXCEPTION(scope, void());

    // Always use ICU date format generator, rather than our own pattern list and matcher.
    // Covers steps 28-36.
    UErrorCode status = U_ZERO_ERROR;
    UDateTimePatternGenerator* generator = udatpg_open(dataLocale.utf8().data(), &status);
    if (U_FAILURE(status)) {
        throwTypeError(&exec, scope, ASCIILiteral("failed to initialize DateTimeFormat"));
        return;
    }

    String skeleton = skeletonBuilder.toString();
    StringView skeletonView(skeleton);
    Vector<UChar, 32> patternBuffer(32);
    status = U_ZERO_ERROR;
    auto patternLength = udatpg_getBestPattern(generator, skeletonView.upconvertedCharacters(), skeletonView.length(), patternBuffer.data(), patternBuffer.size(), &status);
    if (status == U_BUFFER_OVERFLOW_ERROR) {
        status = U_ZERO_ERROR;
        patternBuffer.grow(patternLength);
        udatpg_getBestPattern(generator, skeletonView.upconvertedCharacters(), skeletonView.length(), patternBuffer.data(), patternLength, &status);
    }
    udatpg_close(generator);
    if (U_FAILURE(status)) {
        throwTypeError(&exec, scope, ASCIILiteral("failed to initialize DateTimeFormat"));
        return;
    }

    StringView pattern(patternBuffer.data(), patternLength);
    setFormatsFromPattern(pattern);

    status = U_ZERO_ERROR;
    StringView timeZoneView(m_timeZone);
    m_dateFormat = std::unique_ptr<UDateFormat, UDateFormatDeleter>(udat_open(UDAT_PATTERN, UDAT_PATTERN, m_locale.utf8().data(), timeZoneView.upconvertedCharacters(), timeZoneView.length(), pattern.upconvertedCharacters(), pattern.length(), &status));
    if (U_FAILURE(status)) {
        throwTypeError(&exec, scope, ASCIILiteral("failed to initialize DateTimeFormat"));
        return;
    }

    // 37. Set dateTimeFormat.[[boundFormat]] to undefined.
    // Already undefined.

    // 38. Set dateTimeFormat.[[initializedDateTimeFormat]] to true.
    m_initializedDateTimeFormat = true;

    // 39. Return dateTimeFormat.
}
Exemplo n.º 29
0
FontPlatformData* FontCache::createFontPlatformData(const FontDescription& fontDescription, const FontFaceCreationParams& creationParams, float fontSize)
{
    ASSERT(creationParams.creationType() == CreateFontByFamily);

    CString name;
    RefPtr<SkTypeface> tf = createTypeface(fontDescription, creationParams, name);
    // Windows will always give us a valid pointer here, even if the face name
    // is non-existent. We have to double-check and see if the family name was
    // really used.
    if (!tf || !typefacesMatchesFamily(tf.get(), creationParams.family())) {
        AtomicString adjustedName;
        FontWeight variantWeight;
        FontStretch variantStretch;

        if (typefacesHasWeightSuffix(creationParams.family(), adjustedName,
            variantWeight)) {
            FontFaceCreationParams adjustedParams(adjustedName);
            FontDescription adjustedFontDescription = fontDescription;
            adjustedFontDescription.setWeight(variantWeight);
            tf = createTypeface(adjustedFontDescription, adjustedParams, name);
            if (!tf || !typefacesMatchesFamily(tf.get(), adjustedName))
                return 0;

        } else if (typefacesHasStretchSuffix(creationParams.family(),
            adjustedName, variantStretch)) {
            FontFaceCreationParams adjustedParams(adjustedName);
            FontDescription adjustedFontDescription = fontDescription;
            adjustedFontDescription.setStretch(variantStretch);
            tf = createTypeface(adjustedFontDescription, adjustedParams, name);
            if (!tf || !typefacesMatchesFamily(tf.get(), adjustedName))
                return 0;

        } else {
            return 0;
        }
    }

    FontPlatformData* result = new FontPlatformData(tf,
        name.data(),
        fontSize,
        fontDescription.weight() >= FontWeight600 && !tf->isBold() || fontDescription.isSyntheticBold(),
        fontDescription.style() == FontStyleItalic && !tf->isItalic() || fontDescription.isSyntheticItalic(),
        fontDescription.orientation(),
        s_useSubpixelPositioning);

    struct FamilyMinSize {
        const wchar_t* family;
        unsigned minSize;
    };
    const static FamilyMinSize minAntiAliasSizeForFont[] = {
        { L"simsun", 11 },
        { L"dotum", 12 },
        { L"gulim", 12 },
        { L"pmingliu", 11 }
    };
    size_t numFonts = WTF_ARRAY_LENGTH(minAntiAliasSizeForFont);
    for (size_t i = 0; i < numFonts; i++) {
        FamilyMinSize entry = minAntiAliasSizeForFont[i];
        if (typefacesMatchesFamily(tf.get(), entry.family)) {
            result->setMinSizeForAntiAlias(entry.minSize);
            break;
        }
    }

    // List of fonts that look bad with subpixel text rendering at smaller font
    // sizes. This includes all fonts in the Microsoft Core fonts for the Web
    // collection.
    const static wchar_t* noSubpixelForSmallSizeFont[] = {
        L"andale mono",
        L"arial",
        L"comic sans",
        L"courier new",
        L"georgia",
        L"impact",
        L"lucida console",
        L"tahoma",
        L"times new roman",
        L"trebuchet ms",
        L"verdana",
        L"webdings"
    };
    const static float minSizeForSubpixelForFont = 16.0f;
    numFonts = WTF_ARRAY_LENGTH(noSubpixelForSmallSizeFont);
    for (size_t i = 0; i < numFonts; i++) {
        const wchar_t* family = noSubpixelForSmallSizeFont[i];
        if (typefacesMatchesFamily(tf.get(), family)) {
            result->setMinSizeForSubpixel(minSizeForSubpixelForFont);
            break;
        }
    }

    return result;
}
v8::Local<v8::Value> V8WorkerGlobalScopeEventListener::callListenerFunction(v8::Handle<v8::Value> jsEvent, Event* event)
{
    v8::Local<v8::Function> handlerFunction = getListenerFunction(scriptState()->executionContext());
    v8::Local<v8::Object> receiver = getReceiverObject(event);
    if (handlerFunction.IsEmpty() || receiver.IsEmpty())
        return v8::Local<v8::Value>();

    TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "FunctionCall", "data", devToolsTraceEventData(scriptState()->executionContext(), handlerFunction, isolate()));
    TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline.stack"), "CallStack", "stack", InspectorCallStackEvent::currentCallStack());
    // FIXME(361045): remove InspectorInstrumentation calls once DevTools Timeline migrates to tracing.
    InspectorInstrumentationCookie cookie;
    if (InspectorInstrumentation::timelineAgentEnabled(scriptState()->executionContext())) {
        int scriptId = 0;
        String resourceName;
        int lineNumber = 1;
        GetDevToolsFunctionInfo(handlerFunction, isolate(), scriptId, resourceName, lineNumber);
        cookie = InspectorInstrumentation::willCallFunction(scriptState()->executionContext(), scriptId, resourceName, lineNumber);
    }

    v8::Handle<v8::Value> parameters[1] = { jsEvent };
    v8::Local<v8::Value> result = V8ScriptRunner::callFunction(handlerFunction, scriptState()->executionContext(), receiver, WTF_ARRAY_LENGTH(parameters), parameters, isolate());

    InspectorInstrumentation::didCallFunction(cookie);
    TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "UpdateCounters", "data", InspectorUpdateCountersEvent::data());

    return result;
}